Kafka Streams: how a stream processing application works

Kafka Streams is a Java library for programs that read from Kafka topics, transform the records and write the results back to Kafka. There is no separate cluster to run: the library turns your code into a topology and spreads it over partitions and threads. This page explains that model, then runs a real application on a Kafka 4.2 broker and tests the important operations with TopologyTestDriver.

Share

Contents

What Kafka Streams is and how it runs

A stream processing application reads records as they arrive, transforms or aggregates them, and writes results continuously. You can build one from a plain consumer and producer, but then you have to handle state, rebalances, failures and exactly-once delivery yourself. Kafka Streams is a Java library, part of Apache Kafka, that does this for you. It is not a cluster or a server: it runs inside your application, and you scale by starting more instances of it.

You describe the processing with the Streams DSL, and the library compiles it into a topology:

  • Topology: a graph of processors. Source processors read topics, sink processors write topics, and the processors in between filter, map, join or aggregate.
  • Sub-topology: a part of the graph connected without going through a topic. A key change followed by an aggregation splits the graph in two, joined by an internal repartition topic.
  • Task: one copy of a sub-topology for one input partition. A sub-topology reading a topic with 6 partitions becomes 6 tasks, named 0_0 to 0_5. The task is the unit of parallelism: instances and threads share the tasks between them.
  • Application id: application.id names the application. It is the consumer group id of all its instances and the prefix of its internal topics.
  • State stores: local key-value or window stores, RocksDB by default, that hold aggregation and join state. Each is backed by a changelog topic, so a task can be moved to another instance and rebuilt there.

Instances of an application rebalance tasks among themselves through the consumer group. Kafka 4.2 made a dedicated Streams rebalance protocol, KIP-1071, generally available as group.protocol=streams; the default is still classic.

The three abstractions of the Streams DSL
AbstractionA record meansA null value meansBest for
KStreamAn event that happened: every record countsA record with no valueClicks, payments, log lines
KTableThe latest value for its key, replacing the previous oneDelete this key (a tombstone)Current state, such as a profile or a balance, partitioned like its topic
GlobalKTableSame as KTableDelete this keySmall reference data copied in full to every instance, for joins

The first program starts its own single-node Kafka 4.2 broker inside the JVM with EmbeddedKafkaKraftBroker from spring-kafka-test; a real cluster has 3 or more brokers. The other programs run their topology in TopologyTestDriver, from kafka-streams-test-utils, which feeds records through the topology synchronously without any broker. The processing is the same, and the output is deterministic.

A first application on a real broker

The application reads orders whose value is "product,amount", keeps those of 100 or more, and writes them to another topic. Both topics have two partitions, so the application gets two tasks. It runs with exactly-once processing, and a state listener prints each state change:

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.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
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.serialization.Serdes;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Produced;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class FirstStreamsApp {

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String servers = broker.getBrokersAsString();
        try (Admin admin = Admin.create(Map.of("bootstrap.servers", servers))) {
            admin.createTopics(List.of(new NewTopic("orders", 2, (short) 1),
                    new NewTopic("big-orders", 2, (short) 1))).all().get();
        }

        // the processing logic: a value looks like "book,120"
        StreamsBuilder builder = new StreamsBuilder();
        builder.stream("orders", Consumed.with(Serdes.String(), Serdes.String()))
                .filter((customer, order) -> amount(order) >= 100)
                .mapValues(order -> "BIG " + order)
                .to("big-orders", Produced.with(Serdes.String(), Serdes.String()));
        Topology topology = builder.build();
        System.out.print(topology.describe());

        Properties props = new Properties();
        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "order-filter");
        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
        props.put(StreamsConfig.STATE_DIR_CONFIG,
                Files.createTempDirectory("streams").toString());
        props.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, StreamsConfig.EXACTLY_ONCE_V2);
        try (KafkaStreams streams = new KafkaStreams(topology, props)) {
            streams.setStateListener((now, before) ->
                    System.out.println("state " + before + " -> " + now));
            streams.start();

            try (var producer = new KafkaProducer<String, String>(producerProps(servers))) {
                producer.send(new ProducerRecord<>("orders", "alice", "book,120"));
                producer.send(new ProducerRecord<>("orders", "bob", "pen,3"));
                producer.send(new ProducerRecord<>("orders", "carol", "laptop,950"));
                producer.send(new ProducerRecord<>("orders", "bob", "desk,240"));
            }
            for (String line : readSorted(servers, 3)) {
                System.out.println("big-orders: " + line);
            }
            System.out.println("tasks: " + streams.metadataForLocalThreads().iterator().next()
                    .activeTasks().stream().map(t -> t.taskId().toString()).sorted().toList());
        }
        broker.destroy();
    }

    static int amount(String order) {
        return Integer.parseInt(order.split(",")[1]);
    }

    static Properties producerProps(String servers) {
        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;
    }

    // reads the output topic until the expected number of records arrived
    static List<String> readSorted(String servers, int expected) {
        Properties c = new Properties();
        c.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
        c.put(ConsumerConfig.GROUP_ID_CONFIG, "checker");
        c.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        c.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed");
        c.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        c.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        List<String> lines = new ArrayList<>();
        try (var consumer = new KafkaConsumer<String, String>(c)) {
            consumer.subscribe(List.of("big-orders"));
            long deadline = System.currentTimeMillis() + 30000;
            while (lines.size() < expected && System.currentTimeMillis() < deadline) {
                consumer.poll(Duration.ofMillis(200)).forEach(r -> lines.add(
                        r.key() + " = " + r.value() + " (partition " + r.partition() + ")"));
            }
        }
        return lines.stream().sorted().toList();
    }

    // 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
