Skip to content

Kafka Streams basics — KStreams, KTables, and a windowed aggregation in production

A working introduction to Kafka Streams — the topology DSL, KStream vs KTable, a windowed aggregation, and the state-store, rebalance, and exactly-once knobs an MSP cares about.

Kafka Streams is the JVM library that lets you write stateful stream processors as plain Java or Scala without standing up a separate cluster — your application is the processor. This article is the mental model and the production-shape install we recommend for clients building real-time aggregations, joins, and stream-to-table projections: how a topology compiles to consumer-producer pairs, when to reach for a KTable versus a KStream, what the state store actually is, and the operational levers (exactly-once, num.stream.threads, replication of changelog topics) that decide whether the app survives a rebalance.

How to verify

A Streams app is a normal JVM service consuming and producing Kafka topics. Before writing any topology, confirm:

java -version
/opt/kafka/bin/kafka-topics.sh --bootstrap-server localhost:9092 --describe --topic input.orders
/opt/kafka/bin/kafka-topics.sh --bootstrap-server localhost:9092 --describe --topic output.orders-per-customer
# both topics should exist with replication.factor >= 2 in production

The number of partitions on the input topic caps the parallelism of your Streams app — you cannot run more num.stream.threads (across all instances) than there are input partitions and still have every thread doing work.

What’s happening

A Kafka Streams app declares a topology — a graph of source nodes (Kafka topics), processor nodes (map/filter/aggregate/join), and sink nodes (Kafka topics again). The library compiles the topology into a set of consumers and producers that drive the data through the graph. There is no separate engine; the JVM that hosts your app is the engine.

