Lab: Count per User per Hour with Kafka Streams

The main guide named "Processor 2 (count per user/hour)" as one box in a data flow graph and explained the machinery behind it in the abstract — local index, changelog, commit cycle. This page is the other half: a real Kafka broker, a real click stream, and a real Kafka Streams topology that turns raw clicks into an hourly count per user, with every internal you read about there inspected on disk as it happens.

What "Count Per User Per Hour" Actually Requires

Three ideas compose to make this work, and the rest of the lab builds each one in order:

GroupinggroupByKey() — repartitions so all of one user's clicks land on one task
WindowingwindowedBy(TimeWindows...) — buckets event time into hourly slots
Aggregationcount() — a stateful op backed by a local RocksDB store + changelog
Output keyWindowed<String> — user_id plus the window's start/end timestamps
Data flow of the lab. The clicks topic, keyed by user_id with three partitions, feeds a stream task; there is one task per input partition, with ids 0_0, 0_1 and 0_2. Inside the task, groupByKey keeps the existing user_id key, windowedBy buckets event time into one-hour tumbling windows with a five-minute grace period, and count keeps a running count per user and window. Every update is emitted to the hourly-counts topic with a key like user_1@2026-08-16T14:00:00Z and the running count as the value, so counts climb. The same update is written to two copies of the state: a local RocksDB store at /tmp/kafka-streams/hourly-click-counts/0_n/rocksdb/hourly-counts-store, which is fast and disposable, and the compacted changelog topic hourly-click-counts-hourly-counts-store-changelog, which is the durable backup a restarted task rebuilds from. Both names come from the one string in Materialized.as("hourly-counts-store").
One task, one output, and two copies of the same state RocksDB answers reads; the compacted changelog is what a killed task rebuilds from — the two names Peek under the hood has you list, and the recovery its kill -9 exercise proves.

Every box and arrow here is something Commit Semantics in the main guide already told you about in the abstract, under "How the Local Index + Changelog Works." This lab makes it concrete: you'll watch the changelog topic fill up, kill the process mid-run, and watch it rebuild exact pre-crash counts from nothing but that changelog.

Stand Up the Stack

1.1 — Start a single-broker Kafka with Docker Compose

docker-compose.yml

services:
  kafka:
    image: apache/kafka:3.7.0
    container_name: kafka
    ports:
      - "9092:9092"
    environment:
      KAFKA_NODE_ID: 1
      KAFKA_PROCESS_ROLES: broker,controller
      KAFKA_LISTENERS: PLAINTEXT://:9092,CONTROLLER://:9093
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092
      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@kafka:9093
      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1

bash

$ docker compose up -d
# wait ~10s, then confirm it's listening
$ docker exec kafka /opt/kafka/bin/kafka-topics.sh --bootstrap-server localhost:9092 --list

1.2 — Set up the Java project

One Maven module. Kafka Streams ships everything you need — no separate cluster-side jars, unlike a Spark or Flink job:

pom.xml — the one dependency that matters

<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka-streams</artifactId>
    <version>3.7.0</version>
</dependency>

Create the Clicks Topic

$ docker exec kafka /opt/kafka/bin/kafka-topics.sh --create \
    --bootstrap-server localhost:9092 \
    --topic clicks \
    --partitions 3 \
    --replication-factor 1

Real deployments key by user_id at the producer (producer.send(new ProducerRecord<>("clicks", userId, click))) so this co-partitioning holds automatically — Kafka's default partitioner hashes the key, so the same user_id always lands on the same partition without any coordination between producer and Streams app.

Produce Synthetic Click Events

Click.java — the record

public record Click(String userId, String page, long ts) {}

ClickProducer.java

public class ClickProducer {
    public static void main(String[] args) throws Exception {
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);

        try (KafkaProducer<String, String> producer = new KafkaProducer<>(props)) {
            String[] users = {"user_1", "user_2", "user_3", "user_4", "user_5"};
            String[] pages = {"home", "jobs", "profile", "search"};
            var rnd = new java.util.Random();

            while (true) {
                String userId = users[rnd.nextInt(users.length)];
                String page = pages[rnd.nextInt(pages.length)];
                long ts = System.currentTimeMillis();
                String json = "{\"userId\":\"%s\",\"page\":\"%s\",\"ts\":%d}"
                        .formatted(userId, page, ts);

                producer.send(new ProducerRecord<>("clicks", userId, json));
                System.out.println("sent " + json);
                Thread.sleep(200);
            }
        }
    }
}

