What Is Kafka Streams?
Kafka Streams is a Java library (not a server or cluster) for building applications that read from Kafka topics, process the data and write results back to Kafka. You package it inside your normal application. To scale, you start more instances of the same app.
| Feature | Meaning |
| Library only | No extra cluster. Deploy like any microservice (Docker, Kubernetes) |
| Stateful processing | Counts, joins and windows with local state stores backed by Kafka changelog topics |
| Fault tolerant | State is rebuilt from changelog topics after a crash |
| Exactly-once | processing.guarantee=exactly_once_v2 |
| Scaling | Instances share the work through the consumer group protocol. Parallelism is limited by input partitions |
KStream and KTable
| KStream | KTable |
| Model | A stream of events (every record is a fact) | A table of latest value per key (changelog) |
| Insert same key twice | Two separate events | Second one updates the first |
| Example | Every order placed, every click | Current customer profile, current stock level |
| Kafka topic | Normal topic | Often a compacted topic |
text
topic records: (alice,10) (bob,5) (alice,20)
as KStream: 3 events
as KTable: alice -> 20, bob -> 5 (latest per key)
Stream-table duality: a table is a stream of updates; a stream can be aggregated into a table.
| Type | Use |
KStream<K,V> | Event processing, transformations |
KTable<K,V> | Partitioned state, one value per key |
GlobalKTable<K,V> | Small reference data fully copied to every instance (join without co-partitioning) |
Project Setup
xml
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-streams</artifactId>
<version>4.0.0</version>
</dependency>
Example 1: Word Count
java
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.*;
import org.apache.kafka.streams.kstream.*;
import java.util.Arrays;
import java.util.Properties;
public class WordCountApp {
public static void main(String[] args) {
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "wordcount-app"); // also the consumer group id and state prefix
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
StreamsBuilder builder = new StreamsBuilder();
KStream<String, String> lines = builder.stream("text-lines");
KTable<String, Long> counts = lines
.flatMapValues(line -> Arrays.asList(line.toLowerCase().split("\\W+"))) // split into words
.filter((key, word) -> !word.isBlank())
.groupBy((key, word) -> word) // re-key by word (creates repartition topic)
.count(Materialized.as("word-counts-store")); // stateful: local store + changelog topic
counts.toStream().to("word-counts", Produced.with(Serdes.String(), Serdes.Long()));
KafkaStreams streams = new KafkaStreams(builder.build(), props);
Runtime.getRuntime().addShutdownHook(new Thread(streams::close)); // clean shutdown
streams.start();
}
}
bash
bin/kafka-topics.sh --bootstrap-server localhost:9092 --create --topic text-lines --partitions 3
bin/kafka-topics.sh --bootstrap-server localhost:9092 --create --topic word-counts --partitions 3
# run the app, then:
bin/kafka-console-producer.sh --bootstrap-server localhost:9092 --topic text-lines
> hello kafka hello streams
bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic word-counts --from-beginning \
--property print.key=true --property value.deserializer=org.apache.kafka.common.serialization.LongDeserializer
# hello 2
# kafka 1
# streams 1
Stateless Operations
| Operation | What it does | Example |
filter / filterNot | Keep or drop records | orders.filter((k, o) -> o.total() > 100) |
mapValues | Change the value, keep the key (no repartition) | .mapValues(o -> o.toUpperCase()) |
map | Change key and value (may force repartition) | .map((k, v) -> KeyValue.pair(v.id(), v)) |
selectKey | Set a new key | .selectKey((k, v) -> v.customerId()) |
flatMapValues | One record into zero or many | split text into words |
peek | Side effect such as logging | debugging |
split / branch | Route into several streams by predicate | see below |
merge | Combine streams of the same type | a.merge(b) |
to / through | Write to a topic | .to("out") |
Prefer mapValues: Changing the key with map, selectKey or groupBy makes Streams create an internal repartition topic so records with the same new key meet in the same partition. That costs extra network and storage, so use mapValues when you do not need a new key.
Example 2: Routing Orders
java
KStream<String, Order> orders = builder.stream("shop.orders.created.v1", Consumed.with(Serdes.String(), orderSerde));
orders.split(Named.as("route-"))
.branch((k, o) -> o.total() >= 1000, Branched.withConsumer(s -> s.to("orders.high-value", Produced.with(Serdes.String(), orderSerde))))
.branch((k, o) -> "EU".equals(o.region()), Branched.withConsumer(s -> s.to("orders.eu", Produced.with(Serdes.String(), orderSerde))))
.defaultBranch(Branched.withConsumer(s -> s.to("orders.standard", Produced.with(Serdes.String(), orderSerde))));
Serdes
Streams needs a Serde (serializer plus deserializer) for every key and value type. Set defaults in the config, or pass them explicitly with Consumed.with, Produced.with, Grouped.with, Materialized.with. For JSON create a Serde with Jackson, for Avro or Protobuf use the Schema Registry serdes.
java
Serde<Order> orderSerde = Serdes.serdeFrom(new JsonSerializer<>(), new JsonDeserializer<>(Order.class)); // your own small classes with Jackso
Topology Description
java
Topology topology = builder.build();
System.out.println(topology.describe());
// Topologies:
// Sub-topology: 0
// Source: KSTREAM-SOURCE-0000000000 (topics: [text-lines])
// Processor: KSTREAM-FLATMAPVALUES-...
// Processor: KSTREAM-FILTER-...
// Sink: KSTREAM-SINK-... (topic: word-counts-repartition)
Print the topology to see sub-topologies, state stores and repartition topics. Paste the text into a topology visualizer to get a diagram.
Important Configuration
| Setting | Notes |
application.id | Unique per application. Names the consumer group, internal topics (<app>-<store>-changelog) and state directory |
num.stream.threads | Threads per instance. Total threads across all instances should not exceed the number of tasks (input partitions) |
processing.guarantee | at_least_once (default) or exactly_once_v2 |
state.dir | Local RocksDB state location, use a persistent volume in containers |
commit.interval.ms | How often progress is committed and caches flushed (30000 default, 100 with exactly-once) |
num.standby.replicas | Warm copies of state on other instances for faster failover |
default.deserialization.exception.handler | What to do with unreadable records: fail (default) or log and continue |
Scaling and Failure
- Streams creates one task per input partition. Tasks are spread over threads and instances
- Start a second instance with the same
application.id and work is rebalanced automatically
- If an instance dies, its tasks move and local state is restored from the changelog topics (faster with standby replicas)
- Create input topics before starting the app, and make sure joined topics have the same number of partitions
Conclusion
Kafka Streams is a library that turns your Java app into a scalable stream processor. KStream models events, KTable models current state per key, stateless operations (filter, mapValues, flatMapValues, split) are cheap, and key-changing operations cause repartitioning.
Quick Summary: library; KStream events vs KTable latest; mapValues cheap, key change repartitions; application.id; tasks = partitions.