Topologies:
   Sub-topology: 0
    Source: KSTREAM-SOURCE-0000000000 (topics: [orders])
      --> KSTREAM-FILTER-0000000001
    Processor: KSTREAM-FILTER-0000000001 (stores: [])
      --> KSTREAM-MAPVALUES-0000000002
      <-- KSTREAM-SOURCE-0000000000
    Processor: KSTREAM-MAPVALUES-0000000002 (stores: [])
      --> KSTREAM-SINK-0000000003
      <-- KSTREAM-FILTER-0000000001
    Sink: KSTREAM-SINK-0000000003 (topic: big-orders)
      <-- KSTREAM-MAPVALUES-0000000002

state CREATED -> REBALANCING
state REBALANCING -> RUNNING
big-orders: alice = BIG book,120 (partition 1)
big-orders: bob = BIG desk,240 (partition 0)
big-orders: carol = BIG laptop,950 (partition 0)
tasks: [0_0, 0_1]
state RUNNING -> PENDING_SHUTDOWN
state PENDING_SHUTDOWN -> NOT_RUNNING
  • topology.describe() shows what the DSL built: one sub-topology, from the orders source through the filter and the mapper to the big-orders sink. The generated names, such as KSTREAM-FILTER-0000000001, are numbered in the order the operations were added.
  • The application went from CREATED to REBALANCING while it joined the consumer group and was given its tasks, then to RUNNING.
  • Bob's 3-unit pen order was filtered out; the other three orders arrived with the BIG prefix.
  • Each record kept its key and stayed in the same partition number: carol and bob's desk in partition 0, alice in partition 1. Stateless operations that keep the key do not move data between partitions.
  • The two tasks, 0_0 and 0_1, are sub-topology 0 for partitions 0 and 1. With one instance and one thread, both ran on the same thread. A second instance with the same application.id would take one of them.
  • close() moved the application through PENDING_SHUTDOWN to NOT_RUNNING, committing its progress.

The output consumer uses read_committed, because with exactly_once_v2 the application writes its output in transactions, committed every 100 ms by default. The Kafka transactions page explains what that guarantees. The state.dir is a temporary directory here; in production it must be a persistent path that each instance keeps across restarts.

Stateless operations

Stateless operations look at one record at a time and need no store. The program routes log lines: it drops DEBUG lines, sends errors to one topic, and splits the other lines into words keyed by word. peek prints what passes the filter:

