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.

Share

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 state.dir. An in-memory store can be chosen per store or for the whole application.
  • The cache: an in-memory record cache in front of the store, sized by statestore.cache.max.bytes (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.
  • The changelog topic: each write that leaves the cache also goes to an internal compacted topic named <application.id>-<store>-changelog. When a task moves to another instance, or the local disk is lost, the store is rebuilt by reading this topic.

Because state is partitioned like the input, an aggregation must first bring all records of a key to one task. groupByKey() keeps the current key; groupBy() picks a new one and adds a repartition topic, as the Kafka Streams page shows.

Stateful DSL operations
OperationResultBest for
count()KTable<K, Long>Number of records per key
reduce(f)KTable<K, V>, same type as the inputSums, minimum, maximum, latest
aggregate(init, f)KTable<K, VR>, any typeAverages, lists, several statistics at once
windowedBy(...) then one of the aboveKTable<Windowed<K>, ...>Results per time range
process() with a storeWhatever the processor forwardsLogic the DSL cannot express, such as deduplication

The programs use TopologyTestDriver, which runs a topology without a broker and lets each record carry an exact timestamp, so the windows below are fully deterministic. The program about caching and restoring starts a real single-node Kafka 4.2 broker inside the JVM, from spring-kafka-test, because those effects need real topics; a production cluster has 3 or more brokers.

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:

Java
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);
    }
}
Output
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: acc-1 counted 1, 2, 3, and its total went 1000, 5000, 6600. The output is a changelog of the table, not one final value.
  • reduce(Long::sum) must return the input type, cents as a Long. For anything else, aggregate takes an initializer, here "0/0/0", and an adder that returns the new aggregate.
  • The aggregate is stored as text, "count/sum/max", and turned into a readable form by mapValues. After three payments the average is 2200 cents and the maximum 4000.
  • The payment-total store holds 6600 for acc-1. Naming the store with Materialized.as makes it queryable and gives its changelog a stable name.

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). On a KTable, aggregate also needs a subtractor, because a changed row must be removed from its old group, which is what made the city counts go down on the Kafka Streams page.

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:

Java
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);
        }
    }
}
Output
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.
  • cleanUp() deleted the local RocksDB files. At the restart, Kafka Streams restored the counts 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.

Caching is a trade-off between latency and volume. With the cache, downstream consumers see fewer, later updates; set commit.interval.ms lower to see them sooner. Without it, every intermediate value is written twice, to the output and to the changelog. Restoring from a changelog is fast for 5 records, but can take many minutes for stores with millions of keys, which is what num.standby.replicas is for: a standby task keeps a second copy of the store up to date on another instance.

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:

Java
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);
    }
}
Output
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 types
WindowCreated withOverlapBest for
TumblingTimeWindows.ofSizeWithNoGrace(size)NonePer-minute or per-hour reports
HoppingTimeWindows...advanceBy(step)Each record in size / step windowsMoving averages updated at a fixed step
SlidingSlidingWindows.ofTimeDifferenceWithNoGrace(d)Only where records exist"More than 3 failed logins within 30 seconds"
SessionSessionWindows.ofInactivityGapWithNoGrace(gap)None; sessions mergeUser 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:

Java
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);
    }
}
Output
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 dropped-records-total counted it. Nothing else reports the loss.
  • 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(...)) buffers updates in memory and in a changelog, so give the buffer a bound in production, or use emitStrategy(EmitStrategy.onWindowClose()) on the windowed aggregation, which keeps no separate buffer. Kafka 4.0 removed TimeWindows.of(size), whose default grace was 24 hours; the replacement methods make the grace period explicit.

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:

Java
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);
    }
}
Output
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 pay-1, at minute 2, found its id in the store and was dropped.
  • The punctuator is scheduled on STREAM_TIME, so it runs as record timestamps advance. At minute 12 it purged pay-1 and pay-2, both older than 10 minutes.
  • The third pay-1, 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.

WALL_CLOCK_TIME punctuators run by the system clock instead, even when no records arrive, which suits timeouts. The store created with Stores.persistentKeyValueStore gets a changelog like any DSL store, so the seen ids survive restarts and task moves.

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: groupByKey and groupBy drop records with a null key, and aggregations skip null values. Neither raises an error.
  • Window store retention: a windowed store keeps windows for at least window size plus grace; a store with Materialized.withRetention shorter than that is rejected. Windowed changelogs keep data for an extra windowstore.changelog.additional.retention.ms, one day by default.
  • 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

Situations and what to use
SituationUse
Running totals per keygroupByKey().reduce() or count()
Several statistics, or a result of another typeaggregate() with a serde for the result
Fixed reporting periodsTumbling windows with a grace period that matches how late data arrives
A metric that updates every step over a longer rangeHopping windows
A threshold within any span of timeSliding windows
Activity separated by idle gapsSession windows
Downstream needs one final value per windowsuppress(untilWindowCloses) or EmitStrategy.onWindowClose()
Deduplication, timeouts, custom stateProcessor API with a store and a punctuator
Fewer updates downstreamKeep the cache on and tune commit.interval.ms

To read these stores from outside the topology, for example from a REST endpoint, see interactive queries. Combining a stream with a table or with another stream is covered on Kafka Streams joins.