Kafka Streams: Topology, State Stores and Windowing
Senior level ยท What the library actually runs, where state lives, and how it comes back after a crash.
Prerequisites
- !Consumer groups and partition ownership
- !The difference between a log and a table
What You'll Learn
- 1Describe a Streams topology as source, processor and sink nodes
- 2Choose between KStream and KTable for a given problem
- 3Select a window type from the shape of the question being asked
- 4Explain how changelog topics restore state after a failure
A library that borrows your cluster
Kafka Streams is a client library, not a cluster. There is no separate resource to provision, no scheduler and no coordinator service; you embed it in an ordinary JVM application, and the only infrastructure it needs is the Kafka cluster it already talks to. Parallelism comes from consumer group membership, so a Streams application scales by running more instances and letting partition assignment do the work.
What the library adds on top of a plain consumer is a declarative topology. You describe how records flow from source topics through filters, maps, aggregations and joins to sink topics, and the library compiles that description into a processor graph, manages local state, restores it after failure, and optionally wraps the whole computation in a transaction. The mental shift is from writing a loop to describing a pipeline.
KStream and KTable: two different questions
The distinction between the two core abstractions is whether a record replaces history or adds to it.
| Abstraction | Represents | Duplicate keys | Backed by |
|---|---|---|---|
| KStream | An append-only stream of events | Two events, both kept | Source topic log |
| KTable | The latest value per key | The newer record wins | A changelog topic |
| GlobalTable | A full table on every instance | Same as KTable, replicated everywhere | A compacted topic |
A KStream of clicks keeps every click forever, so counting requires an explicit aggregation. A KTable of user profiles keeps one row per user, so joining a stream to it is a lookup rather than a scan. The difference shows up in state: a KTable-backed operation needs a local store that can be rebuilt from a compacted changelog, while a stateless KStream filter needs nothing at all.
Building a topology that compiles to a processor graph
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "order-enrichment");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka1:9092,kafka2:9092");
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
props.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, StreamsConfig.EXACTLY_ONCE_V2);
StreamsBuilder builder = new StreamsBuilder();
KStream<String, Order> orders = builder.stream("orders",
Consumed.with(Serdes.String(), new OrderSerde()));
KTable<String, Profile> profiles = builder.table("profiles",
Materialized.as("profile-store"));
orders
.filter((key, order) -> order.totalAmount().doubleValue() != 0.0)
.join(profiles, EnrichedOrder::new)
.groupByKey()
.windowedBy(TimeWindows.ofSizeWithNoGrace(Duration.ofMinutes(5)))
.aggregate(OrderTotals::new,
(key, order, acc) -> acc.add(order),
Materialized.<String, OrderTotals, WindowStore<Bytes, byte[]>>as("five-minute-totals")
.withRetention(Duration.ofHours(6)))
.toStream()
.to("enriched-orders", Produced.with(Serdes.String(), new TotalsSerde()));
KafkaStreams streams = new KafkaStreams(builder.build(), props);
streams.setStateListener((newState, oldState) ->
log.info("streams state moved from {} to {}", oldState, newState));
streams.start();
Every call appends a node rather than executing immediately. Nothing runs until start, and the library then assigns each source partition to a stream thread, builds the local store instances, and replays changelogs to bring state up to the current offset before the first record is processed.
Windowing: four shapes of time
Windows exist because most useful questions are about intervals rather than individual records. Tumbling windows are fixed, non-overlapping buckets, so a five-minute window gives counts per five minutes with no double counting. Hopping windows are fixed but overlapping: a ten-minute window advancing every five minutes reports each event twice, which buys smoother curves at the cost of storage.
// Tumbling: [00:00, 00:05), [00:05, 00:10), ...
KTable<Windowed<String>, Long> perBucket = orders.groupByKey()
.windowedBy(TimeWindows.ofSizeWithNoGrace(Duration.ofMinutes(5)))
.count();
// Hopping: overlapping, each record lands in two windows
KTable<Windowed<String>, Long> smoothed = orders.groupByKey()
.windowedBy(TimeWindows.ofSizeWithNoGrace(Duration.ofMinutes(10))
.advanceBy(Duration.ofMinutes(5)))
.count();
// Session: windows grow until an inactivity gap closes them
KTable<Windowed<String>, Long> sessions = clicks.groupByKey()
.windowedBy(SessionWindows.ofInactivityGapWithNoGrace(Duration.ofMinutes(10)))
.count();
Session windows are the odd one out: their boundaries are data-driven, opening on the first event and closing when the inactivity gap elapses, and two sessions that grow close enough merge into one. They fit user activity and sessionisation, and they are a poor fit for operational reporting because no two keys share the same bucket edges.
๐กGrace is not optional in practice
Joins, and which ones need a window
A KStream to KTable join is a lookup: for each incoming event the library reads the current value of that key from the local store and emits the combination. No window is needed and no state beyond the table itself is kept. A KStream to KStream join compares two event streams, and because neither side is bounded, you must say how far apart in time two events may be for them to count as a match.
KStream<String, Enriched> enriched = orders.join(
payments,
(o, p) -> new Enriched(o, p),
JoinWindows.ofTimeDifferenceWithNoGrace(Duration.ofMinutes(2)),
StreamJoined.with(Serdes.String(), new OrderSerde(), new PaymentSerde()));
// Left join keeps orders that never received a matching payment
KStream<String, MaybePaid> maybePaid = orders.leftJoin(
payments,
(o, p) -> new MaybePaid(o, p),
JoinWindows.ofTimeDifferenceWithNoGrace(Duration.ofMinutes(2)),
StreamJoined.with(Serdes.String(), new OrderSerde(), new PaymentSerde()));
Both sides of a stream join keep their own window store, so memory and disk grow with window length and with throughput. That is the practical reason to prefer a table join whenever one side can be expressed as current state.
State stores and how they come back
Aggregations, joins and windowing all need local state, and Kafka Streams persists it twice: in a local store for speed and in a changelog topic for durability. On restart or rebalance the library pauses processing for the affected partitions, reads the changelog from the last checkpointed position, restores the store, and only then resumes consuming input.
KTable<String, OrderTotals> totals = orders.groupByKey()
.aggregate(OrderTotals::new,
(key, order, acc) -> acc.add(order),
Materialized.<String, OrderTotals, KeyValueStore<Bytes, byte[]>>as("totals")
.withKeySerde(Serdes.String())
.withValueSerde(new TotalsSerde())
.withRetention(Duration.ofDays(7)));
Two operational consequences follow. Changelog throughput counts against your cluster like any other topic, so a high-cardinality aggregation on a busy input produces a comparably busy changelog. And retention on the store must exceed the longest period you expect an instance to be offline, because a replica that returns after its changelog has been truncated has to rebuild from the input topic instead.
Scaling without wasted instances
Because assignment is standard consumer group behaviour, the number of stream threads is capped by the number of input partitions the process owns. Adding instances beyond that count adds only rebalances. Before scaling out, check whether the input topics have enough partitions to keep every instance busy, and prefer raising partitions on the bottleneck topic over adding more pods.
Testing topologies before they reach production
Kafka Streams provides a TestTopologyDriver that lets you feed records into a topology in memory, without a running cluster, and inspect the output topic by topic. This is the fastest way to catch a misconfigured window, a join that produces nothing because the key space does not overlap, or a filter that drops every record because the predicate was written against the wrong field. The driver runs the same topology code that production runs, so what you assert in the test is what the topology actually does.
The mistake most teams make is testing only the happy path. A topology that joins a stream of orders with a stream of payments needs a test that feeds an order without a matching payment, a payment that arrives outside the join window, and a record with a null key. Each of those cases exercises a different branch of the topology, and a single happy-path test catches none of them. For windowed aggregations, feed records on both sides of a window boundary and assert the grace period behavior explicitly; off-by-one errors in window boundaries are the single most common source of incorrect aggregations in production Streams applications.
State stores deserve their own tests. A store backed by a changelog will restore correctly if the changelog is written, but a store that is only exercised in memory will not surface a serialization failure until the first real restore after a deploy. Force a restore in a test by restarting the driver with the same state directory, and confirm the restored store produces the same results as the in-memory one. This catches schema incompatibilities in the changelog that would otherwise appear as a silent data corruption after the first instance restart.
The TestTopologyDriver also lets you assert on the number of output records, which is the most reliable way to catch a duplication bug. If a topology that should emit one record per input emits two, the test fails immediately rather than after a downstream consumer flags the anomaly. Treat the record count as a first-class assertion, not just the content of the records you expect.
Common Mistakes
Treating KStream and KTable as interchangeable because both hold records
Fix: Decide whether a duplicate key is a second event or a newer state. Choosing wrong silently changes counts, joins and whether a changelog exists at all.
Adding stream instances when the topic has fewer partitions than instances
Fix: Partitions cap parallelism. Increase partitions or consolidate instances; extra pods only add rebalance churn and store re-restoration.
Leaving window retention at defaults and wondering where late records went
Fix: Set an explicit grace period and a retention that covers your lateness, and monitor records dropped due to lateness.
Calling an external database inside the processor and assuming recovery replays safely
Fix: State store writes are restored from the changelog; external writes are not. Make external effects idempotent or emit to an output topic and let a separate worker apply them.
Best Practices
- Match input partition count to the maximum instances you ever expect to run, then scale within that bound
- Prefer KStream to KTable joins whenever one side is current state; they need no window and far less store
- Give every aggregation an explicit grace period and retention covering the worst observed lateness
- Chart stream thread count and store restoration time so slow recovery is visible during rebalances
- Use exactly_once_v2 together with read_committed readers, since the guarantee only reaches readers that cooperate
Interview Questions
Q1: KStream or KTable for a stream of payment events, and why?
KStream. Each payment is an independent event that must be retained. Keying a table by payment id would keep one row per payment, while keying by order id would hide earlier attempts and break reconciliation.
Q2: How does a state store recover after an instance dies?
The local store is a cache of a changelog topic. On restart the instance reads the changelog from its last checkpoint, replays it into the store, then resumes input from the committed offset, so recovery time scales with changelog size rather than input history.
Q3: Which window type merges automatically, and why does that matter?
Session windows merge when their inactivity gaps overlap, producing variable-length buckets that follow user behaviour. Fixed windows cannot represent sessions, and merging means totals must be recomputed across the merged interval.
Q4: Why does a stream to stream join require a window?
Neither input is bounded, so without a time bound the library would retain both streams forever. The window is the retention policy, and its length directly determines store size and join cost.
Q5: What limits scaling of a Streams application?
Input partitions. Each source partition is assigned to exactly one stream thread, so instances beyond the partition count idle while still triggering rebalances.
Key Takeaways
- Streams runs inside your process and scales with consumer group assignment, not with a separate cluster
- KStream keeps every event; KTable keeps one value per key and forces a changelog topic
- Topology calls build a graph that only executes after start, with stores restored before the first record
- Tumbling, hopping and session windows differ by overlap and by whether boundaries are fixed or data-driven
- Stream joins need a window for retention while table joins do not, which makes table joins the cheaper default