00:00

Kafka Streams State Stores and Stateful Processing

Last updated:

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.

Definition: A state store is a task-local key-value (or window/session) store that Kafka Streams keeps on the application's disk or in memory, and continuously backs up to a compacted changelog topic in Kafka.
Store typeTypical useCreated by
Key-valueRunning totals, latest value per keycount(), aggregate(), reduce(), toTable()
WindowCounts per key per time windowwindowedBy(...) aggregations
SessionActivity sessions with inactivity gapswindowedBy(SessionWindows...)
Versioned key-valuePoint-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

State store with changelog topicThe input topic page-views has two partitions. Instance A runs task 0 with a local RocksDB store for partition 0, and instance B runs task 1 with its store for partition 1. Every store update is also written to the compacted changelog topic. If instance B fails, task 1 moves to instance A, which restores the store from the changelog before processing continues. An optional standby replica keeps a warm copy. page-viewspartition 0partition 1 instance A: task 0RocksDB store (keys of P0) instance B: task 1RocksDB store (keys of P1) changelog topicapp-store-changelogcompacted, 2 partitions every update B fails: task 1 moves to AA restores the store, then resumes restore
State is local for speed and replicated through a changelog topic for fault tolerance.

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.

pom.xml
<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka-streams</artifactId>
    <version>4.4.0</version>
</dependency>
ProductViewCounter.java
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):

Output
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

PropertyDefault (Kafka Streams 4.4)Purpose
state.dir${java.io.tmpdir}/kafka-streamsLocal directory for persistent stores; use a durable volume
num.standby.replicas0Warm copies of each store on other instances
statestore.cache.max.bytes10485760Record cache for all stores of an instance
commit.interval.ms30000 (100 with exactly-once)How often offsets are committed and caches flushed
processing.guaranteeat_least_onceexactly_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 KTable of 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

AdvantagesLimitations
Local reads, no external databaseRestoration of large stores slows failover
Fault tolerance through Kafka itselfEach instance holds only part of the state; queries need routing
Exactly-once with exactly_once_v2Disk usage on every instance, plus changelog storage in Kafka

8. Common Mistakes

  • Leaving state.dir in /tmp on 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=0 in tests to see every update.
  • Querying before the instance is RUNNING, which throws InvalidStateStoreException.
  • 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=1 for large stores.
  • Use exactly_once_v2 when output must match state exactly, for example for financial totals.
  • Monitor restoration with a StateRestoreListener and 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