Stateless and Stateful Operations

Stateless and Stateful Operations in Apache Kafka: Every operator in Streams falls into one of two camps, and the boundary between them is where all the…

Every operator in Streams falls into one of two camps, and the boundary between them is where all the operational cost lives.

STATELESS                        STATEFUL
 filter, map, mapValues,          count, reduce, aggregate,
 flatMap, branch, peek,           joins, windows, suppress
 selectKey, merge, to
      │                                │
 nothing to remember             local state store (RocksDB)
 nothing to restore                        │
 scales trivially                changelog topic (compacted)
                                           │
                                 restored on restart / reassignment

Stateless operators

These transform one record at a time with no memory of previous records.

KStream<String, Order> orders = builder.stream("orders");

// value only: key untouched, partitioning still valid
KStream<String, BigDecimal> totals = orders.mapValues(Order::getTotal);

// drop what you do not need as early as possible
KStream<String, Order> real = orders.filter((k, v) -> !v.isTest());

// split one stream into several by predicate
Map<String, KStream<String, Order>> split = orders
    .split(Named.as("by-status-"))
    .branch((k, v) -> v.isCancelled(), Branched.as("cancelled"))
    .defaultBranch(Branched.as("active"));

Two habits pay off immediately:

  1. Filter early. Every record you discard at the front is a record you do not serialise, repartition, store, or join.
  2. Prefer mapValues and flatMapValues over map and flatMap when the key does not change. This is not style. It is a performance and correctness decision, explained next.

Why changing the key costs you a topic

Kafka guarantees that records with the same key are in the same partition — for the key the producer used. The moment your topology changes the key, that guarantee no longer holds for the new key: records that now share a key can be sitting in different partitions, owned by different instances.

Streams cannot aggregate or join correctly in that state, so before the first stateful operation after a key change it inserts a repartition topic: it writes records back to Kafka, keyed by the new key, and reads them again.

orders (keyed by orderId)
      │
   selectKey(customerId)          ← key changed, partitioning now stale
      │
      ▼
 [ internal repartition topic ]   ← extra write + read, extra latency
      │
      ▼
 groupByKey().count()             ← now safe: same customerId, same partition

Which operations trigger it:

OperationRepartition?Reason
mapValues, filter, peekNoKey untouched, partitioning still valid
map, selectKey, flatMap, transformMarked dirtyThe key may have changed; Streams assumes it did
groupByKey() after a key-preserving chainNoNothing invalidated the partitioning
groupBy(...)AlwaysIt re-keys by definition
Stream-stream / stream-table joinNo, but requires co-partitioningJoin keys must already align

So groupByKey is not automatically free: it triggers a repartition if anything upstream marked the key as possibly changed. And groupBy always repartitions, even when the selector returns the same key — Streams cannot know that.

Repartition topics are not a bug to be eliminated at all costs; they are the mechanism that makes the aggregation correct. But they double the traffic for that stage, so avoid unnecessary ones by using mapValues when the key is not changing, and by re-keying once rather than in several places.

Aggregations

Three operators, in increasing generality:

OperatorShapeUse
count()KTable<K, Long>Occurrences per key
reduce(f)Same type in and outRunning max, sum, last-wins
aggregate(init, adder)Arbitrary result typeBuilding a struct, average, custom accumulator
KTable<String, Long> ordersPerCustomer = orders
    .groupByKey()
    .count(Materialized.as("orders-per-customer"));

KTable<String, OrderStats> stats = orders
    .groupByKey()
    .aggregate(
        OrderStats::empty,                       // initializer
        (key, order, agg) -> agg.plus(order),    // adder
        Materialized.as("order-stats"));

Note the result type: an aggregation produces a KTable, because "count per key" is by definition latest-value-per-key. The duality from the previous topic is doing the work.

An aggregation emits an updated result on every input record, not once at the end. Downstream consumers therefore see a stream of successive intermediate values — 1, 2, 3, 4 — and must treat later values for a key as replacing earlier ones. If you need fewer intermediate emissions, that is what record caching and suppress are for; they change how often results are emitted, never the final value.

State stores and changelog topics

A stateful operator keeps its data in a local store on the instance's disk (RocksDB by default), and mirrors every change to an internal compacted changelog topic.

                write                       async replicate
 record ──► local state store ─────────────► changelog topic
                (RocksDB, on disk)           (compacted, in Kafka)
                     │                              │
              fast local reads             durable, replicated,
                                           survives instance loss

The naming convention is predictable: <application.id>-<store-name>-changelog. Repartition topics follow the same pattern with a -repartition suffix.

On restart, or when a partition is reassigned to a different instance, the store is rebuilt by replaying the changelog for those partitions. This is why compaction matters: the changelog must still hold the latest value for every key.

Restore has a real cost. A large store means a long restore during which the task is not processing, and lag grows. Two levers:

  • Standby replicas (num.standby.replicas) keep warm copies of state on other instances, so a reassignment can resume quickly instead of restoring from scratch. You pay in disk and extra changelog traffic.
  • Persistent local storage. If the instance keeps its state directory across restarts, only the tail of the changelog needs replaying. On ephemeral containers with no persistent volume, every restart is a full restore.

Where state quietly becomes an incident

  • Unbounded key space. Aggregating by a key that grows forever (session IDs, request IDs, raw URLs) makes the store grow forever. Windowed stores expire; unwindowed ones do not. Either window the aggregation or emit tombstones when a key becomes irrelevant.
  • Disk sizing forgotten. Streams instances need real disk for RocksDB. Sizing them like stateless services is the most common deployment mistake.
  • Deleting internal topics manually. Removing a changelog topic deletes your durable state. If you must reset an application, use the reset tool for that job rather than deleting topics by hand.
  • Reusing an application.id. It is the identity of the consumer group and the prefix of every internal topic. Two different topologies sharing one application.id will fight over partitions and corrupt each other's state.
  • Changing the topology in place. Adding or removing stateful operators can change internal topic names and store contents. Treat a topology change like a schema migration: plan whether state is rebuilt from scratch or carried forward.

Streams is still a consumer group

Everything from Module 3 applies unchanged. A Streams application is a consumer group whose members are the instances; application.id is the group.id. Partition count caps parallelism, rebalances stop processing, and lag is measured the same way. Streams adds state restoration on top of a rebalance, which makes rebalances more expensive, not less — one more reason to prefer static membership and persistent state directories.


Exercise: A topology reads page-views keyed by session_id, calls selectKey to re-key by url, then groupByKey().count() into a store, and runs on ephemeral pods with no persistent volumes. Traffic is steady but every deploy causes 20 minutes of growing lag, and the instances' disk usage never stops climbing. Explain both symptoms in terms of repartition and changelog behaviour, and give two changes for each.