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.
Contents
What Kafka Streams is and how it runs A first application on a real broker Stateless operations KStream versus KTable on the same data Changing the key moves data: repartition topics Bad records: deserialization errors and dead letter queues Running Kafka Streams in production Choosing the right building block
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
to0_0 . The task is the unit of parallelism: instances and threads share the tasks between them.0_5 - Application id:
names the application. It is the consumer group id of all its instances and the prefix of its internal topics.application.id - 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=streamsclassic
| Abstraction | A record means | A null value means | Best for |
|---|---|---|---|
KStream | An event that happened: every record counts | A record with no value | Clicks, payments, log lines |
KTable | The latest value for its key, replacing the previous one | Delete this key (a tombstone) | Current state, such as a profile or a balance, partitioned like its topic |
GlobalKTable | Same as KTable | Delete this key | Small 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 EmbeddedKafkaKraftBrokerspring-kafka-testTopologyTestDriverkafka-streams-test-utils
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:
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);
}
}
}
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
shows what the DSL built: one sub-topology, from thetopology.describe() source through the filter and the mapper to theorders sink. The generated names, such asbig-orders , are numbered in the order the operations were added.KSTREAM-FILTER-0000000001- The application went from
toCREATED while it joined the consumer group and was given its tasks, then toREBALANCING .RUNNING - Bob's 3-unit pen order was filtered out; the other three orders arrived with the
prefix.BIG - 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,
and0_0 , 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 same0_1 would take one of them.application.id moved the application throughclose() toPENDING_SHUTDOWN , committing its progress.NOT_RUNNING
The output consumer uses read_committedexactly_once_v2state.dir
Stateless operations
Stateless operations look at one record at a time and need no store. The program routes log lines: it drops DEBUGpeek
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);
}
}
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)]
dropped the cart service'sfilterNot line, soDEBUG printed only three records.peek withsplit sent the record starting withbranch to the first branch, which removed the level withERROR . The value became "card declined", and the key stayedmapValues .payment- The other two lines went to
.defaultBranch turned each into two words, andflatMapValues swapped key and value, so each word became the key.map
| Operation | Changes the key | Use it for |
|---|---|---|
filterfilterNot | No | Dropping records |
mapValuesflatMapValues | No | Changing values; preferred, because the partitioning stays valid |
mapflatMapselectKey | Yes | New keys; a later aggregation or join then repartitions |
split().branch() | No | Routing records to different processing |
merge | No | Combining two streams into one |
peekforeach | No | Side effects such as logging; foreach |
Prefer mapValuesmapmap
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:
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);
}
}
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
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.KStream - 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
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.KTable - 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
store holds the table itself: alice and carol only, because bob was deleted.current-city
The table is built with toTable()builder.streambuilder.tablebuild()
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:
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);
}
}
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)]
stayed in sub-topology 0: the aggregate processor sits right after the source, with its storegroupByKey().count() .views-per-user by page added a sink to thegroupBy topic in sub-topology 0, and a new sub-topology 1 that reads it and counts. On a broker, the topic is namedby-page-repartition , prefixed with the application id. Each record crosses the network twice more.views-by-page-repartition- The repartition filter drops records whose new key is null before they are written.
- Both counts are correct: u1 viewed two pages, and
was viewed twice./home
Naming the operation with Grouped.as("by-page")ensure.explicit.internal.resource.naming=true
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:
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);
}
}
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
, the bad record threw aLogAndFailExceptionHandler , 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.StreamsException logged the error and skipped the record, so a and c were both doubled. The bad record is gone, apart from a log line.LogAndContinueExceptionHandler- With
also set, the bad record was written toerrors.dead.letter.queue.topic.name 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.quantities-dlq
The dead letter queue is new in Kafka 4.2 (KIP-1034). Kafka 4.0 renamed the handler settings to deserialization.exception.handlerproduction.exception.handlerdefault.processing.exception.handler
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:
is the default and commits every 30 seconds.at_least_once commits every 100 ms in transactions and needs 3 brokers for the transaction log.exactly_once_v2 - State directory: keep
on a persistent disk. Losing it is safe but slow, because every store is rebuilt from its changelog.state.dir - Standby replicas:
keeps a warm copy of each store on another instance, so a failover does not wait for a full restore.num.standby.replicas=1 - Uncaught exceptions: register
to decide whether a failed thread is replaced, or the client or application shuts down.setUncaughtExceptionHandler - Testing:
tests topologies in milliseconds, without a broker, as most programs on this page do.TopologyTestDriver
Choosing the right building block
| Situation | Use |
|---|---|
| Filter, convert or route events | KStream |
| Keep the latest value per key | KTabletoTable() |
| Count or sum events per key | groupByKey().count()aggregate()KStream |
| Count current members of a group | groupBy().count()KTable |
| Look up small reference data | GlobalKTable |
| Kafka in, Kafka out, without duplicates | processing.guarantee=exactly_once_v2 |
| Records that may be malformed | LogAndContinueExceptionHandler |
| A simple consume, call a service, done | A plain |
Continue with