Kafka Streams stateful processing: aggregations, state stores and windows
Counting, summing and windowing need state that survives restarts and moves with the work. Kafka Streams keeps that state in local stores backed by changelog topics. This page explains how those stores, their cache and their changelogs behave, then runs every aggregation and window type with exact event times, including the late records that windows silently drop.
Contents
Where Kafka Streams keeps state
A stateless operation needs only the record in front of it. A count needs to remember the previous count, and a window needs every count in the time range it covers. Kafka Streams keeps this state in state stores: local key-value or window stores, one set per task, so each store holds only the keys of its task's partition.
Three layers sit behind every store that the DSL creates:
- The store: RocksDB on local disk by default, under
. An in-memory store can be chosen per store or for the whole application.state.dir - The cache: an in-memory record cache in front of the store, sized by
(10 MB by default, shared by the stores of one instance). Repeated updates to one key are merged in the cache, and only the latest value is written on, when the application commits or the cache fills.statestore.cache.max.bytes - The changelog topic: each write that leaves the cache also goes to an internal compacted topic named
. When a task moves to another instance, or the local disk is lost, the store is rebuilt by reading this topic.<application.id>-<store>-changelog
Because state is partitioned like the input, an aggregation must first bring all records of a key to one task. groupByKey()groupBy()
| Operation | Result | Best for |
|---|---|---|
count() | KTable<K, Long> | Number of records per key |
reduce(f) | KTable<K, V> | Sums, minimum, maximum, latest |
aggregate(init, f) | KTable<K, VR> | Averages, lists, several statistics at once |
windowedBy(...) | KTable<Windowed<K>, ...> | Results per time range |
process() | Whatever the processor forwards | Logic the DSL cannot express, such as deduplication |
The programs use TopologyTestDriverspring-kafka-test
count, reduce and aggregate
Three payments for one account and one for another are enough to see how each operation builds its result, record by record. The program computes the count, the total and a combined statistic from the same grouped stream:
import ch.qos.logback.classic.Level;
import java.util.Properties;
import org.apache.kafka.common.serialization.LongDeserializer;
import org.apache.kafka.common.serialization.LongSerializer;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.KGroupedStream;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.Produced;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Aggregations {
public static void main(String[] args) {
quietLogs();
StreamsBuilder builder = new StreamsBuilder();
// payments keyed by account, value in cents
KGroupedStream<String, Long> byAccount = builder
.stream("payments", Consumed.with(Serdes.String(), Serdes.Long()))
.groupByKey();
byAccount.count(Materialized.as("payment-count"))
.toStream().to("counts", Produced.with(Serdes.String(), Serdes.Long()));
byAccount.reduce(Long::sum, Materialized.as("payment-total"))
.toStream().to("totals", Produced.with(Serdes.String(), Serdes.Long()));
// aggregate: the result type may differ from the input; here "count/sum/max"
byAccount.aggregate(
() -> "0/0/0",
(account, cents, agg) -> {
String[] p = agg.split("/");
return (Long.parseLong(p[0]) + 1) + "/"
+ (Long.parseLong(p[1]) + cents) + "/"
+ Math.max(Long.parseLong(p[2]), cents);
},
Materialized.with(Serdes.String(), Serdes.String()))
.mapValues(agg -> {
String[] p = agg.split("/");
long avg = Long.parseLong(p[1]) / Long.parseLong(p[0]);
return "n=" + p[0] + " avg=" + avg + " max=" + p[2];
})
.toStream().to("stats", Produced.with(Serdes.String(), Serdes.String()));
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "payment-stats");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "unused:9092");
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.LongSerde.class);
try (var driver = new TopologyTestDriver(builder.build(), props)) {
var in = driver.createInputTopic("payments",
new StringSerializer(), new LongSerializer());
in.pipeInput("acc-1", 1000L);
in.pipeInput("acc-2", 250L);
in.pipeInput("acc-1", 4000L);
in.pipeInput("acc-1", 1600L);
System.out.println("counts: " + driver.createOutputTopic("counts",
new StringDeserializer(), new LongDeserializer()).readKeyValuesToList());
System.out.println("totals: " + driver.createOutputTopic("totals",
new StringDeserializer(), new LongDeserializer()).readKeyValuesToList());
var stats = driver.createOutputTopic("stats",
new StringDeserializer(), new StringDeserializer());
stats.readKeyValuesToList().forEach(kv -> System.out.println("stats: " + kv));
System.out.println("store payment-total, acc-1 = "
+ driver.getKeyValueStore("payment-total").get("acc-1"));
}
}
static void quietLogs() {
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
}
}
counts: [KeyValue(acc-1, 1), KeyValue(acc-2, 1), KeyValue(acc-1, 2), KeyValue(acc-1, 3)]
totals: [KeyValue(acc-1, 1000), KeyValue(acc-2, 250), KeyValue(acc-1, 5000), KeyValue(acc-1, 6600)]
stats: KeyValue(acc-1, n=1 avg=1000 max=1000)
stats: KeyValue(acc-2, n=1 avg=250 max=250)
stats: KeyValue(acc-1, n=2 avg=2500 max=4000)
stats: KeyValue(acc-1, n=3 avg=2200 max=4000)
store payment-total, acc-1 = 6600
- Every input record produced one update per result:
counted 1, 2, 3, and its total went 1000, 5000, 6600. The output is a changelog of the table, not one final value.acc-1 must return the input type, cents as areduce(Long::sum) . For anything else,Long takes an initializer, hereaggregate , and an adder that returns the new aggregate."0/0/0"- The aggregate is stored as text, "count/sum/max", and turned into a readable form by
. After three payments the average is 2200 cents and the maximum 4000.mapValues - The
store holds 6600 forpayment-total . Naming the store withacc-1 makes it queryable and gives its changelog a stable name.Materialized.as
The aggregate type needs a serde. A String or a Long have built-in ones; for a Java class, give a JSON or Avro serde with Materialized.with(keySerde, valueSerde)KTableaggregate
The cache, the changelog and a restore
Caching changes how many updates leave a store, and the changelog decides how fast the store comes back. The program counts 1,000 page views from 5 users twice, without and with the cache, then deletes the second application's local state and starts it again:
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.ByteArrayDeserializer;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StoreQueryParameters;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.errors.InvalidStateStoreException;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.Produced;
import org.apache.kafka.streams.processor.StateRestoreListener;
import org.apache.kafka.streams.state.QueryableStoreTypes;
import org.apache.kafka.streams.state.ReadOnlyKeyValueStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class CacheAndChangelog {
static String servers;
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
servers = broker.getBrokersAsString();
try (Admin admin = Admin.create(Map.of("bootstrap.servers", servers));
var producer = new KafkaProducer<String, String>(producerProps())) {
admin.createTopics(List.of(new NewTopic("views", 1, (short) 1))).all().get();
for (int i = 0; i < 1000; i++) { // 1,000 page views from 5 users
producer.send(new ProducerRecord<>("views", "user-" + (i % 5), "/page"));
}
}
String stateDir = Files.createTempDirectory("streams").toString();
System.out.println("cache off:");
try (KafkaStreams app = start("counter-nocache", 0, stateDir, null)) {
waitForTotal(app, 1000);
}
report("counter-nocache");
System.out.println("default 10 MB cache:");
try (KafkaStreams app = start("counter-cached", 10 * 1024 * 1024, stateDir, null)) {
waitForTotal(app, 1000);
}
report("counter-cached");
System.out.println("restart with the local state deleted:");
try (KafkaStreams app = start("counter-cached", 10 * 1024 * 1024, stateDir, true)) {
System.out.println(" store after restore: " + waitForTotal(app, 1000));
}
broker.destroy();
}
static KafkaStreams start(String appId, long cacheBytes, String stateDir, Boolean wipe) {
StreamsBuilder builder = new StreamsBuilder();
builder.stream("views", Consumed.with(Serdes.String(), Serdes.String()))
.groupByKey()
.count(Materialized.as("counts"))
.toStream().to(appId + "-out", Produced.with(Serdes.String(), Serdes.Long()));
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, appId);
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
props.put(StreamsConfig.STATE_DIR_CONFIG, stateDir);
props.put(StreamsConfig.STATESTORE_CACHE_MAX_BYTES_CONFIG, cacheBytes);
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
KafkaStreams app = new KafkaStreams(builder.build(), props);
if (wipe != null) {
app.cleanUp(); // deletes this application's local state directory
app.setGlobalStateRestoreListener(new StateRestoreListener() {
public void onRestoreStart(TopicPartition tp, String store, long from, long to) {
System.out.println(" restoring " + store + " from " + tp
+ ", offsets " + from + " to " + to);
}
public void onBatchRestored(TopicPartition tp, String store, long end, long n) {
}
public void onRestoreEnd(TopicPartition tp, String store, long total) {
System.out.println(" restored " + total + " records into " + store);
}
});
}
app.start();
return app;
}
// queries the store until the counts add up to the expected total
static Map<String, Long> waitForTotal(KafkaStreams app, long total) throws Exception {
while (true) {
try {
ReadOnlyKeyValueStore<String, Long> store = app.store(StoreQueryParameters
.fromNameAndType("counts", QueryableStoreTypes.keyValueStore()));
Map<String, Long> counts = new TreeMap<>();
try (var all = store.all()) {
all.forEachRemaining(kv -> counts.put(kv.key, kv.value));
}
if (counts.values().stream().mapToLong(Long::longValue).sum() == total) {
return counts;
}
} catch (InvalidStateStoreException notReadyYet) {
// the store is not queryable until the application is RUNNING
}
Thread.sleep(100);
}
}
static void report(String appId) {
System.out.println(" records in " + appId + "-out: " + countRecords(appId + "-out"));
System.out.println(" records in " + appId + "-counts-changelog: "
+ countRecords(appId + "-counts-changelog"));
}
static long countRecords(String topic) {
Properties c = new Properties();
c.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
c.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class.getName());
c.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
ByteArrayDeserializer.class.getName());
long n = 0;
try (var consumer = new KafkaConsumer<byte[], byte[]>(c)) {
TopicPartition tp = new TopicPartition(topic, 0);
consumer.assign(List.of(tp));
consumer.seekToBeginning(List.of(tp));
long end = consumer.endOffsets(List.of(tp)).get(tp);
while (consumer.position(tp) < end) {
n += consumer.poll(Duration.ofMillis(200)).count();
}
}
return n;
}
static Properties producerProps() {
Properties p = new Properties();
p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
p.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
p.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
return p;
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO and prints its storage setup: both are silenced.
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
// one broker cannot hold the default 3 copies of the transaction log
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
Map.of("transaction.state.log.replication.factor", "1",
"transaction.state.log.min.isr", "1"));
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
cache off:
records in counter-nocache-out: 1000
records in counter-nocache-counts-changelog: 1000
default 10 MB cache:
records in counter-cached-out: 5
records in counter-cached-counts-changelog: 5
restart with the local state deleted:
restoring counts from counter-cached-counts-changelog-0, offsets 0 to 5
restored 5 records into counts
store after restore: {user-0=200, user-1=200, user-2=200, user-3=200, user-4=200}
- With the cache off, every one of the 1,000 updates was sent downstream and written to the changelog: 1,000 records each.
- With the default cache, each user's 200 updates were merged in memory, and only the final count was written when the application committed on close: 5 records downstream and 5 in the changelog. The exact number depends on when commits happen; with a 30-second commit interval and data processed in under a second, there was only one.
deleted the local RocksDB files. At the restart, Kafka Streams restored thecleanUp() store from offsets 0 to 5 of its changelog, 5 records, and the counts came back as 200 per user without reprocessing the 1,000 input records.counts
Caching is a trade-off between latency and volume. With the cache, downstream consumers see fewer, later updates; set commit.interval.msnum.standby.replicas
Four kinds of windows
A window groups records by their event time, the timestamp stored in each record. One user clicks at 5, 20, 50, 70 and 130 seconds, and the program counts those clicks with each window type at once:
import ch.qos.logback.classic.Level;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.KGroupedStream;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.SessionWindows;
import org.apache.kafka.streams.kstream.SlidingWindows;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.Windowed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WindowTypes {
// final count per window type and window; a later update replaces an earlier one
static final Map<String, Map<String, Long>> RESULTS = new TreeMap<>();
public static void main(String[] args) {
quietLogs();
StreamsBuilder builder = new StreamsBuilder();
KGroupedStream<String, String> clicks = builder
.stream("clicks", Consumed.with(Serdes.String(), Serdes.String()))
.groupByKey();
Duration minute = Duration.ofSeconds(60);
collect("1 tumbling 60s", clicks.windowedBy(TimeWindows.ofSizeWithNoGrace(minute))
.count());
collect("2 hopping 60s, advance 30s", clicks.windowedBy(
TimeWindows.ofSizeWithNoGrace(minute).advanceBy(Duration.ofSeconds(30))).count());
collect("3 sliding 30s", clicks.windowedBy(
SlidingWindows.ofTimeDifferenceWithNoGrace(Duration.ofSeconds(30))).count());
collect("4 session, 30s gap", clicks.windowedBy(
SessionWindows.ofInactivityGapWithNoGrace(Duration.ofSeconds(30))).count());
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "click-windows");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "unused:9092");
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
try (var driver = new TopologyTestDriver(builder.build(), props)) {
var in = driver.createInputTopic("clicks",
new StringSerializer(), new StringSerializer());
for (int second : new int[] {5, 20, 50, 70, 130}) { // event times of one user's clicks
in.pipeInput("u1", "click", Instant.ofEpochSecond(second));
}
}
System.out.println("clicks at 5s, 20s, 50s, 70s, 130s");
RESULTS.forEach((type, windows) -> {
System.out.println(type.substring(2) + ":");
windows.forEach((w, n) ->
System.out.println(" " + w.substring(w.indexOf('|') + 1) + " count " + n));
});
}
static void collect(String type, KTable<Windowed<String>, Long> counts) {
counts.toStream().foreach((w, n) -> {
// time windows exclude their end; sliding and session windows include it
String close = type.startsWith("1") || type.startsWith("2") ? ")" : "]";
// the sort key orders windows by start time; the text after '|' is printed
String window = String.format("%010d%010d|", w.window().start(), w.window().end())
+ "[" + seconds(w.window().start()) + ", " + seconds(w.window().end()) + close;
Map<String, Long> windows = RESULTS.computeIfAbsent(type, k -> new TreeMap<>());
if (n == null) {
windows.remove(window); // a session merged into a bigger one is deleted
} else {
windows.put(window, n);
}
});
}
static String seconds(long millis) {
String s = millis % 1000 == 0 ? (millis / 1000) + "s" : (millis / 1000.0) + "s";
return " ".repeat(Math.max(0, 7 - s.length())) + s;
}
static void quietLogs() {
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
}
}
clicks at 5s, 20s, 50s, 70s, 130s
tumbling 60s:
[ 0s, 60s) count 3
[ 60s, 120s) count 1
[ 120s, 180s) count 1
hopping 60s, advance 30s:
[ 0s, 60s) count 3
[ 30s, 90s) count 2
[ 60s, 120s) count 1
[ 90s, 150s) count 1
[ 120s, 180s) count 1
sliding 30s:
[ 0s, 30s] count 2
[ 5.001s, 35.001s] count 1
[ 20s, 50s] count 2
[20.001s, 50.001s] count 1
[ 40s, 70s] count 2
[50.001s, 80.001s] count 1
[ 100s, 130s] count 1
session, 30s gap:
[ 5s, 70s] count 4
[ 130s, 130s] count 1
- Tumbling: fixed, non-overlapping 60-second windows aligned to the epoch. The clicks at 5, 20 and 50 seconds fall in [0s, 60s), so each click belongs to exactly one window.
- Hopping: 60-second windows that start every 30 seconds, so each click falls in two windows. The click at 50 seconds is counted in [0s, 60s) and in [30s, 90s).
- Sliding: one window for every distinct set of clicks that fit within 30 seconds. Kafka Streams creates a window ending at each click, and windows starting 1 ms after a click, such as [5.001s, 35.001s]. Both ends are included. Windows for the earliest clicks are clamped to start at 0.
- Session: a window grows while clicks keep arriving less than 30 seconds apart. 5, 20, 50 and 70 seconds form one session from 5 to 70 seconds; the click at 130 seconds starts a new one that is still a single point.
| Window | Created with | Overlap | Best for |
|---|---|---|---|
| Tumbling | TimeWindows.ofSizeWithNoGrace(size) | None | Per-minute or per-hour reports |
| Hopping | TimeWindows...advanceBy(step) | Each record in size / step windows | Moving averages updated at a fixed step |
| Sliding | SlidingWindows.ofTimeDifferenceWithNoGrace(d) | Only where records exist | "More than 3 failed logins within 30 seconds" |
| Session | SessionWindows.ofInactivityGapWithNoGrace(gap) | None; sessions merge | User sessions, bursts of activity |
Sessions merge: when a late click fills the gap between two sessions, Kafka Streams deletes both and emits one merged session. The program handles that by removing a window when its count arrives as null, which is how the deletion of a session appears downstream.
Late records, grace periods and final results
Kafka Streams tracks stream time: the largest record timestamp it has seen in a task. A window closes once stream time passes its end plus the grace period, and any record for it that arrives later is dropped. The program sends a click at 55 seconds after one at 70 seconds. It runs once with no grace and once with 20 seconds, and prints both the eager updates and the results of suppress
import ch.qos.logback.classic.Level;
import java.time.Duration;
import java.time.Instant;
import java.util.Properties;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.Suppressed;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.Windowed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LateRecords {
public static void main(String[] args) {
quietLogs();
run(Duration.ZERO);
run(Duration.ofSeconds(20));
}
static void run(Duration grace) {
System.out.println("grace " + grace.toSeconds() + "s:");
StreamsBuilder builder = new StreamsBuilder();
KTable<Windowed<String>, Long> counts = builder
.stream("clicks", Consumed.with(Serdes.String(), Serdes.String()))
.groupByKey()
.windowedBy(TimeWindows.ofSizeAndGrace(Duration.ofSeconds(60), grace))
.count();
counts.toStream().foreach((w, n) -> System.out.println(" update " + w(w) + " = " + n));
counts.suppress(Suppressed.untilWindowCloses(Suppressed.BufferConfig.unbounded()))
.toStream()
.foreach((w, n) -> System.out.println(" FINAL " + w(w) + " = " + n));
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "late-clicks");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "unused:9092");
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
try (var driver = new TopologyTestDriver(builder.build(), props)) {
var in = driver.createInputTopic("clicks",
new StringSerializer(), new StringSerializer());
for (int second : new int[] {10, 30, 70, 55, 100, 200}) {
System.out.println(" click at " + second + "s");
in.pipeInput("u1", "click", Instant.ofEpochSecond(second));
}
driver.metrics().forEach((name, metric) -> {
if (name.name().equals("dropped-records-total")) {
System.out.println(" dropped-records-total = " + metric.metricValue());
}
});
}
}
static String w(Windowed<String> w) {
return "[" + w.window().start() / 1000 + "s, " + w.window().end() / 1000 + "s)";
}
static void quietLogs() {
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
}
}
grace 0s:
click at 10s
update [0s, 60s) = 1
click at 30s
update [0s, 60s) = 2
click at 70s
update [60s, 120s) = 1
FINAL [0s, 60s) = 2
click at 55s
click at 100s
update [60s, 120s) = 2
click at 200s
update [180s, 240s) = 1
FINAL [60s, 120s) = 2
dropped-records-total = 1.0
grace 20s:
click at 10s
update [0s, 60s) = 1
click at 30s
update [0s, 60s) = 2
click at 70s
update [60s, 120s) = 1
click at 55s
update [0s, 60s) = 3
click at 100s
update [60s, 120s) = 2
FINAL [0s, 60s) = 3
click at 200s
update [180s, 240s) = 1
FINAL [60s, 120s) = 2
dropped-records-total = 0.0
- With no grace, the click at 70 seconds moved stream time to 70, which closed [0s, 60s). The final result for that window, 2, was emitted at that moment by
.suppress - The late click at 55 seconds produced no update at all, and
counted it. Nothing else reports the loss.dropped-records-total - With a 20-second grace, [0s, 60s) stayed open until stream time 80. The late click was counted, the window reached 3, and its final result came only when the click at 100 seconds closed it.
- The click at 200 seconds closed [60s, 120s), whose final count of 2 then appeared. Stream time moves only with new records, so a window on a quiet partition is not closed until the next record arrives.
Choose the grace period from how late your data really arrives, for example from mobile clients that go offline. A longer grace accepts more late records but delays final results. suppress(untilWindowCloses(...))emitStrategy(EmitStrategy.onWindowClose())TimeWindows.of(size)
Custom state with the Processor API
Some stateful logic does not fit an aggregation. Deduplication is a common case: payment events may arrive twice, and only the first copy per id should pass. The program adds a store to the topology and uses it from a processor, with a punctuator that forgets ids older than 10 minutes:
import ch.qos.logback.classic.Level;
import java.time.Duration;
import java.time.Instant;
import java.util.Properties;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Produced;
import org.apache.kafka.streams.processor.PunctuationType;
import org.apache.kafka.streams.processor.api.Processor;
import org.apache.kafka.streams.processor.api.ProcessorContext;
import org.apache.kafka.streams.processor.api.Record;
import org.apache.kafka.streams.state.KeyValueStore;
import org.apache.kafka.streams.state.Stores;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Deduplicate {
// forwards the first record for each event id, and forgets ids after 10 minutes
static class DedupProcessor implements Processor<String, String, String, String> {
private ProcessorContext<String, String> context;
private KeyValueStore<String, Long> seen;
@Override
public void init(ProcessorContext<String, String> context) {
this.context = context;
this.seen = context.getStateStore("seen-ids");
// runs as stream time passes, driven by record timestamps, not by the clock
context.schedule(Duration.ofMinutes(1), PunctuationType.STREAM_TIME, now -> {
try (var all = seen.all()) {
while (all.hasNext()) {
KeyValue<String, Long> id = all.next();
if (id.value < now - Duration.ofMinutes(10).toMillis()) {
seen.delete(id.key);
System.out.println(" purged " + id.key);
}
}
}
});
}
@Override
public void process(Record<String, String> record) {
if (seen.get(record.key()) == null) {
seen.put(record.key(), record.timestamp());
context.forward(record);
} else {
System.out.println(" dropped duplicate " + record.key());
}
}
}
public static void main(String[] args) {
quietLogs();
StreamsBuilder builder = new StreamsBuilder();
builder.addStateStore(Stores.keyValueStoreBuilder(
Stores.persistentKeyValueStore("seen-ids"), Serdes.String(), Serdes.Long()));
builder.stream("payments", Consumed.with(Serdes.String(), Serdes.String()))
.process(DedupProcessor::new, "seen-ids")
.to("payments-unique", Produced.with(Serdes.String(), Serdes.String()));
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "dedup");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "unused:9092");
try (var driver = new TopologyTestDriver(builder.build(), props)) {
var in = driver.createInputTopic("payments",
new StringSerializer(), new StringSerializer());
Instant t0 = Instant.parse("2026-01-01T10:00:00Z");
String[][] events = {{"0", "pay-1"}, {"1", "pay-2"}, {"2", "pay-1"},
{"12", "pay-3"}, {"13", "pay-1"}};
for (String[] e : events) {
System.out.println(" minute " + e[0] + ": " + e[1]);
in.pipeInput(e[1], "payment",
t0.plus(Duration.ofMinutes(Long.parseLong(e[0]))));
}
System.out.println("payments-unique: " + driver.createOutputTopic("payments-unique",
new StringDeserializer(), new StringDeserializer()).readKeyValuesToList()
.stream().map(kv -> kv.key).toList());
}
}
static void quietLogs() {
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
}
}
minute 0: pay-1
minute 1: pay-2
minute 2: pay-1
dropped duplicate pay-1
minute 12: pay-3
purged pay-1
purged pay-2
minute 13: pay-1
payments-unique: [pay-1, pay-2, pay-3, pay-1]
- The second
, at minute 2, found its id in the store and was dropped.pay-1 - The punctuator is scheduled on
, so it runs as record timestamps advance. At minute 12 it purgedSTREAM_TIME andpay-1 , both older than 10 minutes.pay-2 - The third
, at minute 13, therefore passed again. The retention period is a trade-off: duplicates that arrive later than it are not caught, and a longer one makes the store bigger.pay-1
WALL_CLOCK_TIMEStores.persistentKeyValueStore
Traps in stateful applications
- Renaming or reordering operations: unnamed stores and repartition topics get generated names with numbers. Changing the topology changes them, and the restarted application starts with empty state. Name every store and grouping.
- Null keys and values:
andgroupByKey drop records with a null key, and aggregations skip null values. Neither raises an error.groupBy - Window store retention: a windowed store keeps windows for at least window size plus grace; a store with
shorter than that is rejected. Windowed changelogs keep data for an extraMaterialized.withRetention , one day by default.windowstore.changelog.additional.retention.ms - Large aggregates: an aggregate that grows without bound, such as a list of every order, makes each update rewrite the whole value to RocksDB and the changelog.
- Wall-clock expectations: windows close on stream time, so a test or a quiet topic that stops sending records never sees the last window close.
Choosing an aggregation and a window
| Situation | Use |
|---|---|
| Running totals per key | groupByKey().reduce()count() |
| Several statistics, or a result of another type | aggregate() |
| Fixed reporting periods | Tumbling windows with a grace period that matches how late data arrives |
| A metric that updates every step over a longer range | Hopping windows |
| A threshold within any span of time | Sliding windows |
| Activity separated by idle gaps | Session windows |
| Downstream needs one final value per window | suppress(untilWindowCloses)EmitStrategy.onWindowClose() |
| Deduplication, timeouts, custom state | Processor API with a store and a punctuator |
| Fewer updates downstream | Keep the cache on and tune commit.interval.ms |
To read these stores from outside the topology, for example from a REST endpoint, see