Java
import ch.qos.logback.classic.Level;
import java.util.Arrays;
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.TestInputTopic;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.kstream.Branched;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.Named;
import org.apache.kafka.streams.kstream.Produced;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StatelessOps {

    public static void main(String[] args) {
        quietLogs();
        StreamsBuilder builder = new StreamsBuilder();
        // key = service name, value = "LEVEL message"
        KStream<String, String> logs =
                builder.stream("logs", Consumed.with(Serdes.String(), Serdes.String()));

        logs.filterNot((service, line) -> line.startsWith("DEBUG"))
                .peek((service, line) -> System.out.println("  kept    " + service + ": " + line))
                .split(Named.as("level-"))
                .branch((service, line) -> line.startsWith("ERROR"),
                        Branched.withConsumer(errors -> errors
                                .mapValues(line -> line.substring(6))
                                .to("errors", Produced.with(Serdes.String(), Serdes.String()))))
                .defaultBranch(Branched.withConsumer(rest -> rest
                        .flatMapValues(line -> Arrays.asList(line.split(" ")).subList(1, 3))
                        .map((service, word) -> KeyValue.pair(word, service))
                        .to("words", Produced.with(Serdes.String(), Serdes.String()))));

        Properties props = new Properties();
        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "log-router");
        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "unused:9092"); // the driver needs none
        try (var driver = new TopologyTestDriver(builder.build(), props)) {
            TestInputTopic<String, String> in = driver.createInputTopic("logs",
                    new StringSerializer(), new StringSerializer());
            System.out.println("piping 4 records:");
            in.pipeInput("cart", "INFO user added item");
            in.pipeInput("cart", "DEBUG cache miss for user");
            in.pipeInput("payment", "ERROR card declined");
            in.pipeInput("search", "WARN slow query today");

            System.out.println("errors topic: " + driver.createOutputTopic("errors",
                    new StringDeserializer(), new StringDeserializer()).readKeyValuesToList());
            System.out.println("words topic:  " + driver.createOutputTopic("words",
                    new StringDeserializer(), new StringDeserializer()).readKeyValuesToList());
        }
    }

    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
piping 4 records:
  kept    cart: INFO user added item
  kept    payment: ERROR card declined
  kept    search: WARN slow query today
errors topic: [KeyValue(payment, card declined)]
words topic:  [KeyValue(user, cart), KeyValue(added, cart), KeyValue(slow, search), KeyValue(query, search)]
  • filterNot dropped the cart service's DEBUG line, so peek printed only three records.
  • split with branch sent the record starting with ERROR to the first branch, which removed the level with mapValues. The value became "card declined", and the key stayed payment.
  • The other two lines went to defaultBranch. flatMapValues turned each into two words, and map swapped key and value, so each word became the key.
Common stateless operations
OperationChanges the keyUse it for
filter, filterNotNoDropping records
mapValues, flatMapValuesNoChanging values; preferred, because the partitioning stays valid
map, flatMap, selectKeyYesNew keys; a later aggregation or join then repartitions
split().branch()NoRouting records to different processing
mergeNoCombining two streams into one
peek, foreachNoSide effects such as logging; foreach ends the stream

Prefer mapValues to map whenever the key does not change. After map, Kafka Streams has to assume the key changed, and marks the stream for repartitioning before the next grouping or join, even if the new key is the same.

KStream versus KTable on the same data

A topic of user locations can be read as a stream of moves or as a table of where each user is now, and the two answer different questions. The program counts per city both ways from the same records, including a move and a deletion. Caching is turned off so that every update is visible:

Java
import ch.qos.logback.classic.Level;
import java.util.Properties;
import org.apache.kafka.common.serialization.LongDeserializer;
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.common.utils.Bytes;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.TestInputTopic;
import org.apache.kafka.streams.TestOutputTopic;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Grouped;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.Produced;
import org.apache.kafka.streams.state.KeyValueStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StreamVsTable {

    public static void main(String[] args) {
        quietLogs();
        StreamsBuilder builder = new StreamsBuilder();
        Consumed<String, String> strings = Consumed.with(Serdes.String(), Serdes.String());
        Grouped<String, String> byCity = Grouped.with(Serdes.String(), Serdes.String());

        // one topic seen two ways: as a stream of moves, and as a table of current cities
        KStream<String, String> moves = builder.stream("user-city", strings);
        moves.groupBy((user, city) -> city, byCity)
                .count()
                .toStream().to("moves-per-city", Produced.with(Serdes.String(), Serdes.Long()));

        KTable<String, String> current = moves.toTable(
                Materialized.<String, String, KeyValueStore<Bytes, byte[]>>as("current-city")
                        .withKeySerde(Serdes.String()).withValueSerde(Serdes.String()));
        current.groupBy((user, city) -> KeyValue.pair(city, user), byCity)
                .count()
                .toStream().to("users-per-city", Produced.with(Serdes.String(), Serdes.Long()));

        Properties props = new Properties();
        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "cities");
        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "unused:9092");
        props.put(StreamsConfig.STATESTORE_CACHE_MAX_BYTES_CONFIG, 0); // emit every update
        try (var driver = new TopologyTestDriver(builder.build(), props)) {
            TestInputTopic<String, String> in = driver.createInputTopic("user-city",
                    new StringSerializer(), new StringSerializer());
            in.pipeInput("alice", "London");
            in.pipeInput("bob", "Paris");
            in.pipeInput("alice", "Paris"); // alice moves
            in.pipeInput("carol", "London");
            in.pipeInput("bob", (String) null); // a tombstone: bob is deleted

            print("moves-per-city (KStream count)", driver.createOutputTopic(
                    "moves-per-city", new StringDeserializer(), new LongDeserializer()));
            print("users-per-city (KTable count)", driver.createOutputTopic(
                    "users-per-city", new StringDeserializer(), new LongDeserializer()));
            KeyValueStore<String, String> store = driver.getKeyValueStore("current-city");
            System.out.print("current-city store:");
            try (var all = store.all()) {
                all.forEachRemaining(kv -> System.out.print(" " + kv.key + "=" + kv.value));
            }
            System.out.println();
        }
    }

    static void print(String title, TestOutputTopic<String, Long> topic) {
        System.out.println(title + ":");
        topic.readKeyValuesToList().forEach(kv ->
                System.out.println("  " + kv.key + " " + kv.value));
    }

    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
