Video in progress
How does a state store work in Kafka Streams: changelog topic, restore and standby replicas? What do you do if a restore takes 40 minutes on prod?
State lives in local RocksDB, and every change is also written to a compacted changelog topic. If a task moves to another instance, the state is restored from the changelog, which takes a long time for a big state. Standby replicas, persistent disks and static membership cut this time sharply.
📖 Answer
If you use count(), aggregate() or a KTable, Kafka Streams creates a state store. There are two layers:
- local RocksDB in the
state.dirdirectory: reads and writes are fast, no network; - the
<application.id>-<store>-changelogtopic: every write also goes here. This is the real backup of the state.
Each input partition is one task, and each task has its own store. In a rebalance, if a task moves to another instance, that instance restores the local store by reading the changelog from the beginning. During that time the task doesn't run, and the lag grows.
Typical causes of a 40-minute restore, and the fixes:
- The pod arrives with an empty disk on every deploy. In Kubernetes,
emptyDirmeans the state is lost every time. With a StatefulSet + PersistentVolume, a returning pod reads only the difference. - The task keeps jumping to another pod. With static membership (
group.instance.id) and a sufficientsession.timeout.ms, the task stays in place during a restart. - There's no standby.
props.put(StreamsConfig.NUM_STANDBY_REPLICAS_CONFIG, 1);
A standby is a copy on another instance that's continuously updated from the changelog. If the main instance dies, the task moves to the standby almost ready. The cost is double the disk and extra traffic.
- The state is needlessly big. Shorten the retention for windows, clean out old keys.
Kafka Streams doesn't hand a task to a new instance immediately: first a "warmup" replica there catches up on the state, and then the task is moved (acceptable.recovery.lag). This also reduces long stalls.
For monitoring I use the restore metrics (restore-rate, records-restored) and log from a StateRestoreListener; otherwise there's no answer to "what was the service doing for 40 minutes?".
Sign up to mark studied questions and save your progress.