Run it in its own terminal and leave it running for the rest of the lab — every later section reads whatever this is currently producing:

$ mvn compile exec:java -Dexec.mainClass=ClickProducer
sent {"userId":"user_3","page":"jobs","ts":1755341042113}
sent {"userId":"user_1","page":"home","ts":1755341042314}
sent {"userId":"user_5","page":"search","ts":1755341042519}
...

Build the Windowed Topology

WindowedCountApp.java

public class WindowedCountApp {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "hourly-click-counts");
        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        // commit.interval.ms defaults to 30000 — see Stream processing and state's "Commit Cycle Consistency"
        props.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 5000); // shortened so this lab moves fast

        StreamsBuilder builder = new StreamsBuilder();

        KStream<String, String> clicks = builder.stream("clicks");

        KTable<Windowed<String>, Long> hourlyCounts = clicks
            .groupByKey()                                              // key is already user_id
            .windowedBy(TimeWindows.ofSizeAndGrace(
                Duration.ofHours(1), Duration.ofMinutes(5)))           // tumbling, 5-min grace
            .count(Materialized.as("hourly-counts-store"));            // names the RocksDB store + changelog

        hourlyCounts
            .toStream()
            .map((windowedUserId, count) -> KeyValue.pair(
                windowedUserId.key() + "@" + windowedUserId.window().startTime(),
                count.toString()))
            .to("hourly-counts", Produced.with(Serdes.String(), Serdes.String()));

        KafkaStreams streams = new KafkaStreams(builder.build(), props);
        streams.start();
        Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
    }
}

Run It, Read the Output

$ mvn compile exec:java -Dexec.mainClass=WindowedCountApp

bash — second terminal, watch counts climb live

$ docker exec kafka /opt/kafka/bin/kafka-console-consumer.sh \
    --bootstrap-server localhost:9092 \
    --topic hourly-counts \
    --property print.key=true \
    --property key.separator=" => "

user_3@2026-08-16T14:00:00Z => 1
user_1@2026-08-16T14:00:00Z => 1
user_3@2026-08-16T14:00:00Z => 2
user_5@2026-08-16T14:00:00Z => 1
user_3@2026-08-16T14:00:00Z => 3
...

Each repeated key is Kafka Streams re-emitting the running total for that user's current hour every time a new click for them arrives — the exact "speculative running count" behavior the main guide's data flow graph implies but doesn't spell out. Late data shows how to collapse this into one final value per window instead.

Peek Under the Hood — the Changelog and RocksDB

bash — the changelog topic Kafka Streams created for you

$ docker exec kafka /opt/kafka/bin/kafka-topics.sh --bootstrap-server localhost:9092 --list
clicks
hourly-counts
hourly-click-counts-hourly-counts-store-changelog   ← app-id + store name + "-changelog"

$ docker exec kafka /opt/kafka/bin/kafka-topics.sh --describe \
    --bootstrap-server localhost:9092 \
    --topic hourly-click-counts-hourly-counts-store-changelog
Topic: hourly-click-counts-hourly-counts-store-changelog   PartitionCount: 3
    Configs: cleanup.policy=compact   ← compacted, not time-retained: see Stream processing and state

cleanup.policy=compact is not a default someone forgot to change — it's load-bearing. The Stream processing and state part explained that changelog entries are full current state per key, not deltas, which is exactly what makes log compaction safe: Kafka can drop every earlier value for user_3@14:00 and keep only the newest, because the newest is the complete answer.

bash — RocksDB's actual files, if you're running the app outside Docker

$ find /tmp/kafka-streams/hourly-click-counts -maxdepth 3 -type d
/tmp/kafka-streams/hourly-click-counts/0_0/rocksdb/hourly-counts-store
/tmp/kafka-streams/hourly-click-counts/0_1/rocksdb/hourly-counts-store
/tmp/kafka-streams/hourly-click-counts/0_2/rocksdb/hourly-counts-store

Three directories, one per partition your single JVM happens to own — 0_0, 0_1, 0_2 are <subtopology>_<partition> task IDs. Scale to three app instances and each one claims exactly one of these directories; nothing about the topology code changes, only how many of these folders exist on how many machines.