moves-per-city (KStream count):
  London 1
  Paris 1
  Paris 2
  London 2
users-per-city (KTable count):
  London 1
  Paris 1
  London 0
  Paris 2
  London 1
  Paris 1
current-city store: alice=Paris carol=London
  • The KStream count counts events. Alice's move to Paris made the Paris count 2, and London kept alice's earlier visit, so carol made it 2. The count never goes down.
  • The stream count ignored the tombstone for bob: grouping by the value gave a null key, and records with a null grouping key are dropped.
  • The KTable count counts current members. When alice moved, the table sent two updates: London went down to 0 as her old row was subtracted, and Paris went up to 2.
  • Bob's tombstone deleted his row, so Paris went down to 1. The table count is the real number of users per city: London 1 for carol, Paris 1 for alice.
  • The current-city store holds the table itself: alice and carol only, because bob was deleted.

The table is built with toTable() from the stream that is already reading the topic. Reading the same topic with both builder.stream and builder.table fails at build() with "Topic user-city has already been registered by another source". Without the cache setting, the default 10 MB cache would merge updates to the same key and emit fewer intermediate results, as the stateful processing page shows.

Changing the key moves data: repartition topics

An aggregation needs all records for a key in one task. When the grouping key is not the record's current key, Kafka Streams first writes the records back to Kafka, partitioned by the new key. The program counts page views per user, which keeps the key, and per page, which changes it:

Java
import ch.qos.logback.classic.Level;
import java.util.Properties;
import org.apache.kafka.common.serialization.LongDeserializer;
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.Topology;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Grouped;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.Produced;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RepartitionTopology {

    public static void main(String[] args) {
        quietLogs();
        StreamsBuilder builder = new StreamsBuilder();
        // page views keyed by user id; the value is the page
        KStream<String, String> views =
                builder.stream("page-views", Consumed.with(Serdes.String(), Serdes.String()));

        views.groupByKey() // the key stays the user: no data has to move
                .count(Materialized.as("views-per-user"))
                .toStream().to("user-counts", Produced.with(Serdes.String(), Serdes.Long()));

        views.groupBy((user, page) -> page, Grouped.as("by-page")) // a new key: data must move
                .count(Materialized.as("views-per-page"))
                .toStream().to("page-counts", Produced.with(Serdes.String(), Serdes.Long()));

        Topology topology = builder.build();
        System.out.print(topology.describe());

        Properties props = new Properties();
        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "views");
        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);
        props.put(StreamsConfig.STATESTORE_CACHE_MAX_BYTES_CONFIG, 0);
        try (var driver = new TopologyTestDriver(topology, props)) {
            var in = driver.createInputTopic("page-views",
                    new StringSerializer(), new StringSerializer());
            in.pipeInput("u1", "/home");
            in.pipeInput("u2", "/home");
            in.pipeInput("u1", "/cart");
            System.out.println("user-counts: " + driver.createOutputTopic("user-counts",
                    new StringDeserializer(), new LongDeserializer()).readKeyValuesToList());
            System.out.println("page-counts: " + driver.createOutputTopic("page-counts",
                    new StringDeserializer(), new LongDeserializer()).readKeyValuesToList());
        }
    }

    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
