Kafka Streams State Stores and Stateful Processing
Many stream processing tasks need memory: counting events per user, summing sales per store, joining an order with the latest customer profile, or detecting a pattern within five minutes. Kafka Streams keeps that memory in state stores, local key-value databases that are backed up to Kafka so they survive crashes.
The Kafka Streams tutorial introduces the library and stateless operations. This tutorial goes deeper into stateful processing: how state stores work, how they are made fault tolerant, how to query them, and how to tune them for production.
1. What Is a State Store?
A state store is a local, embedded storage engine owned by one Kafka Streams task. Operations such as count(), aggregate(), reduce(), windowed aggregations and stream-table joins create one automatically. You can also add custom stores to the Processor API.
| Store type | Typical use | Created by |
|---|---|---|
| Key-value | Running totals, latest value per key | count(), aggregate(), reduce(), toTable() |
| Window | Counts per key per time window | windowedBy(...) aggregations |
| Session | Activity sessions with inactivity gaps | windowedBy(SessionWindows...) |
| Versioned key-value | Point-in-time lookups for joins (Kafka 3.5+) | Stores.persistentVersionedKeyValueStore(...) |
2. Why Stateful Processing Needs State Stores
- Speed: reading local disk or memory takes microseconds, compared with a remote database call per record.
- Fault tolerance without a database: state is rebuilt from Kafka itself after a failure.
- Scaling with partitions: each task has its own store shard, so adding instances spreads state automatically.
3. How State Stores Work
3.1 Local storage
By default, persistent stores use RocksDB in the directory set by state.dir. In-memory stores are available with Stores.inMemoryKeyValueStore(...); they are faster but must be fully restored after every restart.
3.2 Changelog topics
Every write to a store is also sent to a compacted changelog topic named <application.id>-<store name>-changelog, with the same number of partitions as the input. Compaction keeps only the latest value per key, so the changelog stays about the size of the store.
3.3 Restoration and standby replicas
When a task starts on an instance that has no up-to-date local copy, Kafka Streams replays the changelog into the store before processing resumes. For large stores this can take minutes. Setting num.standby.replicas=1 keeps a warm copy on another instance, which makes failover almost immediate.
3.4 Record caches
Aggregations write through a record cache (statestore.cache.max.bytes, 10 MB by default). The cache merges several updates to the same key, so fewer records go to the changelog and downstream. Output appears when the cache is flushed, at the latest at each commit (commit.interval.ms, 30 seconds by default, or 100 ms with exactly-once).
3.5 Interactive queries
A running application can read its own stores with KafkaStreams#store(...). Each instance holds only the keys of its partitions; queryMetadataForKey(...) tells you which instance holds a given key, so a REST layer can forward requests to it.
4. Java Example: Views per Product with a Queryable Store
This application counts page views per product, stores the counts in a named store, writes updates to an output topic and then queries the store directly.
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-streams</artifactId>
<version>4.4.0</version>
</dependency>
package com.javabytechie.kafka;
import java.time.Duration;
import java.util.Properties;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.utils.Bytes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StoreQueryParameters;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Grouped;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.Produced;
import org.apache.kafka.streams.state.KeyValueIterator;
import org.apache.kafka.streams.state.KeyValueStore;
import org.apache.kafka.streams.state.QueryableStoreTypes;
import org.apache.kafka.streams.state.ReadOnlyKeyValueStore;
public class ProductViewCounter {
static final String STORE = "views-per-product";
public static void main(String[] args) throws InterruptedException {
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "product-views");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(StreamsConfig.STATESTORE_CACHE_MAX_BYTES_CONFIG, 0); // demo only: forward every update
StreamsBuilder builder = new StreamsBuilder();
builder.stream("page-views", Consumed.with(Serdes.String(), Serdes.String())) // key: user, value: product
.groupBy((user, product) -> product, Grouped.with(Serdes.String(), Serdes.String()))
.count(Materialized.<String, Long, KeyValueStore<Bytes, byte[]>>as(STORE))
.toStream()
.to("product-view-counts", Produced.with(Serdes.String(), Serdes.Long()));
KafkaStreams streams = new KafkaStreams(builder.build(), props);
Runtime.getRuntime().addShutdownHook(new Thread(() -> streams.close(Duration.ofSeconds(10))));
streams.start();
while (streams.state() != KafkaStreams.State.RUNNING) {
Thread.sleep(200);
}
Thread.sleep(5000); // let the sample data be processed
ReadOnlyKeyValueStore<String, Long> store = streams.store(
StoreQueryParameters.fromNameAndType(STORE, QueryableStoreTypes.keyValueStore()));
try (KeyValueIterator<String, Long> all = store.all()) {
while (all.hasNext()) {
KeyValue<String, Long> entry = all.next();
System.out.println(entry.key + " -> " + entry.value + " views");
}
}
System.out.println("Laptop only: " + store.get("laptop"));
}
}
Output (Kafka 4.4; page-views had one partition and contained six records: laptop three times, phone twice, headphones once):
headphones -> 1 views
laptop -> 3 views
phone -> 2 views
Laptop only: 3
groupBy re-keys each view by product, which makes Kafka Streams create an internal repartition topic. count() keeps the totals in the RocksDB store views-per-product, backed by the changelog topic product-views-views-per-product-changelog. The interactive query reads the local store directly, without going through Kafka, and RocksDB returns keys in sorted byte order. The cache is disabled only so that every update reaches the output topic immediately in this demo.
To make the counts exactly-once, add props.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, StreamsConfig.EXACTLY_ONCE_V2). This uses Kafka transactions, so with default broker settings (transaction.state.log.replication.factor=3, transaction.state.log.min.isr=2) the cluster needs at least three brokers.
5. Configuration
| Property | Default (Kafka Streams 4.4) | Purpose |
|---|---|---|
state.dir | ${java.io.tmpdir}/kafka-streams | Local directory for persistent stores; use a durable volume |
num.standby.replicas | 0 | Warm copies of each store on other instances |
statestore.cache.max.bytes | 10485760 | Record cache for all stores of an instance |
commit.interval.ms | 30000 (100 with exactly-once) | How often offsets are committed and caches flushed |
processing.guarantee | at_least_once | exactly_once_v2 for transactional processing |
replication.factor | -1 (broker default) | Replication of changelog and repartition topics |
6. Real-World Scenarios
- Running totals: sales per store per day with windowed aggregations, served to a dashboard through interactive queries.
- Enrichment: joining a stream of orders with a
KTableof customer profiles kept in a local store. - Fraud rules: counting card transactions per card in a five-minute window and flagging bursts.
7. Advantages and Limitations
| Advantages | Limitations |
|---|---|
| Local reads, no external database | Restoration of large stores slows failover |
| Fault tolerance through Kafka itself | Each instance holds only part of the state; queries need routing |
Exactly-once with exactly_once_v2 | Disk usage on every instance, plus changelog storage in Kafka |
8. Common Mistakes
- Leaving
state.dirin/tmpon containers, so every restart restores from scratch. - Changing the topology or store names in a running application, which creates new changelog topics and loses the old state.
- Expecting immediate output from aggregations; the record cache emits on flush. Set
statestore.cache.max.bytes=0in tests to see every update. - Querying before the instance is
RUNNING, which throwsInvalidStateStoreException. - Unbounded keys in a store (for example per-session IDs that never expire); use windows or a TTL-style cleanup with punctuators.
9. Best Practices
- Name stores explicitly with
Materialized.as(...), so changelog topic names stay stable across code changes. - Use persistent volumes and
num.standby.replicas=1for large stores. - Use
exactly_once_v2when output must match state exactly, for example for financial totals. - Monitor restoration with a
StateRestoreListenerand the restore metrics.
10. Conclusion
State stores give Kafka Streams fast local memory for aggregations, joins and windows. RocksDB keeps the data on disk, compacted changelog topics make it fault tolerant, standby replicas speed up failover, and interactive queries expose it to other services. Name your stores, keep their state on durable storage, and choose the processing guarantee deliberately. Compare Kafka Streams with other engines in Kafka vs Flink.
11. References
Kafka Streams State Stores Interview Questions and Answers
Common interview questions on Kafka Streams State Stores, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. Where does Kafka Streams keep the state of an aggregation?
Answer: In a local state store owned by the task that processes the partition, by default a RocksDB database under state.dir. Every update is also written to a compacted changelog topic in Kafka, which is the durable copy.
Intermediate questions
Q. What happens to a state store when an instance crashes?
Answer: Its tasks are reassigned to other instances. A new owner without an up-to-date local copy replays the store's changelog topic before it processes new records. With num.standby.replicas greater than 0, an instance that already maintains a standby copy takes over almost immediately.
Q. Why does a count() result sometimes appear in the output topic only after several seconds?
Answer: Aggregation results pass through a record cache that merges updates per key. They are forwarded when the cache is full or flushed at commit time, which happens every commit.interval.ms (30 seconds by default with at-least-once). Reducing the interval or the cache size makes output appear sooner but increases traffic.
Tricky and scenario questions
Q. How do you serve a key's value through a REST API when the application runs on several instances?
Answer: Each instance holds only the keys of its own partitions. Configure application.server with each instance's host and port, call streams.queryMetadataForKey(store, key, serializer) to find the active host for the key, and either query the local store or forward the HTTP request to that host.
Q. You renamed a store in your topology and all counts started from zero. Why?
Answer: The changelog topic name is built from the application ID and the store name. A new store name means a new, empty changelog and local store, so the old state is not used. Keep store names stable, or migrate state deliberately, for example by reprocessing the input from the beginning with a new application ID.