The two core abstractions:

  • KStream — an unbounded sequence of records, each independent. Like a log: every record is a fact (“order #123 was created at 10:01”). Operations like mapValues, filter, branch, to work record-by-record.
  • KTable — a changelog projected as a key-value table. The latest record per key wins. Like a materialized view: “customer #456 currently has total spend $1,250.” Updates to the same key overwrite the previous value.

You convert between them: a KStream of customer-id → +amount aggregated by key becomes a KTable of customer-id → running total. The aggregation result is materialized in a state store — by default a RocksDB instance on the local disk of the Streams app, backed by a changelog topic in Kafka. This is the magic: state is local for speed (zero-cost reads), and replicated to Kafka for durability. When the app restarts on another box, it replays the changelog into a fresh RocksDB.

Windowed aggregations group records by time (tumbling, hopping, sliding, session). A 5-minute tumbling window on order counts gives you one count per customer per non-overlapping 5-minute bucket. Windowed state stores grow until the grace period expires, then prune.

The hard parts in production are rebalances (when an app instance joins or leaves, state stores get reassigned, which may mean replaying changelog topics — potentially gigabytes) and exactly-once semantics (processing.guarantee=exactly_once_v2), which uses Kafka transactions to make the input-process-output cycle atomic across all topics involved.

The procedure

  1. Set up the project. Maven dependency:

    <dependency>
      <groupId>org.apache.kafka</groupId>
      <artifactId>kafka-streams</artifactId>
      <version>3.7.0</version>
    </dependency>
  2. Write the topology — KStream filter, then a windowed aggregation to a KTable, then write to an output topic:

    Properties props = new Properties();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, "orders-aggregator-v1");
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka-01:9092");
    props.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, "exactly_once_v2");
    props.put(StreamsConfig.NUM_STREAM_THREADS_CONFIG, "4");
    props.put(StreamsConfig.REPLICATION_FACTOR_CONFIG, "3");
    
    StreamsBuilder builder = new StreamsBuilder();
    
    KStream<String, Order> orders = builder.stream("input.orders",
        Consumed.with(Serdes.String(), orderSerde));
    
    KTable<Windowed<String>, Long> ordersPerCustomerPerHour =
        orders.filter((key, order) -> order.getAmount() > 0)
              .groupBy((key, order) -> order.getCustomerId(),
                       Grouped.with(Serdes.String(), orderSerde))
              .windowedBy(TimeWindows.ofSizeAndGrace(Duration.ofHours(1), Duration.ofMinutes(5)))
              .count(Materialized.<String, Long, WindowStore<Bytes, byte[]>>as("orders-per-customer-store"));
    
    ordersPerCustomerPerHour.toStream()
        .map((wKey, count) -> KeyValue.pair(wKey.key(),
             "{\"customer\":\"" + wKey.key() + "\",\"hour\":\"" + wKey.window().startTime() + "\",\"count\":" + count + "}"))
        .to("output.orders-per-customer-per-hour", Produced.with(Serdes.String(), Serdes.String()));
    
    KafkaStreams streams = new KafkaStreams(builder.build(), props);
    streams.start();
    Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
  3. Create the input and output topics with matching partition counts:

    /opt/kafka/bin/kafka-topics.sh --bootstrap-server kafka-01:9092 \
      --create --topic input.orders --partitions 12 --replication-factor 3
    /opt/kafka/bin/kafka-topics.sh --bootstrap-server kafka-01:9092 \
      --create --topic output.orders-per-customer-per-hour --partitions 12 --replication-factor 3

    The output topic partition count should match the input so the keyed records remain co-partitioned downstream.

  4. Deploy the app with num.stream.threads matching your CPU budget. With 12 input partitions and 4 threads per instance, three instances saturate the partitions. A fourth instance joins, triggers a rebalance, sits idle until you scale up the input partitions.

  5. Watch the rebalance behavior on deploy. When you roll the app:

    /opt/kafka/bin/kafka-consumer-groups.sh --bootstrap-server kafka-01:9092 \
      --describe --group orders-aggregator-v1
    # look at LAG and STATE per partition during the roll

    Lag spikes during a rebalance are normal; they should settle within seconds for a stateless app, and within whatever-it-takes-to-restore-the-state-store for a stateful one. Use static membership (group.instance.id) to avoid full rebalances on rolling restarts.

  6. Monitor the changelog topics. Streams auto-creates a changelog topic per state store (<application-id>-<store-name>-changelog); they are compacted, so they bound at the size of the live state. Inspect them like any other Kafka topic; treat their replication factor and min.insync.replicas with the same seriousness as your user-facing topics.

  7. Wire JMX or Prometheus to the Streams metrics. The library exposes stream-thread-metrics, stream-state-metrics, and stream-record-cache-metrics over JMX. The critical alerts are:

    • stream-thread-metrics:poll-rate dropping to zero (the consumer stopped)
    • stream-state-metrics:put-rate and restore-rate (restore-rate non-zero outside a deploy means a rebalance is replaying state)
    • record-cache hit ratio (low ratio = state-store thrashing, look at heap and RocksDB tuning)

Operational notes

  • The application.id is the consumer group, the changelog topic prefix, and the state-store directory name; renaming it means starting from scratch — treat it as immutable for the life of the app.
  • RocksDB state stores live on the local filesystem (default /tmp/kafka-streams, change this!) and survive restarts only if the path persists. On containerized deployments, mount a persistent volume or you replay the changelog every pod start.
  • Exactly-once semantics require all input topics, the state-store changelogs, and the output topics to share the same Kafka cluster; cross-cluster pipelines fall back to at-least-once.
  • A poison message inside a topology can break the entire thread; configure a DeserializationExceptionHandler and ProductionExceptionHandler to log-and-skip or route to a DLQ instead of crashing the app.
  • Versioning topologies is painful — adding a stateful operator changes the changelog schema. Use a versioned application.id (e.g. orders-aggregator-v2) for breaking changes and let the old version drain.

Stack Harbor runs Kafka Streams apps as part of the real-time data tier for clients with sub-second analytics needs — topologies under code review, exactly-once where it matters, JMX metrics flowing into the same observability stack as the rest of the platform, and rebalance behavior tuned so a deploy does not page anyone. This is the work covered by our Managed Operations practice.