Topologies:
   Sub-topology: 0
    Source: KSTREAM-SOURCE-0000000000 (topics: [page-views])
      --> KSTREAM-AGGREGATE-0000000001, by-page
    Processor: KSTREAM-AGGREGATE-0000000001 (stores: [views-per-user])
      --> KTABLE-TOSTREAM-0000000002
      <-- KSTREAM-SOURCE-0000000000
    Processor: by-page (stores: [])
      --> by-page-repartition-filter
      <-- KSTREAM-SOURCE-0000000000
    Processor: KTABLE-TOSTREAM-0000000002 (stores: [])
      --> KSTREAM-SINK-0000000003
      <-- KSTREAM-AGGREGATE-0000000001
    Processor: by-page-repartition-filter (stores: [])
      --> by-page-repartition-sink
      <-- by-page
    Sink: KSTREAM-SINK-0000000003 (topic: user-counts)
      <-- KTABLE-TOSTREAM-0000000002
    Sink: by-page-repartition-sink (topic: by-page-repartition)
      <-- by-page-repartition-filter

  Sub-topology: 1
    Source: by-page-repartition-source (topics: [by-page-repartition])
      --> KSTREAM-AGGREGATE-0000000005
    Processor: KSTREAM-AGGREGATE-0000000005 (stores: [views-per-page])
      --> KTABLE-TOSTREAM-0000000009
      <-- by-page-repartition-source
    Processor: KTABLE-TOSTREAM-0000000009 (stores: [])
      --> KSTREAM-SINK-0000000010
      <-- KSTREAM-AGGREGATE-0000000005
    Sink: KSTREAM-SINK-0000000010 (topic: page-counts)
      <-- KTABLE-TOSTREAM-0000000009

user-counts: [KeyValue(u1, 1), KeyValue(u2, 1), KeyValue(u1, 2)]
page-counts: [KeyValue(/home, 1), KeyValue(/home, 2), KeyValue(/cart, 1)]
  • groupByKey().count() stayed in sub-topology 0: the aggregate processor sits right after the source, with its store views-per-user.
  • groupBy by page added a sink to the by-page-repartition topic in sub-topology 0, and a new sub-topology 1 that reads it and counts. On a broker, the topic is named views-by-page-repartition, prefixed with the application id. Each record crosses the network twice more.
  • The repartition filter drops records whose new key is null before they are written.
  • Both counts are correct: u1 viewed two pages, and /home was viewed twice.

Naming the operation with Grouped.as("by-page") gave the topic a stable name. Without it, the name contains a generated number, and adding an operation earlier in the code changes that number, which breaks an upgrade of a running application. Name your repartition topics and stores; setting ensure.explicit.internal.resource.naming=true, new in Kafka 4.1, makes generated names a startup error.

Bad records: deserialization errors and dead letter queues

A record that cannot be deserialized, often called a poison pill, stops the whole application by default. The program expects 4-byte integer values, and another producer writes the text "5 pcs" between two good records. It runs three times with different error settings:

Java
import ch.qos.logback.classic.Level;
import java.util.Properties;
import org.apache.kafka.common.header.Header;
import org.apache.kafka.common.serialization.ByteArrayDeserializer;
import org.apache.kafka.common.serialization.IntegerDeserializer;
import org.apache.kafka.common.serialization.IntegerSerializer;
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.errors.LogAndContinueExceptionHandler;
import org.apache.kafka.streams.errors.StreamsException;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Produced;
import org.apache.kafka.streams.test.TestRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PoisonPill {

    public static void main(String[] args) {
        quietLogs();
        run("default handler (LogAndFail)", new Properties());

        Properties skip = new Properties();
        skip.put(StreamsConfig.DESERIALIZATION_EXCEPTION_HANDLER_CLASS_CONFIG,
                LogAndContinueExceptionHandler.class);
        run("LogAndContinueExceptionHandler", skip);

        Properties dlq = new Properties();
        dlq.putAll(skip);
        dlq.put(StreamsConfig.ERRORS_DEAD_LETTER_QUEUE_TOPIC_NAME_CONFIG, "quantities-dlq");
        run("LogAndContinue + dead letter queue", dlq);
    }

    static void run(String title, Properties extra) {
        System.out.println(title + ":");
        StreamsBuilder builder = new StreamsBuilder();
        // values are expected to be 4-byte integers
        builder.stream("quantities", Consumed.with(Serdes.String(), Serdes.Integer()))
                .mapValues(q -> q * 2)
                .to("doubled", Produced.with(Serdes.String(), Serdes.Integer()));
        Properties props = new Properties();
        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "doubler");
        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "unused:9092");
        props.putAll(extra);
        try (var driver = new TopologyTestDriver(builder.build(), props)) {
            var good = driver.createInputTopic("quantities",
                    new StringSerializer(), new IntegerSerializer());
            var bad = driver.createInputTopic("quantities",
                    new StringSerializer(), new StringSerializer());
            good.pipeInput("a", 5);
            try {
                bad.pipeInput("b", "5 pcs"); // a producer that wrote text instead of an int
                good.pipeInput("c", 7);
            } catch (StreamsException e) {
                System.out.println("  StreamsException: " + e.getCause().getMessage());
            }
            System.out.println("  doubled: " + driver.createOutputTopic("doubled",
                    new StringDeserializer(), new IntegerDeserializer()).readKeyValuesToList());
            if (extra.containsKey(StreamsConfig.ERRORS_DEAD_LETTER_QUEUE_TOPIC_NAME_CONFIG)) {
                var dead = driver.createOutputTopic("quantities-dlq",
                        new ByteArrayDeserializer(), new ByteArrayDeserializer());
                for (TestRecord<byte[], byte[]> r : dead.readRecordsToList()) {
                    System.out.println("  dlq record: key=" + new String(r.key())
                            + " value=" + new String(r.value()));
                    for (Header h : r.headers()) {
                        String v = new String(h.value());
                        System.out.println("    " + h.key() + ": "
                                + (v.length() > 60 ? v.substring(0, 60) + "..." : v));
                    }
                }
            }
        }
    }

    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
