Skip to content

Implementations and comparison

Running totals in Kafka Streams

Follow a keyed sum from a Kafka input topic to a KTable and an output topic, then trace the state and offsets used for recovery.

Learn with an AI assistant

Copy the prompt and paste it into a chat with an AI assistant.

You are a tutor for the course "Stream Processing".
Topic: "Running totals in Kafka Streams"
In short: Follow a keyed sum from a Kafka input topic to a KTable and an output topic, then trace the state and offsets used for recovery.
Topic text in Markdown: https://stream-processing-systems.github.io/implementations/running-totals-in-kafka-streams.md
Base your explanations on the topic text. First ask how I want to study: a short summary, a step-by-step walkthrough, or a deep dive with questions that check my understanding. Use the text's example and terms. If you add anything the text does not say, point it out.

Our AI assistant publishes accepted token contributions to a Kafka topic. The reporting application reads them and publishes updated totals for the usage page. Both ends of this path already use Kafka. How does the application keep each account’s total and recover it if an instance stops?

A topology is a set of connected processing steps. Kafka Streams runs those steps inside the Java application. The Kafka brokers store the records that the application reads and writes.1

In accepted-usage, the record key is the account ID and the value is the number of tokens contributed by one accepted request. We remove repeated deliveries before writing this topic. The producer sends all contributions for a given account to the same partition.

This Java excerpt uses Kafka Streams 4.4.0. It defines the topology. Starting it requires building the topology and supplying application settings such as the Kafka broker addresses and the application ID.2

StreamsBuilder builder = new StreamsBuilder();
KStream<String, Long> usage = builder.stream(
"accepted-usage", Consumed.with(Serdes.String(), Serdes.Long()));
KTable<String, Long> totals = usage
.groupByKey(Grouped.with(Serdes.String(), Serdes.Long()))
.reduce(Long::sum,
Materialized.<String, Long, KeyValueStore<Bytes, byte[]>>as("running-totals")
.withKeySerde(Serdes.String())
.withValueSerde(Serdes.Long()));
totals.toStream().to(
"account-token-totals", Produced.with(Serdes.String(), Serdes.Long()));

KStream is the stream of contributions. groupByKey groups by the existing Kafka record key. reduce uses the first contribution as the initial total and adds each subsequent value. The resulting KTable holds one current value per account. Materialized names the state store, and the Serdes set how the account strings and token counts are encoded and decoded.3

In the shared usage example, acme contributes 600 tokens after reaching 1,400, so its row becomes 2,000. toStream() turns table changes into records for the output topic. Their keys tell the usage page which rows to replace. Kafka Streams can combine pending changes for a key in its cache before forwarding them, so the page may see 1,400 and then 2,500.3

The partition determines who does the work. A stream task processes the input partition that contains acme and keeps that account’s accumulated total in its local store. Kafka Streams backs the store used here with a Kafka changelog, an internal topic recording its changes. If another instance takes over the task, it can restore the store from that changelog before resuming.4

The setting application.id ties the processing instances to the same consumer group and internal topic names. Changing the ID starts a separate application with its own state and positions.2 If it starts with the earliest available records and writes to the same output topic, readers can see smaller totals while it catches up. It reaches the same answer if it can read all the original contributions. If Kafka has already removed u-101 and the other contributions are still available, acme ends up at 1,500 instead of 2,500. A full recalculation depends on the history the topic still holds.5

Suppose a task reads the 600-token contribution and fails while publishing 2,000. On recovery, the reading position must agree with the stored total. The default mode, at_least_once, can count the contribution again after a failure even if it appears once in the input topic. Set processing.guarantee=exactly_once_v2 to have Kafka Streams commit the consumed offsets, the logged state changes, and the Kafka output records in one Kafka transaction. The output consumer uses read_committed to read committed transactional records.126

What Kafka commits together With exactly_once_v2, Kafka Streams commits input offsets, changelog records, and output records in one Kafka transaction. ONE KAFKA TRANSACTION Input offsets where reading resumes Changelog records logged changes to task state Kafka output records replacement totals by account

One transaction can cover several input records. The guarantee applies to each record at its Kafka offset. If the input topic holds two copies of the same request at different offsets, both contribute to this sum. If the application also calls an external ledger over HTTP, that call needs its own safe retry protocol.

  • Kafka Streams runs a topology inside the application. The input record key determines the group in this topology.
  • The KTable keeps the current total. The output records carry replacement values keyed by account.
  • The local store can be restored from its Kafka changelog. With exactly_once_v2, Kafka commits the logged changes, input offsets, and Kafka output together.
  1. Apache Kafka 4.4: Kafka Streams Core Concepts.

  2. Apache Kafka 4.4: Configuring a Streams Application.

  3. Apache Kafka 4.4: Streams DSL and Memory Management.

  4. Apache Kafka 4.4: Kafka Streams Fault Tolerance.

  5. Apache Kafka 4.4: Consumer Configuration, auto.offset.reset and Topic Configuration, retention.ms.

  6. Apache Kafka 4.4: Consumer Configuration, isolation.level.

© 2026 Grig Alex · CC BY-NC-SA 4.0