A library, not a cluster
Kafka Streams is a Java and Scala client library, which is the first thing to internalise because it changes how you operate it. There is no separate processing cluster to provision, no resource manager to babysit, and no cluster-level failover: you embed the library in your own application, package it with your build, and run as many instances as your application already has. Parallelism follows the input topic's partition count, fault tolerance follows consumer group semantics, and scaling means starting another instance of the same jar.
That simplicity has a price. Because state lives on the instance that owns the partition, a failure means that instance's state store must be rebuilt from the changelog topic before it can rejoin, and recovery time is a function of how much state you accumulated. The design question in every Streams application is therefore not "how do I transform this record" but "how much state am I creating, and how fast can I rebuild it".
You should leave this lesson able to pick between a stream and a table representation, size a window without creating a state explosion, and name the exact configuration that makes a topology exactly-once rather than merely reliable.
Streams, tables, and the duality between them
A KStream is an unbounded sequence of records where each record is an insert and nothing is ever updated. A KTable is a changelog where each record is an upsert keyed by entity, so the materialised view always reflects the latest value per key. The duality connecting them is that a stream reduces to a table by folding updates per key, and a table becomes a stream of changes â which is why you can switch representation to suit the operation.
The choice has direct consequences. Aggregations and joins on entity state want a table, because you need "the current value", not every historical event. Session analytics and audit trails want a stream, because every event is significant. A GlobalKTable replicates the full table to every instance, which makes local joins possible without a repartition but costs memory proportional to table size.
| Abstraction | Record meaning | Typical source | Best for | Cost |
|---|---|---|---|---|
KStream | Insert | Event topic | Sessions, audit, funnels | Every event retained |
KTable | Upsert per key | Change topic | Entity state, dimensions | State store per key |
GlobalKTable | Upsert, fully replicated | Reference data | Local joins, lookups | Whole table in memory |
KGroupedStream | Intermediate | After groupByKey | Aggregations | Repartition if keys differ |
| Repartition topic | Re-keyed records | After selectKey | Joins on a new key | Extra hop and storage |
A repartition is the hidden step beginners miss. If you change the key with selectKey and then aggregate, the stream must shuffle records to the new key's partition before the aggregation can be correct. The DSL inserts a repartition topic automatically, and while it is correct it also doubles I/O for that branch â check toString of the topology description to see whether it appeared where you expected.
Windowing without creating a state explosion
Windowed aggregation groups records by time before reducing them, and the window type encodes your assumption about activity. Tumbling windows are fixed, non-overlapping intervals: clean for per-minute counters, and each record belongs to exactly one window. Sliding windows are fixed-size and overlapping: a single record can fall into several windows, so state grows with the overlap factor. Session windows are dynamic, closing after an inactivity gap, which models human behaviour well but means window boundaries are data-dependent.
State size follows directly. For a tumbling window of duration W receiving R records per second, live state is roughly R Ã W records, before caching and before late arrivals. Halving the window halves the state. Grace periods add a bounded extension in which late records may still land; a generous grace keeps results correct longer while pinning closed windows in memory longer. Trade deliberately.
StreamsBuilder builder = new StreamsBuilder();
KStream<String, ClickEvent> clicks = builder.stream(
"click-events",
Consumed.with(Serdes.String(), Serdes.JsonSerde<>(ClickEvent.class))
);
KTable<Windowed<String>, Long> perSession = clicks
.groupBy((key, click) -> click.userId(),
Grouped.with(Serdes.String(), Serdes.JsonSerde<>(ClickEvent.class)))
.windowedBy(SessionWindows.ofInactivityGapAndGrace(
Duration.ofMinutes(30), Duration.ofMinutes(5)))
.count(Materialized.<String, Long, WindowStore<Bytes, byte[]>>as("session-counts")
.withRetention(Duration.ofHours(24))
.withCachingEnabled())
.suppress(Suppressed.untilWindowCloses(Suppressed.TimeConfig.MAX_GRACE_MS));
perSession.toStream().to(
"session-counts",
Produced.with(new SessionWindowedSerde<>(Serdes.String()), Serdes.Long())
);
Three choices inside that chain deserve attention. withRetention bounds how long closed windows stay queryable, which caps state. suppress stops intermediate updates from flooding the output topic, so downstream sees one final count per session instead of a stream of partial values. The grace period of five minutes is the lateness budget: records older than that are dropped by the window rather than silently corrupting an already-published count.
Enriching a stream from table state
Stream-table joins are how raw events become useful records. The stream side carries what happened; the table side carries what it means â customer tier, product category, credit limit. Because the table is materialised locally, the join costs a lookup rather than a network round trip, and correctness depends on both sides being co-partitioned: same partition count, same key.
KTable<String, Customer> customers = builder.table(
"customer-profiles",
Consumed.with(Serdes.String(), Serdes.JsonSerde<>(Customer.class)),
Materialized.as("customer-store")
);
KStream<String, EnrichedOrder> enriched = orders
.selectKey((k, o) -> o.customerId()) // repartition implied on next stateful op
.join(customers,
(order, customer) -> new EnrichedOrder(
order, customer.tier(), order.amount() <= customer.creditLimit()),
Joined.with(Serdes.String(),
Serdes.JsonSerde<>(Order.class),
Serdes.JsonSerde<>(Customer.class)));
enriched.filter((k, e) -> !e.withinCreditLimit())
.to("credit-violations", Produced.with(Serdes.String(), Serdes.JsonSerde()));
Two production concerns sit behind that snippet. First, table freshness: a stream-table join reflects the table as it was when the record arrived, so an order processed one second before a profile update joins against the stale value. If that matters, buffer briefly or route the mismatch to a correction stream. Second, the left-join case: when the table has no matching key, you must decide whether to drop, default, or park the record, and a silent default of zeros is a data quality bug waiting for an incident review.
The four conditions for exactly-once
Setting processing.guarantee=exactly_once_v2 is necessary but not sufficient. The guarantee holds only when the whole path is transactional: output topics use acks=all with a replication factor of at least two, state store changelog topics are replicated, consumers read with isolation.level=read_committed, and your processors do nothing non-deterministic outside Kafka â no un-keyed HTTP calls, no unseeded randomness, no writing to an external database that cannot join the transaction.
| Guarantee | Configuration | Duplicate risk | Failure mode |
|---|---|---|---|
| At-most-once | processing.guarantee=at_most_once | None | Records lost on crash |
| At-least-once | at_least_once | Full replay after failure | Duplicates on retry |
| Exactly-once | exactly_once_v2 | None inside Kafka | External side effects escape it |
The last row is where teams get burned. Kafka can make topic-to-topic processing exactly-once; it cannot make your webhook call or warehouse insert part of the same transaction. Wrap external effects in an idempotent sink keyed on the record's event id, or accept that the delivery semantics of that sink are the semantics of your pipeline.
Testing and operating the topology
TopologyTestDriver is the difference between a topology you understand and one you hope about. It runs the whole graph against in-memory topics and stores, so you can feed records, assert on outputs, and inspect state store contents in a unit test that takes milliseconds and needs no cluster. Windows, suppressions, and joins â the parts most likely to be subtly wrong â are all observable this way.
Operationally, three metrics matter: state store size (growth signals missing retention or a key explosion), changelog lag (how far recovery would have to replay after a failure), and consumer lag on the input topic. Keep standby replicas enabled with num.standby.replicas=1 so a warm copy of state exists on another instance, and monitor rebalance duration, because each rebalance pauses processing across the whole group.
â ī¸Rebalance pauses are not free
During a rebalance every instance stops processing while ownership is reassigned, and state restoration for the new owner begins only afterwards. Long state stores plus frequent membership changes compound into minutes of stalled output, so prefer static group membership and incremental cooperative rebalancing over the eager protocol.
Common Mistakes
Calling groupByKey after selectKey without checking for an implicit repartition
Fix: Inspect the topology description and insert an explicit repartition where you want control over placement
Leaving grace open-ended so late records silently vanish after publication
Fix: Set a bounded grace and decide explicitly whether late data is dropped or routed to a correction stream
Assuming exactly-once covers a warehouse insert or an HTTP webhook
Fix: Make external effects idempotent with an event id, or treat the pipeline as at-least-once end to end
Building unbounded session windows with no retention
Fix: Cap state with withRetention and alert on state store size growth
Best Practices
- Run TopologyTestDriver tests for every window, join, and suppression before deploying
- Co-partition both sides of a join and verify partition counts match
- Enable standby replicas to cut recovery time after an instance dies
- Read the topology description in CI so unintended repartitions show up in review
- Keep processors pure: state changes go through stores, side effects go through the sink
Interview Questions
Q1: What is the difference between a KStream and a KTable?
A KStream is insert-only and keeps every event; a KTable is keyed upserts and holds the latest value per key, so it models current state.
Q2: Why would a topology create a repartition topic?
When a stateful operation follows a key change, records must be shuffled to the new key's partition before grouping or joining can be correct.
Q3: What does exactly_once_v2 actually guarantee?
Exactly-once for records moving between Kafka topics with state stores, provided producers ack all, consumers read committed, and no non-Kafka side effect escapes the transaction.
Q4: How do you reduce recovery time after a failure?
Bound state retention, keep standby replicas, and keep changelog topics co-located so restoration replays less data.
Key Takeaways
- Streams runs in your application, so scaling, packaging, and failure recovery follow your app's lifecycle
- Choose stream versus table by whether you need every event or the current value per key
- Window type and grace period together decide both correctness under lateness and state size
- Exactly-once needs the full path transactional and still cannot cover effects outside Kafka
- Test with TopologyTestDriver, monitor state size and changelog lag, and keep standby replicas warm