default handler (LogAndFail):
  StreamsException: Size of data received by IntegerDeserializer is not 4
  doubled: [KeyValue(a, 10)]
LogAndContinueExceptionHandler:
  doubled: [KeyValue(a, 10), KeyValue(c, 14)]
LogAndContinue + dead letter queue:
  doubled: [KeyValue(a, 10), KeyValue(c, 14)]
  dlq record: key=b value=5 pcs
    __streams.errors.exception: org.apache.kafka.common.errors.SerializationException
    __streams.errors.message: Size of data received by IntegerDeserializer is not 4
    __streams.errors.stacktrace: org.apache.kafka.common.errors.SerializationException: Size ...
    __streams.errors.topic: quantities
    __streams.errors.partition: 0
    __streams.errors.offset: 1
  • With the default LogAndFailExceptionHandler, the bad record threw a StreamsException, and record c was never processed. On a broker, the stream thread dies, and after a restart it fails on the same record again, because the offset was never committed.
  • LogAndContinueExceptionHandler logged the error and skipped the record, so a and c were both doubled. The bad record is gone, apart from a log line.
  • With errors.dead.letter.queue.topic.name also set, the bad record was written to quantities-dlq with its original key and bytes. Headers record the exception, message, stack trace and the source topic, partition and offset, which is enough to inspect and replay it.

The dead letter queue is new in Kafka 4.2 (KIP-1034). Kafka 4.0 renamed the handler settings to deserialization.exception.handler and production.exception.handler, deprecating the old default. prefixed names. A third handler, processing.exception.handler, covers exceptions thrown by your own code in processors.

Running Kafka Streams in production

  • Scaling: the number of tasks, set by the input partitions, is the upper limit of parallelism. Threads beyond the number of tasks stay idle. Choose partition counts with growth in mind, because adding partitions later changes which partition each key goes to.
  • Processing guarantee: at_least_once is the default and commits every 30 seconds. exactly_once_v2 commits every 100 ms in transactions and needs 3 brokers for the transaction log.
  • State directory: keep state.dir on a persistent disk. Losing it is safe but slow, because every store is rebuilt from its changelog.
  • Standby replicas: num.standby.replicas=1 keeps a warm copy of each store on another instance, so a failover does not wait for a full restore.
  • Uncaught exceptions: register setUncaughtExceptionHandler to decide whether a failed thread is replaced, or the client or application shuts down.
  • Testing: TopologyTestDriver tests topologies in milliseconds, without a broker, as most programs on this page do.

Choosing the right building block

Situations and what to use
SituationUse
Filter, convert or route eventsKStream with stateless operations
Keep the latest value per keyKTable, or toTable() on a stream
Count or sum events per keygroupByKey().count() or aggregate() on a KStream
Count current members of a groupgroupBy().count() on a KTable
Look up small reference dataGlobalKTable join
Kafka in, Kafka out, without duplicatesprocessing.guarantee=exactly_once_v2
Records that may be malformedLogAndContinueExceptionHandler with a dead letter queue topic
A simple consume, call a service, doneA plain Kafka consumer; Kafka Streams writes its results to Kafka

Continue with stateful processing and windows, joins and interactive queries. For the same processing written in SQL, see ksqlDB.