Query the Store Live — No Output Topic Needed

Add to WindowedCountApp.java, after streams.start()

streams.start();

ReadOnlyWindowStore<String, Long> store = streams.store(
    StoreQueryParameters.fromNameAndType(
        "hourly-counts-store", QueryableStoreTypes.windowStore()));

// e.g. exposed behind a tiny HTTP handler:
Instant now = Instant.now();
Instant hourStart = now.truncatedTo(ChronoUnit.HOURS);
Long count = store.fetch("user_1", hourStart);
System.out.println("user_1 this hour: " + (count == null ? 0 : count));

This reads directly out of the local RocksDB instance in-process — no network hop, no round trip through hourly-counts. It's the same "no network calls for state reads, ever" property Stream processing and state attributed to co-partitioned local state, just consumed by your own code instead of another Streams processor.

Late Data and Getting One Final Count Per Window

8.1 — Why the topology already has a grace period

TimeWindows.ofSizeAndGrace(Duration.ofHours(1), Duration.ofMinutes(5)) from the Build the windowed topology part means a click stamped 2:58pm that arrives at 3:03pm (network delay, retry, whatever) still lands in the 2–3pm window instead of silently falling into 3–4pm — as long as it shows up within 5 minutes of the window's official end. Past the grace period, a late record is dropped, not misfiled; Kafka Streams exposes a dropped-records metric for exactly this.

8.2 — Collapsing the "climbing counter" from Run it into one emission

If a downstream fraud model wants "the final count for 2–3pm," not five intermediate counts building up to it, wrap the windowed KTable in suppress():

KTable<Windowed<String>, Long> hourlyCounts = clicks
    .groupByKey()
    .windowedBy(TimeWindows.ofSizeAndGrace(Duration.ofHours(1), Duration.ofMinutes(5)))
    .count(Materialized.as("hourly-counts-store"))
    .suppress(Suppressed.untilWindowCloses(Suppressed.BufferConfig.unbounded()));

With suppress() in place, hourly-counts only receives one record per (user, window) — emitted once the window's end time plus its grace period has passed, holding everything else back in an in-memory buffer until then. This is a real tradeoff, not a strict upgrade: the interactive-query store from the Query the store live part still updates continuously either way, but the downstream topic now trades latency (nothing until the window truly closes) for a guarantee (exactly one final answer per window) — pick whichever side of that tradeoff a given consumer actually needs.

Beyond Localhost

Scale outRun the same jar N times, same APPLICATION_ID_CONFIG — Kafka Streams rebalances the 3 partitions across instances automatically
Exactly-onceprocessing.guarantee=exactly_once_v2 — wraps changelog flush, offset commit, and output produce in one transaction (main guide Commit Semantics)
Standby replicasnum.standby.replicas=1 — a warm RocksDB copy on another instance, so failover skips the full changelog replay from the Peek under the hood part
Broker durabilityReal clusters run the changelog topic with replication.factor=3, not the lab's 1 — see main guide Replication Factor and min.insync.replicas

Everything from producer to console consumer in this lab pointed at localhost:9092 only because that's what the Docker Compose broker advertised. Point BOOTSTRAP_SERVERS_CONFIG at a real cluster and every line of Java above is unchanged — the co-partitioning guarantee from the Create the clicks topic part that made local state safe in the first place is a property of the topic's partitioning, not of running on one laptop.

Cheat Sheet

Want to…Call
Read a topic as a streambuilder.stream("clicks")
Group by the existing key.groupByKey()
Bucket into tumbling windows + grace period.windowedBy(TimeWindows.ofSizeAndGrace(size, grace))
Count per key per window, named store.count(Materialized.as("store-name"))
Emit only the final value per window.suppress(Suppressed.untilWindowCloses(...))
Turn a KTable back into a stream to publish.toStream().to("output-topic")
Query local state without an output topicstreams.store(StoreQueryParameters.fromNameAndType(...))
Find which instance owns a keystreams.metadataForKey(storeName, key, serializer)
Full end-to-end exactly-onceprocessing.guarantee=exactly_once_v2
List the auto-created changelog topic<application.id>-<store-name>-changelog, cleanup.policy=compact
  • ← Back to the full theory guide — The log as the unifying abstraction, data integration, stream processing, the partition/replication/acks design problem, commit semantics, rebalancing, and exactly-once — everything this lab put into your own hands.