Apache Kafka — Primer + 150-Question Drill
"Kafka is not a queue with extra features. It is an append-only log that many readers walk through at their own pace, and almost every production incident comes from forgetting that one sentence."
01 · Why this primer existsYou Have Used Kafka for Years — Nobody Explained What It Promises
Kafka stores events in an ordered log and lets each reader keep its own place in it. That one design explains its speed, its ordering rules and its delivery guarantees. This chapter teaches the design first, then the settings that follow from it.
Here is a Tuesday that happens to a lot of teams. A shop's order service publishes an OrderPlaced event to a Kafka topic called orders. About 40,000 orders arrive per day, and three copies of the shipping service read the topic.
Nobody on the team thought hard about Kafka when they set it up. They used it the way they had used RabbitMQ: send a message, a worker picks it up, done.
The producer sends events with no key. The topic has six partitions (six separate ordered lanes, explained in the next section). The consumers use the default settings, which include automatic offset commits every five seconds.
On Tuesday afternoon the team deploys a new version of the shipping service. The deploy restarts the three consumers one after another. Over the next ten minutes, three things go wrong at once.
First, 212 orders are never shipped. A consumer had read them, the automatic commit had already told Kafka "I am finished with these", and then the consumer was killed before it did the work. Kafka believed those orders were done. They were not.
Second, 87 customers get two parcels. A different consumer had finished the work but was stopped before its commit went out. When a new consumer took over that lane, it started from the last commit and did the same orders again.
Third, a few dozen customers receive a "Your order has shipped" email before the "Payment received" email. OrderPaid and OrderShipped for the same order had landed in different lanes, and the lanes are read independently.
Nothing crashed in that story and no Kafka bug was involved. Every one of the three failures is documented, expected behaviour of a log that was treated like a queue.
Make the invisible visible: what the shipping consumer's progress marker looked like around one restart.
# illustrative numbers: partition 3 of topic orders, auto-commit every 5 s
offset event consumer A committed offset (stored in Kafka)
810 OrderPlaced o-91 read, shipped ✓
811 OrderPlaced o-92 read, shipped ✓ 811 (auto-commit fires: "up to 811 is done")
812 OrderPlaced o-93 read, NOT yet shipped 811
813 OrderPlaced o-94 read, NOT yet shipped 811
... auto-commit fires again: "up to 813 is done" 813 (but 812 and 813 were never shipped)
--- consumer A is killed by the deploy ---
consumer B takes over partition 3, starts at 813 -> o-93 and o-94 are skipped forever ✗ lostWhat you see: the opposite failure, when the commit is late instead of early.
# illustrative numbers
offset event consumer A committed offset
820 OrderPlaced o-101 read, shipped ✓
821 OrderPlaced o-102 read, shipped ✓
--- consumer A is killed before the next auto-commit --- 815 (last commit was long ago)
consumer B takes over partition 3, starts at 815 -> re-reads 815..821, ships them again ✗ duplicatesWhy: Kafka does not know whether you did the work. It only knows the number you told it, so the moment you report that number decides whether a crash loses events or repeats them.
That single picture is half of what a senior interview asks. The other half is the same idea from other angles: which lane an event lands in, how many readers can share the work, what happens when a server dies, and which promises survive a crash.
The good news is that all of it comes from five ideas. A senior candidate is expected to hold all five in mind at once:
- The log: a topic is a set of append-only files. Records are never changed, only added and, eventually, deleted by age or size. Reading does not remove anything.
- Partitions and keys: a topic is split into lanes called partitions. Order is guaranteed inside one lane and nowhere else. The key you put on a record decides the lane.
- Consumer groups and offsets: readers who share a job form a group, each lane goes to one member of the group, and each member records its position (the offset) in Kafka itself.
- Delivery guarantees: at-most-once, at-least-once and exactly-once are choices about when you commit, and exactly-once has a boundary that stops at Kafka's edge.
- The ecosystem: Spring Kafka for your services, a schema registry so events can change safely, Kafka Connect to move data in and out of databases, and Kafka Streams to compute on the log.
The senior skill is to hear an incident and say which of the five it belongs to. The Tuesday above is idea three (commit timing) and idea two (keys) at the same time.
The page has two halves.
The primer (sections 02–07) walks the five ideas in order: the log; producers; consumers and groups; delivery guarantees and transactions; the ecosystem; and finally running Kafka in production.
Each section opens with an incident, then shows the mechanism as numbers or a picture, then gives configuration and code you can run, and ends with an interview sentence you can say aloud.
The drill (sections 08–11) is 150 interview questions. Some test knowledge of mechanisms, some are production scenarios you must diagnose in order, and some are design exercises with trade-offs. Every answer is collapsed behind a Reveal answer control.
The method that works is the one from Chapter E3: read the question, say your whole answer aloud as if the interviewer were in the room, and only then reveal it. If you skip the saying-aloud step, you are reading, not drilling.
Four neighbours matter. Chapter E7 covers sagas, idempotency keys and the outbox pattern, which this chapter uses without re-teaching from zero. The Distributed Systems primer holds the theory underneath (consensus, replication, ordering).
Chapter E4 covers the Spring Boot machinery every Java sample here assumes. Chapter E9 and Chapter E10 cover where Kafka and your services actually run.
Versions this chapter assumes
Facts in this chapter were checked in November 2026. Apache Kafka 4.0 (March 2025) removed ZooKeeper completely, so every cluster is now KRaft (Kafka's own Raft-based controller quorum). The latest release confirmed when this was written is Kafka 4.3.0, released 22 May 2026.
Spring for Apache Kafka 4.1 goes with Spring Boot 4.1, and in Spring Boot 4 you add the spring-boot-starter-kafka dependency explicitly. Code samples target Java 21 or newer.
Where a setting changed in a recent release, the text says so. Where a number is an example, the code block says "illustrative".
How every pattern in this chapter is laid out
Each design pattern gets its own heading, Pattern: Name, so you can find it again. Under that heading the steps come in the same order:
- The problem: what goes wrong without it, shown on the order and shipping example.
- How it works: numbered steps and a table of state changing over time.
- The setup: the smallest configuration or code.
- What you see: evidence without the pattern and with it, in the same layout.
- The trap: the classic way the pattern itself is misapplied.
- Interview takeaway: the sentence to say aloud.
Pattern map: every pattern in this chapter
Use this table as the index. Pick the problem you are looking at and follow the link.
| Pattern | Problem it solves | Section |
|---|---|---|
| Key-based partitioning | Events for one order land in different lanes and are read out of order. | 02 The log |
| Compacted topic | A topic that holds "latest state per key" would otherwise grow forever. | 02 The log |
| acks=all + min.insync.replicas | One broker dies and acknowledged records vanish with it. | 02 The log |
| Idempotent producer | A producer retry after a lost acknowledgement writes the record twice. | 03 Producers |
| Batch and compress | One tiny request per record wastes the network and the brokers. | 03 Producers |
| Commit after process | Auto-commit tells Kafka "done" before the work is done, so crashes lose events. | 04 Consumers |
| Incremental rebalancing | Every deploy pauses every consumer in the group. | 04 Consumers |
| Static membership | A quick restart triggers a full rebalance twice. | 04 Consumers |
| Queue semantics with share groups | You want job-queue behaviour, not one worker per lane. | 04 Consumers |
| Idempotent consumer | At-least-once delivery applies the same event's effect twice. | 05 Delivery guarantees |
| Consume-transform-produce transaction | Read, compute and write back must succeed or fail as one unit inside Kafka. | 05 Delivery guarantees |
| Non-blocking retry topics | One failing record blocks every record behind it in its lane. | 05 Delivery guarantees |
| Dead-letter topic | A poison record is retried forever or silently dropped. | 05 Delivery guarantees |
| Outbox via CDC | Saving to the database and publishing to Kafka can fail separately. | 05 Delivery guarantees |
| Schema evolution with a registry | Changing an event's shape breaks consumers you cannot see. | 06 Ecosystem |
| Event-carried state transfer | Every service calls the owner just to read a copy of its data. | 06 Ecosystem |
| Change data capture with Connect | Moving rows between systems with hand-written polling code. | 06 Ecosystem |
| Partition sizing | Too few partitions cap throughput; too many cost memory and recovery time. | 07 Production |
| Alert on consumer lag | Consumers fall behind silently until users notice. | 07 Production |
| Pause/resume backpressure | A slow downstream makes the consumer miss its poll deadline. | 07 Production |
02 · The logThe Log — Records, Partitions, Offsets, Replicas, and What Kafka Actually Stores
A Kafka topic is a set of append-only files called partitions. Each record gets a permanent position number, the offset. Reading never deletes, copies on other brokers protect against loss, and old data leaves by age, by size, or by compaction.
Here is an incident that teaches what "the log" means. An analytics team runs a consumer that reads the orders topic once a night and builds a sales report. Over a holiday the consumer's server is switched off for nine days, and nobody notices because the report is only read on Mondays.
The topic uses Kafka's default retention, which is seven days. When the server comes back, the consumer asks Kafka for "my place", which is offset 1,204,500. That record was deleted two days ago.
The consumer's setting auto.offset.reset is at its default, latest, so Kafka answers "start from the newest record". The consumer happily continues from today. Two days of orders are missing from every report, and there is no error message anywhere.
If you think of Kafka as a queue, this is baffling: where did the messages go? If you think of it as a log with a retention clock, it is obvious. The records were never "consumed". They were simply old enough to delete, and the reader was not there in time.
Make the invisible visible: the same partition on three days, and where the nine-day-late reader's offset points.
# illustrative numbers: retention.ms = 7 days, about 150,000 records per day in this partition
day 0 (reader switched off) offsets 1,054,500 ......... 1,204,500 reader's committed offset: 1,204,500
day 7 offsets 1,204,500 ......... 2,254,500 oldest record is still 1,204,500 ✓ reader could resume
day 9 (reader returns) offsets 1,504,500 ......... 2,554,500 oldest record is now 1,504,500
^ reader asks for 1,204,500: "offset out of range"
auto.offset.reset=latest -> jumps to 2,554,500, skips 1,350,000 records ✗ silent gapWhat you see: the consumer's own log line, easy to miss in a busy log file.
# illustrative output
INFO Fetch position FetchPosition{offset=1204500} is out of range for partition orders-2, resetting offset
INFO Resetting offset for partition orders-2 to position FetchPosition{offset=2554500} (reset strategy: latest)Why: Kafka keeps records by time or size, not by whether anyone has read them, and the reader's position is only a number that can point at something already deleted.
The fix: choose the reset strategy on purpose, and alert when a consumer is further behind than a fraction of the retention.
# ✅ fail loudly instead of silently skipping: the consumer throws and an operator decides
auto.offset.reset=none
# or, for a job that must never skip data and can reprocess:
# auto.offset.reset=earliestBridge: what a log is, one level down
Start with the plainest picture. A log here means a file that you only ever add to at the end, like a ship's logbook. You never edit an old line and you never insert a line in the middle.
Each line gets a number the moment it is written: 0, 1, 2, 3, and so on. That number is the line's offset. An offset is never reused, even after old lines are thrown away, so "line 1,204,500" always means the same line or nothing.
A record is one line. It has a key (optional, used to choose a lane), a value (your payload, usually JSON, Avro or Protobuf bytes), a timestamp, and optional headers (small labelled extras, such as a trace id).
A topic is a named stream, such as orders. One file would be a bottleneck, so a topic is split into partitions. Each partition is its own log with its own offsets starting at 0.
That last sentence matters in interviews. Offset 5 in partition 0 and offset 5 in partition 1 are unrelated records. The full address of a record is topic, partition, offset.
A broker is one Kafka server. A cluster has several brokers, and the partitions of a topic are spread across them, so no single machine holds or serves the whole topic.
Notice two consequences. First, two readers can read the same partition at different speeds and neither affects the other. Second, "replaying history" is nothing special: you move your number back.
Make the invisible visible: what actually sits on a broker's disk for one partition.
# illustrative output: ls -l /var/lib/kafka/data/orders-2/
00000000000001054500.log 1.0 GiB <- segment: records from offset 1,054,500 up to the next file's name
00000000000001054500.index 9.8 MiB <- offset -> byte position in the .log file
00000000000001054500.timeindex 14 MiB <- timestamp -> offset
00000000000001204500.log 1.0 GiB
00000000000001354500.log 312 MiB <- the ACTIVE segment: the only file still being appended to
leader-epoch-checkpointA partition is stored as a list of files called segments. The name of each file is the offset of its first record. Only the newest segment (the active one) is written to. Once it reaches about 1 GiB (log.segment.bytes) or a time limit, Kafka closes it and starts a new one.
This is why Kafka is fast. Writing is always at the end of a file, which disks and the operating system's page cache handle very well. Reading a recent record usually hits memory. Deleting old data means deleting a whole file, not rewriting anything.
Partitions and keys: where does a record go?
When a producer sends a record, someone must pick the partition. If the record has a key, the default rule is: hash the key bytes with an algorithm called murmur2, then take the result modulo the partition count.
"Modulo" just means the remainder after division. With three partitions, a hash of 17 gives 17 mod 3 = 2, so partition 2. The same key always gives the same hash, so the same key always goes to the same partition.
If the record has no key (null), the producer spreads records across partitions in batches, to keep batches full. In older versions this was round-robin per record. Since Kafka 3.3 the built-in behaviour is sticky: fill one batch for one partition, then move to another.
Here is the fact the Tuesday incident violated. Kafka guarantees order only inside one partition. Two records with the same key are in the same partition, so they are in order. Two records with different keys may be anywhere and have no order between them.
Pattern: Key-based partitioning
The problem: events that belong together (all events of one order, one account, one device) end up in different partitions, so consumers see them in the wrong order or two consumers update the same thing at once.
How it works: choose the entity whose events must stay in order, and use its id as the record key. The default partitioner hashes the key, so that entity always maps to one partition.
- Pick the key: ask "what must be in order with what?". For order events the answer is the order id. For account balances it is the account id.
- Send with the key: every producer of that topic sets the same key in the same format. A key of
"o-123"and a key of"O-123"hash differently. - One reader per partition: inside a consumer group each partition has one owner at a time, so one consumer sees the entity's events in order.
# illustrative numbers: topic orders has 3 partitions; hash values are made up to show the arithmetic
key murmur2(key) hash mod 3 partition
o-123 1,431,655,765 1 1
o-456 2,863,311,530 2 2
o-789 715,827,882 0 0
o-123 again: same hash, same remainder -> partition 1 every time ✓
# danger: add a partition (3 -> 4) and the same hashes give new remainders
o-123 1,431,655,765 mod 4 = 1 (lucky, same) o-456 2,863,311,530 mod 4 = 2 (same)
o-789 715,827,882 mod 4 = 2 <- moved from partition 0 to 2: old events in 0, new events in 2 ✗The setup: create the topic, then send keyed records. The first command creates six partitions with three copies of each.
bin/kafka-topics.sh --bootstrap-server localhost:9092 \
--create --topic orders --partitions 6 --replication-factor 3 \
--config min.insync.replicas=2
bin/kafka-topics.sh --bootstrap-server localhost:9092 --describe --topic orders// Plain Kafka client; Spring's KafkaTemplate version is in section 06.
ProducerRecord<String, String> rec =
new ProducerRecord<>("orders", order.id(), toJson(order)); // ✅ key = order id
producer.send(rec, (meta, ex) -> {
if (ex != null) log.error("send failed for {}", order.id(), ex);
else log.info("sent {} to partition {} offset {}", order.id(), meta.partition(), meta.offset());
});What you see: the same three events, without and with a key.
# illustrative output
sent o-123 Created -> partition 4 offset 90
sent o-123 Paid -> partition 1 offset 77 consumer on partition 1 sends the "paid" email
sent o-123 Shipped -> partition 4 offset 91 consumer on partition 4 sends "shipped" first ✗ wrong order# illustrative output
sent o-123 Created -> partition 1 offset 77
sent o-123 Paid -> partition 1 offset 78
sent o-123 Shipped -> partition 1 offset 79 one consumer, one lane, in order ✓The trap: the partition count is part of the address. Add partitions to a live keyed topic and the same key may start landing in a different partition, so old and new events for one key are read by different consumers with no order between them. A second trap is a skewed key: if one customer produces half your traffic, one partition gets half the load (a hot partition).
- Works: per-entity ordering (orders, accounts, devices), per-key state in a consumer (counts, balances), compacted topics.
- Fails: keys with very uneven traffic, or when you need total order across all events (use one partition, and accept the throughput limit).
- Interview takeaway: "Kafka orders records only within a partition, and the key picks the partition, so I key every event by the entity whose history must stay in order, and I choose the partition count up front because changing it moves keys."
Retention and compaction: how old data leaves
A log that only grows would fill any disk, so Kafka removes old data by a rule called the cleanup policy. There are two, set per topic with cleanup.policy.
delete (the default) drops whole old segments once they are older than retention.ms (default seven days) or the partition is bigger than retention.bytes (default unlimited). It is the right choice for events: "an order was placed" is a fact about a moment.
compact keeps at least the most recent record for every key and removes older records with the same key. It is the right choice for state: "the current address of customer 7". A record with a key and a null value is a tombstone, a delete marker: after a grace period (delete.retention.ms, default 24 hours) Kafka removes the key completely.
You can combine both with cleanup.policy=compact,delete, which compacts and also deletes anything older than the retention time.
| Option | Pick it when | Cost or catch |
|---|---|---|
delete (default) | Records are events: orders placed, clicks, payments. Readers care about the history within a time window. | Late readers lose data (the nine-day incident). Disk use grows with traffic times retention. |
compact | Records are the latest state per key: customer profile, product price, config. New readers rebuild the full table by reading the topic. | History per key is gone. Old values for a key can still be read until the cleaner runs. Needs a non-null key on every record. |
compact,delete | You want the latest state per key but also a hard age limit (for privacy rules, for example). | Keys silent for longer than the retention vanish even though they were the latest value. |
| Very long retention plus tiered storage | You want to replay months of events and not pay broker-disk prices for them. | Old reads are slower and cost remote-storage requests. See the tiered storage note below. |
Pattern: Compacted topic
The problem: you publish "customer 7 changed address" every time it changes. After a year the topic holds millions of old addresses, and a new service that wants the current address of every customer must read all of them.
How it works: mark the topic cleanup.policy=compact. A background cleaner thread rewrites old segments, keeping only the latest record for each key. The newest segment (the active one) is never touched, so the topic always has a recent tail of full history.
- Write with a key: the key is the entity id (customer 7). The value is the whole new state, not a diff.
- Cleaner runs: when the "dirty" part of the log (records not yet cleaned) passes
min.cleanable.dirty.ratio(default 0.5), the cleaner copies the log keeping only the newest record per key. - Delete with a tombstone: send the key with a null value. Readers see the delete, and after
delete.retention.msthe key disappears. - Rebuild by reading: a new consumer reads from offset 0 and ends up with exactly one row per live key.
# illustrative output: topic customer-address, cleanup.policy=compact
before cleaning after cleaning
offset key value offset key value
0 c-7 "12 Oak St" 3 c-9 "4 Elm Rd"
1 c-9 "4 Elm Rd" 4 c-7 "9 Pine Ave" <- latest for c-7
2 c-7 "40 Main St" 5 c-9 null (tombstone) <- kept for delete.retention.ms, then removed
3 c-9 "4 Elm Rd" (dup of 1) (offsets 0, 1, 2 are gone; offsets never renumber)
4 c-7 "9 Pine Ave"
5 c-9 nullThe setup: create the topic with compaction, and shorten the cleaner's patience if you need faster cleaning for tests.
bin/kafka-topics.sh --bootstrap-server localhost:9092 --create --topic customer-address \
--partitions 6 --replication-factor 3 \
--config cleanup.policy=compact \
--config min.cleanable.dirty.ratio=0.5 \
--config delete.retention.ms=86400000What you see: a new service starts up and builds its table, without and with compaction.
# illustrative numbers
customer-address topic: 400,000 customers, 180 changes each over the retention window = 72,000,000 records
new service rebuilds its table: reads 72,000,000 records, keeps 400,000 ✗ slow start, mostly wasted reads# illustrative numbers
compacted topic: about 400,000 records plus a recent uncompacted tail
new service rebuilds its table: reads about 400,000 records plus the tail ✓The trap: compaction is not instant and not exact. Readers who are caught up still see every record, including old values, because the cleaner only works on closed segments. A compacted topic is also not a database: you cannot look up one key without reading, so a consumer builds its own table (see KTable in section 06).
- Works: latest-state topics (profiles, prices, feature flags), Kafka's own
__consumer_offsetstopic, changelog topics for stream processing. - Fails: event history you need to audit, records without keys (the broker rejects a null key on a compacted topic), anything where "the sequence of changes" is the data.
- Interview takeaway: "A compacted topic keeps the latest value per key, so it is a replayable table; a tombstone deletes a key; and compaction is eventual, so a caught-up reader still sees old values."
Replication: how a partition survives a dead broker
One copy of a partition on one broker is one disk failure from gone. So every partition is stored as several copies called replicas, each on a different broker. The number of copies is the replication factor; three is the normal production choice.
One replica is the leader. All writes and (by default) all reads for that partition go to the leader. The others are followers: they keep fetching from the leader and appending the same records in the same order.
The ISR (in-sync replicas) is the list of replicas that are fully caught up with the leader, the leader itself included. A follower that falls too far behind (by default, silent for more than replica.lag.time.max.ms, 30 seconds) is dropped from the ISR and added back when it catches up.
The high watermark is the highest offset that every ISR member has copied. Consumers can only read up to the high watermark, which guarantees they never see a record that could still be lost if the leader died.
When a broker dies, the controller (see below) picks a new leader from the ISR for every partition the dead broker led. Because ISR members have every acknowledged record, no acknowledged data is lost, as long as you asked for the right acknowledgement level. That condition is the next pattern.
Pattern: acks=all + min.insync.replicas
The problem: a producer with acks=1 gets "success" as soon as the leader writes the record. If the leader dies before a follower copies it, the new leader does not have the record. The producer was told it was safe and it was not.
How it works: with acks=all the leader waits until every replica in the current ISR has the record before it acknowledges. min.insync.replicas is the minimum ISR size that is allowed to accept a write at all. If the ISR shrinks below it, writes fail loudly instead of quietly running with fewer copies.
- Set replication factor 3: three copies, each on a different broker (or rack).
- Set
min.insync.replicas=2: a write needs the leader plus at least one follower. - Producer uses
acks=all: this is the default since Kafka 3.0, so you mostly need to avoid overriding it. - Leave
unclean.leader.election.enable=false: this is the default. It forbids electing a replica that is not in the ISR, even if the cluster has no other candidate.
# replication factor 3
acks min.insync.replicas one broker dies two brokers die
1 1 records only on the leader are lost ✗ lost, and partition may go offline ✗
all 1 no loss, writes continue ✓ ISR can shrink to 1: one copy, then a crash loses data ✗
all 2 no loss, writes continue ✓ writes REJECTED (NotEnoughReplicas); no data lost ✓ (availability traded for safety)The setup: the topic setting and the producer setting side by side.
# topic level (set at creation or with kafka-configs.sh)
min.insync.replicas=2
unclean.leader.election.enable=false
# producer level
acks=all
enable.idempotence=true
delivery.timeout.ms=120000What you see: broker 1 (the leader) crashes just after a send, without and with the pattern.
# illustrative output
producer: send o-500 -> ack from leader (broker 1) offset 8 "success"
broker 1 crashes before broker 2 fetched offset 8
broker 2 becomes leader with offsets 0..7 only; next write reuses offset 8 for another record
consumer: never sees o-500 ✗ acknowledged record lost# illustrative output
producer: send o-500 -> waits until broker 2 also has offset 8 -> ack "success" means two copies exist
broker 1 crashes
broker 2 (in the ISR) becomes leader, has offsets 0..8
consumer: sees o-500 ✓The trap: min.insync.replicas equal to the replication factor (3 of 3) makes every single broker restart a write outage, because the ISR drops to 2 during the restart. The usual safe pair is factor 3 with minimum 2. The other trap: an old tutorial that sets acks=1 for speed and a later reader who copies it.
- Works: any topic where an acknowledged record must survive a broker loss: orders, payments, audit.
- Fails: a two-broker cluster (you cannot have factor 3), or metrics topics where losing a few samples is fine and latency matters more.
- Interview takeaway: "Replication factor 3, min in-sync replicas 2, acks=all: an acknowledged write exists on at least two brokers, and when only one is left Kafka refuses writes rather than pretending."
Who runs the cluster: KRaft controllers and tiered storage
Someone must decide which broker leads which partition, track which brokers are alive, and store topic settings. Before Kafka 4.0 that was an external program called ZooKeeper. Since 4.0 ZooKeeper is gone and Kafka does this itself, in a mode called KRaft.
In KRaft a small group of nodes, the controller quorum (usually three, sometimes five), keeps the cluster's metadata in an internal log called __cluster_metadata. The quorum uses the Raft consensus algorithm: one controller is the active leader, the others copy its log, and a majority must agree on every change. Three controllers survive one failure; five survive two.
A node can have the broker role, the controller role, or both (process.roles). Small clusters and test setups often combine them. Larger production clusters usually run dedicated controllers so heavy broker traffic cannot starve cluster decisions.
process.roles=controller
node.id=1
controller.quorum.voters=1@ctrl1:9093,2@ctrl2:9093,3@ctrl3:9093
controller.listener.names=CONTROLLER
listeners=CONTROLLER://:9093One more feature belongs here. Tiered storage (generally available since Kafka 3.9) keeps recent segments on broker disks and moves older closed segments to cheap remote storage such as an object store. Consumers read old data transparently; brokers stay small and recover faster because they hold less.
It is enabled per cluster with remote.log.storage.system.enable=true plus a remote storage plugin, and per topic with remote.storage.enable=true. You then choose how long data stays on local disk (local.retention.ms) versus the total retention. Reads of old data are slower than local reads and cost remote requests, so use it for long replay windows, not for hot data.
| Option | Pick it when | Cost or catch |
|---|---|---|
| Short retention on broker disk | Consumers are always close to the head and you reprocess rarely. | A late or new consumer cannot replay; keep a second copy elsewhere if you need history. |
| Long retention on broker disk | Moderate volume, replay needed, simplest to run. | Disk cost grows with retention; broker recovery copies more data. |
| Tiered storage | Large volume, weeks to months of replay, you want small brokers. | More moving parts (plugin, object store); slower reads of old records. |
| Sink to a data lake (Kafka Connect) | Analytics and long-term audit by other tools. | Replay then means re-publishing from the lake, not reading the topic. |
That completes the storage picture: records in ordered partitions, copied to replicas, led by a broker chosen by the controller quorum, and removed by age, size, or compaction. The next section is about the programs that write into it.
03 · ProducersProducers — Keys, Batches, Acknowledgements, and Retries That Do Not Duplicate
A producer does not send one record at a time. It groups records into batches per partition, waits briefly to fill them, and retries on failure. The settings that matter are the key, the batch and wait size, the acknowledgement level, and the idempotence switch that makes retries safe.
Here is an incident from a payments team. Their service sends a PaymentCaptured event to Kafka for every card payment. One night a broker is restarted for patching, and for about four seconds the leader of a partition is unavailable.
The producer sends a batch, and the broker writes it, but the acknowledgement is lost on the way back because the connection drops. The producer sees a timeout and does what a good client does: it retries.
The broker receives the same batch a second time and, having no way to know it is a repeat, appends it again. Downstream, the ledger service books 140 payments twice. Finance finds it three days later.
This is the same lost-reply problem as in Chapter E7: from the sender's side, "the write failed" and "the write worked but the reply was lost" look identical. Kafka's answer is built into the producer, and since Kafka 3.0 it is switched on by default.
Make the invisible visible: the broker's partition log during the retry, with idempotence off.
# illustrative output: partition payments-3, enable.idempotence=false
t producer broker log
1 send batch [pay-1, pay-2] offset 500 pay-1, offset 501 pay-2 (written)
2 ack lost (connection reset)
3 timeout -> retry batch [pay-1, pay-2] offset 502 pay-1, offset 503 pay-2 ✗ duplicates, nothing to say "seen before"Why: the broker only appends. Without an identity on each batch it has no way to tell a repeat from a new batch that looks the same.
Bridge: what happens between send() and the broker
Calling producer.send(record) does not touch the network. It returns immediately, and the record goes through four steps inside the client.
- Serialize: key and value are turned into bytes.
- Choose the partition: the key hash from the last section, or the sticky rule for null keys.
- Accumulate: the record is added to a batch held in memory for that partition. A batch is closed when it is full (
batch.size, default 16 KB) or has waited long enough (linger.ms, default 5 ms since Kafka 4.0, previously 0). - Send: a background sender thread picks closed batches and sends them, one request per broker, containing batches for all partitions that broker leads. The reply, or an error, completes the callback you passed to
send.
Two consequences surprise people. First, send() succeeding means "queued", not "stored", so you must check the callback or the returned future. Second, if the buffer fills (a slow broker, a burst), send() blocks for up to max.block.ms (default 60 s) and then throws.
Pattern: Batch and compress
The problem: a producer that sends each record in its own request spends most of its time on network round trips and request overhead. At 20,000 small records a second, brokers and the network are busy with headers, not data.
How it works: let records pile up for a few milliseconds, send them as one batch, and compress the whole batch. Compression works better on a batch than on single records because repeated field names and values compress well together.
- Wait a little:
linger.msis how long a batch may wait for more records. A few milliseconds is a cheap trade for far fewer requests. - Allow room:
batch.sizeis the target batch size in bytes. Raise it from 16 KB to 64 KB or more if records are small and traffic is high. - Compress:
compression.typeis one ofnone,gzip,snappy,lz4,zstd. The batch is stored compressed on the broker and decompressed by the consumer. - Measure: watch the producer metrics
batch-size-avg,records-per-request-avgandcompression-rate-avg.
# illustrative numbers: 20,000 records/s, 500 bytes each, 6 partitions on 3 brokers
no batching (1 record per request): 20,000 requests/s, about 10 MB/s of data
linger.ms=5, batches of about 100 records: 20,000 / 100 = 200 requests/s (100x fewer)
with compression.type=lz4, typical JSON shrinks to roughly a third: about 3.3 MB/s on the wire (ratio depends on your data)| Option | Pick it when | Cost or catch |
|---|---|---|
none | Payloads are already compressed (images, encrypted data) or tiny. | Most network and disk use. |
lz4 or snappy | You want a cheap, fast default with low CPU. | Smaller savings than zstd. |
zstd | Network or disk is the bottleneck and you can spend some CPU. | More CPU on producer and consumer. |
gzip | Compatibility with old tooling. | Slowest and heaviest CPU of the set. |
The setup: producer properties for a high-volume, latency-tolerant topic.
bootstrap.servers=broker1:9092,broker2:9092
key.serializer=org.apache.kafka.common.serialization.StringSerializer
value.serializer=org.apache.kafka.common.serialization.StringSerializer
linger.ms=10
batch.size=65536
compression.type=zstd
acks=all
enable.idempotence=trueWhat you see: producer metrics before and after tuning.
# illustrative output (producer metrics)
record-send-rate 20000/s
request-rate 9400/s <- nearly one request per two records
records-per-request-avg 2.1
compression-rate-avg 1.00 ✗ nothing saved# illustrative output (producer metrics)
record-send-rate 20000/s
request-rate 180/s
records-per-request-avg 110
compression-rate-avg 0.31 ✓ batches are 31 percent of original size
# the cost: each record waits up to 10 ms before it is sentThe trap: batching adds latency, and the latency is exactly linger.ms when traffic is low. For a request-reply style flow that needs a 2 ms answer, a high linger.ms is a bug. The other trap is a huge batch.size with a per-partition buffer: with 2,000 partitions, memory use is partitions times batch size.
- Works: event streams, logs, metrics, any steady high volume.
- Fails: a path where every record's end-to-end latency must be under a few milliseconds, or where the data is already compressed.
- Interview takeaway: "Producers batch per partition. linger.ms and batch.size trade a few milliseconds for far fewer requests, and compression is applied per batch, so I tune them together and watch records-per-request."
Acknowledgements, retries and ordering
acks says how many brokers must have the record before the producer counts it a success. acks=0 means "do not wait" (fire and forget). acks=1 means the leader alone. acks=all means the whole ISR, which is the default since Kafka 3.0 and was covered in the replication pattern.
Retries are on by default (retries is effectively unlimited), but bounded in time by delivery.timeout.ms (default 2 minutes): the total time from send() to final success or failure. request.timeout.ms (default 30 s) limits one attempt.
Now the ordering problem. The producer may have up to max.in.flight.requests.per.connection requests (default 5) on the wire to one broker. Suppose batch 1 fails and batch 2 succeeds, then batch 1 is retried: batch 1 now lands after batch 2, and the order inside the partition is swapped.
# illustrative output
send batch A (Created o-1) -> request 1 in flight
send batch B (Paid o-1) -> request 2 in flight
request 1 fails (transient error) request 2 succeeds -> log: offset 40 = Paid
request 1 retried and succeeds -> log: offset 41 = Created ✗ Paid before CreatedThe old advice was to set max.in.flight.requests.per.connection=1, which is correct but slow. The modern answer is the idempotent producer, which keeps order with up to 5 requests in flight.
Pattern: Idempotent producer
The problem: retries cause duplicates (the payment incident) and reordering (the swapped batches). You need retries for reliability, but plain retries are unsafe.
How it works: with enable.idempotence=true the broker gives the producer a producer id (PID) at startup. The producer numbers every record per partition with a sequence number. The broker remembers the last sequence numbers it accepted for each PID and partition, and uses them to spot repeats and gaps.
- Get an identity: at startup the producer asks a broker for a PID.
- Number the records: each batch to a partition carries the PID and the first sequence number; the next batch continues the count.
- Broker checks: the next expected number is accepted. A number it has already seen is acknowledged but not appended again. A number that skips ahead is rejected (
OutOfOrderSequenceException), which preserves order. - Retry freely: retries carry the same numbers, so they are recognised. The broker keeps metadata for the last five batches per PID and partition, which is why 5 in-flight requests are allowed.
# illustrative output: broker state for PID 77, partition payments-3
incoming batch (seq) last accepted seq decision
0..1 (none) accept, last = 1
0..1 (retry) 1 duplicate: ack, do not append ✓
2..3 1 next expected is 2: accept, last = 3
5..6 3 gap (expected 4): reject OutOfOrderSequence ✓ order preservedThe setup: on a modern client this is already the default. Writing it down still matters for readers of the config and for older clients.
enable.idempotence=true # default since Kafka 3.0
acks=all # required with idempotence
max.in.flight.requests.per.connection=5 # allowed, and order is still preserved
retries=2147483647 # default; bounded by delivery.timeout.msWhat you see: the same lost-acknowledgement night, without and with idempotence.
# illustrative output
broker log: offset 500 pay-1, 501 pay-2, 502 pay-1, 503 pay-2 ✗ ledger books both# illustrative output
broker log: offset 500 pay-1, 501 pay-2 ✓ retry recognised, one copyThe trap: idempotence only covers retries by the same producer instance within one session. If the application itself resends (a crash and restart gives a new PID, or your code calls send twice for one business event), Kafka cannot know they are the same. Duplicates caused by your own restart need an idempotent consumer or a transaction with a stable transactional.id (section 05).
- Works: automatic retries after network errors and leader changes, with order kept per partition.
- Fails: application-level resends, duplicates across producer restarts, and anything beyond a single partition's guarantee.
- Interview takeaway: "The idempotent producer stamps each batch with a producer id and a sequence number so the broker can drop retries; it is the default, it keeps order with five requests in flight, and it does not protect me from my own restart."
Hot partitions and choosing a key
Keys give order, but they also concentrate load. A hot partition is one that receives far more traffic than the others, so one broker and one consumer are overloaded while the rest idle.
Imagine keying by customerId in a marketplace where one wholesale customer produces 60 percent of the events. Partition math makes the problem visible.
# illustrative numbers: 6 partitions, 10,000 events/s total, key = customerId
partition events/s share
0 600 6%
1 700 7%
2 6,400 64% <- the wholesale customer's key hashes here ✗ hot
3 800 8%
4 700 7%
5 800 8%
# one consumer must read 6,400 events/s alone; adding consumers does not help, a partition has one ownerThere are three honest ways out. Pick a finer key (order id instead of customer id) if you only need order per order. Add a salt to the key (customerId + "-" + (n mod 8)) if you can accept order per salted key. Or accept the skew and give that partition's consumer more capacity.
| Option | Pick it when | Cost or catch |
|---|---|---|
| Entity id (order id) | You need order per entity and traffic per entity is similar. | A very busy entity makes a hot partition. |
| Parent id (customer id) | You need order across all of a customer's events. | Skew if customers differ greatly in size. |
| Salted key | One key is too busy and per-key order can be relaxed to per-salt order. | Consumers must merge across salts; order across salts is lost. |
| No key (null) | No ordering needed and you want even spread. | No per-entity order, no compaction. |
The producer is now covered: records are keyed, batched, acknowledged by the right number of replicas, and retried without duplicates. What is left is the other half, the programs that read.
04 · Consumers & groupsConsumers and Groups — Polling, Offsets, Rebalances, and Lag
A consumer polls for records, processes them, and tells Kafka how far it got by committing an offset. Consumers that share a job form a group, and Kafka splits the partitions among them. Most production pain lives in two places: when you commit, and when membership changes.
Here is an incident from a shipping team. Their consumer reads orders, and for each order calls a slow warehouse API that takes about 400 ms. The consumer reads up to 500 records per poll, so a full batch takes 200 seconds to process.
One day the warehouse API slows down to 1.2 seconds per call. A batch of 500 now takes 600 seconds, which is longer than max.poll.interval.ms (default 5 minutes, 300 seconds). Kafka decides the consumer is stuck and removes it from the group.
The group reassigns its partitions to another consumer, which starts from the last commit and reprocesses the same orders. The first consumer finishes its batch, tries to commit, and is told it is no longer a member. Orders are processed twice.
Worse, the second consumer hits the same slow API, also times out, and is also removed. The partitions bounce between consumers all afternoon, with every bounce repeating work. Lag climbs to 2 million records, and nothing is "down".
Make the invisible visible: the timeline of one batch that outlives its deadline.
# illustrative numbers: max.poll.interval.ms = 300,000 (5 min), max.poll.records = 500, 1.2 s per record
t = 0 s consumer A polls: gets offsets 9000..9499 (500 records)
t = 300 s A has processed 250 records; no new poll() yet -> coordinator removes A from the group ✗
t = 301 s partitions reassigned to B; B starts at the last committed offset 9000, re-processes 9000..9249
t = 600 s A finishes 9499, calls commit -> CommitFailedException (A is not a member any more)
result records 9000..9249 were processed twice; the commit for 9000..9499 was thrown awayWhy: a consumer proves it is alive by calling poll() regularly. Processing time between two polls has a hard limit, and when you exceed it Kafka assumes the consumer is dead and hands its work to someone else.
The fix: make the work between polls small enough to fit with a wide margin, or move the slow work off the polling thread (and pause the partitions meanwhile, see the backpressure pattern in section 07).
# ✅ budget: 20 records x 1.2 s = 24 s per poll, far below the 300 s limit
max.poll.records=20
max.poll.interval.ms=300000Bridge: the poll loop, one level down
A Kafka consumer is a loop. It asks the broker for new records, processes them, and repeats. The asking is the poll() call. Nothing is pushed to you; you pull, which is why a slow consumer never overwhelms itself.
Behind poll() a background thread sends heartbeats to the group coordinator every heartbeat.interval.ms (3 s). If the coordinator hears no heartbeat for session.timeout.ms (45 s default), the member is considered dead. Separately, if poll() is not called within max.poll.interval.ms, the consumer leaves the group on purpose. Two clocks, two kinds of failure: a dead process (heartbeats stop) and a stuck process (heartbeats continue, polls stop).
The group coordinator is a broker that manages one group: it tracks members, collects heartbeats and stores the group's committed offsets. It is simply the broker that leads the partition of the internal __consumer_offsets topic that the group id hashes to.
// piece 1: configuration
Properties p = new Properties();
p.put("bootstrap.servers", "broker1:9092");
p.put("group.id", "shipping"); // consumers with the same group.id share the work
p.put("key.deserializer", StringDeserializer.class.getName());
p.put("value.deserializer", StringDeserializer.class.getName());
p.put("enable.auto.commit", "false"); // we will commit ourselves
p.put("auto.offset.reset", "earliest"); // only used when the group has no committed offset
// piece 2: subscribe, then loop
try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(p)) {
consumer.subscribe(List.of("orders"));
while (true) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(500));
for (ConsumerRecord<String, String> r : records) {
ship(r.key(), r.value()); // the work
}
consumer.commitSync(); // piece 3: report progress AFTER the work
}
}Consumer groups: sharing the lanes
A consumer group is a set of consumers with the same group.id that together read a topic. Kafka gives each partition to exactly one member of the group at a time, so no two members read the same lane and each record is processed by one member.
With six partitions and three consumers, each gets two. With six partitions and six consumers, each gets one. With six partitions and ten consumers, four sit idle. The partition count is the ceiling on parallelism within one group.
Different groups are independent. The shipping group and the analytics group each get every record and keep their own offsets. This is the key difference from a queue, where a message goes to one worker in total.
The step that decides who owns what is the assignment. In the classic protocol, one member (the group leader) runs an assignor and sends the result to the coordinator. The assignors you will meet: RangeAssignor (contiguous chunks per topic), RoundRobinAssignor, StickyAssignor and CooperativeStickyAssignor (keeps existing owners where possible, and moves only what must move).
# illustrative: group of 3 consumers, one topic with 6 partitions (RangeAssignor)
members sorted: S1, S2, S3 6 / 3 = 2 each
S1: p0 p1 S2: p2 p3 S3: p4 p5
# S3 leaves (crash) -> 6 / 2 = 3 each: S1: p0 p1 p2 S2: p3 p4 p5
# group of 10 consumers on 6 partitions: 6 get one partition, 4 get nothing (idle but ready as standbys)Offsets and commits: reporting progress
A committed offset is the group's saved bookmark: "for partition 3, the next record I want is 812". It is stored in the internal __consumer_offsets topic. After a restart or a rebalance, the new owner of the partition starts reading at the committed offset.
The committed offset is the next record to read, so after processing offset 811 you commit 812. The client does this arithmetic for you in commitSync() (which commits the position of the last poll) but not if you commit specific offsets by hand: there you must add one.
Two modes. Auto-commit (enable.auto.commit=true, the default, every auto.commit.interval.ms = 5 s) commits on a timer inside poll(), whether or not you finished the work. Manual commit means you call commitSync() or commitAsync() when you choose.
This one choice produces the three delivery behaviours:
| Option | Pick it when | Cost or catch |
|---|---|---|
| Commit before processing (at-most-once) | Losing a record is acceptable and a duplicate is not (rare, e.g. sampled metrics). | A crash after the commit and before the work loses that work forever. |
| Commit after processing (at-least-once) | Almost everything. Losing an event is worse than seeing it twice. | A crash after the work and before the commit repeats it, so the work must be idempotent. |
| Auto-commit on a timer | Throwaway consumers and demos. | It can commit offsets for records you have not finished (loss), and can lag behind finished ones (duplicates). It is the Tuesday incident. |
| Commit offsets in the same transaction as the output | Consume-transform-produce entirely inside Kafka (section 05). | More setup; only covers Kafka writes. |
Pattern: Commit after process
The problem: auto-commit reports progress on a timer, so Kafka can believe records are done that are still in your hands. A crash then loses them, which is the 212 missing orders of the Tuesday incident.
How it works: turn auto-commit off, process the polled records fully, and only then commit. A crash can now cause a repeat, never a loss, and a repeat is handled by making the work idempotent.
- Disable auto-commit:
enable.auto.commit=false. - Process the whole batch: including any database write or call.
- Commit the next offsets:
commitSync()after the batch, or per record for tiny batches. - Make the work repeatable: use an idempotency key or a natural unique key so a replayed record changes nothing.
# illustrative output: partition 3, commit after process
moment last processed committed offset if the consumer dies now
1 poll returns 812..814 811 812 restart at 812: re-reads 812..814, nothing lost ✓
2 ship 812, 813 813 812 restart at 812: 812, 813 repeated (must be idempotent)
3 ship 814 814 812 restart at 812: all three repeated
4 commitSync (committed 815) 814 815 restart at 815: nothing repeated, nothing lost ✓The setup: the same loop as before with the commit placed after the work and a guard for rebalances. This commits the exact next offset for each partition.
while (true) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(500));
Map<TopicPartition, OffsetAndMetadata> done = new HashMap<>();
for (ConsumerRecord<String, String> r : records) {
shipIfNotAlreadyShipped(r.key(), r.value()); // ✅ idempotent by order id
done.put(new TopicPartition(r.topic(), r.partition()),
new OffsetAndMetadata(r.offset() + 1)); // next offset to read = offset + 1
}
if (!done.isEmpty()) consumer.commitSync(done); // ✅ commit AFTER the work
}What you see: a deploy kills the consumer, without and with the pattern.
# illustrative output
before kill: processed up to 811, committed 813 (timer fired early)
after restart: starts at 813 -> orders 812 and 813 never shipped ✗ lost# illustrative output
before kill: processed up to 813, committed 812
after restart: starts at 812 -> order 812, 813 handled again; idempotent guard sees them already shipped ✓ no loss, no double parcelThe trap: committing a whole batch after only some of it was processed (an early continue in the loop, or an exception swallowed in a catch), which turns "at-least-once" back into silent loss. Also: commitAsync without a retry plan can commit offsets out of order.
- Works: any consumer whose events must not be lost, with idempotent handling.
- Fails: work with external side effects that cannot be made idempotent (then you need a transaction or an outbox), and metrics where loss is fine.
- Interview takeaway: "I turn auto-commit off and commit after the work, so a crash repeats events instead of losing them, and I make the handler idempotent so a repeat is harmless."
Rebalances: when ownership changes
A rebalance is the group redistributing partitions among its members. It happens when a member joins (a new pod starts), leaves (a pod stops), is declared dead (heartbeats or polls stop), or when the topic's partition count changes.
In the oldest and still-default-for-many-clusters style, called eager rebalancing, every member gives up all its partitions, waits for the new plan, and then takes what it is given. During that pause nobody in the group reads anything. This is often called "stop the world".
A rolling deploy of 10 pods causes 10 or more such pauses in a row, each a few seconds to a minute depending on group size and how long each member takes to finish its current batch. That is the quiet cost behind "lag spikes on every release".
Make the invisible visible: one consumer joins a group of three, with eager rebalancing.
# illustrative numbers: 6 partitions, consumers S1 S2 S3 running, S4 starts
t=0 s S1: p0 p1 S2: p2 p3 S3: p4 p5 all reading
t=1 s S4 joins -> coordinator triggers rebalance
t=1 s S1, S2, S3 all REVOKE every partition nobody reads ✗
t=1..9 s members rejoin, leader computes plan, plan sent back (9 s pause in this example)
t=9 s S1: p0 p1 S2: p2 S3: p4 S4: p3 p5 reading again (most partitions went back to their old owner anyway)Pattern: Incremental rebalancing
The problem: every membership change pauses the whole group, so every rolling deploy and every autoscale event makes lag spike across all partitions.
How it works: with the cooperative protocol, members keep the partitions that are not moving. Only partitions that change owner are revoked, in a first round, and then handed to the new owner in a second round. The second kind of improvement is on the server side: KIP-848, covered below.
- Choose a cooperative assignor:
partition.assignment.strategy=CooperativeStickyAssignor. The default list since Kafka 3.0 is[RangeAssignor, CooperativeStickyAssignor], which starts with Range and therefore still rebalances eagerly until you remove Range. - Roll it out in two deploys: first add the cooperative assignor alongside the old one, then, when every member runs the new config, remove the old one. Mixing eager and cooperative members in one step is not allowed.
- Handle revocation: implement
ConsumerRebalanceListener.onPartitionsRevokedto commit what you finished for the partitions being taken away. - Or use the new protocol: on Kafka 4.0+ brokers and a client that supports it,
group.protocol=consumermoves assignment to the broker with no group-wide pause.
# illustrative: 6 partitions, S1 S2 S3 each own two, S4 joins (target: 2,2,1,1)
eager: revoke 6, reassign 6 (all six partitions stop, then restart)
cooperative: round 1: S1 and S2 each give up nothing; S3 gives up p5 and S2 gives up p3
round 2: p3 and p5 go to S4
moved: 2 of 6 partitions; reading continues on p0 p1 p2 p4 ✓The setup: the classic protocol configuration, and the new protocol alternative.
# option 1: classic protocol with cooperative assignment (deploy step 2, after everyone knows it)
partition.assignment.strategy=org.apache.kafka.clients.consumer.CooperativeStickyAssignor
# option 2: next-generation protocol (KIP-848), assignment done on the broker, GA in Kafka 4.0
group.protocol=consumer
# group.remote.assignor=uniform # broker-side assignor; "range" is the other built-in choiceWhat you see: consumer lag across a rolling deploy.
# illustrative numbers: 10 pods restarted one at a time, 3,000 records/s arriving
each restart: whole group paused about 20 s -> 3,000 x 20 = 60,000 records of extra lag, 10 times
group-wide lag peaks at 60,000, then drains ✗ visible on dashboards at every release# illustrative numbers: same deploy, cooperative
each restart: only the moving partitions pause (about 1/10 of the group), a couple of seconds
group-wide lag stays small and flat ✓The trap: a pod being killed still loses its partitions after session.timeout.ms if it does not leave cleanly, so ungraceful shutdowns (a SIGKILL) cause a delayed rebalance no matter what assignor you use. Close the consumer on shutdown (consumer.close(), or terminationGracePeriodSeconds long enough in Kubernetes). And do not flip protocols with a mixed group: classic and new-protocol members can coexist only if the group is migrated as documented.
- Works: large groups, frequent deploys, autoscaling, stateful consumers where reloading state is costly.
- Fails: a one-step switch in a live group using only eager members, or code that assumes all partitions are revoked on every rebalance.
- Interview takeaway: "Eager rebalancing stops the whole group on every change; cooperative or KIP-848 rebalancing moves only the partitions that must move, so deploys stop spiking lag."
Pattern: Static membership
The problem: a pod restarts in 10 seconds, but the group sees one member leave (rebalance) and one new member join (another rebalance). The partitions move twice for a restart that should have changed nothing.
How it works: give each consumer a stable identity with group.instance.id. If a member with that identity disappears and comes back within session.timeout.ms, the coordinator gives it the same partitions back and runs no rebalance.
- Assign a stable id: for example the Kubernetes StatefulSet pod name,
shipping-0,shipping-1. - Size the timeout to the restart:
session.timeout.msmust be longer than a normal restart, for example 60 seconds. - Accept the trade: a member that is really dead is noticed only after the timeout, so its partitions sit idle for that long.
# illustrative numbers: pod restarts in 12 s, session.timeout.ms = 60,000
dynamic membership: t=0 leave -> rebalance 1; t=12 rejoin as a new member -> rebalance 2 two group pauses ✗
static membership: t=0 pod stops (no leave sent); t=12 pod returns with same group.instance.id -> gets p2 p3 back, no rebalance ✓The setup: the configuration per pod.
spring:
kafka:
consumer:
group-id: shipping
properties:
group.instance.id: ${HOSTNAME} # stable per pod when run as a StatefulSet
session.timeout.ms: 60000What you see: broker log lines for a pod restart.
# illustrative output
group shipping: member removed (leave) -> rebalance generation 41
group shipping: new member joined -> rebalance generation 42 ✗ two rebalances# illustrative output
group shipping: static member shipping-1 rejoined within session timeout -> assignment unchanged ✓ no rebalanceThe trap: two live consumers with the same group.instance.id (a copy-pasted config) fence each other, and one fails with FencedInstanceIdException. In Kubernetes a plain Deployment gives pods random names, so the id is new on every restart and the pattern does nothing. Use a StatefulSet, or derive an ordinal.
- Works: stateful consumers, fast rolling restarts, StatefulSets.
- Fails: random pod names, or a timeout so long that real failures leave partitions idle for minutes.
- Interview takeaway: "Static membership gives a consumer a stable identity so a restart inside the session timeout is not a rebalance at all; the price is slower detection of a truly dead member."
Lag: the number that tells you the truth
Consumer lag for a partition is the log end offset (the offset the next new record will get) minus the group's committed offset. It is the number of records waiting to be processed. Total lag is the sum across partitions.
Lag is the single most useful health number for a consumer. A steady small lag is normal. A lag that grows means consumers are slower than producers, or are stuck, or are bouncing through rebalances.
bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group shipping
# illustrative output
GROUP TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG CONSUMER-ID
shipping orders 0 812,400 812,415 15 S1
shipping orders 1 811,990 812,004 14 S1
shipping orders 2 790,120 2,790,120 2000000 S2 <- stuck or slow ✗
shipping orders 3 812,001 812,020 19 S2Read the columns: partition 2's consumer is 2 million records behind while the others are 15 behind. That points at one slow or stuck consumer, or one hot key, and not at overall capacity. The fix for each is different, which is why you look at lag per partition and not only the total.
Share groups: queue behaviour on a Kafka topic
Everything so far assumes the rule "one partition has one owner in the group". That makes ordering simple but limits parallelism to the partition count, and one slow record blocks the lane behind it.
Apache Kafka 4.2 made share groups (KIP-932, "Queues for Kafka") production-ready. In a share group many consumers can read from the same partition at once, and each record is acknowledged individually, like a job queue. Per-record ordering inside the partition is not promised.
A consumer in a share group receives a record under a short lock. It then acknowledges it with one of three outcomes: ACCEPT (done), RELEASE (give it back so another consumer tries, counting a delivery attempt), or REJECT (permanently failed, do not redeliver). Since 4.2 a consumer can also RENEW the lock when a record takes longer than expected. A record that exceeds the delivery-attempt limit is archived instead of delivered forever.
Pattern: Queue semantics with share groups
The problem: you have a topic of jobs (send this email, resize this image) where jobs are independent, order does not matter, and some take much longer than others. A consumer group with six partitions caps you at six workers, and a slow job holds up every job behind it in its lane.
How it works: readers join a share group instead of a consumer group. The broker hands out individual records under a lock, tracks each record's state, and redelivers released or expired records up to a delivery limit.
- Fetch: a consumer asks for records and each one becomes "acquired" by that consumer, under a lock timeout.
- Process: the consumer does the work and then acknowledges each record, ACCEPT, RELEASE or REJECT.
- Redeliver: a released record, or one whose lock expired, goes back to the pool for another consumer, with its delivery count increased.
- Stop at the limit: after the maximum delivery count the record is archived, so a poison record cannot loop forever.
# illustrative output: one partition, three records, three consumers
record state moments
r1 available -> acquired by C1 -> ACCEPT done
r2 available -> acquired by C2 -> RELEASE (try later) -> available (delivery count 2) -> acquired by C3 -> ACCEPT
r3 available -> acquired by C1 -> REJECT (bad data) archived, never redelivered ✓
# if C2 had crashed instead of releasing r2: the lock expires, r2 returns to available automaticallyThe setup: the share consumer API (check the exact class and property names against the Kafka documentation for your version; the feature is new in 4.2).
Properties p = new Properties();
p.put("bootstrap.servers", "broker1:9092");
p.put("group.id", "email-workers"); // a SHARE group, created and tuned with kafka-configs.sh
p.put("key.deserializer", StringDeserializer.class.getName());
p.put("value.deserializer", StringDeserializer.class.getName());
try (KafkaShareConsumer<String, String> consumer = new KafkaShareConsumer<>(p)) {
consumer.subscribe(List.of("email-jobs"));
while (true) {
ConsumerRecords<String, String> batch = consumer.poll(Duration.ofSeconds(1));
for (ConsumerRecord<String, String> r : batch) {
try {
sendEmail(r.value());
consumer.acknowledge(r, AcknowledgeType.ACCEPT); // ✅ done
} catch (TemporaryException e) {
consumer.acknowledge(r, AcknowledgeType.RELEASE); // try again, maybe elsewhere
} catch (Exception e) {
consumer.acknowledge(r, AcknowledgeType.REJECT); // permanent: do not redeliver
}
}
consumer.commitSync(); // sends the acknowledgements
}
}What you see: twelve jobs, one of them slow, with six partitions and a consumer group versus a share group of 12 workers.
# illustrative numbers: 12 jobs, 1 s each, except job 5 takes 60 s; at most 6 workers busy
the lane holding job 5 is blocked for 60 s; the jobs queued behind it wait ✗
other lanes finish early and idle# illustrative numbers: same jobs, share group with 12 workers allowed
job 5 occupies one worker for 60 s; the other 11 jobs finish in about 1 s ✓The trap: share groups give up per-key ordering. If two events for the same order are processed by different workers at the same time, they can finish out of order. Use them for independent jobs, not for state changes that must apply in sequence. Also treat this as a newer feature: confirm defaults (lock time, delivery limit) and client availability in your Kafka version before relying on them.
- Works: independent jobs, uneven job duration, worker pools bigger than the partition count, per-record retry.
- Fails: anything needing per-key order, or stream processing that depends on partition ownership (state stores, Kafka Streams).
- Interview takeaway: "A consumer group gives ordering with parallelism capped by partitions; a share group gives queue behaviour with per-record acknowledgement and no order, so I pick by whether the work is a stream of state changes or a pile of independent jobs."
| Option | Pick it when | Cost or catch |
|---|---|---|
| Classic group, eager assignor | Small group, rare changes, you want the oldest and best-understood behaviour. | Whole-group pause on every change. |
| Classic group, cooperative-sticky | Older brokers or clients, you want fewer pauses. | Two-step rollout; assignment still done by a client-side leader. |
New protocol (group.protocol=consumer, KIP-848) | Kafka 4.0+ brokers and a supporting client; large groups; frequent deploys. | Check client and framework support, and migration notes for the group. |
| Share group (KIP-932) | Independent jobs, uneven work, more workers than partitions. | No ordering, newer feature (production-ready in 4.2). |
| RabbitMQ or SQS instead | Pure job queue with routing, priorities and delays, and no need to replay history. | No replay and weaker ordering and streaming tools (see the stack table in section 07). |
That closes the first four ideas: the log, producers, consumers and groups. The next sections cover what a crash does to your guarantees (delivery semantics and transactions), the tools around Kafka (Spring, schemas, Connect, Streams), and how to run it in production.
05 · The primerDelivery Guarantees & Transactions — What "Exactly Once" Really Promises
A consumer can crash between doing the work and recording that it did the work, so Kafka alone can only promise at-least-once to the outside world. Inside Kafka, transactions and the idempotent producer give exactly-once for consume-transform-produce. For everything else, you make the consumer idempotent, retry without blocking, and park poison messages in a dead-letter topic.
Here is the incident behind every "Kafka lost / duplicated our orders" post-mortem. A payment service reads OrderPlaced events from a topic, calls the card processor, then lets Kafka record its progress. On a Tuesday the team deploys a new version at 14:00 while the service is busy.
Kubernetes kills the old pods. 212 of the roughly 10,000 orders that were in flight at that moment had already been charged at the card processor, but the pod died before it told Kafka "I got that far".
The new pods start, ask Kafka where the group left off, and are handed the old position. They read those 212 orders again and charge the cards again. Customers see two charges. Nothing was lost, nothing crashed in Kafka, and every component did what it was designed to do.
The team's mistake was not a Kafka bug. It was assuming that "the broker remembers my position" also means "my side effects happen once". They do not mean that, and this section is about why.
Make the invisible visible: the same consumer with two different orderings of two steps, and a crash in between.
# illustrative output: one record, offset 41, the pod is killed at the moment marked KILL
ORDER A: process first, then commit the offset
1 poll -> got offset 41
2 charge card -> card charged
KILL
3 commit 42 -> never happened
restart: group position is still 41 -> record 41 is read again -> charged twice ✗ duplicate
ORDER B: commit first, then process
1 poll -> got offset 41
2 commit 42 -> Kafka now says "done through 41"
KILL
3 charge card -> never happened
restart: group position is 42 -> record 41 is never seen again -> customer never charged ✗ lost
What you see: two steps that cannot be made into one step. Whichever you put first, a crash between them hurts, and the only choice is which way it hurts.
Why: the card processor and Kafka are two different systems. There is no single "do both or neither" button that spans a card API and a Kafka offset.
Bridge: the three delivery guarantees, in plain words
A delivery guarantee says how many times a consumer's code runs for one record, counting crashes and restarts. There are only three honest answers.
At-most-once means zero or one time. A record may be lost, but it is never repeated. You get this by committing the offset before you process (Order B above).
At-least-once means one or more times. A record is never lost, but it may be repeated. You get this by committing after you process (Order A above). It is the default recommendation, and it is what Commit after process in the consumer section built.
Exactly-once means the effect happens once, even though the code may have run more than once. This is the hard one, and it comes in two very different flavours.
| Guarantee | Offset commit happens | A crash can cause | Use it when |
|---|---|---|---|
| At-most-once | Before processing | A lost record | Losing some data is fine: sampled metrics, a "last seen" ping |
| At-least-once | After processing | A repeated record | Almost always. Pair it with an idempotent consumer |
| Exactly-once inside Kafka | Inside a transaction with the output records | Nothing visible: aborted work is hidden | Read from Kafka, compute, write back to Kafka |
| Exactly-once effect outside Kafka | After processing, plus a dedup record in the same transaction as the effect | A repeated run that does nothing the second time | Databases, payments, emails, any external system |
Bridge: what a Kafka transaction is, one level down
Kafka does have transactions, and they are real. But they cover a narrower job than most people expect. A Kafka transaction lets one producer write to several partitions, and record its consumer offsets, as a single all-or-nothing unit.
That is exactly the shape of a consume-transform-produce loop: read from topic orders, compute something, write to topic invoices, and move forward in orders. If the three actions are one atomic unit, a crash cannot leave "wrote the invoice but did not move forward" (a duplicate) or "moved forward but did not write the invoice" (a loss).
Four pieces make it work, and each is a plain idea:
- Transactional id: a name you give the producer, such as
invoicer-1. If a pod dies and a new one starts with the same name, the broker knows the old one is dead and blocks it from writing any more. That blocking is called fencing. - Transaction coordinator: one broker keeps a small log of "transaction started", "transaction committing", "transaction done" for each transactional id. It is the referee.
- Markers: when the transaction ends, the coordinator writes a commit marker or an abort marker into every partition the transaction touched. A marker is a special record that consumers never see as data.
isolation.level=read_committed: a consumer setting. It tells the consumer to hide records from open or aborted transactions, and only show records whose commit marker has arrived. The default,read_uncommitted, shows everything, including aborted data.
Make the invisible visible: one transaction on the topic invoices, as a read_committed consumer sees it, at four moments.
# illustrative output: P = a data record written by transaction T1, C = commit marker, A = abort marker
moment log contents read_uncommitted sees read_committed sees
1 T1 writes two records [ P0 P1 ] P0 P1 (nothing yet)
2 T1 commits [ P0 P1 C ] P0 P1 P0 P1
3 T2 writes a record, then aborts [ P0 P1 C P3 A ] P0 P1 P3 P0 P1 ✓ P3 hidden
4 T3 writes, still open [ P0 P1 C P3 A P5 ] P0 P1 P3 P5 P0 P1 (waits at P5)
What you see: aborted records are still physically in the log, because a log is append-only. The read_committed consumer simply skips them.
It also stops at the first record of an open transaction. That position is called the last stable offset. One slow transaction therefore delays everyone reading read_committed behind it.
Pattern: Consume-transform-produce transaction
The problem: A service reads from one topic and writes results to another. A crash between the write and the offset commit makes the service either repeat its output or skip it.
How it works: The producer opens a transaction, writes its output, adds the consumed offsets to the same transaction, and commits. Downstream readers use read_committed.
- Begin:
beginTransaction()on a producer that has atransactional.id. Setting that id turns on idempotence automatically. - Send:
send()the output records. They land in the log but are hidden from read_committed readers. - Attach offsets:
sendOffsetsToTransaction(offsets, groupMetadata)records "this group has consumed up to 42" inside the transaction instead of the usual commit. - Commit:
commitTransaction(). The coordinator writes the markers. On any exception,abortTransaction()hides the output and the offsets stay where they were.
The setup: the raw client version first, so you can see each call, then the Spring switch that does the same thing for you.
Properties cp = new Properties();
cp.put("bootstrap.servers", "localhost:9092");
cp.put("group.id", "invoicer");
cp.put("enable.auto.commit", "false"); // the transaction commits offsets, not the consumer
cp.put("isolation.level", "read_committed"); // do not read other people's aborted data
cp.put("key.deserializer", StringDeserializer.class.getName());
cp.put("value.deserializer", StringDeserializer.class.getName());
Properties pp = new Properties();
pp.put("bootstrap.servers", "localhost:9092");
pp.put("transactional.id", "invoicer-1"); // stable per instance; fences old copies
pp.put("key.serializer", StringSerializer.class.getName());
pp.put("value.serializer", StringSerializer.class.getName());
try (var consumer = new KafkaConsumer<String, String>(cp);
var producer = new KafkaProducer<String, String>(pp)) {
consumer.subscribe(List.of("orders"));
producer.initTransactions(); // registers the id, fences any older owner
while (true) {
var records = consumer.poll(Duration.ofMillis(500));
if (records.isEmpty()) continue;
producer.beginTransaction();
try {
Map<TopicPartition, OffsetAndMetadata> next = new HashMap<>();
for (var r : records) {
producer.send(new ProducerRecord<>("invoices", r.key(), invoiceFor(r.value())));
next.put(new TopicPartition(r.topic(), r.partition()),
new OffsetAndMetadata(r.offset() + 1)); // +1: the NEXT offset to read
}
producer.sendOffsetsToTransaction(next, consumer.groupMetadata());
producer.commitTransaction();
} catch (Exception e) {
producer.abortTransaction(); // output hidden; offsets unchanged; batch is re-read
// ❌ TRAP: if the exception is ProducerFencedException, do NOT abort; close and exit,
// a newer instance owns this transactional.id now.
}
}
}
spring:
kafka:
producer:
transaction-id-prefix: invoicer-tx- # setting this makes KafkaTemplate transactional
consumer:
group-id: invoicer
enable-auto-commit: false
isolation-level: read_committed
What you see: the same crash as the opening story, with and without the transaction.
# illustrative output
send invoice-41 to invoices -> offset 7
KILL before the offset commit
restart: orders position still 41 -> invoice-41 sent again -> invoices offset 8 ✗ two invoices for one order
# illustrative output
txn T1: send invoice-41 (offset 7, hidden), offsets 42 added
KILL before commitTransaction
restart: same transactional.id -> coordinator aborts T1 -> offset 7 stays hidden
orders position still 41 -> invoice-41 sent in T2 -> commit -> read_committed sees ONE invoice ✓
The trap: the guarantee covers only what happens inside Kafka. Add one HTTP call or database write inside that loop and it is outside the transaction, so it can still run twice.
producer.beginTransaction();
producer.send(new ProducerRecord<>("invoices", key, invoice)); // ✓ inside the transaction
emailClient.send(customer, invoice); // ❌ TRAP: outside. Abort and retry sends a 2nd email
producer.sendOffsetsToTransaction(next, consumer.groupMetadata());
producer.commitTransaction();
When to use it / when not: Use it when both the input and the output are Kafka topics.
- Works: Enrichment, aggregation and routing pipelines where every step reads a topic and writes a topic. Kafka Streams turns this on with one setting,
processing.guarantee=exactly_once_v2. - Fails: Any step that touches a database, a payment API or an email server. Also costly for tiny batches, because each transaction adds a round trip to the coordinator.
- Interview takeaway: "Exactly-once in Kafka means the offsets and the output records commit atomically in one transaction, and downstream reads read_committed. It is exactly-once for Kafka-to-Kafka. For the outside world I still need idempotency."
Why "exactly-once" stops at Kafka's edge
People hear "exactly-once" and assume it covers the whole system. It cannot, for a reason that has nothing to do with Kafka. When your code calls an external system and the connection drops, you do not know if the call happened.
That is the lost-reply problem from the microservices chapter. No messaging system can fix it, because the missing information is on the other side of a network you do not control.
What Kafka does promise is a precise, smaller thing. The idempotent producer means a retry does not write the record twice into a partition. Transactions mean a group of writes and offsets are atomic. Both are real and both are inside the cluster.
So the honest statement for an interview is: "end-to-end exactly-once effects are built from at-least-once delivery plus idempotent processing". The next pattern is that second half.
Pattern: Idempotent consumer
The problem: At-least-once delivery means a record can arrive twice, after a crash or after a rebalance. Running the side effect twice charges a card twice.
How it works: Each event carries a unique id. The consumer records that id in the same database transaction as its business change. A repeated id hits a unique constraint and the work is skipped.
- Give every event an id: a UUID created once, when the event is first produced (not when it is sent). It travels in the record key, a header or the payload.
- Check and write together: inside one local database transaction, insert the id into
processed_events, then apply the business change. - Let the constraint decide: a second delivery fails the insert (or finds the row), so the transaction does nothing and the listener returns normally.
- Commit the offset last: offset commit stays after processing, as before. A crash anywhere just replays a record that will now be ignored.
# illustrative output
moment processed_events payments table effect
1 event e-9 arrives (empty) (empty) -
2 txn: insert e-9, charge order 7c1e e-9 7c1e CHARGED 49.00 charged once ✓
3 pod killed before offset commit e-9 7c1e CHARGED 49.00 -
4 e-9 redelivered e-9 (insert refused) 7c1e CHARGED 49.00 (unchanged) skipped ✓
The setup: the listener in Spring. The full SQL for processed_events is in the outbox section of the microservices chapter; this is the Kafka side.
@KafkaListener(topics = "orders", groupId = "payments")
@Transactional // the DATABASE transaction, not a Kafka one
public void on(OrderPlaced event) {
int inserted = jdbc.update(
"INSERT INTO processed_events(event_id, consumer) VALUES (?, 'payments') ON CONFLICT DO NOTHING",
event.eventId());
if (inserted == 0) {
log.info("duplicate {} ignored", event.eventId()); // ✅ second delivery ends here
return;
}
payments.charge(event.orderId(), event.amount()); // same transaction as the insert above
}
What you see: two deliveries, without and with the check.
# illustrative output
delivery 1 of e-9: charge 49.00
delivery 2 of e-9: charge 49.00 ✗ customer charged 98.00
# illustrative output
delivery 1 of e-9: insert ok -> charge 49.00
delivery 2 of e-9: insert refused -> "duplicate e-9 ignored" ✓ customer charged 49.00
The trap: doing the id check in memory or in Redis outside the business transaction. The two can disagree after a crash, which brings the duplicate right back.
When to use it / when not: Use it for every consumer that changes state outside Kafka.
- Works: Payments, stock changes, ledger entries, any write you can place in the same database transaction as the dedup row. Natural idempotency (for example "set status to SHIPPED") needs no table at all.
- Fails: A side effect you cannot put in a transaction, such as an email. There, store a "sent" marker first and accept a tiny chance of one lost email over many duplicates, or use the provider's own idempotency key.
- Interview takeaway: "At-least-once plus a dedup record in the same transaction as the effect gives an exactly-once effect. That is how real systems get there, because Kafka transactions end at Kafka's edge."
Retries, and why they fight with ordering
Failures come in two kinds, and treating them the same is the most common design error. A transient failure goes away if you wait: the database is restarting, a downstream API is rate-limiting you. A permanent failure never goes away: the JSON is malformed, or the order refers to a product that does not exist.
The simplest retry is the blocking retry: the listener catches the error, waits, and tries the same record again. Because a partition is read strictly in order, nothing behind that record moves until it succeeds or is given up on.
That keeps order, which is good. But picture a payment API that is down for 10 minutes. A partition receiving 50 records per second is now 30,000 records behind, all waiting on one retrying record.
The other choice is a non-blocking retry: move the failed record to a separate retry topic and carry on with the next one. The main flow keeps its speed, but the retried record now arrives later than records that came after it. Order for that key is broken, so use this only where order for a key does not matter, or where you can detect "this is older than what I already applied".
| Option | Pick it when | Cost or catch |
|---|---|---|
Blocking retry with backoff (DefaultErrorHandler) | Order per key matters, and failures are short | The whole partition waits. Lag grows during any long outage |
Retry topics (@RetryableTopic) | Failures can last minutes and throughput matters | Order for the failed record is lost. More topics to run |
| Straight to dead-letter topic | The failure is permanent (bad data) | Someone must watch and replay the dead-letter topic |
| Pause the consumer and resume later | One dependency is down and everything depends on it | You must write the pause and resume yourself, see Pause and resume |
Make the invisible visible: partition orders-3 when a payment API is down, handled by a blocking retry and by retry topics.
# illustrative numbers: 50 records per second arrive on orders-3
BLOCKING RETRY
t=0 record 900 fails -> retry in 1s, 2s, 4s ...
t=600s record 900 finally succeeds; records 901..30899 still unread (lag = 30,000) ✗ everything late
RETRY TOPICS
t=0 record 900 fails -> copied to orders-retry-0 (delay 10s)
records 901, 902, ... keep flowing on orders-3 (lag stays near 0) ✓
t=10s retry topic delivers 900 again -> fails -> orders-retry-1 (delay 30s)
t=... last attempt fails -> orders-dlt ✓ nothing blocked
Pattern: Non-blocking retry topics
The problem: A blocking retry freezes a whole partition for as long as one record keeps failing. A 10-minute outage becomes a 30,000-record backlog.
How it works: A failed record is republished to a chain of retry topics with growing delays, and finally to a dead-letter topic.
- Fail fast: the listener throws. The framework publishes the record to
orders-retry-0with a header saying how many attempts are used. - Wait on the side: the retry-0 consumer pauses its partition until the delay has passed, then calls the same listener method.
- Back off: another failure moves it to
orders-retry-1, with a longer delay (10 s, 30 s, 90 s is a common shape). - Give up cleanly: after the last attempt the record goes to
orders-dltand a separate handler method is called.
The setup: in Spring Kafka one annotation builds the whole chain.
@RetryableTopic(
attempts = "4", // 1 original + 3 retries
backoff = @Backoff(delay = 10_000, multiplier = 3.0), // 10 s, 30 s, 90 s
dltStrategy = DltStrategy.FAIL_ON_ERROR,
exclude = { DeserializationException.class, IllegalArgumentException.class }) // permanent: skip retries
@KafkaListener(topics = "orders", groupId = "payments")
public void on(OrderPlaced event) {
payments.charge(event.orderId(), event.amount()); // throws on a transient failure
}
@DltHandler
public void dead(OrderPlaced event, @Header(KafkaHeaders.ORIGINAL_TOPIC) String topic) {
log.error("gave up on {} from {}", event.eventId(), topic); // alert here; a human decides
}
What you see: the topics the annotation creates.
# illustrative output
orders
orders-retry-0
orders-retry-1
orders-retry-2
orders-dlt
The trap: retrying a permanent error. A malformed record retried four times with growing delays is just a slow way to reach the dead-letter topic. List such errors under exclude so they go there straight away.
When to use it / when not: Use retry topics when failures are temporary and long.
- Works: Calls to flaky third-party APIs, rate limits, short database failovers, with an idempotent consumer so a retried record is safe.
- Fails: A strict per-key order, such as account balance updates applied in sequence. There, block and retry, or pause the consumer.
- Interview takeaway: "Blocking retry keeps order but stalls the partition; retry topics keep throughput but break order for the failed record. I pick by whether order for a key matters."
Pattern: Dead-letter topic
The problem: A poison pill is a record that fails every time, forever: invalid bytes, a schema nobody can read, a missing foreign key. Without a plan, the consumer retries it endlessly and the partition behind it never moves.
How it works: After a limited number of attempts, the consumer copies the record, plus the reason it failed, into a dead-letter topic and commits past it.
- Limit attempts: a fixed number of tries, with backoff, set in the error handler.
- Publish with context: the recoverer writes the original bytes unchanged plus headers: original topic, partition, offset, exception class and message.
- Move on: the offset is committed past the bad record, so the partition is free again.
- Alert and replay: a human or a tool inspects the dead-letter topic, fixes the cause, and replays the records to the original topic.
# illustrative output: record at orders-3 offset 900 contains broken JSON
BEFORE (no dead-letter topic)
poll -> offset 900 -> deserialize error -> retry -> error -> retry ... forever
orders-3 lag: 0 -> 3,000 -> 30,000 -> ... ✗ one bad record stops the partition
AFTER (3 attempts, then dead-letter)
poll -> offset 900 -> error x3 -> publish to orders.DLT (headers: original offset 900, reason)
commit 901 -> offset 901 is read normally ✓ one bad record, zero stall
The setup: the version without retry topics, using a blocking error handler that finishes in the dead-letter topic.
@Bean
DefaultErrorHandler errorHandler(KafkaTemplate<Object, Object> template) {
var recoverer = new DeadLetterPublishingRecoverer(template); // default target: <topic>.DLT
var handler = new DefaultErrorHandler(recoverer, new FixedBackOff(1_000L, 3)); // 1 s apart, 3 retries
handler.addNotRetryableExceptions(DeserializationException.class,
IllegalArgumentException.class); // permanent: dead-letter at once
return handler;
}
// note: DeadLetterPublishingRecoverer's default destination is "<original topic>.DLT" (dot, capitals) at the SAME partition number;
// give it a destination resolver if the dead-letter topic has fewer partitions.
The trap: a dead-letter topic nobody watches is just a slower way of losing data. Put an alert on its record count, and decide who owns replay.
- Interview takeaway: "Bounded retries, then a dead-letter topic that keeps the original bytes and the failure reason, with an alert on it. The goal is that one bad record never stalls a partition and never disappears."
Pattern: Outbox via CDC
The problem: A service must save an order in its database and also publish OrderPlaced to Kafka. Doing both is a dual write, and a crash between them loses or invents events.
How it works: Write the event as a row in an outbox table in the same database transaction as the order. A change-data-capture tool reads the database's own log and publishes each new outbox row to Kafka.
- One local transaction: insert the order and the outbox row together.
- Capture: Debezium, a connector that reads the database's write-ahead log, sees the committed outbox insert.
- Route: it publishes the row to a topic, using the aggregate id as the record key so one order's events stay in order on one partition.
- Deliver at least once: after a connector restart, a row may be published again, so consumers use the idempotent consumer above.
The full schema, the polling variant and the trade-offs are in the transactional outbox pattern in the microservices chapter. The point to carry from here is how the pieces of this section fit together.
# illustrative output
order service DB --one transaction--> orders row + outbox row (atomic: no dual write)
Debezium --reads the DB log--> topic Order, key=orderId (at-least-once, ordered per key)
payment consumer --one transaction--> processed_events row + charge (idempotent: duplicates skipped)
result: each order charged once ✓
The trap: publishing to Kafka directly from a service method right after the database commit. That is the dual write the outbox exists to avoid.
@Transactional
public void place(Order o) {
orders.save(o);
kafka.send("orders", o.id(), new OrderPlaced(o)); // ❌ TRAP: send() is not part of the DB transaction
// a rollback after this line leaves an event for an order that does not exist;
// a crash after commit but before the send flushes leaves an order with no event
// ✅ FIX: outbox.save(new OutboxRow(o.id(), "OrderPlaced", json(o))); // same transaction, CDC publishes it
}
- Interview takeaway: "Outbox plus CDC turns a dual write into one transaction and a reliable copy. It gives at-least-once publishing, so the consumer side must be idempotent."
Make the invisible visible: which tool gives which guarantee, so you can answer "how do you get exactly-once?" with the right one.
| Option | Pick it when | Cost or catch |
|---|---|---|
| Idempotent producer (default) | Always. It stops a producer retry from duplicating a record in a partition | Covers one producer session and one partition only. Does not stop an application-level resend |
| Kafka transactions | Topic in, topic out, with no outside side effect | Coordinator round trips; read_committed readers wait on open transactions |
| Idempotent consumer (dedup table) | The effect lands in a database | One extra table and insert per event; needs cleanup of old ids |
| Outbox with CDC | A database change must produce an event | Extra moving part (Debezium and Connect); at-least-once only |
| Natural idempotency | The operation is a set, not an add ("status = SHIPPED") | Only works for operations that really are repeat-safe |
06 · The primerSpring Kafka, Schemas, Connect & Streams — The Tools Around the Log
Raw Kafka clients are verbose, so most Java teams use Spring Kafka: a template to send, an annotation to listen, and an error handler for failures. Around it sit a schema registry that stops one team's change from breaking another's consumers, Kafka Connect for moving data in and out of databases, and Kafka Streams for computing over topics.
Here is the incident that sends teams to a schema registry. The order team renames the field amount to totalAmount in their JSON event on a Thursday afternoon. Their own tests pass, because their own code was updated.
Four other services read that topic: payments, invoicing, analytics and a fraud model. At 16:10 the new producer version goes live. Within a minute, three of the four start logging amount is null, and payments charges 0.00 for 340 orders before someone notices the alert.
Nobody was careless. The topic had no contract. A producer and a consumer shared a topic name and a hope that the bytes would look the same tomorrow.
This section covers the tools that put a contract and a safety net around the log. We start with the one every Java team touches first, Spring Kafka, and build it from small runnable pieces into a complete service.
Bridge: what Spring Kafka is, one level down
The plain Kafka client gives you KafkaProducer and KafkaConsumer. You write the poll loop, the thread handling, the commit calls and the error handling yourself, as in the transaction loop earlier.
Spring for Apache Kafka wraps those clients. You get a KafkaTemplate to send, and a @KafkaListener annotation that turns a method into a consumer. Spring runs the poll loop on its own threads, calls your method once per record, and commits offsets after your method returns.
Version note, checked November 2026: Spring for Apache Kafka 4.0 went GA in November 2025 for Spring Boot 4.0, and Spring Kafka 4.1 (June 2026) goes with Spring Boot 4.1. In Spring Boot 4 you add the dependency spring-boot-starter-kafka explicitly. Check the current Spring documentation for exact patch versions.
| Option | Pick it when | Cost or catch |
|---|---|---|
Spring Kafka (KafkaTemplate, @KafkaListener) | You already use Spring Boot. This is the default for most teams | Hides the poll loop, so you must learn what it does on errors and rebalances |
Plain kafka-clients | You need full control of the loop, or no Spring in the service | You own threading, commits, retries and shutdown |
| Spring Cloud Stream | You want the broker to be swappable behind functional bindings | One more abstraction; Kafka-specific features need binder settings |
| Reactor Kafka | The whole service is already reactive | Harder to reason about offsets and backpressure for most teams |
| Kafka Streams | The work is topic-in, topic-out computation with state | Not for calling external services per record |
The code ladder: from one dependency to a full service
We build an order-events service in six rungs. Each rung is small enough to run on its own. The last rung is the whole program. Stack: Java 21 or 25, Spring Boot 4.1, Spring Kafka 4.1, a single Kafka broker in KRaft mode for local work.
Rung 1, the setup: a broker to talk to, and the dependencies.
services:
kafka:
image: apache/kafka:4.3.0 # official image; pick the current 4.x tag you have verified
ports: ["9092:9092"]
environment:
KAFKA_NODE_ID: 1
KAFKA_PROCESS_ROLES: broker,controller # one node plays both roles, fine for a laptop
KAFKA_LISTENERS: PLAINTEXT://:9092,CONTROLLER://:9093
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092
KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT
KAFKA_CONTROLLER_QUORUM_VOTERS: 1@localhost:9093
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 # single node: replication factor can only be 1
KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-kafka</artifactId> <!-- explicit in Boot 4 -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-kafka</artifactId> <!-- module name in Testcontainers 2.x; 1.x called it "kafka" -->
<scope>test</scope>
</dependency>
</dependencies>
Rung 2, the configuration: every setting here is one you should be able to explain.
spring:
kafka:
bootstrap-servers: localhost:9092
producer:
acks: all # default since Kafka 3.0; written out so readers see it
properties:
enable.idempotence: true # default since 3.0; retries cannot duplicate
linger.ms: 5 # wait up to 5 ms to fill a batch
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.springframework.kafka.support.serializer.JacksonJsonSerializer
consumer:
group-id: order-events-service
auto-offset-reset: earliest # a brand-new group starts at the beginning
enable-auto-commit: false # Spring commits after the listener returns
isolation-level: read_committed
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.springframework.kafka.support.serializer.JacksonJsonDeserializer
properties:
spring.json.trusted.packages: shop.orders.events # only deserialize classes from here
spring.json.value.default.type: shop.orders.events.OrderPlaced
max.poll.records: 100
listener:
ack-mode: record # commit after each record; use batch for speed
concurrency: 3 # three consumer threads inside this one app
How it works: concurrency: 3 starts three consumers in the same group inside one JVM. They share the topic's partitions, so with 6 partitions each thread gets 2. More threads than partitions would leave the extra ones idle.
Note: Spring Boot 4 and Spring Kafka 4 moved to Jackson 3, and the JSON serializer classes were renamed to match (the Jackson prefix above). If your build shows the older JsonSerializer as deprecated, that is the reason; check the current reference docs.
Rung 3, the event and the producer: a record type for the event, and a service that sends it.
package shop.orders.events;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.UUID;
public record OrderPlaced(
UUID eventId, // idempotency key for consumers
String orderId, // also the Kafka record key: keeps one order's events in order
String customerId,
BigDecimal totalAmount,
Instant placedAt) { }
@Service
public class OrderEventPublisher {
private static final Logger log = LoggerFactory.getLogger(OrderEventPublisher.class);
private final KafkaTemplate<String, OrderPlaced> kafka;
public OrderEventPublisher(KafkaTemplate<String, OrderPlaced> kafka) {
this.kafka = kafka;
}
public CompletableFuture<SendResult<String, OrderPlaced>> publish(OrderPlaced event) {
return kafka.send("orders", event.orderId(), event) // key = orderId
.whenComplete((result, ex) -> {
if (ex != null) {
log.error("send failed for {}", event.eventId(), ex); // retries already exhausted
} else {
var md = result.getRecordMetadata();
log.info("sent {} to {}-{} @ {}", event.eventId(), md.topic(), md.partition(), md.offset());
}
});
// ❌ TRAP: calling .get() right here makes every request wait for the broker, one at a time
}
}
What you see: the log line for one send.
# illustrative output
INFO OrderEventPublisher : sent 8b1f...c3 to orders-4 @ 1207
Rung 4, the listener: the smallest consumer. Spring calls it once per record.
@Component
public class OrderEventListener {
private static final Logger log = LoggerFactory.getLogger(OrderEventListener.class);
@KafkaListener(topics = "orders", groupId = "order-events-service")
public void on(ConsumerRecord<String, OrderPlaced> record) { // the record gives partition, offset, headers
OrderPlaced e = record.value();
log.info("got {} from {}-{} @ {}", e.eventId(), record.topic(), record.partition(), record.offset());
// business work goes here; if this method throws, the error handler (next rung) decides what happens
}
}
Rung 5, the error handling: bounded retries, then the dead-letter topic, as in the patterns above. One bean wires into the listener container automatically.
@Configuration
public class KafkaErrorConfig {
@Bean
DefaultErrorHandler errorHandler(KafkaOperations<Object, Object> template) {
var recoverer = new DeadLetterPublishingRecoverer(template,
(rec, ex) -> new TopicPartition(rec.topic() + ".DLT", -1)); // -1: let the producer choose the partition
var handler = new DefaultErrorHandler(recoverer, new FixedBackOff(1_000L, 3));
handler.addNotRetryableExceptions(IllegalArgumentException.class); // bad data: straight to the DLT
return handler;
}
}
Rung 6, topics, the idempotent business step and the HTTP entry: the pieces that make it a service.
@Configuration
public class KafkaTopicsConfig {
@Bean NewTopic orders() { return TopicBuilder.name("orders").partitions(6).replicas(1).build(); } // replicas(3) in production
@Bean NewTopic ordersDlt() { return TopicBuilder.name("orders.DLT").partitions(1).replicas(1).build(); }
}
@RestController
@RequestMapping("/orders")
public class OrderController {
private final OrderEventPublisher publisher;
public OrderController(OrderEventPublisher publisher) { this.publisher = publisher; }
@PostMapping
public ResponseEntity<String> place(@RequestBody PlaceOrder cmd) {
var event = new OrderPlaced(UUID.randomUUID(), cmd.orderId(), cmd.customerId(), cmd.totalAmount(), Instant.now());
publisher.publish(event);
return ResponseEntity.accepted().body(event.eventId().toString()); // 202: accepted, not yet processed
}
public record PlaceOrder(String orderId, String customerId, BigDecimal totalAmount) { }
}
How it works: the controller answers 202 Accepted, because the work is asynchronous. A production service would write the order and an outbox row in one transaction instead of calling the publisher directly, as in Outbox via CDC. The ladder keeps the direct send so each rung stays small.
The full service, in one place
Now the same pieces assembled: the final listener adds the idempotency check from the earlier pattern, and the application class ties it together. Read it top to bottom; every line was introduced in a rung above.
Step-by-step: what the full service does, in plain English
- A client posts an order to
/orders. The controller builds anOrderPlacedevent with a fresheventIdand returns 202. - The publisher sends it to topic
orderswithorderIdas the key. All events for one order go to one partition, in order. - One of the three listener threads polls the record, Spring deserializes it, and the listener runs inside a database transaction.
- The listener inserts
eventIdintoprocessed_events. If the insert changes nothing, this is a duplicate and the method returns. - Otherwise it does the business work. If that throws, the error handler retries 3 times, one second apart, then copies the record to
orders.DLTand moves on. - When the method returns, Spring commits the offset. A crash before that line replays the record, and step 4 makes the replay harmless.
@Component
public class OrderEventListener {
private static final Logger log = LoggerFactory.getLogger(OrderEventListener.class);
private final JdbcTemplate jdbc;
private final FulfilmentService fulfilment;
public OrderEventListener(JdbcTemplate jdbc, FulfilmentService fulfilment) {
this.jdbc = jdbc;
this.fulfilment = fulfilment;
}
@KafkaListener(topics = "orders", groupId = "order-events-service")
@Transactional // database transaction around the whole method
public void on(ConsumerRecord<String, OrderPlaced> record) {
OrderPlaced e = record.value();
int inserted = jdbc.update(
"INSERT INTO processed_events(event_id, consumer) VALUES (?, 'order-events-service') ON CONFLICT DO NOTHING",
e.eventId());
if (inserted == 0) {
log.info("duplicate {} ignored (partition {} offset {})", e.eventId(), record.partition(), record.offset());
return; // ✅ redelivery ends here
}
if (e.totalAmount().signum() <= 0) {
throw new IllegalArgumentException("non-positive amount in " + e.eventId()); // permanent: goes to the DLT, no retries
}
fulfilment.reserveStock(e.orderId(), e.customerId()); // transient failures throw other exceptions: retried
}
}
@SpringBootApplication
public class OrderEventsApplication {
public static void main(String[] args) {
SpringApplication.run(OrderEventsApplication.class, args);
}
}
What you see: one good order, one duplicate and one bad record, in the logs.
# illustrative output
INFO OrderEventPublisher : sent 8b1f...c3 to orders-4 @ 1207
INFO OrderEventListener : reserved stock for order o-77 ✓ normal path
INFO OrderEventListener : duplicate 8b1f...c3 ignored (partition 4 offset 1207) ✓ redelivery after a restart
WARN DefaultErrorHandler : non-positive amount in 2a90...e1 -> published to orders.DLT ✓ bad record parked, partition moves on
The trap: auto-created topics. With auto.create.topics.enable on in a shared cluster, a typo in a topic name quietly creates a new one-partition topic with default settings. Declare topics as beans, or manage them in infrastructure code.
Testing it: a real broker in a container
A mock of Kafka tests your mock, not your service. Two real options exist. @EmbeddedKafka starts a broker inside the test JVM: fast to start, nothing to install, but it is not exactly the broker you will run in production. Testcontainers starts a real Kafka in a Docker container: slower by a few seconds, but the same software you deploy.
| Option | Pick it when | Cost or catch |
|---|---|---|
Unit test with a mocked KafkaTemplate | Testing your own mapping logic only | Proves nothing about serialization, partitions or error handling |
@EmbeddedKafka | Fast feedback in the inner loop; no Docker on the build agent | Embedded broker, not your production image |
Testcontainers KafkaContainer | You want the real broker image, and CI has Docker | Needs Docker; start-up of several seconds, reuse the container across tests |
| A shared dev cluster | Full end-to-end checks across teams | Tests interfere with each other; flaky by design |
@SpringBootTest
@Testcontainers
class OrderEventsIT {
@Container
@ServiceConnection // Boot points spring.kafka.bootstrap-servers at the container
static KafkaContainer kafka = new KafkaContainer(DockerImageName.parse("apache/kafka:4.3.0"));
@Autowired OrderEventPublisher publisher;
@Autowired JdbcTemplate jdbc;
@Autowired KafkaTemplate<String, Object> template;
@Test
void duplicate_event_is_processed_once() {
var e = new OrderPlaced(UUID.randomUUID(), "o-1", "c-1", new BigDecimal("49.00"), Instant.now());
publisher.publish(e);
publisher.publish(e); // same eventId sent twice on purpose
await().atMost(Duration.ofSeconds(15)).untilAsserted(() -> {
Integer n = jdbc.queryForObject(
"SELECT count(*) FROM processed_events WHERE event_id = ?", Integer.class, e.eventId());
assertThat(n).isEqualTo(1); // ✅ one row, though two records arrived
});
}
@Test
void bad_record_lands_in_the_dead_letter_topic() {
var bad = new OrderPlaced(UUID.randomUUID(), "o-2", "c-1", new BigDecimal("-1"), Instant.now());
publisher.publish(bad);
// read orders.DLT with a test consumer and assert one record whose key is "o-2"
}
}
How it works: the test sends the same event twice, which is what a redelivery looks like to the listener. The assertion polls with a time limit (Awaitility), because the listener runs on another thread. Never use Thread.sleep for this.
Versions note: package names for @ServiceConnection and the Testcontainers Kafka class moved with Boot 4 and Testcontainers 2; confirm imports against your IDE and the current docs.
- Interview takeaway: "Spring owns the poll loop and the offset commit; I own the listener method and the error handler. I test with a real broker in Testcontainers, and I always test the duplicate and the poison record, not just the happy path."
Schemas: a contract for the bytes on a topic
Back to the Thursday incident. A schema is a written description of what a record contains: field names, types, and which fields are optional. A schema registry is a small service that stores every version of every schema, and hands each one an id.
The producer does not send the full schema with each record. It sends a 5-byte prefix (a magic byte plus a 4-byte schema id) followed by the compact encoded data. The consumer reads the id, fetches that schema once from the registry, caches it, and decodes the bytes.
The key benefit is the check at registration time. When the order team tries to publish a new version, the registry compares it against the older versions using a compatibility mode. If renaming amount breaks readers, the registration is refused, and the bad version never reaches the topic.
Make the invisible visible: the same change, with a JSON topic and with a registry in front.
# illustrative output
WITHOUT A REGISTRY (plain JSON)
16:10 producer v2 deployed: {"orderId":"o-1","totalAmount":49.00}
16:11 payments consumer: amount is null -> charges 0.00 ✗ found by customers
WITH A REGISTRY (Avro, compatibility = BACKWARD)
15:40 CI step registers v2 (field renamed, no default)
registry answers: 409 "schema being registered is incompatible" ✓ build fails before deploy
15:55 developer adds the new field with a default and keeps the old one for a release
registry answers: 200, schema id 18 ✓ safe change
Why: the contract is checked by a machine at build time instead of discovered by a customer at run time.
Pattern: Schema evolution with a registry
The problem: Producers and consumers deploy on different days. Any change to an event's shape can break whichever side is older.
How it works: Events use a typed format (Avro or Protobuf), every schema version is registered, and a compatibility mode decides which changes are allowed.
- Pick a mode per subject: a subject is usually
<topic>-value. The mode says which pairs of versions must work together. - Register in CI: the build registers or checks the new schema and fails on 409.
- Add, do not rename: new fields get a default value; old fields are removed only after nobody reads them.
- Upgrade in the right order: BACKWARD means upgrade consumers first; FORWARD means producers first; FULL means any order.
| Mode | What it guarantees | Allowed changes | Upgrade order |
|---|---|---|---|
| BACKWARD (usual default) | New consumer code can read old data | Add a field with a default; delete a field | Consumers first |
| FORWARD | Old consumer code can read new data | Delete a field that had a default; add a field | Producers first |
| FULL | Both of the above, against the previous version | Add or remove only fields that have defaults | Any order |
| *_TRANSITIVE variants | The same, but against every earlier version, not just the last | Same as base mode | Needed if consumers replay old history |
| NONE | Nothing is checked | Anything | Back to the Thursday incident |
The setup: an Avro schema for version 2 of the event, where the new field has a default so old data still reads.
{
"type": "record",
"name": "OrderPlaced",
"namespace": "shop.orders.events",
"fields": [
{"name": "eventId", "type": "string"},
{"name": "orderId", "type": "string"},
{"name": "amount", "type": "double"},
{"name": "currency", "type": "string", "default": "EUR"}
]
}
spring:
kafka:
producer:
value-serializer: io.confluent.kafka.serializers.KafkaAvroSerializer
properties:
schema.registry.url: http://localhost:8081
auto.register.schemas: false # CI registers; production never creates schemas by itself
use.latest.version: true
What you see: adding currency with a default is accepted, while a field without one is refused under BACKWARD.
# illustrative output
JSON topic, producer renames amount -> totalAmount
payments reads: amount = null ✗ 340 orders charged 0.00
# illustrative output
add "currency" with default "EUR": POST /compatibility -> {"is_compatible": true} ✓
add "region" with NO default: POST /compatibility -> {"is_compatible": false} ✓ refused before deploy
The trap: leaving auto.register.schemas on in production. Any developer's local change then registers itself, and the compatibility check you counted on runs against whatever got in first.
| Option | Pick it when | Cost or catch |
|---|---|---|
| Avro + registry | Many consumers, long-lived topics, schemas evolve | Needs a registry and a build step; binary, so not readable by eye |
| Protobuf + registry | You already use gRPC, or want field numbers and code generation across languages | Same registry need; discipline on field numbers |
| JSON Schema + registry | You want readable payloads and still want checks | Largest payloads of the three |
| Plain JSON, no registry | One producer, one consumer, one team, short-lived | No contract; the Thursday incident is waiting |
- Interview takeaway: "A registry makes the schema a checked contract. BACKWARD means new readers handle old data, so I upgrade consumers first, and I only add fields with defaults."
Kafka Connect and change data capture
Most teams end up writing the same two programs: "copy rows from a database into Kafka" and "copy records from Kafka into a search index or warehouse". Kafka Connect is the framework that runs such copy jobs for you. You describe a job in JSON; Connect runs it, tracks its offsets, restarts it on failure and spreads it over workers.
A source connector reads from an outside system into Kafka. A sink connector writes from Kafka to an outside system. A task is one parallel worker inside a connector.
Change data capture (CDC) means reading a database's own change log (in PostgreSQL the write-ahead log, in MySQL the binlog) and turning every insert, update and delete into an event. Debezium is the common open-source CDC connector. It sees changes in commit order, with no polling query and no added load on the tables.
Make the invisible visible: one row update, as a Debezium event on a topic.
{
"before": { "id": 7, "email": "a@old.example" },
"after": { "id": 7, "email": "a@new.example" },
"source": { "table": "customers", "lsn": 24823912 },
"op": "u",
"ts_ms": 1795100123456
}
What you see: the event holds the row before and after, the operation (c create, u update, d delete) and the log position. The key of the record is the primary key, so all changes to customer 7 land on one partition in order.
Pattern: Change data capture with Connect
The problem: Other systems (search, a cache, an analytics store, another service's read model) need to follow a database. Dual writes from the application lose changes; nightly batch jobs make the copies hours stale.
How it works: A Debezium source connector reads the database log and publishes each change to a topic; sink connectors or consumers apply it elsewhere.
- Enable the log: PostgreSQL needs
wal_level=logicaland a replication slot; MySQL needs row-based binlog. - Start the connector: one POST of JSON to the Connect REST API.
- First, a snapshot: Debezium reads current table contents once, then follows the log from that point.
- Consume the stream: sinks and services read the topics, apply changes in order per key, and tolerate duplicates.
curl -X POST http://localhost:8083/connectors -H 'Content-Type: application/json' -d '{
"name": "customers-cdc",
"config": {
"connector.class": "io.debezium.connector.postgresql.PostgresConnector",
"database.hostname": "pg", "database.port": "5432",
"database.user": "debezium", "database.password": "${file:/secrets/pg.properties:password}",
"database.dbname": "shop",
"topic.prefix": "shop",
"table.include.list": "public.customers",
"plugin.name": "pgoutput",
"tasks.max": "1"
}
}'
# illustrative output: HTTP 201 Created
The trap: an unused replication slot. If the connector is stopped for days, PostgreSQL keeps all WAL the slot has not consumed, and the database disk fills up.
-- illustrative output
SELECT slot_name, active, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal
FROM pg_replication_slots;
-- debezium_slot | f | 38 GB -- ✗ connector down for 3 days; alert on this number and drop dead slots
| Option | Pick it when | Cost or catch |
|---|---|---|
| Kafka Connect with Debezium | Many sinks follow database changes; you want history and order | Run and monitor Connect; slots and snapshots need care |
| Polling outbox in your service | Small volume, no Connect available | Query load and a delay equal to the poll interval |
| Application dual write | Almost never | Loses or invents events at every crash point |
| Nightly batch ETL | Reports that can be a day old | Stale, and heavy on the source at run time |
- Interview takeaway: "CDC reads the database's commit log, so I get every change in order without touching the application. It is at-least-once, so sinks must be idempotent, and I alert on replication-slot lag."
Kafka Streams: computing over topics
Kafka Streams is a Java library, not a cluster. You add it to an ordinary application; each instance reads some partitions, computes, and writes results to other topics. Scaling means starting more copies of the same app.
It has two core ideas. A KStream is a stream of events where each record is a new fact ("order o-1 placed", "order o-1 paid"). A KTable is the latest value per key, as if the topic were a table that is updated in place ("customer 7 currently has email X").
A KTable needs memory of the past, so Streams keeps a state store, a small local database (RocksDB by default) on the instance's disk. Every change to the store is also written to a changelog topic in Kafka. If an instance dies, a replacement rebuilds its store by replaying the changelog.
A window groups events by time, for example "orders per customer per 5 minutes". Late events and window size decide how much state is held.
Make the invisible visible: a stream of order events becoming a table of totals, record by record.
# illustrative output: key = customerId, value = order amount
stream event state store (KTable: total per customer) output topic record
(c-1, 30.00) c-1 -> 30.00 (c-1, 30.00)
(c-2, 10.00) c-1 -> 30.00 | c-2 -> 10.00 (c-2, 10.00)
(c-1, 25.00) c-1 -> 55.00 | c-2 -> 10.00 (c-1, 55.00) <- update, not a new row
Pattern: Event-carried state transfer / KTable
The problem: The order service needs a customer's current shipping country for every order. Calling the customer service on each record adds latency, and when it is down, orders stop.
How it works: The customer service publishes every change to a compacted topic. The order service reads that topic into a local KTable and looks up the customer in memory.
- Publish state, not just notifications: each customer event carries the full current record, keyed by customer id.
- Compact the topic: compaction keeps the latest record per key, so the topic is the full current table.
- Materialise locally: the consumer builds a KTable (or a global one, copied to every instance).
- Join: each order is joined to its customer by key, with no network call.
@Bean
KStream<String, EnrichedOrder> enrich(StreamsBuilder b) {
KStream<String, OrderPlaced> orders = b.stream("orders"); // key: customerId
GlobalKTable<String, Customer> customers = b.globalTable("customers"); // compacted topic, full copy per instance
KStream<String, EnrichedOrder> out = orders.join(
customers,
(orderKey, order) -> order.customerId(), // how to find the customer
(order, customer) -> new EnrichedOrder(order, customer.country())); // no remote call
out.to("orders-enriched");
return out;
}
What you see: the same order path, with a remote call and with a local table.
# illustrative numbers
each order -> HTTP GET customer-service (about 20 ms) -> at most about 50 orders/s per thread ✗
customer-service down 10 min -> orders stop ✗
# illustrative numbers
each order -> local lookup (microseconds) -> limited by Kafka throughput ✓
customer-service down 10 min -> orders continue with the last known customer ✓
The trap: a stream-table join is only as fresh as the table. A customer who changed country one second ago may still be joined with the old value. If you need the exact value at the order's time, use a versioned table or accept the lag.
| Option | Pick it when | Cost or catch |
|---|---|---|
| Kafka Streams | Java service, topic-to-topic, joins, aggregates, exactly-once inside Kafka | Local state to manage; Kafka only; Java/Kotlin only |
| ksqlDB | Analysts or small jobs in SQL | Another server to run; check its current project status before choosing |
| Apache Flink | Large state, event-time windows, many sources, SQL and batch together | A separate cluster and a steeper learning curve |
| Plain consumer with a database | Simple per-record logic, calls to other services | You hand-build state, windows and recovery |
- Interview takeaway: "A KTable is a topic read as latest-value-per-key. Its state store is local for speed and backed by a changelog topic for recovery. I use it to join without a remote call, and I accept that the join is only as fresh as the table."
07 · The primerRunning Kafka in Production — Sizing, Watching, Surviving, and Choosing
Kafka fails in quiet ways: lag creeps up, a replica falls behind, a partition count chosen on day one cannot be lowered later. Size partitions from a throughput calculation, alert on consumer lag and under-replicated partitions, practise losing a broker, and know when a different tool is the better answer.
Here is a Monday-morning incident. A retailer launched a flash sale on Sunday night. The orders topic had 3 partitions, picked a year earlier because "three felt right". By 08:00 the payments consumer group has 3 consumers, one per partition, each processing 400 records per second.
Orders now arrive at 2,400 per second. The group can drain 1,200 per second at best. Lag grows by 1,200 every second, which is 4.3 million records an hour.
The on-call engineer starts 10 more consumer pods. Nothing changes: three consumers work, and ten sit idle, because a partition is read by at most one consumer in a group. The fix needs more partitions, and adding partitions changes which partition a key hashes to, so per-key order breaks during the change.
The root cause was a number nobody calculated. This section is about calculating it, then watching the signals that tell you early, and surviving the failures that follow.
Make the invisible visible: what 10 extra pods do when there are only 3 partitions.
# illustrative output
GROUP TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG CONSUMER-ID
payments orders 0 9,120,000 13,440,000 4,320,000 pod-a
payments orders 1 9,090,000 13,410,000 4,320,000 pod-b
payments orders 2 9,105,000 13,425,000 4,320,000 pod-c
# pods d..m joined the group: ✗ they appear in no row, they own no partition
Why: the partition is Kafka's unit of parallelism. The maximum number of active consumers in a group equals the number of partitions.
Bridge: how to size partitions, one level down
You need partitions for three reasons: write throughput, read throughput, and room for consumers to grow. Start from measurements, not a guess.
Measure how fast one partition can be written (call it p MB/s) and how fast one consumer can process (call it c MB/s, or records per second). The needed partition count is the target throughput divided by the smaller of the two, rounded up, plus headroom.
# illustrative numbers: a calculation pattern, not a benchmark
target: 5,000 records/s peak now, plan for 3x growth = 15,000 records/s
record size: 1 KB average -> 15 MB/s
one consumer: 1,000 records/s (it calls a payment API; this is the slow side)
partitions by consumers: 15,000 / 1,000 = 15
partitions by producer: one partition accepts about 10 MB/s in our test -> 15 / 10 = 2
need = max(15, 2) = 15 -> round up with headroom for key skew: 24 partitions
# consumers will be the limit, not Kafka. Use 24, not 3.
Pattern: Partition sizing by throughput math
The problem: Too few partitions cap throughput and cannot be fixed without reshuffling keys. Too many cost memory, file handles and longer recovery.
How it works: Calculate from measured per-partition and per-consumer rates, add headroom for growth and key skew, and choose a number that divides well.
- Measure the slow side: usually the consumer, because it does real work.
- Divide: target rate (with 2 to 3 years of growth) over the measured rate gives the minimum.
- Add skew headroom: a hot key makes one partition busier, so add 25 to 50 percent.
- Check the cost side: thousands of partitions per broker is a real load; keep a sensible ceiling per broker and test it.
# illustrative output
TOO FEW (3 partitions) max 3 consumers; adding partitions later changes hash(key) mod N -> per-key order breaks ✗
TOO MANY (5,000 per topic) every partition has open files, a leader election and replication state;
a broker restart elects thousands of leaders and takes much longer ✗
JUST ENOUGH (24) room for 24 consumers, a restart stays fast ✓
The setup: creating the topic with the chosen numbers, and the only safe way to add partitions later.
kafka-topics.sh --bootstrap-server broker:9092 --create --topic orders \
--partitions 24 --replication-factor 3 \
--config min.insync.replicas=2 --config retention.ms=604800000 # 7 days
# later, increase only (never decrease):
kafka-topics.sh --bootstrap-server broker:9092 --alter --topic orders --partitions 48
# ❌ TRAP: keys now hash to different partitions. Old records stay where they are; new ones may not.
# ✅ FIX: for strict per-key order, create orders-v2 with the new count and migrate, or double (24 -> 48) during a quiet drain.
- Interview takeaway: "Partitions equal the maximum consumer parallelism and can only grow. I size from the slow side's measured rate with growth and skew headroom, and I treat later changes as a migration because keys will move."
What to watch: three signals that matter
You can watch hundreds of Kafka metrics, but three tell you most of what you need. Each answers one plain question.
Consumer lag: how far behind is each group? It is the log-end offset minus the group's committed offset. Lag that is large but flat is a backlog being worked; lag that grows is a consumer that cannot keep up.
Under-replicated partitions: how many partitions have fewer in-sync replicas than they should? Anything above zero for more than a short moment means a broker is slow, down, or its network is struggling. It is the early warning before data loss becomes possible.
Request latency: how long do produce and fetch requests take at the broker (the 99th percentile)? Rising latency usually means disk, network or overload, and it shows up before clients time out.
| Signal | Healthy | Alarming | First thing to check |
|---|---|---|---|
| Consumer lag | Near zero, or flat during bursts | Grows for 10+ minutes | Is a consumer stuck, slow, or rebalancing repeatedly? Are partitions fewer than needed? |
| Under-replicated partitions | 0 | > 0 for several minutes | A broker down or overloaded; disk or network on the follower |
| Produce / fetch p99 latency | Stable, in milliseconds | Step up or steady climb | Disk saturation, network, too many partitions per broker |
| Offline partitions | 0 | > 0 at all | No leader: page someone now |
Pattern: Alert on consumer lag
The problem: A consumer can be running and green on every health check while it is hours behind. Customers see stale data and nobody is paged.
How it works: Export lag per group and partition, and alert on a lag that stays high or keeps growing, ideally also expressed in time.
- Export lag: use the broker and client metrics, or a lag exporter, into your metrics system.
- Alert on trend and duration: for example "lag above 100,000 for 10 minutes" or "lag rising for 15 minutes".
- Prefer time lag: "oldest unprocessed record is 4 minutes old" is understood by the business; "300,000 records" is not.
- Write the runbook: stuck consumer, slow dependency, rebalance storm, too few partitions, each with its check.
groups:
- name: kafka-lag
rules:
- alert: ConsumerLagGrowing
expr: sum by (consumergroup, topic) (kafka_consumergroup_lag) > 100000
for: 10m # a brief burst does not page anyone
labels: { severity: page }
annotations:
summary: "{{ $labels.consumergroup }} is {{ $value }} records behind on {{ $labels.topic }}"
- alert: ConsumerLagNotDraining
expr: deriv(kafka_consumergroup_lag[15m]) > 0 and kafka_consumergroup_lag > 10000
for: 15m
What you see: the Monday incident, with and without the alert.
# illustrative output
08:00 lag starts growing 08:30 lag 2.1M 09:15 support tickets: "my order is not confirmed" ✗ found by customers
# illustrative output
08:00 lag starts growing 08:10 ConsumerLagGrowing fires, runbook says "check partitions vs consumers"
08:25 partitions raised via the planned migration ✓ found by the team
The trap: alerting on lag during a rebalance or a deploy. Lag spikes briefly whenever consumers restart. The for: duration is what keeps that from paging you.
- Interview takeaway: "Lag is the consumer's health metric. I alert on lag that persists or grows, ideally as age of the oldest unprocessed record, and I link the alert to a runbook."
Pattern: Pause/resume backpressure
The problem: A consumer polls fast, but its downstream (a database, an API) is slow or down. Records pile up in memory, the poll loop takes too long, and the consumer is thrown out of the group.
How it works: The consumer pauses fetching from its partitions while it clears its backlog, but keeps calling poll() so the group still sees it alive.
- Detect pressure: a bounded queue is full, or a circuit breaker opened.
- Pause:
pause()the assigned partitions.poll()returns nothing but still sends heartbeats and stays insidemax.poll.interval.ms. - Drain: the downstream catches up.
- Resume:
resume()and carry on from the same offset.
@Component
public class BackpressureListener {
private final CircuitBreaker breaker;
private final KafkaListenerEndpointRegistry registry;
public BackpressureListener(CircuitBreaker breaker, KafkaListenerEndpointRegistry registry) {
this.breaker = breaker; this.registry = registry;
}
@KafkaListener(id = "payments-listener", topics = "orders")
public void on(OrderPlaced e) {
try {
breaker.executeRunnable(() -> payments.charge(e));
} catch (CallNotPermittedException open) {
registry.getListenerContainer("payments-listener").pause(); // stop fetching; keep polling
throw open; // record is retried, not skipped
}
}
@Scheduled(fixedDelay = 5_000)
void maybeResume() {
var c = registry.getListenerContainer("payments-listener");
if (c.isContainerPaused() && breaker.getState() != CircuitBreaker.State.OPEN) c.resume();
}
}
The trap: sleeping in the listener to "wait it out". The poll loop stops, the group coordinator decides the consumer is dead, and a rebalance starts. Pausing keeps the loop alive; sleeping does not.
# illustrative output
payment API down -> listener sleeps 6 min -> poll gap exceeds max.poll.interval.ms (5 min)
-> consumer removed, rebalance, partitions move, same failure on the next consumer ✗ rebalance storm
# illustrative output
payment API down -> breaker opens -> container paused (poll continues, nothing fetched)
API back -> breaker half-open -> resume() -> processing continues from the same offset ✓ no rebalance
- Interview takeaway: "To slow down I pause the partitions and keep polling, rather than blocking the poll loop. Blocking looks like a dead consumer and triggers a rebalance."
Losing a broker, and upgrading without downtime
A topic with replication factor 3 and min.insync.replicas=2 loses nothing when one broker dies. The controller notices, picks a new leader from the in-sync replicas for each affected partition, and clients refresh their metadata and carry on. Producers using acks=all still succeed, because two replicas remain in sync.
Make the invisible visible: one partition, before and after broker 2 dies.
# illustrative output
BEFORE Partition: 5 Leader: 2 Replicas: 2,3,1 Isr: 2,3,1
broker 2 stops
AFTER Partition: 5 Leader: 3 Replicas: 2,3,1 Isr: 3,1 ✓ new leader, still 2 in sync, writes continue
broker 3 also stops
THEN Partition: 5 Leader: 1 Replicas: 2,3,1 Isr: 1 ✗ below min.insync.replicas=2: acks=all writes are refused
What you see: the second failure refuses writes instead of accepting them on one copy. That is by design: it chooses to refuse writes rather than risk losing acknowledged data.
Security and Kubernetes, in short
Kafka ships open by default: anyone who can reach the port can read and write. Production needs three layers. TLS encrypts traffic and proves the broker's identity. SASL (a login step, with mechanisms such as SCRAM, OAUTHBEARER or mutual TLS) proves who the client is. ACLs (access control lists) say what each identity may do: write to orders, read from orders as group payments, and nothing else.
# illustrative: least privilege for the payments service user
kafka-acls.sh --bootstrap-server broker:9093 --command-config admin.properties --add \
--allow-principal User:payments --operation Read --topic orders --group payments
kafka-acls.sh --bootstrap-server broker:9093 --command-config admin.properties --add \
--allow-principal User:payments --operation Write --topic payments-results
# ✗ not granted: Delete, Alter, Create, or any topic outside the two above
On Kubernetes, Kafka is a stateful system: each broker needs stable identity and its own disk. The usual approach is an operator such as Strimzi, which turns a short YAML description into brokers, KRaft controllers, certificates, users and topics, and performs rolling updates for you. For the container basics see the Docker chapter and the Kubernetes chapter.
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: shop
annotations:
strimzi.io/node-pools: enabled
strimzi.io/kraft: enabled
spec:
kafka:
version: 4.2.0 # use a version your Strimzi release supports
listeners:
- { name: tls, port: 9093, type: internal, tls: true, authentication: { type: scram-sha-512 } }
authorization: { type: simple } # ACLs on
config:
default.replication.factor: 3
min.insync.replicas: 2
The trap: running Kafka on ephemeral storage or letting two brokers share a node or availability zone. A node loss then takes out two replicas at once. Use persistent volumes and spread brokers across zones (rack awareness).
The stack table: Kafka and its neighbours
Kafka is not always the right answer. The honest comparison is by what you need, not by which is "best". Features below are summarised in general terms; check each product's current documentation before a decision.
| Option | Pick it when | Cost or catch | Switch when |
|---|---|---|---|
| Apache Kafka | High throughput, replay, many independent consumers, stream processing, an ecosystem (Connect, Streams) | Operational weight; partitions are fixed units; per-message routing is limited | You mainly need job queues with per-message ack and routing, or one small team with low volume |
| RabbitMQ | Task queues, flexible routing, per-message acknowledgement, low-latency work distribution | Not built for long replayable history; scaling out one queue is harder | You need replay or many consumers reading the same history: move to Kafka |
| Apache Pulsar | Many tenants, geo-replication, queue and stream models in one system, storage separate from brokers | More components to run; smaller ecosystem and talent pool | Your team already runs it well; otherwise Kafka's tooling is the safer default |
| Redpanda | Kafka-compatible API with a single binary and no JVM, if you want simpler operations | Not Apache Kafka; check feature and licence fit with your needs | You depend on a Kafka feature or Connect plugin it lacks |
| AWS Kinesis | You live on AWS and want a managed stream with little to run | Shard limits and pricing; AWS-specific APIs | Multi-cloud, or you need Kafka tooling such as Connect and Streams |
| AWS SQS (or SNS + SQS) | Simple managed queue, a few messages per second to very large volume, no ordering needs | No replay; ordering needs FIFO queues with limits | You need replay, ordering across a stream, or stream joins |
| Google Pub/Sub | Managed global publish-subscribe on Google Cloud | Ordering is per ordering key and has caveats; Google-specific APIs | You need Kafka's log semantics or on-premises deployment |
| Managed Kafka (Confluent Cloud, MSK, and similar) | You want Kafka's API without running brokers | Cost at high volume; less control over upgrades and tuning | Volume makes it expensive, or compliance needs self-hosting |
Make the invisible visible: three requirements and the system each one points to.
# illustrative decision walk
"send 2,000 emails, retry each, route by priority" -> a queue: RabbitMQ or SQS
"five teams read the same order history, new team replays" -> a log: Kafka (or Pulsar, Redpanda)
"we are a 4-person team on AWS, 200 events/s, no replay need" -> SQS/SNS or Kinesis; Kafka would be overhead ✓
- Interview takeaway: "Kafka is a replayable log for many readers and large volume. For plain job queues or tiny teams a managed queue is simpler. I choose by replay, fan-out, ordering and operations cost, and I say when I would switch."
08 · DrillThe log & Producers — Q1–Q40
The first forty questions cover the two things Kafka interviews always open with: what the log actually is on disk and across brokers, and how a producer decides where a record goes and whether it survives. Senior rounds probe the trade-offs (durability against latency, ordering against throughput) rather than the vocabulary. Every answer is written to be said aloud. Say yours first, then reveal.
These questions test whether you can describe Kafka as an append-only log with a retention clock, not as a queue that deletes messages when they are read.
Q1. "What is Kafka, really? Why is it not just a message queue?"
Reveal answer
The real test Whether you say "a replicated, append-only log that consumers read at their own position" or "a queue that is faster".
Strong answer Kafka is a distributed, replicated, append-only log. Producers add records to the end. Records stay on disk until a retention rule removes them, whether or not anyone has read them.
A classic queue (RabbitMQ, SQS) hands a message to one consumer and then deletes it. Kafka does not delete on read. Each consumer group keeps its own bookmark, called an offset, saying "I have read up to here".
That one design choice gives three things a queue cannot give. Two different teams can read the same data independently. A new service can start from the beginning and replay history. A bug fix can rewind a consumer and reprocess yesterday.
The price is that Kafka does not track per-message state such as "this one failed, retry only this one". Position is the only state. That is why retries, dead-letter topics and idempotency are things you build, and why Q71 on share groups exists.
Picture it One topic, two independent readers, one record that is never deleted by being read.
The setup: A topic orders with one partition holds five records. The billing service and the analytics service each read it.
# illustrative output
orders-0 (the log, oldest on the left)
offset: 0 1 2 3 4
record: [A] [B] [C] [D] [E] <- next write goes here (offset 5)
billing group bookmark = 3 (read A,B,C; will read D next)
analytics group bookmark = 5 (read everything; waiting for new data)Make the invisible visible: Now billing reads D and E. Nothing is removed from the log.
# illustrative output
orders-0: [A] [B] [C] [D] [E] still all five on disk
billing bookmark = 5
analytics bookmark = 5
retention: records older than 7 days are deleted by AGE, not by being readWhy: The log is shared, read-only history. Each reader only owns a number. That is why Kafka is a good fit for event history and a poor fit for "give each task to exactly one worker and track its status".
Land it I describe Kafka as a durable log with consumer-owned positions, so I get replay and many independent readers, and I accept that per-message task state is something I must build on top.
- "So can Kafka act as a work queue at all?"
-
Yes, within limits. A consumer group gives you queue-like behaviour, because each partition is given to exactly one member of the group, so each record is processed by one member.
The limit is parallelism. A partition can be read by only one consumer in a group at a time, so with 12 partitions you can have at most 12 busy consumers, however many workers you start. A classic queue with 200 workers pulling from one line cannot be copied directly.
The second gap is per-message state. A queue can say "this task failed, retry only this one". A classic Kafka group has only a position, so one slow or failing record holds up everything behind it in that partition.
Newer Kafka has share groups (KIP-932, production-ready in 4.2). They give per-record acknowledgement and let several consumers read one partition. I would use them for real task-queue work and keep classic groups for ordered streams.
- "What happens to a record nobody reads?"
-
Nothing special happens to it. A record that nobody reads is treated exactly like one that everybody read: it stays on disk until retention removes it. Kafka never checks whether a record was consumed before deleting it.
The default retention is 7 days (
retention.ms= 604800000), or until a size limit if you setretention.bytes. Whichever limit is hit first wins.Retention works on whole files called segments, not single records, so an unread record may live a little past its nominal age until its whole segment is deleted. Q4 covers that in detail.
The practical lesson is about slow consumers. If a consumer group falls behind by more than the retention period, the records it has not read are deleted underneath it. The group then hits an out-of-range offset and resets according to
auto.offset.reset. So I alert on consumer lag long before it approaches the retention window. - "Why does keeping data after reading not blow up the disk?"
-
It does not blow up the disk because the log is written once, in order, and removed in big chunks. The disk cost is something you can calculate in advance from three numbers: incoming bytes per second, retention, and replication factor.
Take 10 MB/s of incoming data, 7 days of retention and replication factor 3.
disk arithmeticruns offline# illustrative arithmetic 10 MB/s x 86,400 s/day = 864,000 MB/day = about 0.86 TB/day x 7 days = about 6 TB x replication factor 3 = about 18 TB across the cluster spread over 6 brokers = about 3 TB per brokerSo the plan is throughput times retention times replication, and then I leave headroom, because a broker should not run above roughly 70 percent full. If 3 TB per broker is too much, I shorten retention, compress batches, or use tiered storage (Q15) to push old segments to cheap object storage. It is a sizing exercise, not a surprise. I also check it again whenever traffic or retention changes.
- "When is a plain queue the better tool?"
-
A plain queue is the better tool when the work is a pile of independent tasks, and each task needs its own handling: a retry count, a delay, a priority, a visibility timeout, or a per-message acknowledgement. RabbitMQ or SQS give you those as built-in features, and nobody needs to replay old tasks.
A good test is to ask what you do when one message fails. In a queue you put that one message back or move it to a dead-letter queue, and the others carry on. In a Kafka partition you must build that yourself with retry topics and a dead-letter topic, because position is the only state.
If I need both, I often keep Kafka as the event backbone, with replay and many readers, and let one service turn selected events into queue tasks for the workers.
I would not force one tool to do both jobs badly. Share groups (Q71) narrow the gap, but I would still pick the tool whose defaults match the job.
Q2. "Explain topic, partition, offset and broker. How do they fit together?"
Reveal answer
Strong answer A topic is a named stream of records, such as orders. A topic is split into partitions. Each partition is one ordered log file set. A broker is one Kafka server that stores some partitions. An offset is a record's position number inside one partition.
The offset is unique only within a partition. "Offset 7" alone means nothing. The full address of a record is topic, partition, offset: orders-2@7.
Ordering is guaranteed inside a partition and nowhere else. Two records in different partitions have no defined order relative to each other.
Partitions are the unit of everything: storage placement, replication, parallel reading and ordering. If you understand partitions, most of Kafka follows.
Picture it A topic with three partitions spread across three brokers, and what an offset looks like.
The setup: Topic orders has 3 partitions and replication factor 1 (to keep the picture small).
# illustrative output
broker-1: orders-0 [0][1][2][3][4]
broker-2: orders-1 [0][1][2]
broker-3: orders-2 [0][1][2][3]
address of one record: orders-2@3 (topic orders, partition 2, offset 3)Make the invisible visible: Five records arrive with keys. The key decides the partition.
# illustrative output
key=cust-7 -> hash -> partition 2 -> orders-2@4
key=cust-7 -> hash -> partition 2 -> orders-2@5 (same key, same partition, in order)
key=cust-9 -> hash -> partition 0 -> orders-0@5Why: Offsets increase per partition, and the same key always lands on the same partition, so all of one customer's events stay in order even though the topic as a whole has no global order.
Land it I say partition is the unit of ordering and parallelism, and an offset only means something together with its partition.
- "Is there any global ordering across the whole topic?"
-
Not unless the topic has exactly one partition. One partition gives a total order over every record, but only one consumer in a group can read it, so throughput is capped at what that single consumer can do.
Between partitions there is no defined order at all. Two records written one millisecond apart to partitions 0 and 5 can be read by a consumer in either order, because different partitions are fetched independently.
In practice I ask what actually needs order. It is almost never "every event in the company". It is "all events about one order" or "all events about one account". If I choose that identifier as the record key, the default partitioner sends all of its events to one partition, so I get the order I need and keep full parallelism across the many different orders.
The trap is to ask for global order out of habit and then be stuck with one partition and a throughput ceiling.
- "Can offsets be reused or change?"
-
No. An offset is assigned once when the record is appended and it only ever grows. Numbers are never recycled, even after the record is gone.
What does change is the start of the log. When retention deletes old segments, the log start offset moves up, so a partition may now begin at offset 40,000 instead of 0. Asking for offset 100 then returns an out-of-range error, and the consumer resets by
auto.offset.reset.Compaction also leaves gaps. If offsets 5 and 6 held old values for a key and were cleaned, the partition goes from 4 to 7. So you cannot assume offsets are consecutive, and code that does
offset + 1as "the next record that must exist" is wrong.The safe rule is to treat an offset as a position marker that is ordered but not dense. Commit "the next offset to read", and never do arithmetic that assumes no gaps.
- "How many partitions can a broker hold?"
-
There is no single magic number. Every partition replica costs the broker a few open file handles, some memory for indexes and buffers, and ongoing replication work. It also adds work for the controller when it elects leaders after a failure.
More partitions per broker means a longer wait when a broker with many leaders dies, because every one of those partitions needs a new leader.
Here is how I would reason about it in a worked example.
partition budgetruns offline# illustrative arithmetic topics: 50 x 12 partitions = 600 partitions x replication factor 3 = 1,800 replicas over 6 brokers = 300 replicas per brokerThat is comfortable. Clusters often run in the low thousands of replicas per broker at most, and I would keep a budget I have load-tested on my own hardware. I size each topic by throughput and the consumer parallelism I want. Q20 does that arithmetic.
- "What is a segment?"
-
A partition's log is not one giant file. It is stored as a series of files called segments, so deleting old data means deleting whole files, which is cheap, instead of editing the middle of a huge file.
Only the newest segment, the active one, is written to. When it fills up, it is closed (rolled) and a new active segment starts. Closed segments are never modified, which is why retention, compaction and tiered storage all work on closed segments only.
one partition on diskruns offline# illustrative output orders-0/ 00000000000000000000.log segment 1 (offsets 0..99999) closed 00000000000000000000.index sparse offset-to-file-position map 00000000000000100000.log segment 2 (offsets 100000..) ACTIVEThe file name is the first offset the segment holds, so Kafka can pick the right file for an offset just by comparing names. A segment rolls when it reaches
segment.bytes(default 1 GiB) or its age limitsegment.ms(default 7 days). Q4 shows why that matters for retention.
Q3. "Why is Kafka fast? People say it writes to disk, which sounds slow."
Reveal answer
Strong answer Kafka's disk use is almost entirely sequential: it only appends to the end of a file and reads forward. Sequential disk access is far faster than random access, and on modern hardware it is close to network speed.
Kafka also leans on the operating system's page cache instead of keeping its own big cache. Recent writes sit in RAM that the OS manages, so a consumer reading near the tail is usually served from memory, not from disk.
For sending data to consumers it can use zero-copy (the sendfile call), which moves bytes from the page cache to the network card without copying them through the Kafka process. That only works when the data is not being re-encoded, so with TLS enabled the benefit is reduced.
Finally, batching: producers and brokers move many records per request, and compression is applied per batch, so the fixed cost of a network call and a disk write is shared by hundreds of records.
Picture it Two ways to write 1,000 records, and why the second is fast.
The setup: One record is 1 KB. The disk can do a sequential write quickly but a random seek slowly.
# illustrative output (shape, not a benchmark)
RANDOM : 1000 records -> 1000 seeks to 1000 places -> head moves, cache misses
APPEND : 1000 records -> 1 batch of 1 MB at file end -> one streaming writeMake the invisible visible: The path of a record from producer to consumer touches memory first.
# illustrative output
producer batch -> broker socket -> append to active segment (page cache)
|-- flushed to disk later by the OS
consumer fetch near tail -> served from page cache -> sendfile -> network
consumer fetch of old data -> read from disk sequentially (readahead helps)Why: Kafka avoids the slow parts of a disk (seeks) and the slow parts of a JVM (big heap caches, extra copies), so throughput is limited by the network or disk bandwidth rather than by the code.
Land it I explain Kafka's speed as append-only writes, page-cache reads, zero-copy sends and batching, not as magic.
- "If data is only in the page cache, is it lost when the broker crashes?"
-
Usually not, but it depends on which kind of failure happens. If only the Kafka process crashes, the page cache survives, because the operating system owns it and still writes it to disk. Nothing is lost.
If the whole machine loses power before the OS flushes those pages, the unflushed data on that broker can be lost.
That is why Kafka relies on replication, not on an fsync after every message, for durability. A record counts as safe when enough other brokers have it. With
acks=allandmin.insync.replicas=2, the producer only gets success after at least two machines hold the record in memory and it will be flushed by them. The chance of two separate machines losing power at the same instant is far smaller than one.So the design trades a very slow flush per record for copies on several machines. Q7 explains the settings. I would not turn on per-message flushing, because it throws away the speed that makes Kafka useful.
- "What breaks zero-copy?"
-
Encryption inside the broker breaks it. Zero-copy means the kernel moves bytes straight from the page cache to the network card with the
sendfilecall, so the Kafka process never touches them. With TLS, the broker must encrypt each byte before sending, so the data has to travel through user space, and the shortcut is lost for those connections.Down-conversion does the same. If an old client asks for an older message format, the broker must rewrite the records, which means reading them into memory.
Kafka still performs well afterwards, because batching, sequential I/O and the page cache still apply. But if someone says "we turned on TLS and broker CPU rose 30%", this is the reason. Encryption is CPU work that zero-copy used to avoid.
I would keep TLS on, since plain text on a network is rarely acceptable, and size the broker CPU for it. Using modern hardware with AES acceleration helps a lot.
- "Does a slow consumer hurt the others?"
-
It can, and it is a real way for one backfill job to slow a whole cluster. Normally consumers read near the tail of the log, and that data is still in the page cache, so reads cost almost no disk work.
A consumer that starts from last month reads old segments that are not in memory. The broker must pull them from disk, and those pages push out the hot pages that the other consumers were using. Now the tail readers also hit the disk, and everyone gets slower.
I would handle it with three tools. First, put a fetch quota on the backfill client (
consumer_byte_rate), so it cannot take all the disk bandwidth. Second, run the backfill off-peak. Third, use tiered storage (Q15), so old reads are served from remote storage instead of the brokers' local disks.The warning sign is page-cache hit rate dropping and disk read latency rising when a new consumer group appears.
- "How would you show someone the batching effect?"
-
I would run the producer performance tool twice with different settings on the same hardware and compare records per second. The numbers below are illustrative, because your result depends on hardware and record size, but the shape is what matters.
batching experimentruns offline# illustrative numbers: same hardware, same 1 KB records linger.ms=0 batch.size=16384 -> ~40,000 records/s many tiny requests linger.ms=20 batch.size=131072 -> ~220,000 records/s fewer, bigger requestsThe reason is fixed cost. Every request pays for a network round trip, a header, a disk write and a response. If one request carries 1 record, that cost is paid per record. If it carries 130 records, each record pays about one hundred and thirtieth of it.
The price is latency. In the second row, a record may wait up to 20 ms for the batch to fill. For most pipelines that is a good trade. For a request-response path I would keep
linger.mssmall.
Q4 · Scenario. "Your topic has retention of 7 days but you still see records that are 8 days old. Is that a bug?"
Reveal answer
Strong answer No. Retention is applied to whole segments, not to single records. A segment is deleted only when its newest record is older than the limit, and the broker checks on a timer.
If a segment holds records from day 1 to day 8 because it was filled slowly, none of it is deleted until the day-8 record itself is 7 days old. So you can see data up to 7 days plus the time it took to fill the segment.
The checks run every log.retention.check.interval.ms (default 5 minutes). The active segment is never deleted, even if it is old, until it rolls.
To make retention tighter, lower segment.ms (so segments roll sooner) or segment.bytes. The cost is more, smaller files.
Picture it Why an 8-day-old record is still there.
The setup: retention.ms is 7 days. Low-traffic topic, so the segment has been filling for 9 days.
# illustrative output
segment-A first record day 0, last record day 4 -> newest is 7+ days old? yes -> DELETED
segment-B first record day 4, last record day 9 -> newest is 2 days old -> KEPT
(contains day-4 and day-5 records that are older than 7 days)Make the invisible visible: Fix by rolling segments daily.
kafka-configs.sh --bootstrap-server localhost:9092 --alter --entity-type topics \
--entity-name orders --add-config segment.ms=86400000
# illustrative output
# now segment-B closes at the day boundary and is deleted as a whole soon after day 7Why: Deletion cost is per file, so Kafka deletes files, not rows. The side effect is that retention is "at least this old" rather than "exactly this old".
Land it I would answer that retention deletes segments, so data can outlive the nominal limit, and I would tune segment.ms if the limit is a compliance requirement.
- "What if the rule is legal, such as delete personal data after 30 days?"
-
Do not rely on retention alone. Retention gives you "at least this age", not "gone by this moment", because whole segments are deleted late (Q4). Replicas, backups, mirrors and downstream sinks also hold copies that retention on this topic never touches.
There are two designs I would reach for. The first is a compacted topic with tombstones (Q5), so a delete is an explicit record per key. The second is crypto-shredding: encrypt each person's data with a per-person key, keep the keys in a key store, and when the law says delete, delete the key. The records stay in the log but become unreadable noise, everywhere they were copied.
Crypto-shredding turns deletion into a key-management action, which has a clear moment of completion that you can show to an auditor. A log-timing rule never does.
Whichever I pick, I list every place the data lands and make the delete flow cover all of them.
- "What is the difference between retention.ms and retention.bytes?"
-
retention.msdeletes closed segments whose newest record is older than a time.retention.bytesdeletes the oldest closed segments when one partition grows past a size. The important detail is that the size limit is per partition, not per topic.If both are set, whichever limit is reached first triggers deletion. Here is a worked example.
retention.bytes is per partitionruns offline# illustrative arithmetic retention.bytes = 10 GB, topic has 12 partitions topic can hold up to 12 x 10 GB = 120 GB with replication factor 3 on disk = up to 360 GB cluster-wideA team that thinks "10 GB for the topic" and sets that value gets a surprise on the disk bill. Both limits also work on whole segments, so neither is exact. The size limit can be overshot by up to one segment (default 1 GiB), and the active segment is never deleted.
I usually set time as the main rule and size as a safety cap against a traffic spike.
- "Can I read data older than retention?"
-
Not from the broker, once its segment is deleted. The data is physically gone from the local disks, and replicas delete on the same rule, so a replica does not keep a hidden copy.
There are only two ways to have it. One is tiered storage (Q15), which keeps old segments in remote storage and lets the same topic serve them. The other is a copy in another system, for example object storage filled by a Connect sink, from which you reload the data into a new topic when you need it.
That is why a replay plan has to check retention first. A request such as "replay the last 30 days" fails quietly if retention is 7 days: the consumer simply starts at the earliest offset that still exists, and nobody sees an error.
I would compare the requested start time with the log start offset before any replay, and write both numbers in the runbook.
- "Why not set retention to forever?"
-
You can. Setting
retention.ms=-1keeps data forever. But you must pay for it in three ways: the disk or object-storage bill grows without limit, a broker that dies must re-copy everything it held, and old data keeps growing the number of segment files to manage.The recovery cost is the one people forget. With 3 TB per broker and a 200 MB/s copy rate, a replacement takes about four hours to catch up (Q15), and during that time the cluster has less redundancy.
For event-sourced topics, where the log is the system of record, people do exactly this. They almost always add tiered storage, so recent data is local and old segments sit on cheap object storage.
My rule is that "forever" is a business decision with a named owner, not a default. If nobody can say who reads data older than a year, I do not keep it in Kafka.
Q5. "What is log compaction and when would you use it instead of time-based retention?"
Reveal answer
Strong answer A compacted topic keeps at least the latest record for every key and removes older records with the same key. Instead of "keep the last 7 days", the rule is "keep the latest state per key".
That turns a topic into a changelog of a table. Read it from the start and you rebuild the current state: the last value for each key. It is what Kafka itself uses for __consumer_offsets.
To delete a key you write a record with that key and a null value, called a tombstone. The tombstone is kept for delete.retention.ms (default 24 hours) so slow consumers can see it, then it is removed too.
Use it for state, not for events. A "customer profile" or "product price" topic fits. A "payment happened" topic does not, because collapsing history would lose events.
Picture it A compaction pass over a log with repeated keys.
The setup: A topic of customer emails, keyed by customer id.
# illustrative output
off: 0 1 2 3 4 5
key: c1 c2 c1 c3 c2 c1
val: a@x.com b@x.com a@y.com c@x.com NULL a@z.comMake the invisible visible: After the cleaner runs on the closed segments.
# illustrative output
off: 3 4 5
key: c3 c2 c1
val: c@x.com NULL a@z.com (offsets 0,1,2 gone; gaps are normal)
# c2 tombstone stays for delete.retention.ms, then it goes tooWhy: Each key keeps only its last value. A consumer that starts at offset 0 rebuilds the table in one pass, which is what makes compaction the base for "table" topics.
Land it I pick compaction when the topic is current state per key and replay must rebuild a table, and time retention when it is a stream of events.
- "Does compaction guarantee only one record per key at any moment?"
-
No. The guarantee is only that the latest record for every key is never removed. It does not say there is exactly one record per key right now.
The log cleaner works in the background on closed segments, and only when enough of the log is "dirty", which is controlled by
min.cleanable.dirty.ratio(default 0.5). The active segment is never cleaned. So at any moment a key can have several records: older ones in cleaned segments that have not been reached yet, and newer ones in the tail.The consequence for code is simple. A consumer must tolerate seeing older values for a key, apply them in order, and let the last one win. If you read the topic from the start, you rebuild the table by overwriting entries as you go.
The trap is to count records in a compacted topic and treat that as the number of keys. It is only an upper bound.
- "How can compaction and time retention be combined?"
-
Set
cleanup.policy=compact,delete. Both run on the same topic. Compaction keeps the latest record per key, and the delete rule removes anything older thanretention.ms, even if it is the latest for its key.That second part is what makes the combination useful. It suits "latest state, but forget keys that have been quiet for 30 days". Think of a session table: you want the current state of each active session, and a session that has not been updated for 30 days is dead and should disappear.
Be clear about one point when you explain it. With the combined policy the topic no longer rebuilds the complete table, because old keys are dropped by age. A consumer starting from the beginning sees only keys that were active within the retention window.
So I use it only when "forgotten after N days" is truly what the business means.
- "What are common mistakes with compacted topics?"
-
Three mistakes appear again and again.
- Null keys: a record without a key cannot be compacted, because the cleaner has no way to decide what is "latest". The broker rejects such a record on a compacted topic, and the producer sees an error. The fix is to always set a key.
- Events instead of state: compaction keeps only the latest record per key, so putting events there (such as "payment happened") quietly deletes history. If you need every event, use time retention, and keep the compacted topic for current state.
- Expecting instant delete: a tombstone is removed only after the cleaner reaches it and after
delete.retention.ms(24 hours by default). Anyone promised "gone in a minute" will be disappointed.
I also watch that the cleaner thread is alive. If it dies, the topic grows forever and nobody notices until the disk is full (Q14).
- "How would you size it?"
-
The disk need is roughly the number of distinct keys, times the size of the latest value, times the replication factor, plus the uncompacted tail that the cleaner has not reached yet.
compaction sizingruns offline# illustrative arithmetic 20 million customers x 1 KB latest value = 20 GB x replication factor 3 = 60 GB + about 30% for the uncleaned tail = about 78 GBThe 30 percent is an assumption and not a rule. The tail depends on how fast you write and how often the cleaner runs. With
min.cleanable.dirty.ratioat its default of 0.5, up to half of the closed log can be older versions before cleaning starts, so a topic that is updated heavily can be well above 30 percent. I would measure on the real topic after a week of traffic.Then I divide by the number of brokers and check against the 70 percent disk guideline from Q14.
Q6. "Explain replication: leader, followers and the ISR."
Reveal answer
Strong answer Each partition has a replication factor, say 3. One replica is the leader and handles all reads and writes for that partition. The others are followers that copy the leader's log by fetching from it.
The ISR (in-sync replicas) is the set of replicas, including the leader, that are caught up closely enough. A follower falls out of the ISR if it has not caught up within replica.lag.time.max.ms (default 30 seconds).
If the leader dies, the controller picks a new leader from the ISR, so no committed record is lost. Committed means all ISR members have it.
Durability therefore depends on two settings working together: how many replicas must acknowledge (acks=all) and the minimum ISR size that still accepts writes (min.insync.replicas). Q7 covers them.
Picture it One partition, three replicas, one follower falling behind.
The setup: Partition orders-0, replication factor 3, replicas on brokers 1, 2, 3. Broker 1 is the leader.
# illustrative output
orders-0 leader=1 replicas=[1,2,3] ISR=[1,2,3]
leader log end offset = 100
follower 2 offset = 100 follower 3 offset = 100Make the invisible visible: Broker 3 has a slow disk and stops keeping up.
# illustrative output
t=0s follower 3 offset = 70 (leader at 100)
t=31s follower 3 still behind -> removed from ISR
orders-0 leader=1 replicas=[1,2,3] ISR=[1,2] <- under-replicated: 2 of 3Why: The ISR is the safety net: a write counts as committed only when everyone in the ISR has it, and a new leader can only be chosen from the ISR, so committed data survives the leader failing.
Land it I describe the ISR as the replicas that are honestly caught up, and I say durability means acknowledging only after all of them have the record.
- "What is the high watermark?"
-
It is the highest offset that every member of the ISR has copied. Consumers can only read records below the high watermark, so they never see a record that could vanish in a failover.
The reason is safety. A record that exists only on the leader is at risk: if the leader dies now, a new leader is chosen from the followers, and they do not have it. A consumer that had already read it would have seen something that never officially existed.
After a producer write, there is a short delay until the followers fetch the record and report back, and then the watermark moves up. That delay is part of the end-to-end latency with
acks=all, usually a few milliseconds in one zone.The related name is the log end offset (LEO), the next offset to be written on a replica. On the leader, LEO is ahead of the high watermark until the followers catch up. Q13 goes through it in more detail.
- "Do followers serve reads?"
-
By default, no. Consumers read from the leader of each partition, and followers only copy the log. That keeps the rule simple: one place to read and one place to write.
Since KIP-392 a consumer can fetch from the closest replica. You set
client.rackon the consumer, and a replica selector on the brokers (replica.selector.classset to the rack-aware selector). The consumer then reads from a follower in its own zone, if one exists.The purpose is money, not speed. Cloud providers charge for data crossing zones, and a consumer in zone A reading a leader in zone B pays that fee on every byte. Reading from a local follower removes it.
The price is slightly older data, because a follower learns the new high watermark a moment after the leader does. I would turn it on when consumers and leaders sit in different zones and the transfer bill is visible.
- "What does under-replicated mean in monitoring?"
-
It means a partition has fewer members in its ISR than its replication factor, so at least one follower is behind or gone. The broker metric
UnderReplicatedPartitionscounts how many partitions are in that state.How I read it depends on how long it lasts.
- A few minutes, during a rolling restart: normal. A broker was stopped, and its replicas are catching up.
- Stays above zero: a broker is slow, down, or the network between brokers is bad. Look at disk latency, network errors and the follower's fetch rate.
- Grows over time: the cluster is overloaded or one disk is failing.
It is one of the first alerts I would set, and I would not restart the next broker in a rolling upgrade until it is back to zero. A second broker down at the same moment is how an under-replicated partition becomes an offline one.
- "How many replicas should I run?"
-
Three is the standard. With replication factor 3 and
min.insync.replicas=2, you can lose any one broker and still have two copies, so writes withacks=allcontinue and no committed data is lost.Two replicas cannot do that safely. With a factor of 2 and min ISR 2, losing one broker stops all writes. With min ISR 1, losing the leader after an acknowledged write can lose that record. So two is either unavailable or unsafe on one failure.
More than three costs real resources. Every extra replica adds disk, network and write latency, because the leader waits for more fetches. For example, factor 5 on 20 TB of data is 100 TB of disk.
The exceptions are special designs, such as stretched clusters across five sites, or a very high-value topic where surviving two failures matters. For everything else, I choose 3 and spend the extra effort on spreading the replicas across zones.
Q7. "Walk me through acks=all and min.insync.replicas. What do they guarantee together?"
Reveal answer
The real test Whether you know that acks=all alone is not enough: it only waits for the current ISR, which might be just the leader.
Strong answer acks=all makes the leader wait until every replica currently in the ISR has the record before replying success. That alone is weak, because if the ISR has shrunk to just the leader, "all" means "one".
min.insync.replicas (call it min ISR) sets the smallest ISR size at which the leader will accept a write with acks=all. With replication factor 3 and min ISR 2, a write needs at least 2 copies. If the ISR drops to 1, writes fail with NotEnoughReplicas instead of silently being kept on one machine.
Together they say: I will tell the producer "success" only when at least 2 brokers have the record. You can lose any 1 broker with no data loss and still accept writes.
The trade-off is availability. If two of three brokers are down, the topic stops accepting writes. For payments I accept that. For clickstream I might not.
Picture it Three settings combinations and what a producer sees when two brokers fail.
The setup: Replication factor 3. Brokers 2 and 3 go down, leaving the leader alone in the ISR.
# illustrative output
acks=all, min.insync.replicas=1 : write OK ISR=[1] -> ONE copy exists ❌ can lose it
acks=all, min.insync.replicas=2 : write FAIL NotEnoughReplicas -> producer retries/errors ✅ no false success
acks=1 : write OK leader only ❌ can lose itMake the invisible visible: The topic config that gives the safe behaviour.
kafka-topics.sh --bootstrap-server localhost:9092 --create --topic payments \
--partitions 6 --replication-factor 3 --config min.insync.replicas=2Why: acks=all defines who must confirm. Min ISR defines the minimum number of confirmers. Without the second, the first can quietly collapse to one.
Land it I would say acks=all with replication factor 3 and min.insync.replicas=2 is the baseline, and I would state the cost: writes stop if two brokers are gone.
- "What is the exact error a producer sees when the ISR is too small?"
-
The producer gets
NotEnoughReplicasExceptionwhen the ISR is already below the minimum, so the leader refuses the write before appending it. It getsNotEnoughReplicasAfterAppendExceptionwhen the record was appended but the ISR shrank before the leader could confirm that enough copies existed. Both are retriable, so the producer tries again.The second one is the interesting one, because the record may already be in the log. If the producer retries, it can write the record a second time. That is why duplicates are possible without the idempotent producer, which Q32 explains.
In operations, these errors are your signal that the safety setting is working. A burst of them means brokers dropped out of the ISR, and the cluster is protecting data by refusing writes.
I alert on the producer's error rate and treat it as an incident to investigate, not noise to retry silently.
- "Does min.insync.replicas apply when acks=1?"
-
No.
min.insync.replicasonly matters when the producer usesacks=all(also written-1). Withacks=1the leader replies after writing to its own log, and withacks=0the producer does not wait for any reply. Neither of them looks at the ISR size.This is a classic trap. A team sets min ISR to 2 on the topic, believes the data is safe, and never checks the producers. One service still carries an old override of
acks=1, or a different client library with a different default. When a broker dies, the leader had the only copy of the last few records, and they are lost.So I check both sides. On the broker, the topic's min ISR. On the client, the effective
acks. The client logs its full configuration at startup, which is the quickest place to look.Since Kafka 3.0 the Java producer defaults to
acks=all, but other clients may not. - "Since 3.0 the producer default is acks=all. Does that make things safe by default?"
-
Not completely. It makes the producer side safe by default, but the topic default for
min.insync.replicasis 1. So by defaultacks=allcan still shrink to a single copy: if the followers fall out of the ISR, "all" means just the leader, and the write succeeds.Think of the two settings as a pair.
acks=allmeans "wait for everyone currently in sync". Min ISR says "how many is the least that counts as enough". With min ISR at 1, a one-broker ISR counts as enough.So I always set min ISR explicitly on topics that matter. I would put it in the topic-creation template, or in the broker default
min.insync.replicas=2, so nobody has to remember it. The same goes fordefault.replication.factor=3, since a topic created with factor 1 cannot be made safe by any producer setting.The check I run is a topic description listing the factor and min ISR together.
- "What latency does acks=all add?"
-
It adds roughly one follower fetch round trip, because the leader must wait until the followers have the record before replying. Inside one zone, that is often a few milliseconds. Across zones it is more, since each fetch crosses the inter-zone network, and the slowest in-sync follower sets the pace.
latency budgetruns offline# illustrative numbers, not a benchmark acks=1 : leader append ~1 ms -> ~2 ms total acks=all : + follower fetch ~3-5 ms -> ~5-8 ms total (same zone) cross-zone followers add the inter-zone round trip each timeThese figures are made-up assumptions to show the shape. On your own hardware, measure with the producer performance tool.
The cost is small compared with what it buys. Batching hides most of it, because one round trip carries many records, so throughput barely changes while per-record latency rises by a few milliseconds. I accept that for any data I cannot lose. For fire-and-forget metrics I might not, and I would say that trade-off out loud to the team.
Q8 · Scenario. "A broker holding the leaders of 100 partitions dies at 02:00. Describe what happens, minute by minute."
Reveal answer
Strong answer The controller notices the broker is gone (its session expires, or the connection drops). For each partition that broker led, the controller picks a new leader from the ISR and tells the other brokers.
Producers and consumers get a "not leader" error on their next request, refresh their metadata and retry against the new leader. With acks=all and an ISR of 2, there is no data loss, and the pause is typically seconds.
The dead broker's partitions are now under-replicated (ISR 2 of 3). When the broker returns, it truncates anything past the committed point, catches up from the new leader, and rejoins the ISR.
If the broker is gone for good, you assign its replicas to other brokers, which copies the data. That copy is the slow part, and it competes with normal traffic.
Picture it The failover sequence for one of the 100 partitions.
The setup: orders-3, replicas [1,2,3], leader 1, ISR [1,2,3]. Broker 1 dies.
# illustrative output
02:00:00 broker 1 stops
02:00:06 controller sees session timeout (broker.session.timeout.ms)
02:00:06 controller: orders-3 new leader = 2 (from ISR [2,3]), leader epoch +1
02:00:07 producers get NOT_LEADER, fetch metadata, resend to broker 2
02:00:07 orders-3 ISR=[2,3] (under-replicated 2/3)Make the invisible visible: Broker 1 is repaired at 02:40.
# illustrative output
02:40:00 broker 1 starts, truncates log to its last known committed offset
02:40:05 fetches from leader 2 until caught up
02:41:30 rejoins ISR -> ISR=[2,3,1]
preferred leader election later moves leadership back to broker 1 (auto.leader.rebalance.enable)Why: Failover is fast because the new leader already has the data. The expensive part is the catch-up, and the risk window is the time with fewer copies than planned.
Land it I would say the failover is automatic and quick, I would watch under-replicated partitions until they reach zero, and I would not take down a second broker until they do.
- "What if broker 2, the new leader, also dies before broker 1 returns?"
-
Broker 2 becomes the leader and the ISR for the partition shrinks to [2,3]. That is still two copies, so with min ISR 2 writes continue. If broker 2 then dies too, the ISR drops to [3].
The controller can elect broker 3, because it is in the ISR and holds every committed record. But writes with
acks=allnow fail withNotEnoughReplicas, since the ISR is below the minimum of 2. Reads can still be served from the high watermark. No committed data is lost.The partition is alive for reads and paused for writes. That is the system doing exactly what the settings promise: it prefers refusing a write to keeping it on one machine.
If both 2 and 3 are down and only broker 1 returns, broker 1 is out of date, and you face the unclean election decision in Q9.
The lesson I would draw is to bring broker 1 back quickly, which restores the ISR.
- "How long is the unavailability window?"
-
The window is the sum of three parts: the time for the controller to notice the broker is gone, the time to elect new leaders, and the time for clients to refresh their metadata and retry. For a clean failure of a broker holding a modest number of partitions, that is often a few seconds.
Two things stretch it. First, detection. A broker that is killed abruptly is noticed when its session or connection to the controller breaks, while a broker that hangs may take longer. Second, volume. A broker that led 100 partitions needs 100 elections, and with thousands of partitions per broker the elections take noticeably longer.
A planned restart is different. Controlled shutdown moves the leaders away first, one partition at a time, so clients see almost nothing. That is why I always stop brokers cleanly and never kill them for convenience.
When someone asks for a number, I answer "seconds, and I would measure it in staging, because it depends on partition count".
- "What do clients do during it?"
-
Producers get retriable errors, such as "not leader for partition". They refresh their metadata to find the new leader, and with retries enabled they resend. The overall limit is
delivery.timeout.ms, which is 2 minutes by default. Consumers pause fetching for the affected partitions and resume once the metadata refresh shows the new leader.Nothing is lost on the producer side if the failover is shorter than the delivery timeout. The record sits in the producer's buffer and goes out as soon as a leader exists.
The trap is a short timeout. If a team sets
delivery.timeout.msto 5 seconds, a failover of 8 seconds surfaces as failed sends, and the application must handle them. I would size the timeout above the expected failover time with room to spare, and make sure the send callback logs every failure.Also the buffer matters. If
buffer.memoryfills during the pause,send()blocks up tomax.block.ms. - "What do you check afterwards?"
-
I work through a short checklist, in this order.
- Under-replicated partitions: must fall to zero. Until then the cluster has less redundancy than designed, and a second failure could cause loss.
- Offline partitions: must be zero, always. A non-zero value means a partition has no leader at all.
- Preferred leader balance: after the broker returns, leadership should move back to the preferred replicas, so that one broker is not carrying all the traffic. Auto leader rebalancing does this, or I run the preferred-leader election tool.
- Consumer lag: it grew during the pause and should now shrink steadily.
Only when all four are healthy would I touch the next broker. I also read the broker log for the reason it died, so I fix the cause and not only the symptom.
Q9. "What is unclean leader election, and would you ever turn it on?"
Reveal answer
Strong answer Unclean leader election lets a replica that is not in the ISR become leader when no ISR replica is available. It restores availability but can lose records that were committed.
The setting is unclean.leader.election.enable, and it defaults to false. With false, the partition stays offline until an ISR member returns. You choose consistency over availability.
With true, an out-of-date replica becomes leader. Its log is shorter. When the old leader later returns, its extra records are truncated away. Consumers may have already read some of them and offsets get reused for different data.
I would leave it off for business data. I might turn it on for a low-value, high-volume topic, such as metrics, where being offline costs more than a few lost points.
Picture it How offsets get reused after an unclean election.
The setup: ISR is [1], replica 2 is behind. Leader 1 has offsets 0..9, replica 2 has 0..6. Broker 1 then dies.
# illustrative output
before : leader=1 log 0..9 (committed 0..9) replica 2 log 0..6
broker 1 down, ISR empty, unclean election ON -> leader=2 (log 0..6)
new writes get offsets 7,8,9 with DIFFERENT data
broker 1 returns -> truncates its 7..9 and follows 2 ❌ original 7..9 lostMake the invisible visible: Contrast with clean election.
# illustrative output
unclean OFF: ISR empty -> partition OFFLINE, writes fail, nothing lost
broker 1 returns -> becomes leader with log 0..9 -> service resumes ✅Why: The ISR is the list of replicas that provably have the committed data. Leaving it breaks the promise, so the default is to stop rather than guess.
Land it I keep unclean election off and accept downtime, because an offline partition is visible and fixable while silent data loss is not.
- "Why would a team ever want it on?"
-
When availability matters more than completeness, and the data is replaceable. Typical examples are telemetry, debug logs and cache-invalidation messages. A partition that stays offline for an hour because its last in-sync replica is dead can cost more than losing a minute of readings.
Look at it as a choice between two failures. With unclean election off, the failure is visible: producers get errors, dashboards turn red, and someone fixes it. With it on, the failure is silent: the partition keeps working, and some records that were once acknowledged are gone.
Visible failures get repaired. Silent ones are discovered months later in a report that does not add up. For business data, I always choose the visible one.
Even for replaceable data, I would make it a deliberate per-topic setting with a note saying why, and never a cluster-wide default.
- "Can it be set per topic?"
-
Yes.
unclean.leader.election.enablecan be a topic-level override of the broker default, so a metrics topic can have it on while the payments topic keeps it off. The samekafka-configs.shcommand that sets retention changes it.There is also a one-time route. An administrator can trigger an unclean election for a specific partition with the leader-election tool, using the unclean election type, only when a partition is stuck offline.
one-time unclean electionruns offline# illustrative command kafka-leader-election.sh --bootstrap-server localhost:9092 \ --election-type unclean --topic metrics --partition 3I prefer this one-time action for an emergency. It is a human decision made with the facts in front of them: "this partition has been offline for an hour, the dead broker's disk is gone, and I accept the loss". Leaving the setting on permanently makes that decision for you, every time, with nobody watching.
- "How do consumers see the damage?"
-
A consumer that had read up to offset 8 may find, when it resumes, that the new leader's log ends at offset 7. Or offset 8 now holds a different record that was written after the failover. Either way, the consumer's position no longer matches the data.
What it does next depends on the situation. If its position is beyond the end, it gets an out-of-range error and resets according to
auto.offset.reset:earliestreprocesses everything,latestskips ahead. If the offset exists but holds different data, newer clients detect the divergence through leader epochs and truncate their position to the right point.Kafka uses leader epochs so consumers and followers can detect this and reconcile, but the lost records are still gone. The epochs fix confusion, not loss.
The practical result is duplicates in downstream systems, or missing records, or both. That is the real bill for an unclean election.
- "How does it relate to min.insync.replicas?"
-
They guard two different moments, and you need both for zero loss.
Min ISR protects the write path. It decides whether the leader accepts a write now: with min ISR 2, a write needs two copies, so a record is never acknowledged while it exists on just one machine.
Unclean election is about the failure path. It decides whether, when every in-sync replica is gone, Kafka may promote a replica that is behind. Keep it off and the partition waits for an in-sync replica to return.
Take either setting alone and there is a gap.
- Min ISR 2, unclean on: every acknowledged record had two copies, but if both holders die, an old replica can take over and the records are lost.
- Min ISR 1, unclean off: a single-copy record is acknowledged, and if that one machine dies, the record is gone.
So for payments I set min ISR 2 and unclean election off together.
Q10. "What did KRaft replace, and why does it matter to someone running Kafka?"
Reveal answer
Strong answer KRaft replaced ZooKeeper. Before, Kafka stored cluster metadata (topics, partitions, leaders, configs) in a separate ZooKeeper cluster. KRaft stores it in an internal log, __cluster_metadata, managed by Kafka's own controller quorum using the Raft consensus protocol.
Kafka 4.0 (March 2025) removed ZooKeeper completely, so every current cluster is KRaft. Kafka 4.3.0 came out on 22 May 2026 and is the latest I am sure about.
It matters in four ways. There is one system to run, secure and monitor instead of two. Controller failover is faster, because the new controller already has the metadata log. Clusters scale to more partitions. And the metadata is now a log, like data, which brokers replay.
A KRaft cluster has controller nodes (usually 3, or 5 for bigger risk tolerance) and brokers. They can be combined on small clusters, but separate controller nodes are the production choice.
Picture it The old and new shapes, with the number of moving parts.
The setup: A production cluster with 6 brokers.
# illustrative output
BEFORE (ZooKeeper) AFTER (KRaft, Kafka 4.x)
6 brokers 6 brokers
3 ZooKeeper nodes 3 controller nodes (Kafka processes)
two config styles, one config style,
two security setups, one security setup,
two upgrade paths one upgrade pathMake the invisible visible: What a controller does on failure.
# illustrative output
controllers: C1 (active leader), C2, C3 each hold the metadata log
C1 dies -> C2 or C3 wins a Raft election (majority 2 of 3) in about a second
the new active controller already has every committed metadata record
no full reload of cluster state from an external systemWhy: Putting metadata into Kafka's own replicated log removes the external dependency and makes failover a log-continuation, not a rebuild.
Land it I say ZooKeeper is gone as of Kafka 4.0, and I would run three dedicated KRaft controllers and treat their quorum as the most important thing to protect.
- "How many controllers do you need and why odd numbers?"
-
KRaft uses a Raft quorum, and Raft needs a majority of the controllers to agree before it can make any decision. A majority of 3 is 2, so a group of 3 survives one failure. A majority of 5 is 3, so a group of 5 survives two.
That is why the number is odd. An even number adds cost without adding tolerance, as the table shows.
Controllers Majority needed Failures tolerated 3 2 1 4 3 1 5 3 2 Four controllers tolerate the same single failure as three, but cost one more machine and make it slightly harder to reach a majority.
Three is the usual choice. I choose five where a second failure during maintenance is a real risk, for example when one controller is already down for a planned upgrade. Past five there is little gain, and every extra member slows commits slightly.
- "What happens if the controller quorum loses its majority?"
-
The cluster loses the ability to change metadata. No new topics can be created, no partition can get a new leader, and no config change is accepted. It can still serve what already works.
Existing leaders keep serving reads and writes for a while, because brokers hold the metadata they last received. So at first the cluster looks fine. The danger is the next failure. If a broker dies, nobody can elect a replacement leader, and those partitions stay offline until the quorum is back.
That makes the controller quorum the most important thing to protect, as the land line says. A short plan follows from it:
- Run three dedicated controller nodes in separate racks or zones.
- Monitor them separately from the brokers, and alert when the quorum has fewer than all members.
- Practise the recovery: restore a failed controller from its metadata log, and know how to read the controller's state.
I would never put controller duty on the busiest brokers in production.
- "How did teams migrate from ZooKeeper?"
-
Kafka 3.x offered a ZooKeeper-to-KRaft migration path. The process stood up KRaft controllers next to the old ZooKeeper cluster, copied the metadata across, switched brokers over in steps, and finally removed ZooKeeper. Check the migration documentation for the exact 3.x version you run, because the supported path changed between releases.
The key constraint is that Kafka 4.0 (March 2025) has no ZooKeeper mode at all. A cluster still on ZooKeeper cannot upgrade straight to 4.x. It must first move to KRaft while on a 3.x version that supports the migration, and only then upgrade.
So if someone describes a legacy cluster to me, the order of work is:
- Upgrade: bring it to the latest 3.x that supports migration.
- Migrate: move metadata to KRaft and verify.
- Upgrade again: go to 4.x.
I would rehearse the whole thing on a copy first.
- "Does KRaft change anything for application code?"
-
For application code, no. Producers and consumers talk to brokers with the same protocol as before, and nothing in the send or poll calls changes. A service written against Kafka 2.x still connects to a KRaft cluster with only
bootstrap.servers.What changed is on the operations side. Admin tools take
--bootstrap-serverand never a ZooKeeper address. Tools that once wrote straight to ZooKeeper now go through the brokers. Metadata is stored in an internal log and not in ZooKeeper nodes. Security is configured for controllers as well as brokers.So a runbook is the place to look. Any line that mentions a ZooKeeper connect string, a
zookeeper.connectproperty or--zookeeperis out of date, and a script using one fails on 4.x.I would search the repository and runbooks for the word "zookeeper" as the first step of an upgrade project.
These questions test whether you can find the real cause of lost data, choose settings for a stated risk, and do throughput arithmetic out loud.
Q11 · Scenario. "A producer team says "we use acks=all, yet we lost 300 orders during last night's broker crash". Where do you look?"
Reveal answer
The real test Whether you check the topic's replication factor and min ISR before blaming Kafka.
Strong answer acks=all only waits for the current ISR. So the first question is how big the ISR was at the moment of the crash. If the topic has replication factor 1, or min.insync.replicas=1, "all" meant one broker.
I check four things in order. The topic description (replication factor, min ISR). The ISR history around 02:00 in broker logs and the under-replicated metric. Whether unclean leader election was enabled. And whether the producer really ran with acks=all, since an old override or a different client library may have set acks=1.
Then I check the producer side: did it ignore send failures? A fire-and-forget send() with no callback loses records without anyone noticing.
Only after those do I suspect a Kafka bug. In my experience the answer is nearly always configuration.
Picture it Reading the evidence, from topic to producer.
The setup: Topic orders, 300 orders missing after broker 2 crashed.
kafka-topics.sh --bootstrap-server localhost:9092 --describe --topic orders
# illustrative output
Topic: orders PartitionCount: 6 ReplicationFactor: 2
Configs: min.insync.replicas=1 # ❌ TRAP: one copy is enough
Partition: 3 Leader: 2 Replicas: 2,1 Isr: 2 # ISR had shrunk to just broker 2Make the invisible visible: What the ISR was doing in the hour before the crash.
# illustrative output
01:40 Shrinking ISR for orders-3 from 2,1 to 2 (follower 1 lagging)
01:40 producer sends acks=all -> satisfied by leader alone (ISR size 1 >= min ISR 1)
02:00 broker 2 disk fails, its log is gone
02:03 broker 1 elected (unclean election was ON) -> its log is 300 records shorterWhat you see: Replication factor 2, min ISR 1 and unclean election on, which together mean "one copy is enough, and an old copy may lead".
The fix: Replication factor 3, min ISR 2, unclean election off, and a producer that checks every send result.
kafka-configs.sh --bootstrap-server localhost:9092 --alter --entity-type topics \
--entity-name orders --add-config min.insync.replicas=2,unclean.leader.election.enable=false
# replication factor is changed by a partition reassignment, not by a configWhy: Each setting guards a different moment. Min ISR guards the write, unclean election guards the failover, and producer callbacks guard the application edge.
Land it I would say the loss is almost certainly a one-copy write, and I would verify with the topic description and the ISR history before touching the producer.
- "Can the producer detect that its write was never really safe?"
-
Not by itself, if it is on
acks=1or if the topic allows a one-copy write. The producer cannot see the ISR. It only sees the reply, and a reply of "success" arrives whether the record has one copy or three.With
acks=alland a proper min ISR, the answer changes. The broker refuses a write that would end up on fewer copies than the minimum, and the producer receives an error. That error is the detection, and it is the whole point of the pair.So the design is in two halves. First, make the broker reject unsafe writes, with min ISR 2 and replication factor 3. Second, make the producer treat any send error as an alert: a callback that logs, counts and raises a metric, and never a fire-and-forget
send()that drops failures silently.Where I cannot trust the application, I add an audit: compare a count of events the service says it sent with the count the topic holds for the same period.
- "How do I change the replication factor of an existing topic?"
-
You write a reassignment plan that lists the new replica set for each partition, and run the partition reassignment tool. The brokers then copy the data in the background. The factor changes when the new replica list is longer or shorter than the old one.
The copy competes with live traffic, so I use a throttle in bytes per second and run it off-peak.
reassignment shaperuns offline{"version":1,"partitions":[ {"topic":"orders","partition":3,"replicas":[2,1,3]} ]}This plan lists partition 3 with three replicas. If it previously had one, the factor goes from 1 to 3 for that partition. A real plan lists every partition of the topic.
The steps I follow: generate the plan, review it, execute with
--throttle, then verify until it reports completion and remove the throttle. The first replica in the list is the preferred leader. Because it is a planned operation and not a switch, I rehearse it on a smaller topic first. - "How do I find which messages were lost?"
-
You cannot read what the log no longer has, so you compare against something that remembers independently: the orders table in the database, or the producer's own record of what it intended to send.
The method is a reconciliation. Take the set of order ids in the database for the night in question. Take the set of order ids found in the topic for the same period. The difference is the lost set.
- Collect: export order ids and timestamps from the database for the outage window.
- Read: consume the topic for the same window and collect the ids it holds.
- Subtract: ids present in the database and absent from the topic are the lost events. Republish them.
That is the strongest argument for the outbox pattern (see e07,
#pat-outbox). The database row is written in the same transaction as the business change, so it remembers what was meant to be sent, and a gap becomes repairable instead of a mystery. - "Would exactly-once have prevented this?"
-
No. Exactly-once and durability answer different questions. Exactly-once is about duplicates and about writing to several places atomically: "if the producer retries, the broker keeps one copy", or "these three writes become visible together". It does not make a record that lives on one broker survive that broker's death.
Durability is about how many copies exist when you tell the producer "success". That is controlled by replication factor,
min.insync.replicas,acksand unclean election, which this chapter covered in Q6 to Q9.The right way to say it is as layers. Replication settings give you a record that survives a failure. The idempotent producer gives you a record that is stored once even with retries. Transactions give you atomic multi-partition writes. Each layer assumes the one below it is solid.
Mixing these up is a common interview slip, so I name them separately, and I tell the team that turning on exactly-once would not have saved those 300 orders.
Q12 · Design. "Design the topic and producer settings for a payments-events topic where losing an event is unacceptable."
Reveal answer
Strong answer I start from the failure I must survive: one broker or one zone lost with zero data loss, and the system still accepting writes. That gives replication factor 3 across three zones and min.insync.replicas=2.
On the producer: acks=all, enable.idempotence=true (both defaults since 3.0, but I set them explicitly), a generous delivery.timeout.ms, and a send callback that records failures.
On the broker side: unclean.leader.election.enable=false, default.replication.factor=3, and rack awareness so replicas sit in different zones.
Upstream, I would not trust a plain send() after a database commit. I write the event to an outbox table in the same transaction and let a relay or CDC publish it.
The honest cost: latency of a few milliseconds more per write, and writes stop if two replicas are unavailable.
Picture it The settings as one reviewable block.
The setup: Three brokers, one per zone, topic payments-events.
# topic (created with kafka-topics.sh --replication-factor 3 --partitions 12)
min.insync.replicas=2
unclean.leader.election.enable=false
retention.ms=2592000000
# producer
acks=all
enable.idempotence=true
delivery.timeout.ms=120000
max.in.flight.requests.per.connection=5
compression.type=lz4Make the invisible visible: What each zone failure looks like.
# illustrative output
lose 0 zones : ISR=3 writes OK
lose 1 zone : ISR=2 writes OK (min ISR 2) no data loss ✅
lose 2 zones : ISR=1 writes REJECTED no data loss ✅ (availability traded away)What you see: At worst the producer gets an error; it never gets a false "success".
Why: Every choice moves a failure from silent loss to a visible error, and visible errors can be retried or alerted on.
Land it I would pick replication factor 3, min ISR 2, acks=all, unclean election off, and an outbox in front, and I would say out loud that I am trading write availability for no loss.
- "What if the business needs writes even when two zones are down?"
-
Then it is a different requirement, and I would say so out loud. A cluster that stops accepting writes when two replicas are gone is doing its job. Making it accept writes anyway means giving up the zero-loss promise on those writes.
The better answer is to move the buffering to the application edge. The outbox table does exactly that. The service writes the event into its own database in the same transaction as the business change, and a relay publishes it when Kafka is available again. The customer's order succeeds, and the events wait safely in a durable table.
That gives availability where the user sees it, without lowering the cluster's safety. The cost is delay: events reach consumers late, and the outbox table must not fill up. I would alert on the age of the oldest unpublished row.
If a second cluster in another region is acceptable, a producer can fail over to it, but that creates two logs with a gap to reconcile, which is another conversation.
- "Why 12 partitions?"
-
Because of the consumer parallelism I want and the throughput I expect. The approach is the one from Q20: divide the target throughput by what one consumer instance handles, round up, and add headroom. Twelve gives me up to 12 parallel consumers, divides evenly across 3 zones and 2, 3, 4 and 6 consumer instances, and leaves growth room.
The reason I decide it carefully is that with keyed data, partition count is hard to change later. Q22 shows that adding partitions moves keys and breaks per-key order. So I choose a number with headroom now.
If the expected throughput is small, 6 is also fine. The point is to arrive at the number from arithmetic and not from habit.
For payments events, I would also check that no single key dominates, because a hot key fills one partition however many I add (Q24).
- "Would you use transactions for this topic?"
-
Only if a consume-transform-produce step must be atomic (Q62). For a simple publish of events from a service, the idempotent producer plus an outbox is enough. The producer then stores each record once even with retries, and the outbox ensures nothing is forgotten.
Transactions add real cost. Each one involves a coordinator, extra requests to begin and commit, and a marker written to every partition touched. Readers who want to ignore uncommitted data must use
isolation.level=read_committed, and they see records only after commit, so latency rises.Here is how I would decide. If the flow is "read from topic A, compute, write to topic B, and record the input offset, all or nothing", I use a transaction, because otherwise a crash between steps gives duplicates or gaps. If the flow is "write one event", I do not.
I add transactions when the use case demands them, not by default.
- "How would you test that the settings work?"
-
I would run a failure drill in a staging cluster built like production. Produce at a steady rate, kill one broker, then two, and compare acknowledged records with records that are readable afterwards.
- Baseline: produce 120,000 records and count the acknowledgements.
- One broker down: kill a broker mid-run. Expect no errors beyond a short pause, and every acknowledged record readable.
- Two brokers down: expect producer errors, because the ISR drops below 2, and still every acknowledged record readable.
drill result you wantruns offline# illustrative output acked by producer: 120,000 readable by consumer: 120,000 after 1 broker killed OK 2 brokers killed: producer errors began; acked 120,000 -> readable 120,000 OKThe pass condition is that the two numbers match. A drill that only checks "the cluster stayed up" proves nothing about loss, so I also run it again after every configuration change, and after every broker or Kafka version upgrade, because a setting that held last quarter may not hold now.
Q13. "What is the high watermark, and why can a consumer not read the very latest record the leader has?"
Reveal answer
Strong answer The high watermark (HW) is the offset up to which all ISR replicas have the data. Consumers can only read below it. The leader may hold records past it that followers have not copied yet.
The reason is safety. If the leader crashed right now, a record only on the leader could vanish. A consumer that had read it would have seen something that never officially existed.
The related name is log end offset (LEO): the next offset to be written on a replica. The leader's LEO is ahead of the HW until followers catch up.
With transactions there is one more bound, the last stable offset (LSO), which holds back records of still-open transactions for read_committed consumers (Q63).
Picture it Leader and two followers, with the three markers.
The setup: Leader has 10 records (offsets 0 to 9). Follower A has 0 to 8. Follower B has 0 to 7.
# illustrative output
leader LEO=10 [0][1][2][3][4][5][6][7][8][9]
follower A LEO=9 [0][1][2][3][4][5][6][7][8]
follower B LEO=8 [0][1][2][3][4][5][6][7]
HW = min(LEO of ISR) = 8 -> consumers may read offsets 0..7Make the invisible visible: Followers fetch again and the marker moves.
# illustrative output
follower A LEO=10, follower B LEO=10 -> HW=10 -> consumers may read 0..9Why: The gap between LEO and HW is the unsafe tail. Hiding it from consumers is what makes a failover invisible to them.
Land it I explain the high watermark as the "everyone has it" line, and I say consumers never read past it so a failover cannot take back what they saw.
- "Does the high watermark add latency for consumers?"
-
Yes, slightly. A record becomes visible to consumers only after every ISR member has fetched it and the leader has advanced the high watermark. In a healthy same-zone cluster that adds a few milliseconds on top of the leader's own write.
A slow ISR member raises that delay for everyone. The leader cannot advance the watermark until the slowest in-sync follower catches up, so a follower with a sluggish disk makes every consumer and every
acks=allproducer wait.That is exactly why Kafka removes a lagging follower from the ISR after
replica.lag.time.max.ms(30 seconds by default). Removing it lets the watermark move again, and the ISR shrinks. It then catches up and rejoins.The trade-off is worth knowing. A tighter lag limit shortens the stall but makes followers drop out during brief hiccups, which makes under-replication alerts noisier. I would leave the default unless I measure a real problem.
- "How does the high watermark relate to acks=all?"
-
The leader replies to an
acks=allproducer when the record has been replicated to every ISR member, which is the same point as the high watermark moving past that record. So "acknowledged" and "readable by consumers" happen at nearly the same moment.That is a very useful property. If a producer receives success, any consumer that polls afterwards will see the record. There is no window where the producer was told "done" but a reader still cannot see the data.
It also means a consumer never reads a record that the producer was later told failed because of replication: records beyond the watermark are hidden. A producer can still see an error for a record that was appended, such as the
NotEnoughReplicasAfterAppendcase from Q7, and retry it, which is why idempotence matters.With
acks=1the link is broken. The leader replies before replication, so a producer can hold a success for a record that consumers cannot read yet, and that could still be lost in a failover. - "What are leader epochs for?"
-
Each time leadership of a partition changes, the epoch number goes up by one. Every record batch is stamped with the epoch of the leader that wrote it, and each replica remembers where each epoch started in its log.
When a follower comes back after a failure, it asks the new leader: "where did my last epoch end?" The leader answers with an exact offset, and the follower truncates its log to that point, then copies forward. It cuts off precisely the records that the new leader never had.
Before epochs, a returning follower truncated to its own high watermark and then copied. In rare failure sequences, such as two quick leader changes, that could keep records the new leader did not have, or drop ones it did. Replicas ended up with different data at the same offset.
The result is that replicas converge to the same log after failures. Consumers also use the epoch to detect that their position came from an older leader.
- "What does
read_uncommittedversusread_committedchange?" -
It decides how far the consumer may read.
isolation.level=read_uncommittedis the default. It reads up to the high watermark and sees every record, including records of transactions that were later aborted.read_committedreads only up to the last stable offset (LSO) and skips records of aborted transactions. The LSO is the offset before the first transaction that is still open, so one long-running transaction can hold back everything behind it.- Producers use no transactions: both settings behave the same, and nothing is held back.
- Producers use transactions and you want atomic reads: set
read_committed. - A transaction hangs open: readers with
read_committedstall behind it until it commits, aborts, or times out.
So I set
read_committedonly when producers really use transactions. Otherwise it changes nothing and only adds a source of surprise.
Q14 · Scenario. "A broker's disk fills up at 90% of the retention window. What happens and what do you do?"
Reveal answer
Strong answer When a broker's log directory runs out of space, the broker cannot append, and it takes that directory offline. With a single log directory the broker shuts down. Its partition leaders move away, and replicas of those partitions go under-replicated.
The urgent action is to free space safely without making things worse. I would not delete files by hand under the broker. Instead I lower retention.ms or retention.bytes on the biggest topics so Kafka deletes old segments itself.
Then I find out why. The usual causes are retention longer than the disk plan, a traffic spike, a consumer-less topic nobody expires, or a compacted topic whose cleaner thread died.
The lasting fix is capacity alerts at 70 percent, a disk plan from throughput times retention (Q1), and tiered storage for old data (Q15).
Picture it Find the heavy topics, then shrink retention on the right one.
The setup: Broker 4 at 98 percent disk. Log directory /var/kafka.
kafka-log-dirs.sh --bootstrap-server localhost:9092 --describe --broker-list 4 | head
# illustrative output (sizes in GB per topic on broker 4)
clickstream 410
orders 60
audit-log 220 # retention.ms=-1 by mistakeMake the invisible visible: Reduce retention on the topic that should never have been infinite.
kafka-configs.sh --bootstrap-server localhost:9092 --alter --entity-type topics \
--entity-name audit-log --add-config retention.ms=1209600000
# illustrative output
# 5 minutes later: audit-log on broker 4 drops 220 GB -> 70 GB, disk 71%What you see: The cleaner thread deletes closed segments older than 14 days within one check interval.
Why: Letting Kafka delete through its own rules keeps the index files and replicas consistent. Deleting files by hand can corrupt the log.
Land it I would shrink retention on the culprit topic, never touch segment files by hand, and then add disk alerts and a sizing plan so it does not recur.
- "Can the broker survive with multiple log directories?"
-
Yes. With JBOD, which means several disks listed in
log.dirs, a failed or full directory goes offline and the broker keeps serving the partitions stored on the other directories. The partitions on the bad disk become under-replicated, and their leadership moves to other brokers.That is a big difference from a single log directory. With one directory, a full disk shuts the broker down, and all its partitions fail over at once. With several, only a slice of its partitions is affected.
Replication still protects the data. After I replace or clean the disk, I restart the broker, and the missing replicas copy back from the current leaders. The copy takes time, so I watch the under-replicated metric until it is zero.
I would not run on one huge disk if I can avoid it. Several smaller disks limit the effect of one failure, at the cost of some uneven filling between them, which needs monitoring.
- "What if the full topic is compacted and not shrinking?"
-
Check the log cleaner first. Compaction runs on cleaner threads inside the broker. If one dies, for example on a corrupted record or a key plus value too large for its buffer, compaction silently stops on that broker and the topic grows without limit.
The broker log names the failed cleaner thread. A log line along the lines of "cleaner thread stopped" is what I search for. The cleaner metrics also show it, since the "time since last run" metric for the cleaner keeps growing.
- Find: search the broker log for the cleaner failure and read the cause.
- Fix: repair the cause. For a too-small buffer, raise
log.cleaner.dedupe.buffer.size; for a bad record, deal with that topic or segment. - Restart: restart the broker so the cleaner starts again, then watch the log size shrink.
I would also alert on the cleaner's health, so the next failure is found before the disk is full.
- "How do I prevent a runaway producer from filling a disk?"
-
Use client quotas on produce bytes per second for that client id or user, and use
retention.bytesas a second cap per partition. A quota makes the broker slow the client down once it exceeds its rate, so one runaway job cannot take the whole disk plan with it.set a produce quotaruns offline# illustrative command kafka-configs.sh --bootstrap-server localhost:9092 --alter \ --add-config 'producer_byte_rate=10485760' --entity-type clients --entity-name batch-loader # batch-loader is now limited to 10 MB/s (10485760 bytes per second)The arithmetic shows why it works. At 10 MB/s a client can write at most 864 GB per day. Without a quota, a bug that loops at 200 MB/s writes 17 TB in a day, which fills a disk in hours.
Quotas are applied per broker, so the effective limit for a client spread across several brokers is higher than the number you set. I give each important client its own client id, so that a quota or an alert names the culprit.
- "Should I reassign partitions to a roomier broker?"
-
As a second step, yes. If one broker is simply fuller than the others because of uneven partition placement, I move some of its partitions to a roomier broker with a throttled reassignment. The first step is still to free space or slow the writes, because a reassignment itself needs disk and network on both ends.
The copy competes with live traffic, so I set a throttle in bytes per second, and I run it off-peak. A reassignment that is not throttled can saturate the network and make the incident worse.
For a larger cluster, I would not do this by hand every time. A balancing tool, with Cruise Control being the common open-source one, watches disk use, traffic and leader counts per broker, and proposes moves that even them out. It can also run self-healing after a broker failure.
Whichever way, the aim is that no broker is far above the average, because the fullest broker decides when the cluster has a problem.
Q15. "What is tiered storage and when is it worth it?"
Reveal answer
Strong answer Tiered storage keeps recent data on the brokers' local disks (the hot tier) and moves older closed segments to remote storage such as object storage (the remote tier). It has been generally available since Kafka 3.9.
Consumers read the same topic the same way. If they ask for old offsets, the broker fetches those segments from the remote tier.
It is worth it when you want long retention (months or years) but do not want to buy broker disks and wait for huge re-replication for data that is rarely read. Local retention stays short, so broker recovery is fast.
It is not worth it for short-retention topics, and it does not make old reads as fast as local ones.
Picture it Two retention settings on one topic.
The setup: Topic events should be replayable for 1 year but only the last 2 days are read daily.
remote.storage.enable=true
local.retention.ms=172800000 # 2 days on broker disks
retention.ms=31536000000 # 365 days in total (rest in object storage)Make the invisible visible: What lives where after 10 days.
# illustrative output
day 0..2 : on broker local disk (hot) AND uploaded to remote
day 2..365 : only in remote object storage
broker disk need: 2 days of data, not 365 -> about 99% less per-broker diskWhy: Separating how long you keep data from how much broker disk you buy is the point. Broker loss also recovers faster because a new broker only copies the hot tier.
Land it I would use tiered storage for long-retention topics read mostly at the tail, and I would stay with local storage for short-retention, latency-critical ones.
- "What do I give up?"
-
Mostly speed and simplicity. Reads of old data are slower, because the broker must fetch those segments from remote storage, and each fetch costs object-storage requests and bandwidth. Cost moves from disk to request charges, so a heavy backfill can produce a visible bill.
You also take on a component. The remote storage plugin is something you run, upgrade and monitor, and when the remote store is slow or down, old reads fail even though the brokers are healthy.
There are feature limits as well. I recall that compacted topics have restrictions with tiered storage, and that details changed between versions, so I would check the current documentation for the version I run before planning on a particular combination. I would not claim more than the documentation states.
Short answer for an interview: tiered storage gives cheap long retention and faster broker recovery, and it costs read latency and one more thing to operate.
- "Does it change durability?"
-
Not for recent data, which is still replicated across brokers exactly as before, with the same replication factor and min ISR. What changes is old data. Once a segment has been uploaded and is older than the local retention, the remote store becomes its home.
So the durability model for old data is the storage provider's. Object storage typically keeps many copies in several facilities, so the durability is usually very high, often higher than a broker disk with three replicas. The guarantee you quote for old data is the provider's published figure, not Kafka's.
There is one detail I would state carefully. Only closed segments are uploaded. The active segment stays local and depends on replication until it rolls.
The new risk is operational, not statistical. If someone deletes the bucket, misconfigures access or lets a lifecycle rule expire the objects, old data goes with no replica to fall back on. I protect the bucket with versioning and tight permissions.
- "How does it speed up broker recovery?"
-
A replacement broker only has to copy the local tier, not the whole history. Old closed segments live in the remote store and are not copied at all. That turns a day-long recovery into minutes. Here is the simple arithmetic.
recovery copy sizeruns offline# illustrative numbers without tiering: 3 TB per broker at 200 MB/s copy rate = 15,000 s = about 4.2 hours with tiering : 60 GB hot tier at 200 MB/s = 300 s = 5 minutesThese numbers are assumptions chosen to show the ratio: the recovery time scales with the local data size. Your copy rate is limited by the disk, the network and any throttle you set.
Why it matters: while a replacement catches up, the cluster has less redundancy. Four hours of reduced safety is a real risk, and five minutes is not. The same effect helps when you add brokers or move partitions, since there is less data to move.
- "When would you not use it?"
-
I would avoid it in three situations.
- Retention is already short: if topics keep 3 days, there is little old data to move, and the extra component buys nothing.
- The team cannot run the plugin reliably: a remote tier with weak monitoring turns old data into a hidden liability.
- Old reads are frequent and latency-sensitive: if consumers often read days-old data and need millisecond response, the remote fetches will hurt.
In those cases, plain local retention, sized with the arithmetic from Q1, is simpler and faster. If the real need is long-term analysis rather than replay, a Connect sink that writes the data to a lake or warehouse may fit better, since query engines read that format directly.
The question I ask first is "who reads data older than a week, and how fast do they need it?" The answer usually picks the tool.
Q16 · Scenario. "You deleted a customer in the database and wrote a tombstone to the compacted topic, but the customer still shows up in a downstream cache a week later. Why?"
Reveal answer
Strong answer Three common causes. First, the tombstone's key did not match the key of the earlier records, for example a different serializer or a wrapped key, so it deleted nothing. Second, the consumer ignored the null value and never removed the entry. Third, the cache rebuilt from a copy that was read before the tombstone was written.
Mechanically, a tombstone is a record with the same key and a null value. Compaction removes older records for the key. The tombstone itself stays for delete.retention.ms (24 hours by default), then is removed.
A consumer that was offline longer than that, and restarts from a snapshot taken earlier, can miss the delete entirely. The topic no longer shows it.
The fix is on the consumer side: apply null values as deletes, and make sure consumers are not offline longer than the tombstone's retention.
Picture it A tombstone arriving, and a consumer that ignores it.
The setup: Key cust-42 was written with a@x.com; then a null value is written for the same key.
# illustrative output
log : cust-42=a@x.com ... cust-42=NULL
consumer loop:
if (value != null) cache.put(key, value) // ❌ TRAP: null is skipped, nothing is deleted
// ✅ if (value == null) cache.remove(key); else cache.put(key, value);Make the invisible visible: Window in which a late consumer can miss it.
# illustrative output
day 0 tombstone written
day 1 delete.retention.ms (24 h) elapses; tombstone removed by compaction
day 3 consumer restarts from an old snapshot: never sees tombstone -> cust-42 stays ❌Why: The log promises the latest value per key, and a deleted key eventually has no record at all. A consumer must be able to rebuild by replay from the start, or its snapshot must be newer than the tombstone window.
Land it I would check key equality first, then the consumer's null handling, then the consumer downtime against delete.retention.ms.
- "How do I make deletes safer for slow consumers?"
-
Raise
delete.retention.msabove the longest time a consumer might be offline. The default is 24 hours. If a cache service can be down for a long weekend, 7 days is a safer value.The reason is how a tombstone works. It is a record with the key and a null value. Compaction first removes older records for the key, and the tombstone itself stays only for
delete.retention.ms, then it is removed too. A consumer that was offline longer than that, and which restarts from an older snapshot, never sees the delete. The topic has no trace of it any more, and the old value stays in the cache.There are two ways to be safe. One is the longer tombstone window, which costs a little disk. The other is to rebuild the cache from the topic on startup, not from a snapshot, so the cache reflects what the compacted topic says now.
- "Does a tombstone also delete the record from followers?"
-
Yes. Compaction runs on every replica of the partition, and the tombstone itself is replicated like any other record. So followers also drop the older values for that key, and they keep the tombstone for
delete.retention.msas the leader does.There is no cluster-wide moment of deletion, though. Each replica cleans its own log on its own schedule, so for some time one follower may still hold an old value that another has already removed. Reads normally come from the leader, so consumers mostly see the leader's view.
This matters in two ways. First, a deletion you announce as "done" is only done once every replica has cleaned. Second, a leader change can move readers to a replica that has not cleaned yet, so the old value can briefly reappear for a consumer that reads from the start.
I would never describe compaction as an immediate erase. It is eventual cleanup, driven by the dirty ratio and segment rolls.
- "Is compaction a legal-deletion tool?"
-
Only partly. Compaction eventually removes old values for a key from the topic, which helps. But it is not a legal-deletion tool, because the topic is only one of many places the data lives. Backups, mirrored clusters, tiered-storage copies, Connect sinks, caches and data lakes hold copies that compaction never touches.
Timing is also loose. Cleaning is asynchronous, the active segment is skipped, and the tombstone itself stays for a day by default. A regulator who asks "when was the data gone?" gets an answer of "eventually, in this one place".
For privacy deletion, I design the delete flow across all stores:
- List every system that receives the data, including sinks and backups.
- Send a delete event that each of them must act on, and track the acknowledgements.
- Prefer crypto-shredding for data inside logs: delete the person's encryption key and the copies become unreadable.
I would not promise anyone "compaction deletes it" without checking every copy.
- "How do I confirm the tombstone exists?"
-
Read the topic from the beginning with the console consumer, printing keys and values so that nulls are visible, and filter for the key. A tombstone shows up as the key followed by
null.check for tombstoneruns offline# illustrative command and output kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic customers \ --from-beginning --property print.key=true --property print.value=true | grep cust-42 cust-42 a@x.com cust-42 nullTwo lines for the key mean the old value has not been compacted away yet, and the second, null, line is the tombstone. After the cleaner has run, the first line disappears, and after
delete.retention.msthe tombstone does too.If there is no null line at all, the tombstone was never written, or it was written with a different key than the earlier records, which is the first cause on the page. I would compare the key bytes, not only the text, because a different serializer produces a different key even when it prints the same.
Q17 · Design. "Choose retention and cleanup policies for three topics: clickstream, order events, and a customer-profile table."
Reveal answer
Strong answer I pick by asking what the data is. Clickstream is a high-volume stream whose value fades fast: time retention of 3 to 7 days. Order events are business history: longer time retention, maybe 30 days local with tiered storage for a year. The customer profile is current state per key: compaction.
For each one I also set partitions and replication to match its value. Clickstream tolerates replication factor 3 with min ISR 1 if loss is acceptable, but I would still prefer 2. Orders get min ISR 2. The profile table is small, so partitions are few and replication is 3.
I also decide who the readers are. Analytics needs history; a service that rebuilds cache needs the compacted table.
Picture it The three topics as a decision table.
The setup: Expected volumes: clickstream 50 MB/s, orders 2 MB/s, profiles 0.1 MB/s with 10 million keys.
# illustrative output
topic policy retention RF minISR why
clickstream delete 3 days 3 1 huge, low value per record, replayable from source
orders delete + tiered 30 d local 3 2 business history, audit
1 year total
profiles compact (by key) 3 2 current state; rebuild tables by replayMake the invisible visible: Disk estimate for clickstream, because it dominates.
# illustrative numbers
50 MB/s x 86,400 = 4.32 TB/day
x 3 days = 12.96 TB
x RF 3 = about 39 TB across the clusterWhy: One cluster hosts all three because the settings are per topic. The cost sits almost entirely in the biggest, least valuable topic, so that is where retention discipline pays.
Land it I match policy to what the data is: delete by age for streams, compact for state, tier for long history.
- "Would compression reduce the clickstream number?"
-
Yes. Compression is applied per batch, and text-like events such as JSON clicks often shrink three to five times with lz4 or zstd. That reduces disk, network and page-cache pressure, and so the disk number I computed would drop accordingly. The exact ratio depends on the data.
Here is a rough effect, with assumed numbers only.
compression effectruns offline# illustrative arithmetic, assumed 4x ratio raw clickstream : 50 MB/s x 86,400 s x 3 days x RF 3 = about 39 TB compressed (4x) : about 9.7 TBCompression costs CPU on the producer, and on the broker if it has to recompress, which it avoids when the producer and topic use the same codec. Consumers pay CPU to decompress.
I would measure the ratio on a real sample of events before trusting any number, because already-compressed payloads such as images gain almost nothing. I would also test both lz4 and zstd, since one trades more CPU for a smaller size.
- "Why not keep clickstream in Kafka forever?"
-
Because of cost and because the value fades. Clickstream is high volume and its use is mostly short-term: a dashboard, a recommendation signal, a stream job. Keeping a year of it on broker disks, three times over with replication, costs a great deal for data that few people read.
For long-term analysis, I would sink it to object storage with a Connect sink, in a columnar format. Storing a terabyte there is far cheaper, and query engines read it directly without any broker in the path.
That gives a clear split of roles. Kafka is the hot, recent buffer where streams and services read within days. The lake is the long memory for analysts and for model training.
If someone insists that old clicks must be replayable through Kafka, tiered storage (Q15) is the middle path. I would first ask who replays them, and how often, before paying for it.
- "What if some orders must live for seven years for audit?"
-
I would not rely on a Kafka topic as the record of truth for seven years. The system of record for an audit is a database or an archive with defined access controls, backups and retrieval procedures. Kafka with tiered storage can physically hold the data, but I would still keep an archive copy in object storage with a retention lock.
The point is accountability, not capacity. An auditor wants to know who is responsible for the data, how it is protected against alteration, and how fast it can be retrieved. A topic is a delivery mechanism. A mistake in its config could erase years of history.
- Kafka: 30 days local, tiered storage for a longer period, for replay and operations.
- Archive: a Connect sink to write-once object storage for the seven-year obligation.
- Database: the order table remains the source of truth.
Then the legal duty is met by the archive, and Kafka stays a convenience.
- "Do the three topics share partition counts?"
-
No. Each topic should get a count from its own peak throughput and its own consumer parallelism. Using one default for all three wastes resources or caps throughput.
A worked example, with assumed numbers, shows the spread.
partition sizingruns offline# illustrative arithmetic, assumed per-consumer rates clickstream : 120 MB/s peak / 10 MB/s per consumer = 12 -> choose 24 (headroom) orders : 6 MB/s peak / 3 MB/s per consumer = 2 -> choose 6 profiles : tiny, compacted -> choose 3Clickstream needs many partitions for throughput. Orders need a moderate number, mainly to allow a few parallel consumers and to spread leaders. The profile table needs few, since it is small and read mostly at startup.
A single default of, say, 24 for all would give the profile table 24 small partitions, each with files, indexes and replication work, for no benefit. A default of 3 would cap clickstream far below its peak.
I size each from its peak, as in Q20.
Q18. "How does Kafka find a record by offset or by timestamp quickly?"
Reveal answer
Strong answer Each segment has a sparse offset index that maps some offsets to byte positions in the log file, and a time index that maps timestamps to offsets. To find offset N, Kafka picks the segment by file name, uses the index to jump near the position, then scans forward a short distance.
The index is sparse (one entry per index.interval.bytes, default 4 KB), so it is small enough to stay in memory, and the short scan is cheap.
Lookup by time (offsetsForTimes) uses the time index to find the first offset whose timestamp is at or after the requested time. That is how "replay from 09:00 yesterday" works.
Timestamps come either from the producer (CreateTime, default) or the broker (LogAppendTime), and that choice matters for the accuracy of time-based replay.
Picture it Finding offset 150,123.
The setup: Segments start at offsets 0, 100,000 and 200,000. The offset index of the second segment is sparse.
# illustrative output
1. offset 150123 -> segment file 00000000000000100000.log (largest start offset <= 150123)
2. index: offset 150000 -> byte position 61,440,000 (nearest entry not past 150123)
3. seek there and scan forward about 123 records until offset 150123Make the invisible visible: Time lookup from code.
Map<TopicPartition, Long> query = Map.of(new TopicPartition("orders", 0),
Instant.parse("2026-11-18T09:00:00Z").toEpochMilli());
Map<TopicPartition, OffsetAndTimestamp> found = consumer.offsetsForTimes(query);
consumer.seek(new TopicPartition("orders", 0), found.get(new TopicPartition("orders", 0)).offset());Why: Two small sparse indexes turn a search over gigabytes into an index lookup and a short read.
Land it I explain that Kafka does a segment pick, a sparse index jump and a short scan, and that time replay uses the time index.
- "What if producer timestamps are wrong?"
-
The request is a best-effort timestamp lookup. With the default
message.timestamp.type=CreateTime, the producer stamps each record when it creates it, so a client with a wrong clock writes wrong times. A time-based replay then lands in the wrong place: you ask for 09:00 and get data from 09:40, or from yesterday.It can also confuse retention. Kafka uses record timestamps in some retention decisions, and a record with a time far in the future keeps a segment alive, while one far in the past can make a segment look old enough to delete at once. The effect is on whole segments, because the segment's largest timestamp is what counts.
If client clocks cannot be trusted, set
message.timestamp.type=LogAppendTimeon the topic. The broker then stamps records itself when it appends them, which gives a consistent clock.The price is losing the "when it happened" time, and I would carry that inside the payload as event time.
- "Can I seek to the end or beginning easily?"
-
Yes. The consumer API has
seekToBeginningandseekToEndto move the position, andbeginningOffsetsandendOffsetsto learn the actual numbers. All of them take the set of partitions you assigned.The one point to remember is what "beginning" means. It is the log start offset, which moves up as retention deletes old data. A partition may begin at 40,000 today, and next week at 90,000.
So I never hard-code 0 as the beginning. If I do, the consumer asks for an offset that no longer exists, gets an out-of-range error, and then falls back to
auto.offset.reset, which may belatestand skip everything.A good habit for a replay tool is to print the beginning, the end and the offset it chose for each partition before it starts. The end offset is the next offset to be written, so it points one past the last record. A consumer position equal to it simply means "caught up".
- "What does the console tool do to reset a group by time?"
-
The groups tool can reset a group's committed offsets to the first offset at or after a time. The group must be inactive when you do this, with no running consumers, or the tool refuses.
I always run with
--dry-runfirst, which prints the offsets the reset would produce and changes nothing. Then I rerun with--execute.reset by timeruns offline# illustrative command kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group billing --topic orders \ --reset-offsets --to-datetime 2026-11-18T09:00:00.000 --dry-runBehind it, the tool does the same lookup as
offsetsForTimes, using the time index for each partition. Each partition ends at a different offset, because the time points to a different position in each log.Before running it for real, I compare the chosen time with the log start offset (see the last answer below), stop the consumers cleanly, and tell the team that records will be reprocessed, so consumers must be idempotent.
- "What happens if the requested time is before retention?"
-
The lookup returns the earliest offset that exists, not an error. So you silently start later than you asked. If a team says "replay from last Monday" and retention is 7 days with the topic written to for only some of that, the replay starts at the oldest surviving record, and the missing days simply are not there.
The danger is silence. Nothing in the result says "your time was before the log start", so a consumer that reprocesses "everything since Monday" may process only since Wednesday, and the report that follows is short.
A replay plan therefore compares two numbers: the requested time, and the time of the record at the log start offset. If the requested time is earlier, the plan must say so, and either accept the gap or restore the missing range from tiered storage or an archive.
I would log both numbers at the start of every replay, so nobody assumes full history.
Q19. "What is the difference between a topic's replication factor and its partition count, and which can you change later?"
Reveal answer
Strong answer The partition count is how many pieces the topic is split into: it controls parallelism and ordering scope. The replication factor is how many copies each partition has: it controls durability.
You can increase the partition count later, but never decrease it. Increasing breaks key-to-partition mapping for new records, so per-key order across the change is not guaranteed (Q22).
You can change the replication factor only through a partition reassignment, which copies data. It is possible but a planned operation, not a config toggle.
Because of this, I choose the partition count with headroom up front and treat it as nearly permanent.
Picture it One topic as a grid: partitions across, replicas down.
The setup: Topic with 3 partitions and replication factor 3 on 4 brokers.
# illustrative output
broker1 broker2 broker3 broker4
orders-0 leader follower follower -
orders-1 - leader follower follower
orders-2 follower - leader follower
# 3 partitions x 3 replicas = 9 replica files in totalMake the invisible visible: What changes when each knob turns.
# illustrative output
add partitions 3 -> 6 : more parallelism; key hash mod 6 differs from mod 3 ⚠ order across the change
raise RF 3 -> 4 : reassign, copies data, extra disk and network
lower partitions 6 -> 3: not supported (create a new topic and migrate)Why: The two numbers answer different questions: "how many readers in parallel and where does order apply" versus "how many copies".
Land it I would say partitions are for parallelism and order, replicas are for safety, and I pick partitions with future headroom because they cannot shrink.
- "What if I need fewer partitions later?"
-
Create a new topic with the right count and migrate the data. The usual steps are below.
- Create: make the new topic with the target partition count and the same settings.
- Copy: dual-write from producers, or mirror from the old topic to the new one with MirrorMaker, a Connect job or a small stream application that re-keys the records.
- Move: switch consumers to the new topic once they have caught up, keeping order in mind for each key.
- Retire: after a safe period, stop producing to the old topic and delete it.
The hard part is per-key ordering during the move. If the old topic is not fully drained before consumers switch, new records for a key could be processed before older ones. Draining the old topic first fixes that.
It is a project, not a command, with a plan, a rehearsal and a rollback. That is why the first choice of partition count matters so much, and why I add headroom up front.
- "Do more partitions always mean more throughput?"
-
No. More partitions raise the potential parallelism, but only up to a point, and they cost things on the broker side. Each partition adds file handles, memory for indexes and buffers, replication work between brokers, and extra elections after a failure. Past a certain count the cluster gets slower, not faster.
The consumer side limits it too. A consumer group can use at most one consumer per partition, and the actual throughput also depends on how fast each consumer processes. If you have 12 consumers and 100 partitions, the extra partitions add overhead and no speed.
The producer side behaves differently. More partitions mean smaller batches per partition when traffic is fixed, because the same records are spread thinner, which can lower compression and increase request counts.
So the answer I give is "partitions as many as the parallelism I can use, plus headroom, and no more". I verify the number with a load test and not with a rule of thumb.
- "How many total replicas can a cluster hold?"
-
It depends on broker resources, and I would not quote a single global number. What people watch is the number of partition replicas per broker, and they keep it within a budget they have tested on their own hardware.
The costs that grow with the count are the ones listed in the previous answer, plus controller work: every partition is a piece of metadata that must be replicated to all brokers and re-elected after failures. Recovery after a broker loss gets slower as that number rises.
The honest approach is to test with realistic hardware and watch the right signals as the count grows:
- Controller and request latency under load.
- Time to elect leaders after killing a broker.
- Memory and open file handles per broker.
When the numbers start to degrade, I have found the budget for that cluster. A quote copied from another company's blog post belongs to their hardware, and I treat it only as a rough hint for where to start testing.
- "What does rack awareness do?"
-
With
broker.rackset on every broker, Kafka spreads a partition's replicas across racks or zones when it places them. Losing one zone then loses at most one replica of each partition.Here is the effect with replication factor 3.
replicas per zoneruns offline# illustrative placement orders-0 : leader zone-a, follower zone-b, follower zone-c orders-1 : leader zone-b, follower zone-c, follower zone-a zone-a lost -> every partition still has 2 replicas, min ISR 2 holdsIt is the reason a 3-zone cluster with replication factor 3 and min ISR 2 survives a whole zone failure and continues to accept writes.
Without rack awareness, Kafka may put all three replicas of a partition on brokers in the same zone, and one zone failure takes the partition offline. So I set
broker.rackfrom the start. It also pairs with fetch-from-follower (KIP-392) to cut cross-zone traffic costs.One more check: rack awareness only affects placement of new replicas, so after adding the setting to existing brokers I run a reassignment to move old partitions into the spread.
Q20 · Design. "The business expects 200 MB/s peak into one topic and a consumer that can process 10 MB/s per instance. How many partitions?"
Reveal answer
Strong answer I size from both ends. For the producer side, I divide the target by what one partition sustains. For the consumer side, I divide the target by what one instance processes, since a partition can only be read by one group member at a time.
With a consumer rate of 10 MB/s and a target of 200 MB/s I need at least 20 consumers working in parallel, so at least 20 partitions. I would add headroom, say 1.5 to 2 times, giving 32 or 36.
For the producer side, a single partition often sustains somewhere in the tens of MB/s, but that varies with hardware and record size, so I benchmark it rather than assume.
Then I check cluster limits: 36 partitions times RF 3 is 108 replicas, trivial for a cluster. And I keep the key distribution in mind, because a skewed key makes some partitions hotter than the average.
Picture it The arithmetic in three lines, and the headroom choice.
The setup: Target 200 MB/s peak, consumer 10 MB/s each, measured producer limit 25 MB/s per partition.
# illustrative numbers
by consumers: 200 / 10 = 20 partitions minimum
by producers: 200 / 25 = 8 partitions minimum
need = max(20, 8) = 20
with 1.8x headroom = 36 partitions (room to grow to 36 consumers)
replicas = 36 x 3 = 108Make the invisible visible: What skew does to the plan.
# illustrative output
even keys : each of 36 partitions ~ 5.5 MB/s -> fine
skewed : 1 partition gets 40% = 80 MB/s ❌ exceeds one partition and one consumer
fix : salt the hot key (key + random 0-9) or split by a finer keyWhy: Partition count is the ceiling on consumer parallelism, so it must come from the slowest stage, not the fastest.
Land it I would give a minimum from the consumer rate, add headroom for growth and skew, then validate the number with a load test.
- "What if the consumer can scale only to 12 instances for cost reasons?"
-
Then partitions beyond 12 do nothing for that group, because each partition is read by one consumer at a time. With 12 instances at 10 MB/s each, the group tops out at 120 MB/s, well under the 200 MB/s target.
There are three honest options.
- Make each consumer faster: batch the work, use async I/O, avoid a per-record database call. Going from 10 to 17 MB/s per instance would reach 200 MB/s with 12 instances.
- Accept a lower target: if the business can live with 120 MB/s at peak, say so, and let lag absorb the rest.
- Share a partition: use share groups (Q71, production-ready in 4.2), where several consumers can read one partition, trading away per-partition order.
I would not add partitions to fix a consumer-side limit, because the extra partitions would sit idle. The key is that the consumer count, not the partition count, is the bottleneck.
- "How do I find the producer's per-partition limit?"
-
Run the producer performance tool against a test topic with 1 partition, then 3, then more, and watch where the rate flattens. The partition count at which adding more stops helping tells you the cluster's limit, and the rate at one partition tells you the per-partition ceiling.
perf testruns offline# illustrative command and output kafka-producer-perf-test.sh --topic perf --num-records 5000000 --record-size 1000 \ --throughput -1 --producer-props bootstrap.servers=localhost:9092 acks=all 5000000 records sent, 180000 records/sec (171 MB/sec)The output above is made up to show the format. The tool reports records per second and megabytes per second. Use the settings you plan for production: the same record size, compression,
acks=all, replication factor andlinger.ms, because each one changes the result.The result depends on hardware, record size and settings, so I do not trust a number from someone else's cluster. I run the test on mine, a few times, and use a conservative figure.
- "Will I regret too many partitions?"
-
Both extremes hurt, so I plan for the risk that is harder to repair. Too many partitions raises memory use, file handles and controller workload, and slows elections after a failure. But a modest overshoot is tolerable: a topic with 36 partitions instead of 24 costs little.
Too few partitions caps throughput and parallelism, and fixing it later is hard. Adding partitions moves keys and breaks per-key order (Q22), and reducing them is impossible without a migration to a new topic.
So an undersized topic is the harder one to repair, and I lean towards a modest overprovision. In my example, 36 partitions times replication factor 3 is 108 replicas, which is trivial for a cluster.
The limit to that lean is the overall budget per broker, and the consumers. I would not choose 500 partitions for a topic that will have 20 consumers. "Within reason" means a factor of about one and a half to two over the computed minimum.
- "How does it change if the consumer group needs ordering per key?"
-
Per-key order is preserved by the partition, as long as the number of partitions does not change. The key is hashed with murmur2 and taken modulo the count, so the same key always lands on the same partition. If the count changes from 36 to 48, many keys move, and order across the change is lost (Q22).
So the sizing decision gets stricter. I choose the final count before any keyed data flows, and I avoid resizing later. That includes thinking about growth for the next two or three years, not only today's peak.
Ordering also adds a constraint on the consumer. Within a partition, records must be processed in order, so a consumer cannot hand them to a free-for-all thread pool. If it needs parallelism beyond one thread per partition, it must preserve order per key with a keyed hand-off.
That is another reason to include headroom now: it is the cheapest time to get it right.
These questions test whether you know exactly what order Kafka promises, what silently breaks it, and how to choose a key that gives order without a hot spot.
Q21. "How does the default producer partitioner pick a partition?"
Reveal answer
Strong answer If the record has a key, the producer hashes the key bytes with murmur2 and takes the result modulo the number of partitions. Same key, same partition, as long as the partition count does not change.
If the key is null, the producer does not hash. Since Kafka 3.3 the built-in behaviour is a sticky/uniform approach: it fills a batch for one partition and then moves to another, which gives larger batches and still spreads load over time.
You can also set the partition explicitly on the record, or plug in a custom Partitioner. In recent versions the default partitioner is built into the producer, and you rarely need a custom one.
The key point to say out loud: the mapping is a pure function of key and partition count. That is what makes per-key ordering work, and it is also why changing the count breaks it.
Picture it Hashing five keys into four partitions.
The setup: Topic orders, 4 partitions. Keys are customer ids.
# illustrative output (hash values invented to show the shape)
key murmur2(key) mod 4 partition
cust-7 2,031,447,118 2 2
cust-9 884,120,555 3 3
cust-7 2,031,447,118 2 2 (same key, same partition)
cust-12 1,502,992,640 0 0Make the invisible visible: In code, the three ways to pick a partition.
// 1. by key (normal)
producer.send(new ProducerRecord<>("orders", "cust-7", payload));
// 2. explicit partition (you own the mapping)
producer.send(new ProducerRecord<>("orders", 2, "cust-7", payload));
// 3. no key (spread for throughput, no per-key order)
producer.send(new ProducerRecord<>("orders", payload));Why: The key is the only thing that ties related records to one partition, so it is the one design decision in the producer that you cannot fix later without a migration.
Land it I say the default is murmur2 of the key modulo the partition count, null keys are spread in batches, and the mapping only holds while the count stays the same.
- "Does the hash depend on which language the producer is written in?"
-
It can, which is a real trap. The Java client uses murmur2 on the serialized key bytes. Some other clients used a different hash by default. For example, librdkafka (the C library behind many Go, Python and .NET clients) has historically defaulted to a CRC32-based partitioner, unless you set the partitioner to
murmur2_random.The consequence is easy to picture. A Java service and a Go service both produce to one topic with the key
cust-42. If they hash differently, the two services put the same customer on different partitions. Per-key order then breaks across the two writers, and a consumer sees that customer's events in an unpredictable interleaving.The fix is configuration. I set the partitioner explicitly in every non-Java client so it matches Java's, and I add a test that produces a known key from each service and checks that the partition number is the same.
- "Is the key serialized before hashing?"
-
Yes. The hash is over the serialized bytes of the key, not over the object in memory. A key of
42written as a string uses the bytes for the characters "4" and "2". The same number written as a 32-bit integer is four bytes. They hash to different values, so they usually land on different partitions.same key, different bytesruns offline# illustrative "42" as string -> bytes 34 32 -> murmur2 -> partition A 42 as int32 -> bytes 00 00 00 2A -> murmur2 -> partition BChanging a key's serializer is therefore a partitioning change, even if the value looks the same on screen. After the change, new records for an existing key go to a new partition while old ones stay behind, which breaks per-key order as in Q22.
So I treat the key's serializer and format as part of the topic's contract. A rolling deploy that moves from string keys to a new format needs the same care as a resize: drain, or migrate to a new topic.
- "When would you set the partition explicitly?"
-
Rarely. I set the partition explicitly when the business rule is the partition itself, such as one partition per region, with consumers assigned by region. Then the record's partition number carries meaning, and I do not want a hash deciding it.
The producer API accepts a partition number on the record, and when it is set, the key is not used to choose the partition.
The costs are real:
- You now own load balancing. If one region sends five times more traffic, its partition is hot and nothing spreads it.
- You own the mapping when the partition count changes, and you must change every producer and consumer together.
- A wrong number outside the valid range makes the send fail.
In most cases the key does the job better. If I need "region" to be the order domain, I use the region as the key and let the hash place it, and I accept that two regions may share a partition. I use explicit partitions only when sharing is not acceptable.
- "What does null-key sticky behaviour do to ordering?"
-
Nothing is promised. A record with no key has no partition affinity, so it can land on any partition. In current clients, each batch is filled for one partition and then the producer switches, so a run of records goes to one partition and the next run goes elsewhere.
Two related events for the same customer, sent without a key, can therefore end up on different partitions, and a consumer can see them in either order. Even on one partition, a consumer sees only that partition's share.
That is fine for events where order does not matter, such as metrics, logs, or clicks that are counted. It is wrong for anything with a per-entity sequence: "order created", then "order paid", then "order shipped" for one order. For those, use a key, normally the entity id.
The test I apply is simple. If I replaced the stream with a randomly shuffled copy of itself, would the result still be right? If yes, a null key is fine. If no, I need a key.
Q22 · Scenario. "You added partitions from 6 to 12 on a live topic and a downstream service now sees events for the same customer out of order. Explain."
Reveal answer
The real test Whether you can explain it from the hash formula, not just say "partitioning changed".
Strong answer The partition for a key is murmur2(key) mod N. When N changes from 6 to 12, many keys map to a new partition. New events for customer 7 go to the new partition while older events for customer 7 are still in the old one.
The two partitions are read by different consumers or at different speeds, so the consumer may see a new event before it finishes older ones. Order across the boundary is lost, though order within each partition remains.
The fix right now: make consumers tolerate it (sequence numbers or versions in the payload so older events are ignored). The lasting fix is to avoid resizing a keyed topic: create a new topic with the right count and migrate.
Expanding is safe only when order per key does not matter, or when you can drain old data first.
Picture it One key, before and after the resize.
The setup: cust-7 hashes to value H. Before: H mod 6 = 1. After: H mod 12 = 7.
# illustrative output
before resize (N=6): cust-7 -> partition 1 : e1 e2 e3
resize to N=12
after resize (N=12): cust-7 -> partition 7 : e4 e5
consumer A reads partition 1 slowly (still on e2)
consumer B reads partition 7 quickly -> applies e4 before e3 ❌Make the invisible visible: Make the consumer order-proof with a version.
// payload carries a per-customer version
if (event.version() <= stored.version()) {
return; // ✅ stale or duplicate: ignore
}
repo.save(event.apply(stored)); // newer: applyWhy: Kafka only orders within a partition. A resize moves a key to a different partition, so the order guarantee has to come from somewhere else for the changeover window.
Land it I would say we broke the key-to-partition mapping, and I would add per-entity versions now and migrate to a right-sized new topic if strict order matters.
- "Is there a way to resize without any ordering gap?"
-
Yes, but it takes care and a pause in the flow. The idea is to make sure that all old events for a key are fully consumed before any new event for the same key can be read.
- Create: make a new topic at the target size, with the same settings.
- Pause or dual-write: stop producers briefly, or have them write to the new topic only, from a cut-over time.
- Drain: let consumers read the old topic to its end, until lag is zero and the last offset is processed.
- Switch: point consumers at the new topic, then restart producers if you paused them.
The key point is that old events are completely consumed before new events for the same key become readable. Then the sequence per key is old events first, new events second, whatever partition they live on.
The cost is a window of delay, or extra complexity from dual-writes. For a payment-like flow I accept it.
- "Could we choose a partition count that makes resizing safe?"
-
Not really. Doubling is a little friendlier for some hashing schemes, where each old bucket splits cleanly into two, but murmur2 modulo does not behave that way. About half of the keys move, and the ones that stay are not predictable from the key alone.
Look at a few examples with a made-up hash value h:
what doubling doesruns offline# illustrative hash values h = 7 : 7 mod 6 = 1 7 mod 12 = 7 -> moved h = 14 : 14 mod 6 = 2 14 mod 12 = 2 -> stayed h = 21 : 21 mod 6 = 3 21 mod 12 = 9 -> movedSo no partition count makes a resize safe for order. Consistent hashing could limit moves, but Kafka's default partitioner is a plain modulo.
Look at the first example. Key hash 7 sits on partition 1 with six partitions and on partition 7 with twelve. The new record goes to partition 7 while the older ones for that key are still waiting on partition 1, so two consumers may process them at different speeds.
I keep the rule simple: choose the count once, with headroom.
- "How do I tell which keys moved?"
-
Compute the partition before and after from the key. A short script can list the keys whose partition differs, which tells you which entities may have crossed the boundary.
which keys moveruns offline// illustrative: the same function the default partitioner uses int before = Utils.toPositive(Utils.murmur2(keyBytes)) % 6; int after = Utils.toPositive(Utils.murmur2(keyBytes)) % 12; boolean moved = before != after; // about half the keys move when doublingI would run it over the active keys, for example customers with events in the last few hours.
It is a small cost to run before any resize, and it also shows how many entities are affected, so you can judge the risk and the size of the clean-up, and decide whether to resize at all.
Use the same hash and the same key bytes as the real producer. If the producer is not Java, or the key serializer differs from the one in your script, the script gives wrong answers.
- "Does compaction suffer too?"
-
Yes, and in a more confusing way. A compacted topic keeps the latest record per key per partition. After a resize, one key can have records in two partitions: the old values stay in the old partition, while new values go to the new one. Each partition cleans on its own, so each can hold a "latest" for that key.
The result is two live values for one key, which should never be true for a table. A consumer rebuilding state from the start reads both, and the final value depends on which partition it reads last. That is a race, and it can differ from run to run.
It gets worse with deletes. A tombstone for the key goes to the new partition, while an old value remains in the old partition forever, since nothing compacts it away. The deleted customer comes back from the dead.
That is another reason not to resize compacted topics. Create a new one and migrate.
Q23. "What ordering does Kafka actually guarantee? Be precise."
Reveal answer
Strong answer Records with the same partition are stored and delivered in the order they were appended. A single producer's records to one partition are appended in the order sent, provided retries cannot reorder them (idempotence on, or max in-flight set to 1).
There is no ordering across partitions, none across different producers to the same partition except by arrival order at the broker, and none across topics.
On the consumer side, one partition is read by one member of a group at a time, so a consumer sees that partition's records in order. If the consumer then hands records to a thread pool, the order is lost inside the application.
So order is a chain: key, to partition, to single consumer, to single-threaded processing. A break anywhere ruins it.
Picture it The ordering chain and where it can break.
The setup: Events for order 88: Created, Paid, Shipped, all with key order-88.
# illustrative output
producer : sends C, P, S in order link 1 ✓ (idempotent producer)
partition : same key -> partition 4 link 2 ✓ (count unchanged)
consumer : one member reads partition 4 link 3 ✓ (not rebalancing mid-way)
handler : single thread per partition link 4 ✗ if a thread pool processes P before CMake the invisible visible: A thread-pool break in code.
// ❌ TRAP: records of one key handled on different threads, order lost
for (ConsumerRecord<String, Event> r : records) {
pool.submit(() -> handle(r));
}
// ✅ route by key to the same worker so order per key survives
for (ConsumerRecord<String, Event> r : records) {
workers[Math.floorMod(r.key().hashCode(), workers.length)].submit(() -> handle(r));
}Why: Kafka's promise ends at the consumer's poll. Anything the application does after it can undo the order.
Land it I say order is guaranteed per partition, and it holds end to end only if the producer, the key, the consumer and the handler all preserve it.
- "What about two producers writing the same key?"
-
Both append to the same partition, so the order is whichever arrives first at the broker. There is no shared sequence between two producers: each one has its own idempotence sequence numbers, which only order that producer's own batches.
So if service A sends "set status to paid" and service B sends "set status to cancelled" for the same order, the final order in the log depends on network timing, retries and batching. A one-millisecond difference in arrival decides it. Neither producer is wrong, and the log is still consistent: it faithfully records the order of arrival.
When a business rule requires a specific order, there are two clean answers. One is a single writer per key, so there is only one sequence to preserve. The other is a version number or logical clock in the payload, so consumers can ignore stale updates and the arrival order stops mattering.
I prefer the version number, because it also survives replay and retries.
- "Do retries break order?"
-
They can, if nothing prevents it. Imagine the producer sends batch 1 and batch 2 to the same partition at the same time. Batch 1 fails and is retried, batch 2 succeeds. The broker then holds batch 2 before batch 1, and the order has been changed by the retry.
The idempotent producer prevents this. Every batch carries a sequence number per partition, and the broker checks that numbers arrive in sequence. If batch 2 shows up first, the broker rejects it as out of order, and the producer retries both in the right sequence. This works with up to 5 requests in flight per connection (
max.in.flight.requests.per.connection=5). Q29 explains it.Without idempotence, the only safe setting is
max.in.flight.requests.per.connection=1. That keeps order but costs throughput, because each batch waits for the previous one to be acknowledged.Since idempotence is the default now, I leave it on and keep the in-flight count at 5 or lower.
- "Is order kept during a rebalance?"
-
The log order is kept. A rebalance does not rewrite anything. What changes is who reads. A partition may move to another consumer, which resumes from the last committed offset of that partition.
Look at the time line. A consumer processed offsets 100 to 140 but had committed only up to 120. It loses the partition. The new owner starts at 120, so offsets 120 to 140 are processed a second time. The consumer sees repeats, not a reordering.
rebalance replayruns offline# illustrative timeline old owner : processed 100..140, committed 120 -> partition revoked new owner : starts at 120, processes 120..140 again (duplicates, same order)That repetition is why consumer code must be idempotent (Q65). The usual tools are a unique id checked in the database, or an upsert keyed by the record's identity.
Ordering can break only if the application hands records to a thread pool, which is a separate problem.
- "Does a transaction add ordering across partitions?"
-
No. Transactions give atomic visibility of writes to several partitions: either all the records of a transaction become visible to
read_committedreaders, or none do. They do not create an order between those partitions.Take a transaction that writes one record to partition 0 and another to partition 5. After commit, a reader sees both, but it still can read the partition 5 record before the partition 0 one, because the partitions are fetched independently. The order of the two writes inside the transaction is not a promise to readers.
Within one partition, the order of records in the log is still the order they were appended, as always.
So atomic visibility and ordering are different guarantees, and I keep them apart when I explain them. If a consumer needs "A before B", the two events must share a key and a partition, or carry a sequence or version in the payload.
Q24 · Scenario. "One partition of a 12-partition topic carries 60% of the traffic and its consumer is always behind. Diagnose and fix."
Reveal answer
Strong answer This is a hot partition, caused by key skew: one key (or a few) has far more traffic than the others, and all its records go to one partition and one consumer.
I confirm it from numbers: bytes in per partition, and lag per partition. If 11 partitions have lag near zero and one has 2 million, it is skew, not a slow cluster.
The fixes depend on whether I need order for that key. If not, add a salt to the key (for example, key + a number from 0 to N) to spread it. If order per key matters, I split on a finer key, such as order id instead of tenant id, or process the hot key's records in parallel using in-partition ordering rules.
Adding more consumers does not help, because one partition is read by one consumer at a time.
Picture it Finding the skew and spreading it.
The setup: Topic events keyed by tenant. Tenant big-corp produces 60% of events.
# illustrative output
partition msgs/s lag
0 900 3
1 850 0
...
7 12,000 2,100,000 <- big-corp, the hot partition
...
11 880 1Make the invisible visible: Salt the hot tenant only.
String key = tenant;
if (HOT_TENANTS.contains(tenant)) {
key = tenant + "#" + ThreadLocalRandom.current().nextInt(8); // 8 sub-keys
}
producer.send(new ProducerRecord<>("events", key, payload));What you see: big-corp now spreads over up to 8 partitions, each about 1,500 msgs/s.
Why: Ordering and balance pull in opposite directions. Salting trades per-tenant order for balance, so I only do it where order is not needed or where the order can be rebuilt downstream.
Land it I would prove skew with per-partition rates, then spread the hot key with a salt or a finer key, and say what order I gave up.
- "What if the hot key needs strict order?"
-
Then I break the entity into smaller ordered units. Order matters only inside a real business sequence. If the strict order is per order id and not per tenant, I key by order id. That keeps each order's events in sequence and spreads one tenant's orders across all partitions.
Often the original key was just too coarse. "Tenant" was a convenient key, but nothing needed all of a tenant's events in order.
If one stream truly needs strict order at a high rate, the order domain cannot be split, so one partition and one consumer carry it. The only lever is to make that single consumer faster:
- Process records in batches instead of one by one.
- Use async I/O for database or API calls, while still committing in order.
- Remove per-record work that is not needed, such as a synchronous lookup.
I would say plainly to the business: strict order at this rate has a ceiling set by one consumer, and we can raise the ceiling or relax the rule.
- "Does the salt hurt consumers that aggregate per tenant?"
-
Yes. A per-tenant aggregation, such as "total orders per tenant per minute", now sees that tenant's data on several partitions and several consumers. Each consumer holds only a slice of the tenant's records, so no single one can compute the total.
The fix is a second stage. The first stage reads the salted stream, computes partial totals per salted key, and writes them out. The second stage re-keys by the real tenant and sums the partials. Kafka Streams does this for you when you change the key, by inserting a repartition topic.
two-stage aggregationruns offline# illustrative stage 1: key = tenant-7#0..#3 -> partial sums on 4 partitions stage 2: key = tenant-7 -> sum of 4 partials = tenant totalThe extra stage costs one more topic, more latency and more things to monitor. It is a cost I name before choosing the salt. If the aggregation is the main purpose of the data, I would rather look for a finer key than salt the one I have.
- "Could I just add partitions?"
-
It would not fix a single hot key, because that key still maps to exactly one partition, whatever the count is. The hash of the hot key's bytes is a fixed number, and modulo any count gives one partition. Adding partitions only redistributes the other keys.
It would also cause new problems. Raising the count moves keys and breaks per-key order (Q22), and the hot key's partition stays as busy as before, so the lag stays.
More partitions do help in the other kind of skew: many medium keys that happen to collide on a few partitions. Then spreading them over more partitions gives each fewer neighbours. That is why I first look at the distribution of traffic over keys.
- One key dominates: salt the key or use a finer key.
- Many keys, uneven landing: more partitions may help, with the order caveat.
The diagnosis decides the fix, and the per-key byte count is the number I want.
- "How do I alert on skew before lag builds?"
-
Track the ratio of the busiest partition's rate to the average rate, and alert when it stays above about 3 times for a sustained period.
skew ratioruns offline# illustrative numbers average = 2,500 msgs/s over 12 partitions (30,000 total / 12) busiest = 12,000 msgs/s ratio = 12,000 / 2,500 = 4.8 -> alert at > 3The same idea works for consumer lag: compare the lag of the worst partition with the median. If 11 partitions are near zero and one is climbing, it is skew, not a slow cluster.
The ratio warns before the lag builds. A partition receiving 4.8 times the average still looks fine while its consumer keeps up, but as soon as the rate rises or the consumer slows, lag grows quickly.
I would plot the max, the median and the ratio on one dashboard, with a second panel for per-partition consumer lag next to it, so the cause and the effect sit side by side.
Q25. "What happens to a record with a null key, and when is that acceptable?"
Reveal answer
Strong answer A record without a key has no partition affinity, so the producer spreads such records across partitions. The current default fills a batch for one partition, then picks another, which keeps batches big while balancing over time.
It is acceptable when records are independent: metrics, logs, clicks where no later event depends on an earlier one. Throughput and balance are best with null keys.
It is not acceptable when you need per-entity order, compaction (needs a key), or joins in Streams by key.
Also remember a null value is a tombstone. A null key and a null value are different things.
Picture it Null-key records distributing across three partitions.
The setup: Three partitions, records without keys, batch size big enough for 4 records.
# illustrative output
batch 1 (4 records) -> partition 2
batch 2 (4 records) -> partition 0
batch 3 (4 records) -> partition 1
# whole batches go to one partition: fewer requests, even spread over timeMake the invisible visible: Old round-robin versus sticky.
# illustrative output
old round-robin: 12 records -> 12 tiny batches on 3 partitions (many small requests)
sticky/uniform : 12 records -> 3 batches of 4 (fewer, bigger requests)Why: Without a key there is no reason to split a batch, so keeping the batch together lowers request count while spreading load.
Land it I use null keys for independent events and a key whenever order, compaction or joins are needed.
- "Can a compacted topic have null keys?"
-
No. A compacted topic needs a key for every record, because compaction decides "latest" by key. A record without a key has no identity to compare, so the broker rejects it on a compacted topic, and the producer gets an error.
If you see that error, the producer is not setting a key, or the topic was switched to
cleanup.policy=compactwhile an old producer still sends unkeyed events. The record is refused and not silently dropped.The repair is in the producer. Choose a key that identifies the thing whose state the topic holds: the customer id for a customer table, the product id for a price table.
A null value is different. On a compacted topic, a null value with a key is valid, and it means "delete this key" (a tombstone). A null key is invalid, and a null value is a delete. The two are easy to mix up.
So I check both fields when a team reports a compaction problem.
- "Do null keys cause skew?"
-
Over time they spread evenly, but short-term imbalance is possible. Because a whole batch goes to one partition, a burst of traffic that fills several batches goes to a few partitions at once, and the others get a share later. Over minutes the load evens out.
The producer's built-in logic also takes partition health into account. If one partition's broker is slow or down, the producer can avoid it for new batches, since there is no key forcing a record to that partition. That is a benefit of null keys: a slow broker does not stall the whole stream.
The effect on consumers is that lag per partition can differ for a while, and a dashboard may show one partition ahead of the others. That alone is not skew in the sense of Q24.
I would worry only if the imbalance stays for hours. Then I look at the producer's partitioner settings, or at records being sent with a key that I did not intend.
- "What if I want even spread but with some key?"
-
Use a key with many distinct values and even frequency, such as a random UUID. That gives a good balance and the same key always goes to the same partition, which helps if you later want to compact or join on that key.
Here the compromise is clear. A random key has no business meaning, so it ties records to a partition only by that random value. Two related records, for example two events of one order, get different random keys and land anywhere, with no order between them.
- Order matters: use the entity id as the key and accept the distribution it gives.
- Order does not matter, and I want a key anyway: a UUID or another well-spread id works.
- Order does not matter and I need nothing from the key: use no key and let the sticky logic batch efficiently.
I would choose a key for a reason. If the only reason is "spread", the null-key path is simpler and gives larger batches.
- "How does a consumer see null-key records?"
-
Exactly like any other record, except that
record.key()returns null. Everything else, the value, the offset, the timestamp, the partition, works as usual.The common bug is in code that assumes a key exists. A line such as
record.key().toString()throws a null pointer exception on the first unkeyed record. In a consumer loop that exception can kill the thread, the poll loop stops, and the group is rebalanced after the timeout, so one unkeyed record can stop a whole pipeline.guard the keyruns offline// illustrative String key = record.key() == null ? "(no key)" : record.key(); log.info("partition={} offset={} key={}", record.partition(), record.offset(), key);Guard it, especially in generic listeners and logging helpers that handle many topics. A one-line check is cheaper than a stuck consumer at night. In Kafka Streams or Spring listeners the same rule holds, so I add a test that sends one record with a null key through the handler.
Q26 · Design. "Choose the key for an order-events topic. Candidates: customer id, order id, region, or no key."
Reveal answer
Strong answer The key must be the unit within which order matters and which has enough distinct values for balance. For order events, that is almost always the order id: Created, Paid, Shipped, Cancelled for one order stay in sequence.
Customer id keeps all of one customer's orders in order, which is stronger than needed and risks a hot partition for a very large customer. Region has too few values and skews badly. No key loses order entirely.
If a downstream consumer needs per-customer aggregation, it can re-key into a second topic. Do not force the first topic's key to serve both.
I would also write the key into the payload, so the order id is visible without relying on the Kafka key.
Picture it A comparison of the four candidates.
The setup: Expected: 5 million orders per day, 1 million customers, one large customer with 5 percent of traffic, 3 regions.
# illustrative output
key order within balance verdict
order id one order excellent ✅ chosen
customer id one customer 1 customer=5% ⚠ hot partition risk
region one region 3 values only ❌ cannot use more than 3 partitions
none nothing excellent ❌ events of one order can arrive out of orderMake the invisible visible: The producer code with the chosen key.
ProducerRecord<String, OrderEvent> rec =
new ProducerRecord<>("order-events", event.orderId(), event); // key = order id
producer.send(rec, (md, ex) -> { if (ex != null) log.error("send failed {}", event.orderId(), ex); });Why: A good key is the smallest group of records that must stay in order, and large enough in count to spread.
Land it I would key by order id, because it is the smallest group needing order, and I would re-key downstream if another view needs a different grouping.
- "What if "customer cancels all orders" needs ordering with their other orders?"
-
Then the key has to be the customer id, because the thing that must stay in order is now everything one customer does. Kafka only promises order inside one partition, and a partition is chosen by the key. So if "cancel all orders" must be seen after that customer's earlier "created" and "paid" events, those events all need the same key.
The price is a coarser group. Every order of one customer lands on one partition, so one customer with huge volume (a reseller, a test account, a bot) can overload that partition while others sit idle. I would accept that risk but watch it. I would look at the biggest customers' event rates, and if one is far above the rest, give it a dedicated topic, or add a sub-key such as customer plus month, and accept that order only holds inside the sub-key.
The rule I follow: the requirement picks the key, and I then check what it costs. I do not pick a key first and hope the requirement fits.
- "Should the key be the whole object or just an id?"
-
Just a stable identifier, such as the order id as a string or a long. Kafka hashes the key bytes with murmur2 to choose the partition, and it also stores the key on every single record. A key that is a whole object means more bytes on disk, more bytes on the network and more bytes to compress, for no benefit.
There is a worse problem. The hash works on serialized bytes, so two objects that mean the same thing but serialize differently (field order, a timestamp field, a different library version) get different hashes and land on different partitions. Order for that entity is then silently broken.
The key should also never change during the life of the record's subject. If an order's key is its status, then "Paid" and "Shipped" go to different partitions and arrive in any order. I use an id that is assigned once and never edited, and I keep descriptive fields in the value, not the key.
- "What if a key's cardinality is small?"
-
Then you get fewer working partitions than you paid for. Partition choice is murmur2(key) mod partitions, so only as many partitions can ever receive data as there are distinct keys. Twelve partitions with three region keys use at most three of them, and by bad luck two regions can even hash to the same partition, leaving two busy and ten empty.
The consumers show it too. A group of twelve consumers on that topic has at least nine sitting idle, because an empty partition gives them nothing to read. So the key's number of distinct values is a hard ceiling on parallelism, whatever the partition count says.
My check before choosing: count distinct values, and want them to be many times the partition count (hundreds or thousands against a dozen partitions) so the hash spreads them evenly. If the natural key is low-cardinality, I add a finer part (region plus order id) or key by something else and give up ordering across the region.
- "How do I verify the key distribution before launch?"
-
I take a sample of real or realistic keys and run them through the same hash the producer will use, then count records per partition for the partition count I plan to use. Real data matters, because skew comes from the data, not from the hash.
The sample should span a busy period and include the largest customers. A quiet Tuesday can hide a key that dominates on Friday night. I also run it for two or three candidate partition counts, since the result changes with the count.
distribution checkruns offline# illustrative output, 12 partitions, 1M sampled keys partition share 0 8.4% 1 8.2% ... 11 8.5% -> within 1 point of 8.33% (even) 5 31.0% -> hot key: one id is a third of the trafficEven is about 8.3 percent each. If one partition is several times that, one key is the cause, and I fix the key or isolate that key before launch. Afterwards I keep watching per-partition bytes in production, because data drifts.
Q27. "When would you write a custom partitioner, and what are the risks?"
Reveal answer
Strong answer A custom partitioner is for a rule the default cannot express: send premium tenants to dedicated partitions, route by region, or spread one known-hot key across several partitions while keeping others by hash.
The risks are real. You own the mapping, so you must keep it stable across deploys, consistent across every producer in every language, and resilient to a changed partition count.
A bug in a partitioner can send everything to one partition, and it is often found in production as a hot spot.
I try the default plus a salted key first, because a key-level change is simpler to test than a custom class.
Picture it A partitioner that isolates one big tenant.
The setup: Tenant big-corp gets partitions 0 to 3; everyone else hashes into partitions 4 to 11.
public class TenantPartitioner implements Partitioner {
public int partition(String topic, Object key, byte[] keyBytes,
Object value, byte[] valueBytes, Cluster cluster) {
int n = cluster.partitionCountForTopic(topic);
String k = (String) key;
if (k.startsWith("big-corp")) {
return Math.floorMod(k.hashCode(), 4); // partitions 0..3
}
return 4 + Math.floorMod(k.hashCode(), n - 4); // partitions 4..n-1
}
public void close() {}
public void configure(Map<String, ?> configs) {}
}Make the invisible visible: Register it, and test the spread.
partitioner.class=com.example.TenantPartitioner
# test: feed 100,000 sample keys through partition() and print the histogram before shippingWhy: A custom rule moves a hidden decision into code. A histogram test is the safety net.
Land it I write one only when a business rule needs a mapping, and I protect it with a unit test that checks the spread and the stability.
- "Can a consumer rely on the custom mapping?"
-
Only if the mapping is written down and the exact same code runs in every producer. If a consumer assumes that tenant X always lives on partition 2, it is welded to the producer's internal rule. The day the rule changes, the consumer reads the wrong data or misses data, and nothing in Kafka warns anyone.
There are two cases. A consumer that just reads whatever it is assigned and never cares which partition holds what is safe, and that is what I prefer. A consumer that has to read one tenant specifically, for example a dedicated worker for a premium tenant, can use manual assignment (
assign()on a chosen partition) and then the mapping is a real contract.If I accept that contract, I treat it like an API: documented, versioned, covered by a test in both producer and consumer repositories. Otherwise I make the consumer filter by a field in the record, which costs a little CPU and removes the coupling.
- "What happens when someone adds partitions?"
-
When someone adds partitions,
nin the formula changes, and every rule that uses it can change its answer. The default murmur2(key) mod n will send many existing keys to a different partition. A custom rule "hash mod n" does the same, and old and new records for one key are now on two partitions, so order for that key is broken across the change.Rules that use fixed numbers are more robust. "Premium tenants go to partitions 0 to 3, everyone else hashes over partitions 4 to n minus 1" keeps the premium part stable when n grows, although the second part still moves.
What I do: write down which parts depend on
n, treat a partition increase as a planned migration rather than a casual change, and test with a unit test that feeds a few thousand keys atnandn+1and prints how many moved. A surprise is better found in a test than in production. - "How do I roll out a changed partitioner safely?"
-
A changed mapping is a resize in disguise: the same key can now go to a different partition, so old and new records for that key are not ordered against each other. I never swap it on a live keyed topic. My steps:
- Create a new topic: with the new partition count or the new rule, same config otherwise.
- Dual-write or migrate: produce to both, or copy old data across with a consumer-producer job, and verify counts per key match.
- Switch consumers: let them drain the old topic to the end, then move them to the new one, committed offsets noted in a runbook.
- Retire the old topic: after the retention window, once nobody reads it.
If order does not matter for some keys, a plain change is fine. For anything keyed and ordered, the new topic costs a day of work and removes a hard-to-debug class of bug.
- "Is it better to set the partition directly on records?"
-
Yes,
ProducerRecordhas a constructor that takes a partition number, and when it is set the partitioner is not asked. It is simpler when the rule is easy to compute: the code that creates the record calls one function,partitionFor(tenant), and passes the result. No custom class, no registration through thepartitioner.classsetting, and the rule sits right beside the business code that uses it.The trade-off is the same one as a custom partitioner: you own the mapping. Every producer must call the same function. If one service forgets, its records follow the default rule and land somewhere unexpected. Also, a fixed partition number breaks if the topic has fewer partitions than the number you ask for.
So I choose by reuse. With one producer service and a simple rule, setting the partition directly is lighter. With many producers or several languages, I put the rule in a shared library or behind a small gateway, and I add a test.
Q28 · Scenario. "With a single partition and a single producer, you still see records stored out of order after a network blip. How?"
Reveal answer
The real test Whether you know retries plus several in-flight batches can reorder.
Strong answer The producer sends up to max.in.flight.requests.per.connection batches without waiting for replies. If batch 1 fails and batch 2 succeeds, then batch 1 is retried and lands after batch 2. The log now holds batch 2 then batch 1.
The idempotent producer fixes this: each batch carries a sequence number, and the broker accepts them in order, rejecting or holding out-of-order sequences so the retry slots back in correctly. It is on by default since 3.0 and supports up to 5 in-flight requests safely.
If someone disabled idempotence, order is only safe with max.in.flight.requests.per.connection=1.
So the checks are: is enable.idempotence true, and what is the in-flight value?
Picture it The reordering sequence, and the fix.
The setup: Batches B1 (records 1 to 3) and B2 (records 4 to 6) are sent back to back. Idempotence is off.
# illustrative output
t0 send B1, send B2 (both in flight)
t1 B1 fails (timeout), B2 succeeds -> log: [4,5,6]
t2 B1 retried and succeeds -> log: [4,5,6,1,2,3] ❌ order brokenMake the invisible visible: The same blip with sequence numbers.
# illustrative output
B1 seq=0..2 B2 seq=3..5
broker receives B2 first: expects seq 0 -> OUT_OF_ORDER_SEQUENCE, B2 not appended
producer retries B1, then B2 in order -> log: [1,2,3,4,5,6] ✅Why: Sequence numbers let the broker see a gap and refuse to put later data first.
Land it I would check idempotence and in-flight settings first, because retries with several batches in flight can reorder within one partition.
- "Why is 5 the safe maximum in-flight with idempotence?"
-
The broker keeps the sequence numbers of only the last 5 batches it accepted from each producer for each partition. That memory is how it recognises a duplicate and how it spots a gap. With up to 5 batches in flight, any retried batch is still inside what the broker remembers, so it can slot the retry in the correct place or reject it safely.
If the client allowed 6 or more in flight, a retry might refer to a batch the broker has already forgotten. The broker could not tell whether it is a duplicate or a new batch, and the guarantee would break. So the client refuses to start the combination.
Setting
max.in.flight.requests.per.connectionabove 5 while idempotence is explicitly on is a configuration error (ConfigException). Then I either lower it to 5 or less, or turn idempotence off and give up the guarantee. Five is already plenty: it is far more than most pipelines need to keep a connection busy. - "Does ordering hold if the producer restarts?"
-
No. Idempotence protects one producer session, not the application across restarts. A new producer instance asks the broker for a new producer id, and its sequence numbers start again at 0. The broker therefore cannot connect the new instance's batches to the old one's.
Here is the gap. Suppose the old instance sent a batch, the broker wrote it, and the process crashed before the application learned the result. After restart, the application may send the same business record again. The broker sees a different producer id and accepts it, so there is now a duplicate. Order across the restart is also only as good as the application's own logic, because the new session is a fresh stream.
There are two real fixes. Transactions with a stable
transactional.idlet the broker fence the old instance and continue from its state. Or the consumer is idempotent, using a business key to ignore a second copy. I choose by whether the duplicates cost money. - "What if the broker returns OutOfOrderSequence?"
-
It is a sign that the broker's idea of the producer's sequence does not match what the client sent. In a healthy cluster it should almost never happen, so I treat it as a clue and not as noise.
The usual cause is that the broker lost or expired the producer's state. For example, retention deleted all records from that producer, or the producer sat idle until the broker dropped its state. The next batch then carries a sequence number the broker no longer has any context for. Another cause is data loss on the partition, such as an unclean leader election or log truncation.
What the client does depends on the version and on whether the producer is transactional. The client may reset its state or fail the affected sends. I do not retry it blindly.
I check the broker logs and recent leader changes, and treat the failed send as an unknown outcome.
- "What do I lose with max.in.flight=1?"
-
You lose throughput, because each connection must wait for the broker's reply before it sends the next batch. The time spent waiting is mostly the network round trip plus the broker's write and replication time, and the producer sits idle during it.
throughput effectruns offline# illustrative numbers: 5 ms round trip, 100 KB batches in-flight 1: 100 KB per 5 ms = about 20 MB/s per connection in-flight 5: 500 KB per 5 ms = about 100 MB/s per connectionThe numbers are a ceiling and ignore broker time, but the ratio is the point: five batches in flight can carry up to five times as much per connection. A producer to a distant region, with a 50 ms round trip, suffers ten times more.
With idempotence on, the cost is not needed: ordering stays correct with up to 5 in flight. So I only use 1 on very old clients without idempotence, and I measure before I decide, since larger batches and a longer linger can also fill the gap.
Q29. "Explain how the idempotent producer works: producer id, sequence numbers and what it does not cover."
Reveal answer
Strong answer When a producer starts with idempotence on, the broker gives it a producer id (PID) and an epoch. For each partition the producer numbers its batches 0, 1, 2 and so on: the sequence number.
The broker keeps the last sequence it accepted per PID and partition. If a batch arrives with a sequence it has already seen, it drops the duplicate and still replies success. If the sequence skips ahead, it rejects it.
So a retry after a lost acknowledgement does not create a duplicate. This is the fix for the "success was lost, we sent it again" problem.
What it does not cover: duplicates across producer restarts (new PID), duplicates produced by the application calling send() twice, and anything beyond one partition. For those you need transactions or an idempotent consumer.
Picture it A lost acknowledgement, with and without idempotence.
The setup: The producer sends a record. The broker appends it, but the reply is lost in the network.
# illustrative output
send(order-88) -> broker appends at offset 41 -> reply lost
timeout -> producer retries -> broker appends again at offset 42 ❌ duplicateMake the invisible visible: The same event with PID and sequence.
# illustrative output
send(order-88) PID=17 seq=9 -> appended at offset 41 -> reply lost
retry PID=17 seq=9 -> broker: seq 9 already accepted -> no append, reply OK (offset 41) ✅What you see: One record in the log, and the producer believes it succeeded once.
Why: Deduplication needs an identity (PID) and a counter (sequence). The broker stores only a small window per partition, which is enough for retries but not for restarts.
Land it I explain idempotence as PID plus sequence per partition, and I am careful to say it protects retries within a session, not the whole pipeline.
- "Is it enabled by default?"
-
Yes. Since Kafka 3.0 the producer default is
enable.idempotence=truetogether withacks=all. Idempotence needs a few other settings to be compatible:acks=all, retries above 0, and at most 5 in-flight requests per connection.The defaults already fit, so a normal producer gets it without any extra line. What matters is what happens if someone sets a conflicting value. If you set, say,
acks=1explicitly while leaving idempotence at its default, recent clients quietly turn idempotence off or raise a configuration error, depending on whether you also set idempotence yourself. The exact behaviour has differed between versions, so check the documentation for yours.My habit is to avoid the guessing. I set the options consistently, and I log the effective producer config at startup. A producer that silently ran without idempotence for a year because of one old
acks=1line in a shared config file is a classic find. - "Does it cost anything?"
-
A little, and it is cheap enough that I never turn it off for cost. The broker keeps a small state per producer id and partition: the last 5 batches' sequence numbers and a few fields. That is some memory per active producer, so a cluster with a very large number of short-lived producers feels it first, mostly through memory and the time to rebuild the state after a restart.
On the wire, each batch carries a few extra fields: the producer id, the epoch and the first sequence number. That is a few bytes on batches that are usually kilobytes, so the network cost is invisible.
Older advice said idempotence hurt throughput, because it was off by default and came with restrictions such as one in-flight request. Those restrictions are gone. With the modern defaults, the difference I have seen in tests is within noise.
So the judgement is simple: leave it on, and only look at the cost if a broker shows memory pressure from a huge producer count.
- "How does it differ from transactions?"
-
They solve different sizes of problem, and transactions are built on top of idempotence.
- Idempotence: no duplicates from retries, inside one producer session, for one partition at a time. Cost: almost nothing. No special API.
- Transactions: an all-or-nothing write across several partitions, plus consumer offsets in the same step, using
transactional.idso it survives a restart. - Visibility: consumers need
isolation.level=read_committedto hide records from aborted transactions. Idempotence needs no consumer change.
I use idempotence everywhere. I add transactions only where a consume, transform and produce step must be atomic, because transactions add latency, extra broker round trips and operational care: a stable
transactional.idper instance, plus a plan for fenced producers. - "What about duplicates from my own code?"
-
Kafka cannot help you there. If your application calls
send()twice for the same business event, for example because a web request was retried or a handler ran again after a failure, Kafka sees two different records. Each gets its own sequence number, and each is accepted. Idempotence only knows about retries of the same batch from the same producer.The trap is that the broker has no idea two records mean the same thing. Only the business meaning says so, so the business has to supply the identity: an event id, an order id plus an action, or a request idempotency key.
The fix goes on the consuming side. The consumer keeps a record of ids it has already handled, for example a table with a unique constraint, and ignores a second copy. On the producing side, an outbox that writes each event once to the database and then publishes it from there prevents the application itself from sending twice. I use both for events that carry money.
Q30 · Design. "You must keep strict order per tenant, but one tenant produces 100 times more than the rest. How do you design the topic?"
Reveal answer
Strong answer First I check if "per tenant" order really needs to include every event. Often the order that matters is per entity inside the tenant (per user, per account). If so, key by that entity and the big tenant spreads naturally.
If the requirement truly is one totally ordered stream for that tenant, the stream cannot be split. Then I isolate it: a dedicated topic and a dedicated consumer for the big tenant, tuned for speed, and the shared topic for everyone else.
I make that consumer fast: batch the processing, use async writes where order allows, and measure per-record time to know the ceiling.
If even that is not enough, the honest answer is that strict total order at that rate is the constraint to negotiate with the business.
Picture it Split the big tenant out, keep the rest shared.
The setup: Tenant big-corp at 20,000 events/s, other tenants total 5,000 events/s over 2,000 tenants.
# illustrative output
events.shared 12 partitions key = tenant+entity (all small tenants)
events.bigcorp 1 partition key = entity (strict order, one fast consumer)
router in producer: tenant == big-corp ? events.bigcorp : events.sharedMake the invisible visible: Ceiling for the single consumer.
# illustrative numbers
one consumer handles 1 record in 0.05 ms when batched = 20,000 records/s (just at the limit)
at 0.1 ms per record = 10,000 records/s ❌ lag grows 10,000/sWhy: Strict order is a single lane. The design question is whether one lane is fast enough, and if not, whether the rule can be loosened.
Land it I would first narrow what "strict order" must cover, then isolate the big tenant in its own lane and measure whether one fast consumer can keep up.
- "Could multiple partitions plus a merge preserve order?"
-
Only if every record carries a global sequence number assigned by the producer, and the merge step sorts by it. The key difficulty is knowing when it is safe to release something. To release number 105, the merger must be sure that 104 is not still on its way on some other partition. That means buffering records from all partitions and waiting until each one has shown a number past 105.
A slow or empty partition then stalls the whole merge, so the design needs timeouts or heartbeat records to keep it moving. It also needs memory for the buffer, and a rule for what happens when a number is truly missing.
The result is one more moving part that adds latency and can fail in odd ways, and the merger itself is a single stream, which is the very bottleneck we were avoiding. I would rather loosen the rule than build it: negotiate order per entity (per account or per user) and let Kafka's partitioning do the ordering for free.
- "What if the big tenant changes from 20,000 to 100,000 events per second?"
-
Then a single lane no longer works, because one consumer has to read, process and commit that whole stream in order. Even with a very fast handler, 100,000 events per second means about 10 microseconds per event on one thread, and most real handlers need more than that.
At that point I go back to the requirement and ask what the ordering protects. Usually it is a per-entity rule: order per account, or per order, with different entities allowed to run in parallel. Then I key by the entity and spread the tenant over many partitions. If a real total order is still demanded, I ask whether eventual order is acceptable, where events carry a version or timestamp and the consumer discards stale updates.
I bring numbers to that talk: events per second now, the growth, and the processing time per event. Most business owners relax the rule once they see what it costs. If they do not, we are choosing between ordering and scale, and that is their decision, not mine.
- "How do I keep the router simple?"
-
I keep the routing rule in one place, as plain data, and avoid clever logic. A small map from tenant id to topic name, loaded at startup or from a config service, with a default entry meaning the shared topic. The producer asks the map, "where does this tenant go?", and nothing else.
Moving a tenant between lanes is a planned migration. You stop writing to the old lane, let its consumer drain to the end, switch the map, and then start the new lane. That drain step matters, because without it, old and new records for the tenant can be handled out of order (the same procedure I described in Q22).
The main mistake to avoid is having the rule copied into several services. Then one of them is updated late and a tenant's events are split between two topics. I put the rule in one shared library or in one gateway service that all producers go through, with a test that checks the map and the default.
- "How do I monitor both lanes?"
-
I watch each lane on its own, because an average over both hides the problem. For each topic I want lag per partition, the big consumer's records per second against the produce rate, and the processing time per record, since that last number is the real ceiling of a single lane.
alertruns offline# illustrative thresholds events.bigcorp lag > 50,000 for 5 min -> page processing time p99 > 0.2 ms -> warn (ceiling approaching)The second line is the early warning. If one record takes 0.2 ms, one thread tops out near 5,000 events per second. If the tenant is at 4,000 and growing, the lag alert is days away but the ceiling is close.
I also graph the shared lane separately, so I can see that isolating the big tenant worked and that everyone else stays healthy. A lane that is quiet on every chart is also worth a look, since it may mean the router sends nothing there.
These questions test whether you can tune batching and acknowledgements for a stated goal, and read a producer failure from its symptoms.
Q31. "Compare acks=0, acks=1 and acks=all. When would you pick each?"
Reveal answer
Strong answer acks=0: the producer does not wait for any reply. Fastest, and it cannot even know if the broker was reachable. acks=1: the leader replies after writing to its own log. acks=all: the leader replies after every in-sync replica has the record (and the ISR is at least min.insync.replicas).
With acks=1, if the leader dies right after replying and before followers copy, the record is lost, yet the producer was told it succeeded.
I pick acks=all for anything that matters, which is why it became the default in 3.0. I pick acks=1 for data where an occasional loss is cheap and latency matters, like debug logs. I would almost never use acks=0.
The cost of acks=all is a follow-up fetch round trip, usually a few milliseconds in one zone.
Picture it Three acknowledgement levels on one timeline.
The setup: Leader L, followers F1 and F2. The producer sends one record.
# illustrative output
acks=0 : producer sends -> (done, no reply) loss undetectable
acks=1 : L appends -> reply OK -> (F1,F2 copy later) L dies now: lost ❌
acks=all: L appends -> F1 copies -> F2 copies -> reply OK L dies now: F1 has it ✅Make the invisible visible: Latency cost, as illustrative numbers.
# illustrative numbers, same zone
acks=0 ~0.3 ms (no wait)
acks=1 ~2 ms
acks=all ~5-8 ms (adds follower fetch)Why: Each level moves the "success" signal later in the replication chain. Later means safer and slower.
Land it I choose acks=all by default and drop to acks=1 only for data I am happy to lose, saying so explicitly.
- "Does acks=all guarantee no loss?"
-
No,
acks=allis necessary but not sufficient. It means the leader waits for every replica that is currently in the in-sync set (the ISR). If the ISR has shrunk to just the leader, "all" means one copy, and a leader crash then loses the record even though the producer got a success.Three more things must be true for no loss.
min.insync.replicasmust be at least 2, so a write is refused when fewer than two copies exist (with replication factor 3, the usual pairing). Unclean leader election must be off, so a stale replica never becomes leader. And the application must act on failures: a send that fails and is ignored is lost data that Kafka did nothing wrong about.I would put it this way in an interview:
acks=allplus replication factor 3 plus min ISR 2 plus no unclean election survives the loss of one broker with no acknowledged record lost. It does not survive two brokers at once, or a bug in my own code. - "Why would anyone use acks=0?"
-
Almost always only for data that is worthless if lost and huge in volume, where the producer must never be slowed down: sampled debug traces, or metrics that are re-sent a moment later anyway. The producer writes to the network buffer and moves on, so latency is lowest and the code path is simplest.
The danger is that it hides everything. With
acks=0the producer never hears from the broker, so it cannot tell if the broker was down, if the leader moved, or if the record was too large. Retries do not happen, because nothing ever reports a failure. A whole outage can pass without one error in your logs.There is also a reason it is rare now: with batching and linger,
acks=1costs very little extra latency, andacks=allonly a few milliseconds more. I have rarely seen a case where the saving was worth going blind. If someone asks for it, I ask them to show the measurement, and I want a counter of how many records they accept losing. - "What does the producer see on a timeout with acks=all?"
-
The producer first sees a retriable error, such as a request timeout or a not-enough-replicas error, and then retries the batch on its own. Retrying continues until
delivery.timeout.ms(default 2 minutes) has passed sincesend()was called.If time runs out, the send fails with a
TimeoutException. You see it in the callback, or in theFutureif you callget(). Nothing is thrown at thesend()call itself, which already returned.The key point is what that failure means. The record may be in the log, because the broker could have written it and only the reply was lost. It may also not be there. The outcome is unknown. So an at-least-once design must assume the record might exist: if the application resends it, a duplicate can appear, and consumers must tolerate that.
I log the failure with the key and the topic, count it in a metric, and decide a policy: retry with the same business id, park it in an outbox, or alert.
- "Does acks affect ordering?"
-
Not by itself. The acknowledgement mode decides when the producer learns that a write succeeded. It does not decide the order in which batches land in the log.
Order inside a partition depends on two other settings: whether idempotence is on, and how many requests may be in flight on a connection. With idempotence on and at most 5 in flight, retries keep their order, as I described in Q28. With idempotence off and more than one in flight, a retry can land behind a later batch, whatever
ackssays.People mix these up because both appear in the "reliability" section of the docs. A weak
ackscan cause loss. It cannot cause reordering. A weak ordering setup can cause reordering. It cannot cause loss.So when someone reports "messages arrive in the wrong order", I do not start with acks. I check idempotence, max in flight, and whether the records share a key, since different keys can go to different partitions, where no order exists at all.
Q32. "What are linger.ms and batch.size, and how do they interact?"
Reveal answer
Strong answer The producer collects records for each partition into a batch. batch.size (default 16 KB) is the maximum size of a batch in bytes. linger.ms is how long the producer may wait for more records before sending a batch that is not full. Since Kafka 4.0 the default linger.ms is 5; before it was 0.
A batch is sent when it is full or when linger time passes, whichever comes first. A longer linger gives bigger batches, better compression and fewer requests, at the price of a little added latency.
Setting batch.size too small wastes the linger; setting it large only helps if records arrive fast enough to fill it.
The tuning rule: for throughput, raise linger.ms to 5 to 20 and batch.size to 64 to 256 KB; for the lowest latency, keep linger near 0 and accept more requests.
Picture it 1,000 records per second with two settings.
The setup: Each record is 1 KB; one partition receives 1,000 records per second.
# illustrative output
linger.ms=0 : each record leaves alone -> ~1,000 requests/s, 1 KB each
linger.ms=10: ~10 records fit in 10 ms -> ~100 requests/s, 10 KB each
batch.size=16 KB, so a 10 KB batch is sent by the timer, not by being fullMake the invisible visible: The knobs together.
linger.ms=10
batch.size=65536
compression.type=lz4
# a batch leaves when it reaches 64 KB OR 10 ms have passedWhy: Fixed request costs (network, broker work) are shared by every record in a batch. Waiting a few milliseconds buys a large reduction in those costs.
Land it I tune linger and batch size together, raise linger by a few milliseconds for throughput, and quantify the latency I am spending.
- "What is the latency cost?"
-
At most
linger.msfor a record that arrives into an empty batch, and usually less. The wait starts when the first record enters the batch, so later records in the same batch wait less. A batch also leaves early if it fills up tobatch.size.The record's total time is the linger wait, plus the network trip, plus the broker's write, plus replication when
acks=all. So a 10 ms linger adds up to 10 ms on top of a base of maybe 3 to 10 ms in one zone.Whether that is acceptable depends on the budget. For a user waiting on a response with a 20 ms total budget, spending 10 ms on batching is too much, and I would keep linger near 0 or send from an outbox instead. For a background pipeline where seconds are fine, a 20 ms linger is free, and the larger batches give better throughput and compression. I decide by the slowest path that a person actually waits on, not by an average.
- "What is buffer.memory and how does it relate?"
-
buffer.memory(default 32 MB) is the producer's total pool for records that are waiting to be sent or are still being sent. Every batch being built comes out of this pool.If the application produces faster than the network and brokers can take, the pool fills. Then
send()stops accepting new records and blocks, up tomax.block.ms(default 60 seconds). After that it throws an exception. This is the point where a Kafka slowdown turns into a slow application (see Q36).The relation to batches is that each partition being written to holds a batch of up to
batch.sizein memory. A large batch size across many partitions uses the pool quickly. So when I raisebatch.size, I check the arithmetic againstbuffer.memory, and I also keep an eye on the metricbuffer-available-bytes, which tells me how close to the wall I am. - "Does batch.size apply per partition?"
-
Yes. The producer keeps one batch per partition at a time. Each one can grow up to
batch.size, so total memory in batches depends on how many partitions the producer is currently writing to, not on the total topic count.memory estimateruns offline# illustrative numbers, buffer.memory = 32 MB 100 partitions x 64 KB batch = 6.4 MB inside 32 MB, fine 2,000 partitions x 64 KB batch = 128 MB exceeds buffer.memory, sends will blockIn practice batches are rarely all full at once, so this is the worst case. Still, a producer that writes keyed records across thousands of partitions fills many small batches slowly, and batches become small and inefficient. Two things help: a longer linger, and fewer partitions per producer where design allows.
So I size
buffer.memoryas at least partitions written timesbatch.size, with headroom. - "How do I know the batches are good?"
-
I watch two producer metrics before and after any change:
batch-size-avgandrecords-per-request-avg. They tell me what batches actually look like, instead of what I configured.If
batch-size-avgis far belowbatch.size, say 2 KB against a 64 KB setting, batches leave nearly empty. That means linger is too short, or traffic per partition is too thin to fill them, and raisingbatch.sizefurther does nothing. If it is close tobatch.size, batches fill and leave on size, so a bigger size or more bandwidth may help.I also check
request-latency-avgandcompression-rate-avg, because bigger batches should lower request counts and improve compression, and the end-to-end latency must stay inside my budget.The method is plain: change one setting, run the same load, compare these numbers, and keep the change only if the evidence moves the right way.
Q33. "Which compression type would you choose and why?"
Reveal answer
Strong answer Compression is applied per batch by the producer, stored compressed on the broker, and decompressed by the consumer. The options are none, gzip, snappy, lz4 and zstd.
My default is lz4 for low CPU and good speed, or zstd when I want a better ratio and can afford a bit more CPU. Gzip compresses well but is slower. Snappy is similar to lz4 in aim.
Compression helps most with text-like records (JSON, logs) and with larger batches, because there is more repeated content to squeeze. It reduces network, broker disk and page cache use.
The broker keeps the batch as it received it if the topic's compression setting is producer, so it does not re-compress and uses little CPU.
Picture it One 64 KB batch of JSON under three settings.
The setup: A batch of 64 JSON order records.
# illustrative numbers (ratio depends on data)
none : 64 KB
lz4 : ~22 KB fast
zstd : ~15 KB better ratio, more CPU
gzip : ~16 KB slowestMake the invisible visible: What it saves across the cluster.
# illustrative numbers
50 MB/s ingress, zstd ratio ~4x -> 12.5 MB/s on the wire and on disk
x replication 3 -> 37.5 MB/s total disk write, versus 150 MB/s uncompressedWhy: Fewer bytes everywhere is cheaper than the CPU it costs, for most text data. Already-compressed data (images, encrypted payloads) gains little.
Land it I would use lz4 or zstd at the producer, measure the ratio on real data, and leave the topic setting as producer so brokers do not recompress.
- "Can mixed compression types in one topic work?"
-
Yes. Each batch has a header that names its own codec, so a consumer reads any mix of codecs from one topic with no configuration. Records written by different producers, or by the same producer before and after a config change, coexist.
The cost is not correctness but confusion. With mixed codecs, the compression ratio and CPU cost vary by producer, and a dashboard that shows "average batch size" becomes hard to read. So I standardise per producer and per topic.
There is also a broker side. The topic setting
compression.typedefaults toproducer, meaning keep the batch as it arrived. If the topic names a specific codec that differs from the producer's, the broker must decompress and recompress each batch, which costs broker CPU. For that reason I leave the topic setting atproducerunless there is a deliberate reason, such as forcing one codec for old consumers or saving disk on a topic fed by uncompressed producers. - "Does compression hurt latency?"
-
It adds a little CPU time for each batch, and for lz4 that is usually tiny compared with the network time it saves. Sending 30 KB instead of 100 KB across a link is quicker even after the compression step.
The producer compresses in its sending path, so the extra time comes just before a batch is sent. It shows up in total latency only when the host's CPU is already close to its limit. Then compression time competes with your application threads, and sends get slower. That is the case where I watch CPU and, if needed, move to a lighter codec, or none.
Consumers pay a decompression cost for each batch they read, again small for lz4 and a bit larger for zstd at high levels.
My judgement: compression nearly always saves more time than it costs for text-like records on a network. I measure on real data and real hosts, because a stream of already-compressed payloads, such as JPEG bytes or encrypted blobs, gains nothing and only burns CPU.
- "Why do tiny batches compress badly?"
-
A compressor finds repeated patterns, and a batch with only one or two records has little that repeats. A single 200-byte JSON record shows its field names once, so there is nothing to refer back to. On top of that, a compressed batch has fixed overhead, such as its header and codec framing.
The effect is real: a batch of one small record can come out slightly larger after compression than before. A batch of 500 similar records repeats the same field names 500 times, and compresses very well, often to a fraction of the size.
That is another reason to give the producer a little linger. With
linger.msat 5 to 20 ms, records accumulate into batches of tens or hundreds, and the compression ratio improves, which also cuts broker disk and replication traffic.So when compression gives a poor ratio, I check
batch-size-avgandcompression-rate-avgtogether before I blame the codec. - "Does TLS interact with compression?"
-
They fit together well, because compression happens in the producer before TLS encrypts the traffic on the connection. Compress first, then encrypt, is the right order. Encrypted data looks random, and random data cannot be compressed.
The trap is encrypting the payload yourself, for example by encrypting each message value with a key before calling the producer. The producer then receives random-looking bytes, and compression finds nothing to remove. You pay the CPU and save no bytes.
If you need end-to-end protection, so that even the brokers cannot read the data, you have to accept this. Application-level encryption defeats compression, and the extra size is the price.
If you only need protection on the wire and on disk, use TLS between clients and brokers, plus disk or volume encryption on the brokers. Compression then still works, because it sees plain data. Another point I note: compressing before encrypting can leak information in some designs, so for secrets mixed with attacker-controlled text I check with the security team.
Q34 · Scenario. "Your producer sends 8,000 records per second but the target is 50,000. CPU on the app host is 15%. How do you find and fix the bottleneck?"
Reveal answer
Strong answer Low CPU on both sides suggests the producer is waiting, not working. The usual cause is tiny batches with linger.ms near 0 and a synchronous send pattern (waiting for each result before the next send).
First I check how the application sends. If it calls send(...).get() per record, throughput is capped by round-trip time: with 5 ms round trips, that is 200 records per second per thread.
Then I check metrics: batch-size-avg, records-per-request-avg, request-latency-avg, and buffer-available-bytes. Small batches mean raise linger and batch size. A full buffer means the broker or network is the limit.
Fixes in order: send asynchronously with a callback; set linger to 5 to 20 ms and batch size to 64 KB or more; add compression; and then look at the number of partitions and brokers.
Picture it The anti-pattern and the fix.
The setup: One thread sends 8,000 records per second to events.
// ❌ TRAP: waits for the broker on every record, throughput = 1 / round trip
for (Event e : events) {
producer.send(new ProducerRecord<>("events", e.key(), e)).get();
}
// ✅ async: many records in flight, batches fill
for (Event e : events) {
producer.send(new ProducerRecord<>("events", e.key(), e), (md, ex) -> {
if (ex != null) failures.increment();
});
}
producer.flush();Make the invisible visible: The metrics before and after.
# illustrative output
before after
records-per-request 1.2 85
batch-size-avg (bytes) 1,300 84,000
records sent per s 8,000 52,000Why: A producer is fast when many records are in flight and share requests. A blocking send turns every record into its own round trip.
Land it I would look for blocking sends and tiny batches first, because low CPU on both sides points to waiting, and fix with async sends, linger and batching.
- "How do I avoid losing failures with async sends?"
-
I always read the callback and count failures, because an async send that has no callback is fire and forget by accident. The callback gives me an exception for each failed record. I increment a failure metric, log the key and the topic, and decide what to do next.
For a shutdown I call
flush()first, which waits until every buffered record has either succeeded or failed, so no record is left behind in memory when the process exits.For business events, I want more than a counter. I write the event into an outbox table in the same database transaction as the change, and a separate publisher reads the outbox and sends to Kafka. If a send fails, the row stays unsent, and the publisher tries again. That gives at-least-once delivery, so consumers must deal with duplicates.
For low-value data such as metrics, counting the failures and watching the rate is enough.
- "What if the broker is the bottleneck?"
-
I first prove it with broker-side numbers, and only then change anything on the client. Useful ones are the request handler idle percentage and the network processor idle percentage, which tell me how busy the broker's threads are, plus disk I/O wait, produce request latency, and the under-replicated partition count.
If request handlers are nearly always busy (idle ratio under about 0.3, as a common rule of thumb), the broker is the limit. Also check whether one broker holds far more leader partitions than the others, because then a single machine carries a disproportionate share.
Then the fix is on the server side: add brokers and move partitions onto them, spread leaders evenly, use compression to cut network and disk bytes, or use faster disks. A cluster limited by the broker gets no help from more producer threads.
The point is not to tune the client further when the server is the limit. Extra batching only hides the problem for a while, and more connections add load on a machine that is already struggling.
- "Does adding producer threads help?"
-
Often yes, but mainly by sharing one producer, not by creating many. A
KafkaProduceris thread-safe, and all threads that share it feed the same batches. More records arrive per partition per unit of time, so batches fill faster and fewer, larger requests are sent.Many separate producer instances do the opposite. Each one has its own small batches, its own connections and its own sender thread, so you get more tiny requests and more load on the broker.
If the bottleneck was a blocking call such as
send().get(), adding threads does help in a crude way, because each thread waits on its own request. But the cleaner fix is to stop waiting: send asynchronously from fewer threads.So my rule is one producer instance per application and config. The exception is when I need separate transactional ids, a different configuration (such as a different
acksor compression for a different data class), or isolation so that one noisy use case cannot fill another's buffer. - "What number should I expect from one producer?"
-
It depends on hardware, record size, replication, compression and settings, so I never quote a number from memory. I measure with the performance tool that ships with Kafka, against a test topic that looks like production, and compare runs.
measureruns offline# illustrative kafka-producer-perf-test.sh --topic events --num-records 2000000 --record-size 500 \ --throughput -1 --producer-props bootstrap.servers=localhost:9092 \ linger.ms=10 batch.size=65536 compression.type=lz4 # example output shape: 2000000 records sent, 210000 records/sec (100 MB/sec)I change one setting at a time and rerun: linger, batch size, compression. Running the same test against the real cluster and against a copy of the application tells me whether the limit is the client, the network or the brokers.
For the question in the scenario, 50,000 records per second at a few hundred bytes is a modest load for a tuned producer, so I would expect to hit it. The 8,000 figure points to a configuration problem, not a hardware limit.
Q35. "Explain delivery.timeout.ms, request.timeout.ms and retries. How do they fit together?"
Reveal answer
Strong answer delivery.timeout.ms (default 120,000) is the upper bound on the whole send: from when send() returns to the moment the result (success or failure) is reported, including batching time, retries and waits. request.timeout.ms (default 30,000) is how long one request waits for a reply before it counts as failed.
retries defaults to a very large number, so in practice retries continue until delivery.timeout.ms runs out. You control the retry window with the delivery timeout, not by counting retries.
retry.backoff.ms (default 100) is the pause between attempts.
The rule: delivery.timeout.ms must be at least linger.ms + request.timeout.ms, or the client refuses to start.
Picture it One failing send on a timeline.
The setup: delivery.timeout.ms=120000, request.timeout.ms=30000, a broker that is unreachable.
# illustrative output
t=0s send() accepted into batch
t=5ms batch sent, no reply
t=30s request timeout -> retry 1
t=60s request timeout -> retry 2
t=90s request timeout -> retry 3
t=120s delivery timeout -> callback gets TimeoutException (record may or may not be on the broker)Make the invisible visible: A config that is valid, and one that is not.
# ✅ valid: 120000 >= 5 + 30000
delivery.timeout.ms=120000
request.timeout.ms=30000
linger.ms=5
# ❌ TRAP: 20000 < 5 + 30000, the producer rejects this
# delivery.timeout.ms=20000Why: One number (delivery timeout) says how long you are willing to try. The others say how long one try takes. Retries just fill the time.
Land it I set delivery.timeout.ms to cover expected failover time, and I treat a failure after it as "unknown outcome", not "not written".
- "Why treat a timeout as unknown?"
-
Because the failure message only says that the producer gave up waiting. It does not say what the broker did. The broker may have written the record and the reply was lost on the way back, or the write may never have happened. From the producer's seat, the two cases look the same.
Inside the delivery window the producer's retries are safe, because idempotence lets the broker drop a repeated batch. But once the producer reports the failure to your code, it has stopped retrying. If your code then sends the same record again, it is a new send with a new sequence number, so you can end up with two copies.
So I describe the outcome as unknown, and I design for it. The producer side keeps the business id with the record and may resend. The consumer side stores the ids it has handled and ignores a second copy, so "written twice" and "written once" produce the same end result.
Treating a timeout as "not written" is the classic mistake.
- "How long should the delivery timeout be?"
-
Longer than the time a normal failover takes, so a leader election does not turn into failed sends. A leader change on a healthy cluster takes seconds, and a broker restart with several partitions may take tens of seconds. The default of 120 seconds covers that with room to spare, which is why I rarely change it for backend pipelines.
The window also has a cost: while a record waits, it holds buffer memory, and any caller blocked on the result waits as well. Records sent during a long outage pile up in the buffer until it is full.
For a request-response user flow, two minutes is far too long. A person will not wait that long, and the web thread would be tied up. There I use a much shorter value, such as 5 to 10 seconds, and show a clear failure or route the event through an outbox.
Remember the rule from the answer:
delivery.timeout.msmust be at leastlinger.msplusrequest.timeout.ms, so I check that when I lower it. - "What happens to ordering during retries?"
-
With idempotence on and no more than 5 requests in flight, order inside a partition is kept even through retries. The broker uses the sequence numbers: if batch 2 arrives before batch 1 is confirmed, it holds or rejects it, so the retry of batch 1 still ends up first.
Without idempotence, the story changes. Suppose two batches are in flight and the first fails and is retried while the second succeeds. The log then holds batch 2 followed by batch 1, as described in Q28.
There is one more case. If a batch is abandoned after
delivery.timeout.ms, the producer reports failure for it, and the following batches may still be written. That means a record you thought failed is missing from the sequence while later records exist. The consumer sees a gap in business terms, even though Kafka's order is intact.This is why I keep idempotence on and treat failed sends as events that need an explicit response.
- "What is max.block.ms?"
-
max.block.ms(default 60,000) limits how longsend(), and also calls likepartitionsFor(), may block the calling thread. It covers two waits that happen before a record is even accepted: fetching metadata for the topic, and waiting for free buffer space.It is a separate clock from
delivery.timeout.ms, which only starts after the record is in the buffer. So in the worst case the caller can be held formax.block.msfirst, and the record then has up todelivery.timeout.msmore to be delivered.two clocksruns offline# illustrative send() blocked waiting for metadata or buffer space -> clock: max.block.ms record accepted, waiting for broker reply -> clock: delivery.timeout.ms request on the wire, waiting for one reply -> clock: request.timeout.msI usually lower
max.block.mson web-facing producers, so a Kafka problem fails fast and does not hold request threads (the Q36 scenario).
Q36 · Scenario. "Your service's HTTP requests start hanging, and a thread dump shows threads stuck in KafkaProducer.send(). Why?"
Reveal answer
Strong answer send() can block in two situations: waiting for metadata (the topic's partition leaders) and waiting for buffer space when buffer.memory is full. It blocks up to max.block.ms (default 60 s) and then throws.
So if Kafka is slow or down, the producer's buffer fills, then every request thread calling send() waits. That turns a Kafka problem into a web outage.
The fixes: lower max.block.ms so the failure is quick, move the send off the request path (an outbox or an in-memory queue with a bounded size), and make the caller return a clear error or accept the work for later.
The deeper design point: do not make user-facing latency depend on the broker.
Picture it How one slow broker reaches the web threads.
The setup: Brokers become slow. Producer buffer 32 MB, HTTP pool of 200 threads.
# illustrative output
broker slow -> batches not acknowledged -> buffer.memory (32 MB) fills
buffer full -> send() blocks (up to max.block.ms = 60 s)
200 HTTP threads each wait in send() -> pool exhausted -> site stops answering ❌Make the invisible visible: Decouple with an outbox, and a short block limit.
max.block.ms=2000 # fail fast instead of hanging a request thread
# the request writes the event to an outbox table in its DB transaction
# a separate relay thread publishes from the outbox to KafkaWhy: A buffer is a shock absorber of finite size. When it is full, blocking is the only choice left, so the decision is who blocks.
Land it I would decouple the request from the send with an outbox or bounded queue, and set a short max.block.ms so a Kafka slowdown cannot take down the web tier.
- "Is a bigger buffer.memory the fix?"
-
It only delays the problem. A bigger
buffer.memorygives the producer more room to absorb a slowdown, so the web threads start blocking later. But if the broker stays slow or down, the buffer still fills, and then every thread blocks exactly as before.A quick sum shows the limit. If the app produces 5,000 records per second at 1 KB each, that is about 5 MB per second. A 32 MB buffer lasts roughly 6 seconds of a full outage, and a 128 MB buffer about 25 seconds. Neither covers a ten-minute incident.
So I treat it as a reasonable second measure, sized for brief hiccups such as a leader election. The main cure is to take the send off the request path with an outbox or a bounded queue, and to lower
max.block.msso failure is quick and visible. - "How do I see this coming?"
-
I want the signal while the buffer is still filling, not when threads are already stuck. Two producer metrics show it:
buffer-available-bytesfalling, andrecord-queue-time-avgrising, which is how long records wait in the buffer before being sent. On the broker side, produce request latency is the first thing to climb.early warningruns offline# illustrative thresholds buffer-available-bytes < 20% of buffer.memory for 2 min -> warn record-queue-time-avg > 100 ms for 5 min -> warn produce request latency p99 > 500 ms -> warnI also watch how many web threads are inside
send()in a staging load test, because blocked threads are the real danger, and the metrics above should rise before they pile up.The point is to alert on trends rather than failures. By the time the first
TimeoutExceptionappears, the requests have already been hanging for as long asmax.block.ms, and users have felt it. - "Should the web thread ever call send().get()?"
-
Only when the caller really must know the result before it responds, such as a payment confirmation or an action where "accepted" means "durably recorded". Even then I bound it:
get(timeout)with a short timeout, and a defined failure path that shows the user a clear error.The reason to avoid it by default is arithmetic. A blocking send waits for a full round trip plus replication, say 5 to 15 ms with
acks=allin one zone. One thread can then do only about 70 to 200 sends per second, and each request thread is held for that long. If Kafka slows to a second per request, the whole thread pool soon waits on it.For most events, such as audit trails, notifications and analytics, the user does not need to wait. I write the event to an outbox and respond immediately, and the publisher takes care of Kafka. That keeps the web tier independent of the broker, which was the design point of the scenario.
- "What does the outbox change about guarantees?"
-
It makes two things become one atomic step: the business change and the intent to send. In one database transaction, the application writes the order and a row in an outbox table saying "publish this event". Either both are committed or neither. There is no window in which the order exists but the event is lost, or the event is sent but the order rolled back.
A separate publisher reads unsent outbox rows and sends them to Kafka, marking each one after the broker acknowledges it. If Kafka is down, the rows wait, and the web request is not affected at all. If the publisher dies after sending but before marking the row, it sends again, so delivery is at least once and consumers must remove duplicates.
This is the pattern described in e07
#pat-outbox. The trade is immediacy for reliability: the event may arrive a few hundred milliseconds later than a direct send, and you take on a table, a publisher process, and cleanup of old rows. For events that matter, I take that trade.
Q37. "What does flush() and close() do, and what goes wrong if you skip them?"
Reveal answer
Strong answer flush() forces all buffered records to be sent and blocks until they are acknowledged or failed. close() flushes and then shuts the producer down, waiting up to a timeout.
If an application exits without them, records still sitting in the buffer, which can be up to linger.ms worth plus anything not yet acknowledged, are lost silently.
In a Spring app the producer factory closes on shutdown, but a plain main or a killed container does not give it a chance unless you handle shutdown signals.
I call flush() at logical boundaries (end of a batch job) and close() on shutdown, and I make sure the container gives enough grace time.
Picture it A short job that loses its tail.
The setup: A batch job sends 10,000 records then returns from main.
for (int i = 0; i < 10_000; i++) {
producer.send(new ProducerRecord<>("events", "k" + i, "v" + i));
}
// ❌ TRAP: main returns here; the last batch (about 8 ms of data) is still in memory
// ✅ producer.flush(); then producer.close();Make the invisible visible: What the broker holds in each case.
# illustrative output
without flush : topic has 9,870 records (130 lost in the buffer)
with flush : topic has 10,000 recordsWhy: send() returns when the record is queued, not when it is delivered. Queued records live in process memory only.
Land it I flush at the end of a job and close on shutdown, and I give the container a shutdown grace period longer than the delivery timeout I care about.
- "What is the shutdown timeout for close()?"
-
close()with no argument waits as long as it takes for the buffered records to be sent, which in some versions can be forever when the broker is unreachable.close(Duration)waits up to that time, then abandons the remaining records and shuts down.So the choice has a real consequence. Without a limit, a dead broker can hang your application's shutdown, and an orchestrator then kills the process anyway, losing the same records. With a limit, you decide how long you are willing to wait, and the unsent records are reported as failed to their callbacks, so you can log how many were lost.
I pass an explicit duration, usually a bit shorter than the container's grace period. For example, with a 30 second grace period, I choose a 20 second close. That leaves time for the rest of the shutdown and keeps the process from being killed halfway through.
Check the exact blocking behaviour for your client version in the Javadoc, since it has been adjusted over releases.
- "Does Kubernetes affect this?"
-
Yes, in a very direct way. When Kubernetes stops a pod, it sends
SIGTERMand then waitsterminationGracePeriodSeconds(default 30) before it sendsSIGKILL. ASIGKILLcannot be caught, so anything still in the producer's buffer is gone.The three time budgets must fit together for a clean stop, with the grace period larger than the sum of the steps:
grace budgetruns offline# illustrative budget, all in seconds stop accepting new work 2 flush / close(Duration) the producer 20 close consumers, DB pool, other 5 terminationGracePeriodSeconds 30 (must be larger than the sum, 27)The application must also handle the signal. A Java process stops cleanly on
SIGTERMthrough a shutdown hook, and Spring Boot's graceful shutdown does the same. But a shell script wrapper that does not forward the signal can swallow it, and then the producer never flushes. See e10 for the pod lifecycle. - "What does flush() cost if called after every record?"
-
It removes the batching and sends the producer into a crawl.
flush()blocks until everything in the buffer is acknowledged. If you call it after each record, each batch holds exactly one record, and each send waits for a full round trip before the next record can go.The effect is easy to compute. With a 5 ms round trip and
acks=all, one thread tops out near 200 records per second. A producer that could send 100,000 records per second with batching now sends a few hundred. Compression also gets worse, since every batch is tiny, and the broker handles many more requests for the same data.So I flush at boundaries: the end of a batch job, a test, or before shutdown. In a steady stream, I rely on
linger.msand callbacks, not onflush(). The one exception is when the code must guarantee that something is durable before it takes a next step, and then I flush once for a group of records, not for each. - "How does a Spring KafkaTemplate handle it?"
-
KafkaTemplate.flush()calls the producer's flush for the current producer. The default producer factory also destroys its producers when the Spring context closes, and closing a producer flushes it. So in a normal Spring Boot shutdown, buffered records are sent before the application ends, as long as the JVM exits gracefully and is not killed first.I check three things in practice. The grace period of the container must be longer than the time the flush needs. Spring Boot's
server.shutdown=gracefuland the Kafka listener containers must be allowed to stop in order: consumers finish their records, then producers flush. And the application should not start new sends during shutdown.A
kill -9, an out-of-memory kill, or a node failure skips all of it, and so does a crash inside the JVM. Those cases lose whatever was in the buffer, up tolinger.msworth of records plus anything unacknowledged. For events that must not be lost, the outbox pattern is the answer, not the shutdown hook.
Q38. "Describe the full life of a producer record from send() to a consumer reading it."
Reveal answer
Strong answer send() serializes key and value, picks a partition, and puts the record in that partition's batch in the accumulator (the in-memory buffer). The call returns.
A background sender thread collects ready batches (full or past linger), groups them by destination broker, and sends one produce request per broker. The leader appends to its log and waits for followers according to acks.
Followers fetch from the leader, the high watermark rises, and the leader replies. The producer completes the callback. Consumers fetch up to the high watermark and receive the batch.
Knowing each stage lets me say where a given setting acts: serializer and partitioner in send(), linger and batch in the accumulator, acks and retries at the broker call, high watermark at the read side.
Picture it The stages in a line, with the settings that act at each.
The setup: One order event for cust-7, topic orders with 6 partitions.
# illustrative output
send(record)
1 serialize key+value
2 partitioner: murmur2(cust-7) mod 6 -> partition 2
3 accumulator: append to batch for orders-2 (linger.ms, batch.size)
4 sender thread: batch ready -> produce request to leader of orders-2
5 leader appends to log (acks, min.insync.replicas)
6 followers fetch; high watermark moves
7 leader replies -> callback fires (delivery.timeout.ms, retries)
8 consumer fetch returns the batch up to HW (fetch.min.bytes, fetch.max.wait.ms)Make the invisible visible: Where the time goes, with invented but plausible numbers.
# illustrative numbers
serialize + partition 0.05 ms
wait in batch (linger) 5.00 ms
network to leader 0.50 ms
leader append 0.20 ms
follower replication 3.00 ms
reply + callback 0.50 ms
consumer fetch wait up to fetch.max.wait.ms (500 ms default if no data)Why: Latency is a sum of waits you configured. Seeing them as a list is how I decide which one to change.
Land it I walk the path stage by stage, because it tells me which setting controls which delay or risk.
- "Where can a record be lost on this path?"
-
There are three places, and they correspond to steps in the path. First, before the batch leaves the application: the record sits in the accumulator, in memory. If the process dies there, with no flush, the record is gone, and nothing on the broker ever knew about it.
Second, on the broker with a weak
acks. Withacks=1the leader replies after its own write. If the leader dies before followers copy, a new leader without the record takes over, and the producer was already told "success". That is steps 5 and 6.Third, at the consumer, after the fetch: if the consumer commits its offset before processing, a crash after the commit skips the record on restart.
I can name the fix for each: a flush plus an outbox,
acks=allwith min ISR 2, and process-then-commit. Walking the path this way shows that I know the whole pipeline, and not only one stage. - "Where can it be duplicated?"
-
Three common places, and each needs a different fix.
The first is a retry after a lost reply: the broker wrote the batch, the acknowledgement was lost, and the producer sent it again. Idempotence (producer id plus sequence number) removes this, within one session.
The second is a producer restart or the application sending the same event twice. The new instance has a new producer id, so the broker cannot see a duplicate. The fixes are a stable transactional id with transactions, or a business key that the consumer uses to ignore repeats.
The third is the consumer: after a rebalance, or a crash between processing and commit, the next owner starts from the last committed offset and handles some records again. The fix is idempotent processing, such as an upsert, a unique constraint, or a table of handled ids.
So duplicates are part of normal operation in an at-least-once system. I do not try to prevent all of them. I make them harmless.
- "What is the "metadata" step I skipped?"
-
Before the step where the batch is sent, the producer must know which broker is the leader for the target partition, for example orders-2. It gets that from topic metadata, requested from any broker at startup and cached.
It refreshes the cache in three situations: every
metadata.max.age.ms(default 5 minutes), when a send fails with an error such as not-leader-for-partition, and when it sees a topic or partition it does not know yet.Here is what a leader change looks like. The old leader stops, the producer's request fails with a not-leader error, the producer fetches new metadata, sees that broker B leads orders-2 now, and retries the batch there. With default retry settings, this finishes in well under a second, and the application sees nothing but one slow send.
The metadata step also explains why a producer pointed at an unreachable cluster blocks inside
send()and not later. - "Why does the consumer add up to 500 ms?"
-
Because of the broker's wait setting. A consumer's fetch request asks the broker for data, and the broker may hold the request open until enough data has arrived.
fetch.min.bytes(default 1 byte) says how much is enough, andfetch.max.wait.ms(default 500) says how long to wait at most.With the defaults, the broker answers as soon as it has even one byte. So when the partition has data, there is no wait at all. The 500 ms applies only when the partition is empty: the broker holds the request and answers when a record arrives, or after 500 ms with nothing.
So the extra latency from this step is small when data is flowing.
If I raise
fetch.min.bytes, say to 64 KB, the broker waits until 64 KB is available or 500 ms passes. Larger fetches use fewer round trips and less CPU, but each record may be delayed up to 500 ms. I raise it for throughput jobs and leave it at the default for latency-sensitive ones.
Q39 · Design. "Design producer configs for two producers: a clickstream tracker (high volume, loss tolerable) and a payment-events publisher (low volume, no loss). Compare them in one table."
Reveal answer
Strong answer They sit at opposite ends of the same dial, so I give each its own producer instance and config instead of one shared default.
Clickstream: favour throughput. Large batches, a moderate linger, strong compression, and acks=1 is acceptable, though I would keep acks=all with min ISR 1 if the cost is low.
Payments: favour safety. acks=all, idempotence on, a long delivery timeout, small linger, and an outbox so an unavailable broker does not drop events.
I would also separate them by client id and apply quotas so a clickstream burst cannot starve the payment path.
Picture it The two configs side by side.
The setup: Clickstream 40 MB/s of small JSON; payments 50 events/s of 1 KB each.
# illustrative output
setting clickstream payments
acks 1 (or all, min ISR 1) all
enable.idempotence true true
linger.ms 20 5
batch.size 131072 16384
compression.type zstd lz4
delivery.timeout.ms 30000 120000
max.in.flight.requests 5 5
on failure drop and count outbox retry, alert
min.insync.replicas (tp) 1 2Make the invisible visible: The two configurations in a Spring properties file.
spring:
kafka:
producer:
acks: all
compression-type: lz4
properties:
enable.idempotence: true
linger.ms: 5
delivery.timeout.ms: 120000
# the clickstream producer is a separate bean with its own ProducerFactory and propertiesWhy: Different data deserves different trade-offs. One config for both means one of them is wrong.
Land it I give each use case its own producer settings and its own client id, and I put the safety budget where the data is valuable.
- "Why separate client ids?"
-
Quotas and metrics are applied per client id, so the client id decides who shares a limit and who can be told apart in a graph. If the clickstream tracker and the payment publisher both use the same client id, or the default empty one, they share a single quota. A clickstream spike then uses up the budget and throttles the payment path.
With separate ids, I can set a quota on the tracker, such as a limit in bytes per second, so that a burst slows only the tracker. The payment publisher keeps its own allowance and stays fast.
The metrics also separate. Broker request logs, throttle times and producer metrics all carry the client id, so when something slows down I can see in one graph whether it is the payment path or the click path. With one shared id, those lines are mixed, and I would be guessing.
- "Can the clickstream drop events silently?"
-
Not silently. Loss that is accepted must still be counted. The producer callback, or the send future, reports each failure, and the tracker increments a counter for each one, labelled by error type, so I can graph it and alert on it.
This changes the conversation from a worry to a number. If one in a thousand click events is lost during a broker restart, that is 0.1 percent. The analytics team can decide whether that matters. An unknown loss is a bug, because nobody can say whether the dashboards are 0.1 percent or 20 percent off.
I also check the shutdown path, since a forgotten
flush()is the commonest reason for a quiet loss. And I send a regular heartbeat event with a known count, so the downstream job can compare what was sent with what arrived.So the tracker may lose events, but it must know how many, and it must raise a flag when the rate changes.
- "Does a higher linger help payments?"
-
Very little, because the volume is low. With 50 payment events per second and a linger of 5 ms, a typical batch holds about 0 or 1 records: on average a new event arrives every 20 ms, so batches almost never fill. A longer linger of 50 ms would only add up to 50 ms of delay and bring a handful of records per batch.
The saving would also be small. Fewer requests help a broker that is under load, but 50 requests per second is nothing for it. Compression of a tiny batch gains little too.
Meanwhile latency matters for payments. A customer is waiting for confirmation, or a downstream step is, so I keep linger short, and I put my effort into the settings that protect data:
acks=all, idempotence, a generous delivery timeout and the outbox.Batching tuning pays off only at volume. I would revisit it if payment events grew to thousands per second.
- "Should payments use transactions?"
-
Only if I can name the requirement. Transactions are for an atomic step that spans several writes: for example, a consume, transform, produce chain where the output record and the input offset must commit together (Q62). They cost extra round trips, a stable transactional id, and care with fencing.
For the plain case, a payment is saved in the database and then published as an event. Here the simpler design is the outbox: the event is written in the same database transaction as the payment, a publisher sends it to Kafka at least once, and the consumer ignores duplicates by event id. It has fewer moving parts, and the failure cases are easy to explain.
I would justify transactions with a specific case. One example is a stream processor that reads "payment authorised" and writes "ledger entry" to another topic, where a crash must not leave a ledger entry without its offset commit. Without such a case, idempotence plus the outbox is enough.
Q40 · Scenario. "After a deploy, a producer starts failing with RecordTooLargeException on some messages. What are the limits, and how do you fix it?"
Reveal answer
Strong answer Several limits must agree: the producer's max.request.size (default 1 MB), the broker's message.max.bytes (about 1 MB default), the topic's max.message.bytes, and the consumer's max.partition.fetch.bytes and fetch.max.bytes. A record bigger than the smallest limit fails.
The first question is whether the large records are legitimate. A new field that embeds an image or a huge list is the usual cause. Raising limits everywhere works but makes batches and memory heavier and can slow the cluster.
The better fix for large payloads is the claim check pattern: store the big file in object storage and send a small record with its address. Kafka is built for many small records, not for megabytes each.
If a limit raise is needed, change it in a safe order: broker or topic first, then the consumers, then the producer, so no layer rejects what another now accepts.
Picture it The limits as a chain, and the claim-check fix.
The setup: A 3 MB payload arrives at a producer with default limits.
# illustrative output
producer max.request.size 1,048,576 ❌ 3 MB record rejected here first
broker message.max.bytes 1,048,588
topic max.message.bytes (inherits broker)
consumer max.partition.fetch.bytes 1,048,576 (a bigger record would stall this consumer unless raised)Make the invisible visible: Claim check in code.
String url = objectStore.put("reports/" + id + ".pdf", pdfBytes); // big data goes elsewhere
producer.send(new ProducerRecord<>("reports", id, new ReportReady(id, url, pdfBytes.length)));
// consumer reads the small event, then downloads from url when it needs the fileWhy: Large records slow replication, fill page cache and stall consumers. Passing a pointer keeps the log lean.
Land it I would first ask whether the payload belongs in Kafka, and use a claim check for anything over about 1 MB instead of raising limits across the stack.
- "What if a consumer cannot fetch a record larger than its limit?"
-
Modern consumers still return at least one record, even if it is bigger than the fetch limits, so a single large record does not make a consumer stall forever. The fetch settings (
max.partition.fetch.bytesandfetch.max.bytes) act as soft limits for the first batch. That is how it works in current versions, and I would check the documentation for the version in use.But I do not rely on that. If a limit is smaller than a record, fetches return one record at a time, and throughput suffers, since each fetch handles a single record and the broker does more work. Memory use also becomes harder to predict.
Very old consumers could get stuck on such a record, so I align the numbers anyway.
My rule is to align the numbers: the consumer's fetch size should be at least as large as the biggest message the broker accepts. A consumer must be able to read everything the producer can send.
- "What is the impact of raising message.max.bytes?"
-
A higher
message.max.bytesmakes everything around a record heavier. Batches in producer memory are larger, replication moves bigger chunks (followers needreplica.fetch.max.bytesto match), and consumers need a larger fetch buffer for each partition they read.The memory arithmetic is what surprises people, since it multiplies by partitions.
consumer memoryruns offline# illustrative numbers max.partition.fetch.bytes 10 MB x 100 assigned partitions = up to 1 GB buffered (fetch.max.bytes caps one response, but plan for the worst case)Large records also hurt latency for others. A 10 MB record takes longer to write, replicate and fetch, and it holds up the partition's smaller records behind it.
So I raise the limit only with a measured need, check each of the memory numbers, and still prefer the claim check for anything beyond a megabyte or so.
- "How do I find which records are large?"
-
I add a measurement in the producer, before the send. After serialization, I know the exact size in bytes, so I log a warning with the key and the topic when it passes a threshold, say 500 KB, and I feed the size into a histogram metric. Then I can see the shape of the traffic, not only the failures.
The exception message itself also contains the size and the limit, for example that the request included a message of 2,500,000 bytes while the limit is 1,048,576. That identifies the failing record, and the key shows which customer or code path made it.
From the histogram I take the 99th and 99.9th percentile record size, and these numbers drive the rest of the sizing: the batch size, the buffer memory, the consumer fetch size and the broker limits.
A common find is that 99.9 percent of records are under 5 KB and a handful of them are 3 MB because one field carries an embedded document. That tells me to fix the producer, not to widen every limit.
- "Does compression change the limit?"
-
It depends on which check you mean. The broker's check, against
message.max.bytesor the topic'smax.message.bytes, applies to the record batch as stored, so the compressed size counts. The producer's check againstmax.request.sizeuses the size before compression as an estimate in most versions. That is how I remember it, and I would confirm it on the client version in use.So compression can help with the broker's limit and may not help with the client's. A 3 MB JSON document that compresses to 400 KB can pass the broker and still be rejected by the producer when
max.request.sizeis 1 MB.I do not trust my memory of such details when a deploy is on the line. I test with a real payload of the largest realistic size, with the real compression setting, and watch the actual error. Then I choose between raising the limits in the safe order and using the claim check pattern.
09 · DrillConsumers, Groups & Delivery — Q41–Q80
The second forty questions move to the read side: how a consumer finds its place, how a group splits partitions, what a rebalance really does, and what "at-least-once" and "exactly-once" mean in practice. These are the questions where scenario answers separate people who have run Kafka from people who have read about it. Say your answer first, then reveal.
These questions test whether you can explain where a consumer's position lives, what commits really mean, and how to read lag.
Q41. "Explain the consumer poll loop and what a consumer group is."
Reveal answer
Strong answer A consumer calls poll() in a loop. Each call returns a batch of records from its assigned partitions, and also keeps the consumer alive: heartbeats go out on a background thread, but poll() itself must be called regularly or the group decides the consumer is stuck.
A consumer group is a set of consumers sharing a group.id. Kafka splits the topic's partitions among them so that each partition is read by exactly one member of the group at a time. Different groups are independent and each gets every record.
The group has a coordinator, which is one of the brokers. It tracks membership, assigns partitions and stores committed offsets.
So a group gives you two things: parallelism (partitions split across members) and fail-over (if a member dies, its partitions go to the others).
Picture it Two groups reading one topic with 4 partitions.
The setup: Topic orders with partitions 0 to 3. Group billing has two members, group analytics has one.
# illustrative output
group billing: member B1 -> partitions 0,1 member B2 -> partitions 2,3
group analytics: member A1 -> partitions 0,1,2,3
# each group sees every record; inside one group each partition has exactly one readerMake the invisible visible: The loop in code.
try (KafkaConsumer<String, String> c = new KafkaConsumer<>(props)) {
c.subscribe(List.of("orders"));
while (running) {
ConsumerRecords<String, String> batch = c.poll(Duration.ofMillis(500));
for (ConsumerRecord<String, String> r : batch) {
handle(r);
}
c.commitSync(); // commit AFTER processing (Q45)
}
}Why: The loop is the contract: you must call poll often, process what it returns, and commit what you finished.
Land it I describe a group as a set of consumers that split partitions between them, with the poll loop as both the data path and the proof of life.
- "What happens if poll() is not called for a long time?"
-
After
max.poll.interval.ms(default 5 minutes) passes with no call topoll(), the consumer is declared failed. It is removed from the group, and its partitions go to the other members. The background heartbeat thread may still be sending heartbeats, so the group looked alive, but the poll limit is a separate check that catches code stuck in processing.The consumer finds out when it next calls
poll()or tries to commit. Its commit then fails with aCommitFailedException, because it no longer owns those partitions. Meanwhile the new owner has started from the last committed offset, so the records the slow consumer was working on are handled twice.This is the most common cause of surprise rebalances (Q53). A slow database call or a batch that is too big is usually the reason. The fixes are to lower
max.poll.records(default 500), speed up the handler, or raise the limit when slow work is real, in that order. - "Is the consumer thread-safe?"
-
No.
KafkaConsumeris not thread-safe, and it checks for concurrent use and throws aConcurrentModificationExceptionif two threads call it at once. The single exception iswakeup(), which may be called from another thread to make a blockingpoll()throw, and that is the standard way to stop a consumer cleanly.To process in parallel, keep one thread that owns the consumer, for polling and committing. Hand the records to a pool of workers and wait for them to finish before committing, or track which offsets are done (Q77). Letting workers call the consumer breaks the rule, and it gets the commit order wrong.
The alternative is one consumer per thread, each in the same group, with their own connections. That is simple and safe, and each thread takes some partitions. It costs more memory and connections, but it keeps order per partition without extra code. Spring's
concurrencysetting on a listener container does exactly this. - "How does a consumer know where to start?"
-
It looks for a committed offset for each assigned partition, stored for this group. If one exists, it starts reading at that offset, which is the next record to process. This is why a restarted consumer carries on where it stopped.
If no committed offset exists, for example for a new group, it uses
auto.offset.reset.latest(the default) starts at the end, so only new records arrive.earlieststarts at the oldest record the log still holds.nonethrows an exception, which forces a decision.The position can be overridden in code.
seek()moves the consumer to any offset, and the tools can reset a stopped group's offsets from the command line. Q46 and Q47 go through the consequences, including the case where a committed offset exists but the data it points to has been deleted by retention, so the reset policy applies again. - "What does the coordinator do?"
-
The coordinator is one broker that manages one group. It keeps the member list, receives heartbeats and notices when a member is gone, starts and runs rebalances, and records the committed offsets. Without it, there would be nobody to decide who reads which partition.
Which broker is the coordinator is not chosen by an election. Kafka hashes the group id and takes it modulo the number of partitions of the internal topic
__consumer_offsets(50 by default). The broker that leads that partition is the group's coordinator. Consumers ask any broker, "who is my coordinator?", and then talk to that one.A consequence is that a group's offsets and its coordinator live together, so offset commits go straight to the right partition. If that broker fails, a new leader is elected for the partition, and the group's coordinator moves with it. The group then goes through a rebalance as members reconnect to the new coordinator.
Q42. "What limits the parallelism of a consumer group?"
Reveal answer
Strong answer The number of partitions. One partition is read by one member of a group at a time, so a group of 12 consumers on a topic with 8 partitions has 4 idle members.
That makes the partition count the ceiling on how many consumers can work, and it is why partition count is chosen with a view to consumer scaling (Q20).
Adding consumers beyond partitions only helps as hot spares, which is sometimes the point: standby members take over quickly when one fails.
To scale beyond partitions you either raise the count (with the ordering cost in Q22), speed up each consumer, or use share groups (Q71).
Picture it More consumers than partitions.
The setup: Topic with 4 partitions. A group scales from 4 to 6 consumers.
# illustrative output
4 consumers: C1->p0 C2->p1 C3->p2 C4->p3
6 consumers: C1->p0 C2->p1 C3->p2 C4->p3 C5->(none) C6->(none) <- idle, still heartbeatingMake the invisible visible: Why throughput does not rise.
# illustrative numbers, each consumer handles 5 MB/s
4 consumers x 5 = 20 MB/s
6 consumers x 5 = still 20 MB/s (only 4 partitions can be read in parallel)Why: Kafka assigns whole partitions, never parts of one, which keeps per-partition order simple.
Land it I say the partition count is the ceiling on useful consumers per group, so I plan partitions around the parallelism I want.
- "Is an idle consumer useless?"
-
It is useful as a hot standby, but it adds nothing to throughput. If one of the active members dies, the group's coordinator hands that member's partitions to an idle one almost at once. Compared with starting a new process, which needs time to boot, connect and warm up, the recovery can be much faster.
The cost is real, though. An idle consumer holds a connection, memory and a pod's resources, and it produces no work. In a cluster with a hundred such idle instances across many services, the waste adds up.
I decide by the failure budget. For a service where a minute of lag after a crash is fine, I run exactly as many consumers as partitions, and let the orchestrator replace a failed one. For a service where the lag must stay small, I keep one or two spares. I also note that with a rebalance protocol like the newer one (KIP-848, group.protocol=consumer), a takeover costs less than it used to, which makes spares less important.
- "If I have 3 partitions and 2 consumers, what is the split?"
-
One consumer gets two partitions and the other gets one. Partitions cannot be divided, so the split is 2 and 1, and there is no even way to share three equal chunks between two workers.
The consequence is that the group is only as fast as its busiest member. If each partition brings 10,000 records per second, one consumer must handle 20,000, and it will fall behind long before the one with 10,000 does. The lag shows up on its two partitions only, which is a hint when you look at per-partition lag.
So I choose consumer counts that divide the partition count evenly where I can: 12 partitions with 2, 3, 4 or 6 consumers gives equal shares, but 5 consumers gives a 3-3-2-2-2 split.
It is also a reason for partition counts like 12, 24 or 48, which have many divisors. This is one more detail to settle when the partition count is chosen (Q20), because changing it later is expensive.
- "Can two groups share a partition?"
-
Yes. Groups are independent of each other. Each group has its own members, its own committed offsets and its own coordinator state. Two groups reading the same topic each receive every record, without affecting one another.
That is how one topic can feed many consumers. For example, the "orders" topic can have a billing group, a search-indexing group and an analytics group. Each reads the whole topic at its own speed. If analytics falls behind, billing is not affected, because Kafka keeps the log and only the offsets differ.
Only inside one group is a partition read by a single member. The reverse is also useful: if two services accidentally use the same
group.id, they share the partitions, and each sees only part of the data. That is a classic configuration bug.So the rule I give: a different service means a different group id, and the same service across its pods shares one.
- "How do I increase parallelism without more partitions?"
-
I speed up each consumer. The most common win is batching the slow part: instead of one database insert per record, collect the 500 records returned by a poll and write them in one batch statement. This often gives a ten times gain for the same hardware.
The second option is a bounded worker pool inside each consumer, where records are handed to threads by key. All records with the same key go to the same thread, so per-key order is kept while different keys run in parallel (Q77). The consumer thread still polls and commits only after the workers finish the batch.
The third is moving slow external calls to be asynchronous, with a limit on how many are in flight, so one slow request does not hold up everything.
If the work is really a queue of independent jobs and order does not matter, share groups (Q71) let several consumers read from one partition. They are newer, so I check the maturity for my version before relying on them. Otherwise, adding partitions is the last resort, because it breaks key ordering.
Q43. "Where are offsets stored, and what does a commit actually write?"
Reveal answer
Strong answer Committed offsets are stored in an internal compacted topic called __consumer_offsets. A commit is a normal produce to that topic: key is (group, topic, partition), value is the offset (and metadata).
The committed offset means "the next record to read": if the last processed record was offset 41, the commit value is 42.
Because the topic is compacted, only the latest commit per key is kept in the long run. On restart or rebalance, the new owner reads that value and resumes there.
Committing is separate from processing. Kafka does not know whether you processed anything; it only knows what you told it.
Picture it The commit record and the "+1" rule.
The setup: Group billing processed offsets 38 to 41 of orders-2.
# illustrative output
__consumer_offsets
key = (billing, orders, 2)
value = 42 <- next offset to read, not the last one read
restart: consumer asks coordinator -> gets 42 -> poll() starts at offset 42Make the invisible visible: Look at it with the tool.
kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group billing
# illustrative output
GROUP TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG
billing orders 2 42 47 5Why: The commit is a bookmark in a shared notebook. If you write it before you finish reading, a crash leaves the bookmark ahead of the work.
Land it I say commits live in __consumer_offsets, they hold the next offset to read, and they only mean what the application makes them mean.
- "What if I commit offset 42 but processed only up to 40?"
-
Then on restart the consumer resumes at 42, and record 41 is never processed. From the application's point of view that is data loss, and Kafka cannot warn you: it only knows the offset you committed and has no idea what your code did.
A short example makes the numbers clear. The poll returns records 40, 41 and 42. If the code processes 40, then commits "next = 42" by mistake (it should be 41 if 40 was the last done), a crash leaves 41 skipped.
The same thing happens through the usual off-by-one error: committing
record.offset()instead ofrecord.offset() + 1causes the opposite problem, one record repeated. Spring and the plain client's no-argumentcommitSync()do the right arithmetic for you, which is a reason to prefer them over hand-made offsets.This is the "commit before processing" mistake from Q45 in another form. The rule is that you may only commit offsets of records you have finished.
- "Can I store offsets outside Kafka?"
-
Yes. Some designs store the offset in their own database, in the same transaction as the result of processing, and on startup they
seek()each assigned partition to the stored value. Kafka's own committed offset is then ignored, or kept just for monitoring.The benefit is a real exactly-once effect into that database. A crash leaves either both the result and the offset, or neither, so there is nothing to repeat or skip.
The price is more code. The consumer needs a rebalance listener, since after each assignment it must read the stored offset and seek to it. It also loses some tools: the groups command and the usual lag monitors read Kafka's committed offsets, so lag dashboards show wrong numbers unless you also commit them to Kafka for display.
I use this when the sink is a relational database and duplicates are expensive. For most pipelines, an idempotent write and Kafka's own offsets are simpler, so that is my default.
- "How long are committed offsets kept?"
-
For an active group, offsets are kept as long as the group keeps committing: the group's records are compacted, but never deleted. For an empty group, one with no members, the broker deletes the offsets after
offsets.retention.minutes, which defaults to 7 days since Kafka 2.0. The clock starts when the group becomes empty.After that, the group has no committed offset, and on the next start it follows
auto.offset.reset. Withlatest, it silently skips everything produced meanwhile. Withearliest, it reprocesses the whole log.So a consumer paused for 10 days, for example during an incident or a long holiday freeze, may find its position gone. I work around it in two ways: I note the offsets before a planned long pause, and I raise the retention for groups that are known to stop for long periods. I also alert on groups that go quiet, so I notice before the seven days are up.
- "What does __consumer_offsets cost?"
-
It is a normal topic with 50 partitions by default, so it has a real cost in write load, and the cost grows with the commit rate. Each commit is a produce request to the coordinator's partition, and it is also replicated, like any other write.
commit rateruns offline# illustrative numbers 50,000 records/s, commit per record = 50,000 commits/s heavy commit once per poll batch of 500 = 100 commits/s comfortableBecause the topic is compacted, only the latest commit per group, topic and partition is kept in the end, so disk use stays modest. But the cleaner has to work through a lot of obsolete entries if the commit rate is high.
So I commit per batch, or once every second or so, and not per record. The cost of committing less often is a bigger repeat window after a crash, which is a few hundred records and is harmless when processing is idempotent.
Q44 · Scenario. "A team uses enable.auto.commit=true. After a crash they find some orders were never processed. Explain."
Reveal answer
Strong answer With auto commit, the consumer commits the offsets of the records returned by the last poll() at the start of the next poll(), once auto.commit.interval.ms (default 5 s) has passed. It does not wait for the code to finish processing.
If the loop gets records 100 to 199, starts processing, and a later poll() commits 200 before the handler finished record 150, a crash at that moment loses 150 to 199: the group resumes at 200.
The mirror failure can also happen: processed records not yet committed are reprocessed after a crash, which is a duplicate. Auto commit is the "at most once or at least once, by timing luck" setting.
The fix is manual commit after processing, and an idempotent handler for the duplicates that remain.
Picture it The timing, with a crash in the middle.
The setup: Batch of records 100 to 199 returned by poll. Auto commit interval 5 s.
# illustrative output
t=0s poll() returns 100..199
t=0s handler starts, slow database, 1 record per 100 ms
t=5s next poll() call happens only after the loop ends, so commit of 200 happens at the START of next poll
t=9s (if the handler hands work to a thread pool, poll runs again at t=0.1s and commits 200 early)
t=9s crash: handler had done 100..139 -> group resumes at 200 ❌ 140..199 lostMake the invisible visible: Manual commit after processing.
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
...
for (ConsumerRecord<String, String> r : batch) {
handle(r); // finish the work first
}
consumer.commitSync(); // ✅ then record the progressWhy: Auto commit ties the commit to time and poll calls, not to your work. Manual commit ties it to your work.
Land it I would turn auto commit off for anything that matters and commit after processing, accepting duplicates and handling them with idempotent code.
- "Is auto commit ever fine?"
-
Yes, in cases where losing or repeating a few records is acceptable and where processing is synchronous inside the loop. Examples are metrics collection, a cache refresher that tolerates gaps.
With synchronous processing, auto commit behaves as at-least-once. The commit goes out at the start of the next
poll(), and by then the loop has finished the previous batch. A crash means a repeat of up to one batch, and not a loss.The trap is combining auto commit with an asynchronous handoff. If the loop passes records to a thread pool and calls
poll()again at once, the commit can cover records that the pool has not finished. A crash then loses them, and the loss is silent because Kafka believes they were done.So my rule: auto commit only when the handler runs in the loop thread. Once I add threads, queues or async calls, I switch to manual commits placed after the work is done.
- "Why does synchronous processing make auto commit at-least-once?"
-
Because the commit and the next poll happen on the same thread, in sequence. The consumer only commits at the start of a
poll()call, and it can only reach the next poll after the code has finished with the previous batch. Everything returned before is already processed when its offset is committed.Here is a timeline with numbers. Poll returns records 100 to 199. The loop handles them one at a time. At the next poll, 5 seconds later, the commit says "next = 200". If the process crashes while handling record 150, no commit has been made for that batch yet, so the restart re-reads from 100, and records 100 to 149 repeat. That is a duplicate, not a loss.
The loss case needs decoupling: processing continues after the poll returns. A background thread handling record 150 while the loop polls again and commits 200 is exactly the unsafe pattern.
So the important property is that the same thread both processes and polls.
- "What does Spring Kafka do by default?"
-
Spring sets
enable.auto.commit=falseon its consumers and takes over the commits itself, according to the container'sAckMode. The default isBATCH: after your listener has handled all the records from one poll, Spring commits their offsets. If the listener throws an error that is not handled, the offsets are not committed for that batch, and the error handler decides what happens next.The other modes give finer control.
RECORDcommits after each record, which is safe but slow in volume.MANUALandMANUAL_IMMEDIATElet your code callAcknowledgment.acknowledge()when it has finished, andTIMEandCOUNTcommit periodically.So the defaults are the safe at-least-once style, and the code works correctly unless someone overrides them. I check that nobody has set
enable.auto.commit=truein the Spring properties, since that fights with the container and brings back the old problem. - "How do I choose between commitSync and commitAsync?"
-
commitSync()blocks until the broker confirms, and it retries on temporary errors. So the result is certain, and the cost is the wait on every commit, usually a few milliseconds.commitAsync()returns at once and reports the result to a callback. It does not retry, because a retried older commit could overwrite a newer one.In a busy loop the difference matters. With 100 polls per second, a sync commit of 5 ms adds half a second of waiting every second. Async hides that wait.
A common pattern uses both:
commitAsync()inside the loop for speed, and onecommitSync()when shutting down or when partitions are revoked, because the final commit must not be lost. If an async commit fails, the next one carries a later offset anyway, so a single failure is harmless. Many teams usecommitSync()per batch and never need more, since a batch commit is already cheap.
Q45. "Why does the order "process, then commit" matter? Show what each order gives you."
Reveal answer
Strong answer If you commit before processing, a crash after the commit and before finishing loses the record: at-most-once. If you process, then commit, a crash after processing and before the commit repeats the record: at-least-once.
Kafka has no way to make "do work" and "commit offset" one atomic step on its own, unless the work output is also in Kafka (transactions, Q62) or in the same database as the offset.
So for most systems, process then commit is right, and the duplicates it can create are handled by an idempotent consumer (Q65).
This is the single most important consumer decision, because it decides the failure mode: loss or repetition.
Picture it Two crash points, two outcomes.
The setup: A consumer reads offset 7, charges a payment, and commits.
# illustrative output
poll 7 -> commit 8 -> crash -> (payment never charged)
restart: resumes at 8 -> order 7 is never processed ❌ lost (at-most-once)Make the invisible visible: The other order.
# illustrative output
poll 7 -> charge payment -> crash before commit
restart: resumes at 7 -> charge runs again ⚠ duplicate (at-least-once)
fix: use payment idempotency key = order id, so the second charge is ignored ✅Why: A lost payment is silent and unrecoverable; a repeated payment attempt can be made harmless with a key. So I pick the failure I can repair.
Land it I process first, commit second, and I make the processing safe to repeat.
- "Is there any way to be exactly-once with a database sink?"
-
Yes, when the sink is a relational database: write the result and the offset in one database transaction, and on startup
seek()to the stored offset. A crash then leaves both or neither, so there is nothing to repeat and nothing to skip.offset in the same transactionruns offline// illustrative sketch @Transactional void handle(ConsumerRecord<String, String> r) { ordersRepo.save(toOrder(r.value())); offsetsRepo.upsert(r.topic(), r.partition(), r.offset() + 1); // same transaction } // on partition assignment: consumer.seek(tp, offsetsRepo.get(tp))Notice the
+ 1: the stored value is the next record to read. The seek on assignment must run from a rebalance listener, because partitions move between consumers.The cost is that Kafka's own committed offsets no longer describe progress, so lag dashboards need extra care. I use this for a database sink where duplicates are expensive, and use idempotent upserts elsewhere.
- "What about processing that calls an external API?"
-
The external call cannot join your database transaction, so the order "process, then commit" leaves a window: the call is made, the process crashes, and on restart the call is made again. The way out is to make the repeated call harmless.
The first choice is the API's own idempotency key. Many payment, email and shipping APIs accept a key, and a second request with the same key returns the first result without doing it again. I use something stable and tied to the business event, such as the order id plus the action, and not a random value generated on each attempt.
If the API has no such key, I keep a local record. Before calling, I insert a row "order 42 call started" in a table with a unique key, and I mark it complete after the call. A repeat finds the row and either skips it or checks the API's state before acting.
This is the same idempotent consumer table described in Q65, applied to a call that has side effects outside my systems.
- "How often should I commit?"
-
After each batch returned by a poll is the usual answer. A batch is a natural unit: the work is done, one commit covers it, and the cost is one request per batch, not per record.
The trade-off has two sides. Committing more often, say after each record, adds load on the coordinator and slows the loop, and it shrinks the number of records repeated after a crash. Committing less often, say every 30 seconds, is cheaper, but a crash repeats everything since the last commit.
The repeat window is simply the number of records between commits. With 500 records per batch and a commit per batch, a crash repeats at most 500 records. If processing is idempotent, that is harmless. If each repeat costs money, I either shrink the batch or move to a design where the offset is stored with the result.
I rarely tune this finely. I pick per batch, measure the commit rate, and only revisit if the coordinator shows load or the repeat window becomes a problem.
- "What happens on a rebalance between process and commit?"
-
A rebalance can take the partition away between the processing and the commit, and then the new owner starts from the old committed offset. Records that the first consumer had already processed are processed again. The first consumer's late commit then fails, since it no longer owns the partition.
A rebalance listener narrows the gap. In
onPartitionsRevoked, the consumer commits the offsets of everything it has finished, before it gives the partitions up. In the classic protocol this callback runs before the partitions move, so the commit usually succeeds. With cooperative rebalancing, only the revoked partitions are affected, which helps.The window cannot be eliminated entirely. A consumer that is kicked out for being too slow cannot commit at all, and a crash leaves no time for callbacks. So repeats are always possible after a rebalance, and the real protection is idempotent processing. I treat the listener as an optimisation that reduces the number of duplicates, not as a guarantee.
Q46. "What does auto.offset.reset do, and when is the wrong value dangerous?"
Reveal answer
Strong answer It decides where a consumer starts when there is no valid committed offset: a new group, or an offset that has been deleted by retention. latest starts at the end (new records only), earliest starts at the beginning of the log, none throws an error.
The default is latest. For a new consumer group with latest, anything produced before it first connects is skipped, which surprises people who expect to "get everything".
earliest on a new group reprocesses the whole retained history, which could be days of data and might flood a downstream system or send old emails again.
For critical consumers I prefer none or earliest explicitly, so a lost offset becomes a deliberate decision, not a silent jump.
Picture it A new group and a lost offset.
The setup: Topic with offsets 0 to 9,999 retained. A new group reports starts.
# illustrative output
auto.offset.reset=latest -> starts at 10,000 : sees only future records (history skipped)
auto.offset.reset=earliest -> starts at 0 : reads 10,000 old records (history replayed)
auto.offset.reset=none -> throws NoOffsetForPartitionException (you decide)Make the invisible visible: The lost-offset case.
# illustrative output
committed offset = 500, but retention deleted everything below 2,000
earliest -> jumps to 2,000 (log start): records 500..1,999 are gone, silently
latest -> jumps to the end: even more skipped ❌
none -> error raised, alert, a person choosesWhy: The setting is a policy for "I don't know where I was". The wrong policy turns a data gap into silence.
Land it I set auto.offset.reset on purpose for each consumer, and for critical flows I would rather fail loudly than silently skip.
- "Does it apply every time the consumer starts?"
-
No. It is used only when the consumer has nothing valid to resume from: there is no committed offset for that partition, or the committed offset is out of range, for example because retention deleted the data it pointed to. When a valid committed offset exists, the setting is ignored.
This surprises people. A developer changes
auto.offset.resetfromlatesttoearliest, restarts the service to replay old data, and nothing happens. The group already has committed offsets, so the consumer resumes where it was, and the new value is never consulted.A second subtlety is the out-of-range case. If a group was stopped for longer than the topic's retention, its committed offset may point to deleted records. The consumer then falls back to the reset policy for that partition, silently with
latestorearliest, or with an error undernone.So I remember it as "what to do when there is no usable bookmark", not as "where to start every time".
- "How do I make an existing group read from the start?"
-
Stop the group, then reset its offsets from outside, or call
seekin the code. Changingauto.offset.resetdoes nothing for a group that already has commits. The group's tool needs all members stopped, because it refuses to change a group that is active.reset to earliestruns offline# illustrative kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group reports --topic orders \ --reset-offsets --to-earliest --dry-run # check the plan, then repeat with --executeI run it first with
--dry-runto see the new positions, and then with--execute. Other options exist:--to-datetime,--shift-byand--to-offset, which cover replaying from a point in time.Before I do it, I ask what replay will do downstream. It may resend emails or charge cards twice if the consumer is not idempotent, so I write that in the change request. The other route is a fresh group id with
earliest, which leaves the old group untouched and is easy to roll back. - "What is the risk of earliest on a big topic?"
-
A new group floods downstream systems with history. The size of the flood is the retained log, and the time to chew through it is simple arithmetic.
replay timeruns offline# illustrative numbers 500,000,000 records / 20,000 per second = 25,000 s = about 6.9 hours at 5x the normal rate the database also sees 5x the writes for that timeThe consumer will run flat out, so all of its dependencies feel it: the database gets a write burst, caches churn, and an API with rate limits may start refusing calls. If the handler sends emails or notifications, customers get them for old events.
There is also the lag alert. A new group starts with a lag of 500 million, and everyone's dashboards show a crisis for hours.
So for a new consumer on a big topic, I decide on purpose. I may set a rate limit, start from a timestamp instead of the beginning (
offsetsForTimes), or process the history in a separate one-off job with its own capacity. - "What is a safer way to bootstrap a new consumer?"
-
Take a snapshot from the source system, load it, and then start the consumer from a known position that matches the snapshot. This avoids the two bad cases: missing data (latest) and flooding (earliest). The order matters, because the position must be captured before the snapshot is read:
- Note the point: record the current end offsets, or a timestamp, for each partition just before taking the snapshot.
- Load the snapshot: read the full state from the source database into the new service's store.
- Start from the point: set the consumer's starting offsets with
seek(), oroffsetsForTimes()for the timestamp, and begin the normal stream. - Check the overlap: a few records may be in both the snapshot and the stream, so the handler must be idempotent.
With this, there are no gaps and the only duplicates are the overlap. It takes more steps than just
earliest, and for large topics it saves hours.
Q47 · Scenario. "A deploy renames the consumer group.id by mistake, from billing to billing-v2. What happens?"
Reveal answer
Strong answer The new group has no committed offsets, so it applies auto.offset.reset. With latest it skips everything that arrived while the deploy happened and before it connected: data loss. With earliest it replays all retained history: a flood of duplicates.
The old group billing stays in Kafka with its offsets and, if its consumers are stopped, it simply holds a position and shows growing lag.
The repair: stop the new group, compute where billing stopped, and reset billing-v2 to that point; or revert the config and restart billing, which resumes exactly where it left.
Prevention: treat group.id as an identity, review it in code review, and alert on lag for the expected group names.
Picture it Both groups side by side, and the repair command.
The setup: Topic orders, end offset 90,000. billing committed 89,500.
# illustrative output
group committed end lag
billing 89,500 90,000 500 (stopped)
billing-v2 (none) 90,000 - latest: starts at 90,000 -> 500 records skipped ❌Make the invisible visible: Copy the old position to the new group.
kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group billing-v2 --topic orders \
--reset-offsets --to-offset 89500 --execute
# newer tools can also copy: --from-file with a CSV of topic,partition,offsetWhy: Offsets belong to a group id. A different id is a different identity with a blank notebook.
Land it I would revert or copy the committed offsets, and I would add an alert on lag per expected group so a silent rename shows up within minutes.
- "Can I rename a group safely on purpose?"
-
Yes, as a planned migration, and the order of steps protects you. First stop the old group so it cannot move its offsets any more. Then read its committed offsets for each partition. Then write those same offsets into the new group id, with the reset tool, while the new group has no members. Then start the new group.
The new group begins exactly where the old one stopped, so there is no gap and no replay. I check one or two partitions by hand: the new group's current offset should equal the old group's.
Do it per partition, because offsets differ for each partition. A single "set everything to N" would be wrong. The tool's export and import options help here: a dry run prints the plan, and the output can be saved as a file and applied to the new group.
I also keep the old group's offsets in place for a while, since they are the rollback. If the new group has trouble in the first hour, I can go back to the old name and lose nothing.
- "How do I detect a group that is gone silent?"
-
The strongest signal is that a group that should exist has no members, so I alert on member count, as well as on lag. Lag alone can miss a disappeared group: if the old group stops entirely, the tools may still show its last offsets, and lag grows only as new records arrive. It does rise, but in a quiet period, or on a low-volume topic, it can take a long time to cross a threshold.
I keep a list of expected group names and check each against the broker's list. The check says "billing: expected, not found" or "billing: found, 0 members". That catches a rename within minutes.
I also alert on a new, unexpected group id, which would be billing-v2 appearing from nowhere. Unknown groups often point to a typo, a test pointed at production, or a forgotten consumer that is still running and holding partitions it should not.
Include an alert for the member count dropping to zero for more than a couple of minutes.
- "How does the tool show an empty group?"
-
The group tool can show the state of a group, and an empty group shows
Emptywith zero members. The offsets are still listed, so you can see where it stopped, and the lag against the current log end.stateruns offline# illustrative kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group billing --state GROUP COORDINATOR STATE #MEMBERS billing broker-2 Empty 0The other common states are
Stable,PreparingRebalance,CompletingRebalanceandDead. A group that flips between Stable and the rebalance states repeatedly is the one with a flapping member.In the rename scenario, the check shows billing as Empty and billing-v2 as Stable, with different offsets. That one view tells me which group is doing the work and which is parked, and I can compare their offsets side by side, which is the first step of the repair.
- "How long are the old group's offsets kept?"
-
After a group becomes empty, its offsets expire after
offsets.retention.minutes, which is 7 days by default. When that time passes, the broker removes the group's committed offsets, and the old group's position is gone. The group, if restarted, would useauto.offset.reset.So the repair has a clock on it. If a rename happens on Friday evening and nobody notices until the following Saturday, the old group's offsets have expired, and "revert the config and resume exactly where it left" is no longer possible. The only choice left is to decide a new starting point, possibly by timestamp.
My habit is to write down the offsets before changing anything. A saved copy of the
--describeoutput, or an offsets export, takes seconds and turns a stressful guess into a precise repair.For groups that must survive a long pause, I raise
offsets.retention.minuteson the broker (check the current docs for its scope and defaults).
Q48 · Design. "Design the commit strategy for a consumer that writes each batch of records to a relational database."
Reveal answer
Strong answer I process a whole poll batch inside one database transaction, and commit the Kafka offsets only after the database commit succeeds. If the database commit fails, I do not commit offsets, and the batch is re-read.
Then duplicates after a crash are possible (database committed, crash before the offset commit), so writes must be idempotent: an upsert by record key, or a unique constraint on (topic, partition, offset) or a business id.
For stronger behaviour I store the offsets in the database in the same transaction and seek to them on assignment. That removes duplicates entirely for that sink.
Batch size matters: a batch of 500 records per transaction is a good start; a huge batch risks long transactions and exceeding max.poll.interval.ms.
Picture it One iteration of the loop, with the failure points marked.
The setup: Batch of 500 records; the target table orders has a unique key order_id.
ConsumerRecords<String, OrderEvent> batch = consumer.poll(Duration.ofMillis(500));
if (batch.isEmpty()) continue;
tx.execute(status -> {
for (ConsumerRecord<String, OrderEvent> r : batch) {
jdbc.update("insert into orders(order_id, status) values (?,?) " +
"on conflict (order_id) do update set status = excluded.status",
r.value().orderId(), r.value().status()); // idempotent upsert
}
return null;
});
consumer.commitSync(); // after the database commitMake the invisible visible: Crash points and what happens.
# illustrative output
crash before DB commit -> nothing written, batch re-read ✅
crash after DB commit, before offset commit -> batch re-read, upserts repeat harmlessly ✅
DB down -> exception, no offset commit, retry with backoff ✅Why: The offset commit is the last step, and the writes are safe to repeat. Together they give at-least-once delivery with exactly-once effect in the table.
Land it I commit offsets after the database transaction and make the writes idempotent, so a repeat is harmless.
- "What if the batch is large and the transaction is slow?"
-
I first make the transaction smaller, in one of two ways. The first is to split the poll's records into groups of, say, 100, run each in its own transaction, and commit offsets after each. The second is to lower
max.poll.recordsso a poll returns fewer. Either way, a failure repeats fewer records.The time budget is the constraint. Processing time for one poll must stay far below
max.poll.interval.ms, or the group removes the consumer and rebalances. The budget is records per poll times time per record.time budgetruns offline# illustrative numbers, max.poll.interval.ms = 300 s max.poll.records 500 x 20 ms per record = 10 s per batch fine max.poll.records 500 x 800 ms per record = 400 s per batch over the limit, rebalanceA long transaction also holds locks and row versions in the database, which hurts other users of the tables. So smaller is better for the database as well. I pick the batch size by measuring, and aim for transactions of well under a second to a few seconds.
- "Would you use commitAsync here?"
-
Rarely. A per-batch
commitSync()costs a few milliseconds, and at batch rates (a few polls per second) that is nothing. It is simple and its result is certain: when the call returns, the offsets are committed. This matters because the commit is the last step of the database write plus offset protocol, and I want to know if it failed.commitAsync()brings questions that need answers: what if commit 7 fails and commit 8 succeeds, and what if the callback arrives after a rebalance? For the small gain at this rate, it is not worth the reasoning.If throughput really demands it, for instance a very fast handler polling thousands of times a second, I use async commits inside the loop and one sync commit at shutdown and on revocation. That keeps the loop fast and guarantees the final position.
I would measure the commit time first. In many systems it is under 5 ms and not a bottleneck.
- "What if one record in the batch is poison?"
-
A poison record, one that always fails, makes the whole transaction fail, the batch is not committed, the next poll returns the same records, and it fails again, forever. One bad row then blocks the partition, and lag grows behind it. There are three ways out, and I often combine them:
- Validate first: check the record's shape and rules before opening the transaction, so a bad record never reaches the database.
- Dead-letter topic: catch the failure for that record, publish it with the error to a topic such as
orders.DLT(Q67), and carry on with the rest. - Fall back to singles: if the batch fails, retry the same records one at a time, each in its own transaction, so only the bad one fails and is parked.
Whatever I choose, I make sure a parked record is visible, with an alert, because a dead-letter topic nobody watches is a silent loss. Never let one bad record block a partition.
- "How does Spring Kafka express this?"
-
With a batch listener, Spring hands the listener a list of records from each poll. The method is annotated as transactional, or runs under a transaction manager, so the whole list is processed in one database transaction. Offsets are acknowledged after the method returns successfully.
The container's
AckModecontrols when. WithBATCH(the default), the offsets are committed after the listener returns, which matches "database commit first, offsets second". WithMANUAL_IMMEDIATE, my code callsAcknowledgment.acknowledge()at the end of the method, which makes the point of the commit explicit.If the listener throws, the offsets are not committed, and the error handler decides what happens: retry, back off, or send to a dead-letter topic with
DeadLetterPublishingRecoverer. For a batch listener, the error handler needs to know which record failed, so I throwBatchListenerFailedExceptionwith the index.The code in Part B shows the configuration in full.
Q49 · Scenario. "After a deploy, consumer lag on a 12-partition topic rises to 2 million and keeps growing. Walk me through what you do."
Reveal answer
The real test Whether you triage by evidence (which partitions, what changed) before touching settings.
Strong answer I start with what changed and where the lag is. Per-partition lag tells me the shape: all partitions growing means the whole consumer is slower or smaller; one partition means a hot key or a stuck record.
Then I check the consumers: how many members are in the group, whether they are rebalancing repeatedly, CPU, garbage collection, time per record, and errors in logs. A deploy often changes one of these: a slower new query, a smaller pod count, a new external call.
Short-term actions: roll back the deploy if the cause is clear; scale consumers up to the partition count; and, if records are poison, move them aside to a dead-letter topic.
After recovery I compute the time to drain: lag divided by (consume rate minus produce rate). That tells the business when the data will be current.
Picture it Triage table and the drain time.
The setup: Before deploy: lag near 0. After: 2,000,000 and growing 5,000 per second.
kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group billing
# illustrative output
PARTITION LAG
0 170,000
1 168,500
...
11 166,900 # all similar -> whole group slowed, not one hot keyMake the invisible visible: What changed, and the drain arithmetic.
# illustrative numbers
produce rate 20,000/s; consume rate after fix 26,000/s
net drain = 26,000 - 20,000 = 6,000/s
2,000,000 / 6,000 = about 333 s = roughly 5.5 minutes after the fix
# if the fix only reaches 20,500/s: 2,000,000 / 500 = 4,000 s = 67 minutesWhat you see: Per-partition shape plus a before and after of time per record points at the cause.
Why: Lag is a symptom. The cause is either a rate drop on the consumer side, a rate rise on the producer side, or stuck consumers. Evidence separates them quickly.
Land it I would check per-partition lag shape, the consumer's time per record and group membership, roll back or scale based on the cause, and give the business a drain estimate.
- "How do I tell a slow consumer from a stuck one?"
-
I look at whether the committed offset moves at all. A slow consumer still makes progress, and its committed offset grows, only slower than the producers. A stuck consumer's committed offset does not change, and the time since the last commit keeps growing.
The test costs nothing: run the describe command twice, a minute apart, and compare the current offsets of each partition.
is it movingruns offline# illustrative output t=0 p3 CURRENT-OFFSET 1,204,000 t=60s p3 CURRENT-OFFSET 1,204,000 -> not moving: stuck t=0 p7 CURRENT-OFFSET 880,000 t=60s p7 CURRENT-OFFSET 889,500 -> moving at 158 records/s: slowA stuck partition is usually one of three things: a poison record that keeps failing and retrying, a deadlock or hung call inside the handler (a thread dump shows it), or a consumer that lost its partition and is no longer polling. Each has a different fix, so I find the cause before I scale anything.
- "What if scaling consumers does not help?"
-
Then either you already have one consumer per partition, or the bottleneck is not the consumer. In the first case, the partition count is the ceiling and extra consumers sit idle (Q42). In the second, something that all consumers share is the limit, such as a database, an external API or a lock.
More consumers then push harder on the same limit. If a database handles 4,000 writes per second at best, ten consumers or twenty will see the same 4,000, and latency and errors grow because the queue at the database gets longer.
So I check the dependency: its latency, its error rate, its connection pool use, and its CPU. A rising query time or a pool that is always full is the sign.
The real fixes are on that side: batch the writes, add an index, add a cache, add capacity to the dependency, or reduce the work per record. Scaling the consumer comes after that, and only up to the partition count.
- "Should I just skip the lag?"
-
Only as a business decision, because skipping means data loss. Resetting the group to
latestdrops all 2 million records. For some data, such as live location pings or metrics that are worthless after a minute, that is the right call, and it ends the incident at once. For orders, payments or anything that must be applied, it is not.My role is to lay out the options with their costs, and let the data's owner choose. For example:
optionsruns offline# illustrative A. keep draining : 2,000,000 / (consume - produce) = back to normal in 3 h B. scale and drain : 12 consumers, back to normal in 1 h C. skip to latest : back to normal now, 2,000,000 records never processedIf the owner picks skipping, I save the skipped offset range first, so that the records can be replayed later if someone changes their mind. A skip is easy to do and hard to undo.
- "How do I prevent this next time?"
-
I add checks to the deploy, so that a slow version is caught before it reaches every consumer. First, I run the new version against production-like load or a replay of real traffic, and compare the processing time per record with the old version. Second, I roll it out with a canary: one pod runs the new code, and I watch its rate and errors against the others for ten minutes or so.
Third, I alert on the growth rate of lag, not only its size. A rule such as "lag has grown for 10 minutes in a row" fires within minutes of the bad deploy, long before lag reaches 2 million. A size-only threshold fires late, since 2 million is a late number.
I also keep rollback quick and rehearsed, since rolling back is the fastest fix when the cause is a recent change.
See
#pat-lag-alertingin the production section for the full alert design.
Q50. "How do you measure consumer lag, and why is "lag in records" not enough?"
Reveal answer
Strong answer Lag per partition is log end offset minus the group's committed offset. Total lag is the sum across partitions. The groups tool, broker metrics, and tools such as Burrow or a Prometheus exporter report it.
Records alone can mislead: 100,000 records of lag is nothing for a topic doing 50,000 per second (two seconds) and a crisis for a topic doing 10 per second (almost three hours).
So I also want lag in time: how old is the oldest unprocessed record, or lag divided by the recent consume rate. Time is what the business feels.
And I look at the trend, because steady lag of 1,000 is healthy and growth of 1,000 per minute is not.
Picture it The same lag, two very different meanings.
The setup: Two topics, each with 100,000 records of lag.
# illustrative numbers
topic consume rate lag lag in time
clicks 50,000/s 100,000 2 seconds fine
invoices 10/s 100,000 10,000 s = 2.8 h ❌ seriousMake the invisible visible: The calculation from the tool output.
kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group billing
# illustrative output
PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG
0 9,500 10,000 500
# lag = 10,000 - 9,500 = 500
# time lag = 500 / (consume rate 250/s) = 2 sWhy: A count has no meaning until it is divided by a rate. The business cares about how stale the data is.
Land it I report lag as records, as seconds, and as a trend, because each tells a different part of the story.
- "What is an alert rule you would set?"
-
I alert on lag in time, because that is what the business feels, and I add a separate alert for growth. A typical rule: fire when the lag has been above the tolerance for a sustained period, for example more than 2 minutes behind for 5 minutes in a row. The sustained condition filters out the brief spikes of a rebalance or a deploy.
The second rule is on the trend: lag has been growing steadily for 10 minutes. That catches a consumer that is falling behind slowly, before lag reaches the tolerance. It is the earliest signal I have that something changed.
A plain threshold on the record count alone creates both kinds of errors. Set to 100,000, it pages all night on a busy topic where that is two seconds, and it stays silent on a quiet topic that has been stuck at 5,000 records for an hour.
I also attach a runbook link to the alert, so the first person woken up knows which three things to check.
- "Why does lag sometimes show as zero when something is wrong?"
-
Lag only measures how far the committed offset is behind the end of the log. It does not measure whether real work happened. So several failure modes hide behind a low number. Cases where lag looks fine and the system is not:
- Commit before processing: the offsets advance, so lag is zero, while the handler fails or drops records.
- Stopped group: some tools show nothing for a group with no members, and the topic's growth is not shown as lag if the group was deleted.
- Silently skipping: the handler catches an error, logs it and moves on, so offsets advance without the work being done.
So I pair lag with processing metrics: records handled, errors per minute, dead-letter volume and the age of the newest handled record. Together they tell me about progress, and not only about offsets.
- "Does lag include compaction gaps or transaction markers?"
-
Yes, slightly. Offsets are not always consecutive. Compaction removes older records with the same key, which leaves gaps, and transactions add control records (commit and abort markers) that take an offset but are not data. So the difference between the log end offset and the committed offset can be a little larger than the number of real records waiting.
For example, lag of 1,000 on a heavily compacted topic might hold only 600 records that would be delivered. On an ordinary topic without transactions, the two numbers are almost the same.
This is accurate enough for alerting, since I care about direction and size, not the exact count. It matters only if someone uses the lag number as a precise count of work to do, for instance when promising a time to finish.
For that purpose, I use the consume rate over a recent window: lag divided by the rate gives the time to drain, and that number inherits the same small error.
- "What is a good dashboard?"
-
A dashboard that tells me, in this order, whether the group is alive, how far behind it is, and where. Per group: lag in seconds. Per partition: a heatmap, so one hot or stuck partition shows as a bright stripe. Consume rate against produce rate on one chart, because a gap between them is the early sign. And the number of members, plus the number of rebalances.
panelsruns offline# illustrative layout panel 1: lag seconds per group (line) panel 2: lag per partition (heatmap) panel 3: produce rate vs consume rate (two lines) panel 4: members in group (step), rebalances per hour (bar)I add annotations for deploys, so a change in a line can be tied to a release. I keep each chart readable on one screen, and I put the alert thresholds on them as lines.
The test of a good dashboard is that the person on call can answer "is it getting worse, and since when?" in under a minute.
These questions test whether you can name what triggers a rebalance, tell the old protocol from the new one, and cure a rebalance storm with the right timeout.
Q51. "What is a rebalance and what triggers one?"
Reveal answer
Strong answer A rebalance is the process of redistributing a group's partitions among its members. It happens whenever the group's membership or the topic's shape changes.
The triggers: a consumer joins; a consumer leaves cleanly; a consumer is declared dead (no heartbeat within session.timeout.ms, or no poll() within max.poll.interval.ms); the subscribed topics gain partitions; or a regex subscription matches a new topic.
In the classic protocol, a rebalance is disruptive: members stop fetching while the group agrees on a new assignment. During that pause lag grows for every partition in the group.
The goals are to make rebalances rare (stable membership, correct timeouts) and cheap (cooperative or the new KIP-848 protocol).
Picture it A group of three and a fourth member joining.
The setup: Topic with 6 partitions; consumers C1, C2, C3 hold two partitions each.
# illustrative output
before : C1[p0,p1] C2[p2,p3] C3[p4,p5]
C4 joins -> rebalance
after : C1[p0,p1] C2[p2,p3] C3[p4] C4[p5]
# classic eager protocol: all four stop, give up all partitions, then get new onesMake the invisible visible: What the group experiences in time.
# illustrative timeline (eager protocol)
t=0s C4 joins, coordinator starts rebalance
t=0s C1,C2,C3 revoke ALL partitions, stop processing
t=3s new assignment computed and sent
t=3s all consumers resume (from committed offsets)
# 3 s of zero throughput for 6 partitions; in a big group it can be tens of secondsWhy: A rebalance is the cost of flexibility: every membership change forces agreement, and during agreement nobody reads.
Land it I say rebalances are triggered by membership or topic changes, and I design to make them rare with static membership and correct timeouts, and cheap with cooperative or KIP-848.
- "Why do consumers resume from committed offsets after a rebalance?"
-
Because the committed offset is the only progress the group has recorded. The old owner may have processed records after its last commit, but it never told anyone, so the new owner cannot know.
Think of the committed offset as a bookmark saved on the broker. The consumer reads ahead of the bookmark and moves it only when it commits. If the partition changes hands, the new owner opens the book at the bookmark, not at the page the old owner had reached.
A concrete case: the old owner processed offsets 100 to 149, committed up to 120, then lost the partition. The new owner starts at 120, so offsets 120 to 149 are processed twice.
That is why I commit after processing, accept at-least-once, and make handlers idempotent. Committing before processing would flip the risk to lost records, which is usually worse.
- "How can I see rebalances happening?"
-
I look in three places: the client log, the broker view of the group, and a metric.
- Client log: the consumer prints lines such as "Revoking previously assigned partitions" and "Adding newly assigned partitions". A burst of these, repeated every few minutes, is a rebalance storm.
- Group state:
kafka-consumer-groups.sh --describe --stateshows the group state. During a rebalance it passes throughPreparingRebalanceandCompletingRebalancebefore returning toStable. Catching it in a non-stable state twice in a minute is a warning sign. - Metrics: the client exposes rebalance counts and rebalance latency, and the broker side exposes group state counts.
I would alert on rebalances per hour, because a single graph of that number tells you the group is unhealthy long before lag does. Lag is the late symptom; the rebalance count is the early one.
- "What about adding partitions to a topic?"
-
The group notices on its own, but not instantly. Consumers refresh topic metadata every
metadata.max.age.ms(five minutes by default), so a new partition can go unread for up to that long. A regex subscription is checked on the same refresh.When the metadata shows the new partitions, the group rebalances and hands them out. Until then, records written to the new partitions sit unread and lag there grows quietly.
The trap is the starting point. A brand-new partition has no committed offset for the group, so
auto.offset.resetdecides. Withlatest, the consumer starts at the end and skips anything produced before it picked the partition up. Withearliest, it reads from the start.So if I add partitions to a live topic, I set
earliestfor that group first, and I remember that key order changes as well. - "Are all rebalances bad?"
-
No. A rebalance is the group's repair mechanism, and the question is whether it was needed.
The needed ones come from real events. A pod crashed and its partitions must go to someone else. A deploy scaled the group from 6 to 12 members and the work should spread. Those rebalances do useful work, and the only goal is to keep each one short.
The unneeded ones come from the group being unstable for no good reason:
- a handler slower than
max.poll.interval.ms, so healthy consumers are declared dead; - a session timeout shorter than a normal garbage-collection pause;
- a rolling restart where each pod leaves and returns as a new member.
A useful rule: after a quiet day, the count should be near zero. If I see ten rebalances an hour with no deploy, I fix the cause. I do not try to remove every rebalance, because that would mean never changing the group.
- a handler slower than
Q52. "Explain eager versus cooperative rebalancing in the classic protocol."
Reveal answer
Strong answer In eager rebalancing, every member revokes all its partitions at the start, then the new assignment is made, then everyone takes partitions again. It is simple and causes a full stop of the group.
In cooperative (incremental) rebalancing, used by CooperativeStickyAssignor, members only give up the partitions that must move. The rest keep processing. It takes two short rounds: first to revoke the moved partitions, second to assign them.
The effect is that a new member joining takes a few partitions from others without halting the whole group.
Both belong to the classic protocol. The newer KIP-848 protocol (GA in Kafka 4.0, group.protocol=consumer) moves assignment to the broker and avoids the group-wide stop altogether (Q56).
Picture it The same join under both modes.
The setup: 6 partitions, 3 consumers, a fourth joins and should end up with one partition.
# illustrative output
EAGER
round 1: C1,C2,C3 revoke p0..p5 (all stop)
round 2: assign C1[p0,p1] C2[p2,p3] C3[p4] C4[p5]
COOPERATIVE
round 1: only C3 revokes p5 (C1, C2 keep working, C3 keeps p4)
round 2: p5 assigned to C4Make the invisible visible: Turn it on.
partition.assignment.strategy=org.apache.kafka.clients.consumer.CooperativeStickyAssignor
# migration from eager needs two rolling restarts (old list + cooperative, then cooperative only)Why: Most partitions do not need to move. Eager moves everything anyway; cooperative moves only what is needed.
Land it I would use cooperative-sticky on the classic protocol, or move to the new consumer protocol, so scaling and deploys do not freeze the whole group.
- "How do I migrate a live group from eager to cooperative?"
-
I do it in two rolling deploys, because members of one group must agree on a protocol they all support.
- Deploy one: set
partition.assignment.strategyto a list with the old assignor first andCooperativeStickyAssignorsecond, and roll every member. While old and new members mix, the group picks the first protocol all of them support, which is still the eager one. - Deploy two: remove the old assignor so the list holds only the cooperative one, and roll again. Once every member lists only cooperative, the group switches.
The mistake is to deploy the cooperative-only list in one step. During the roll, an old member and a new member share no assignor, and the join fails with an inconsistent group protocol error. I also watch the rebalance count during both steps, because the first roll still pays eager costs.
- Deploy one: set
- "Does cooperative remove duplicates?"
-
No. Cooperative rebalancing shortens the pause, but it does not change what happens to a partition that moves.
A partition that moves still resumes from its last committed offset. Anything the old owner processed after that commit is processed again by the new owner. That repeat window depends on how often you commit, not on the assignor.
What cooperative gives you is that the partitions which stay put keep processing during the rebalance. If 2 of 12 partitions move, 10 never stop.
To keep the repeat window small, I commit inside
onPartitionsRevoked. That callback runs just before the partition is taken away, so it is the last chance to save progress for it. With the cooperative protocol it is called only for the partitions that are actually leaving, which makes the commit cheap.Duplicates still need idempotent handlers.
- "What does "sticky" mean?"
-
Sticky means the assignor tries to leave each partition with its current owner when it recomputes the plan, and moves only what it must to keep the spread even.
The reason to care is what lives next to a partition on the consumer: warm caches, open connections, a local state store, or buffered batches. Moving a partition throws that away and the new owner has to rebuild it.
A small example makes the difference clear. Three consumers hold 12 partitions, four each, and a fourth consumer joins. A non-sticky assignor may reshuffle nearly everything. A sticky one takes one partition from each of the three and gives the new member three of them, so only 3 of 12 move.
The Range and RoundRobin assignors recompute from scratch each time and do not try to preserve ownership, so they can move many more partitions than needed.
- "Is Kafka Streams affected?"
-
Yes, but Streams is not a plain consumer, so the answer is different.
Kafka Streams uses its own assignor, because it must place tasks and their local state, not just partitions. In recent versions it supports incremental, cooperative-style rebalancing in the classic Streams protocol, so tasks that stay put keep running while others move.
There is also a newer server-side protocol for Streams, KIP-1071, which became GA in 4.2. It moves the assignment work to the broker, much like KIP-848 does for consumers. In 4.2 its feature set is limited, so I would read the current documentation and check that the features I use are covered before depending on it.
In the meantime I reduce the cost of rebalances in Streams with static membership and standby replicas, so a moved task finds a nearly warm copy of its state instead of rebuilding from the changelog.
Q53 · Scenario. "Your consumers keep getting kicked out of the group every few minutes during a batch job and lag climbs. The logs mention max.poll.interval.ms. What is happening?"
Reveal answer
The real test Whether you can tell apart a crashed consumer from one that is merely slow between polls.
Strong answer The consumer processes one batch for longer than max.poll.interval.ms (default 5 minutes). It is not calling poll(), so the coordinator decides it is stuck, removes it, and triggers a rebalance. Its partitions go elsewhere, its next commit fails, and the batch it was working on is processed again by someone else.
The result is a loop: the new owner also gets a slow batch, also times out, and the group keeps churning with growing lag and many duplicates.
The fixes are to reduce the work per poll (max.poll.records smaller), speed up the handler, raise max.poll.interval.ms to a value above the realistic worst case, or pull long work out of the poll loop and use pause/resume (Q74).
I measure first: time per record times records per poll, compared with the interval.
Picture it The arithmetic that predicts the failure.
The setup: max.poll.records=500, normal time per record 100 ms, after the deploy 700 ms because of a slow query.
# illustrative numbers
before: 500 x 0.1 s = 50 s per poll limit 300 s ✅
after : 500 x 0.7 s = 350 s per poll limit 300 s ❌ consumer evicted at 300 sMake the invisible visible: Fix the budget two ways.
max.poll.records=100 # 100 x 0.7 s = 70 s per poll, safe
max.poll.interval.ms=600000 # headroom if a few records are slower
# also fix the slow query; settings only buy timeWhat you see: Poll calls come every 70 s, no evictions, no rebalances.
Why: The broker cannot see inside your handler. The poll interval is its only proof you are alive and making progress.
Land it I would compute batch time against the poll interval, shrink the batch first, and fix the root cause of the slowdown.
- "What is the difference between heartbeats and the poll interval?"
-
They answer two different questions, and a separate clock guards each.
The heartbeat comes from a background thread inside the client. It says "this process is alive". The broker declares the member dead if it hears nothing for
session.timeout.ms(45 seconds by default now), and the client sends a heartbeat roughly everyheartbeat.interval.ms, usually about a third of the session timeout.The poll interval is checked by the client itself. If
poll()is not called again withinmax.poll.interval.ms(5 minutes by default), the client leaves the group, because the processing loop is not making progress.This is exactly why the scenario hurts. A consumer in a long batch has a healthy heartbeat thread, so the session never expires. Only the poll limit catches it, and it does so by design.
So a stuck handler shows up as poll-interval trouble, while a dead process shows up as session-timeout trouble.
- "Why not set max.poll.interval.ms to an hour?"
-
Because the limit does two jobs, and an hour breaks the second one. It leashes the batch, and it is also how the group detects a consumer that is hung.
Say a handler deadlocks on a database lock. The heartbeat thread still works, so the broker thinks the member is alive. Only the poll limit can reveal the problem. With a 5-minute limit, its partitions move after 5 minutes. With a 1-hour limit, those partitions sit untouched for an hour and lag grows the whole time.
A quick calculation shows the cost:
hung consumer costruns offline# illustrative numbers partition rate 300 records/s 5 min limit : 300 x 300 = 90,000 records stuck before the group reacts 60 min limit: 300 x 3,600 = 1,080,000 records stuckI would set the limit just above the measured worst-case batch time, not far above it.
- "What does the commit failure look like?"
-
The commit throws
CommitFailedException, and the message says the group has already rebalanced and assigned the partitions to another member. It also suggests that the time betweenpoll()calls was longer thanmax.poll.interval.ms.The sequence behind it is worth knowing:
- Slow batch: the handler runs past the poll limit, and the client leaves the group.
- Reassignment: the coordinator gives the partitions to another member, which starts at the last committed offset.
- Failed commit: the slow consumer finishes, tries to commit, and the broker refuses because it no longer owns the partitions.
The batch it just processed will be processed again by the new owner, so duplicates follow.
I treat this exception as a diagnosis, not an error to retry. Retrying the commit never works. The right response is to look at batch time against the poll interval, and a log search for this exception is a good first step when a team reports "lag keeps climbing".
- "What if only a few records are very slow?"
-
Then I stop letting the slow ones set the pace for everyone, and I have two ways to do it.
The first is to keep them inside the consumer but off the poll thread. I pause the partition, give the slow record to a worker thread, and keep calling
poll(). Polling a paused partition returns nothing, but it keeps the heartbeat and the poll clock healthy. When the worker finishes, I commit that offset and callresume().The second is to move the slow ones out. A fast consumer checks a quick property of each record, forwards slow ones to a side topic such as
orders-slow, and commits. A separate group, sized and configured for slow work, reads the side topic, with its own largermax.poll.interval.msand perhapsmax.poll.records=1.I prefer the side topic when the slow share is stable, because it isolates the failure and lets me scale the slow lane alone.
Q54. "Compare session.timeout.ms, heartbeat.interval.ms and max.poll.interval.ms."
Reveal answer
Strong answer Three clocks, three questions. session.timeout.ms: is the process alive? The coordinator removes a member that sends no heartbeat in that time. heartbeat.interval.ms: how often heartbeats are sent (usually one third of the session timeout). max.poll.interval.ms: is the loop making progress? Time allowed between two poll() calls.
Short session timeouts detect crashes fast but cause false evictions during GC pauses or network blips. Long ones are calmer but slow to detect a real crash.
Defaults in recent clients are a 45-second session timeout and a 5-minute poll interval. With the new KIP-848 protocol, these are controlled on the broker side by group settings, not by the client in the same way.
I tune them to the failure I want to detect and the pauses I must tolerate.
Picture it Which clock fires for which failure.
The setup: Three failures: process killed, long GC pause of 20 seconds, handler stuck for 8 minutes.
# illustrative output
failure session.timeout (45 s) max.poll.interval (5 min)
process killed fires after 45 s (no)
GC pause 20 s no (heartbeats resume) no
handler stuck 8 minutes no (heartbeat thread OK) fires at 5 minMake the invisible visible: A tuning example for a flaky environment.
session.timeout.ms=30000
heartbeat.interval.ms=10000
max.poll.interval.ms=300000
# rule of thumb: heartbeat.interval.ms <= session.timeout.ms / 3Why: Separate clocks for "alive" and "working" let Kafka tolerate slow processing without waiting minutes to notice a dead process.
Land it I describe session timeout as process liveness, poll interval as progress, and I tune them against the pauses I expect.
- "What happens if I set the session timeout very low?"
-
The group starts evicting healthy consumers, and each eviction makes the next one more likely.
A very short session timeout, say 3 seconds, has to survive everything that can delay a heartbeat: a stop-the-world garbage-collection pause, a CPU-starved container, a short network blip. Any one of them pushes the gap past the limit, and the coordinator declares the member dead and starts a rebalance.
That rebalance pauses the group. Pods that were busy catching up are now more likely to miss their own heartbeats, so more evictions follow. This is the flapping pattern, and the logs show the same members leaving and rejoining.
The balance I pick is to measure the longest pause I actually see, then set the timeout comfortably above it. The default of 45 seconds is already conservative, so I would change it only with a measured reason, and I would remember the broker enforces a minimum value.
- "Is the heartbeat thread affected by a long handler?"
-
No. The heartbeat thread is separate from the thread that calls
poll()and runs the handler, so a long handler does not stop heartbeats.This was a deliberate redesign. Before Kafka 0.10.1, heartbeats were sent from inside
poll(), so a slow handler also meant a session timeout. The fix split the two clocks, which is why we now havesession.timeout.msfor liveness andmax.poll.interval.msfor progress.The consequence for diagnosis is useful. If a consumer is evicted while a handler runs long, the cause is the poll interval, not the session timeout, and raising the session timeout will not help.
The one thing that does stop the heartbeat thread is the whole process freezing, for example a long full garbage-collection pause or the machine being suspended. Then the session timeout is the clock that fires.
- "What are the broker limits on session timeout?"
-
The broker accepts only a range.
group.min.session.timeout.ms(6 seconds by default) is the lowest, andgroup.max.session.timeout.ms(30 minutes by default) is the highest. If the client asks for a value outside that range, the join is rejected with an error that says the session timeout is not within the allowed range.Check the broker settings, because operators sometimes tighten them. The fix is either to change the client value or, if there is a good reason, to change the broker limits. Changing broker limits affects every group on the cluster, so I do it with care.
These two settings protect the cluster from clients that pick extreme values. A 1-second timeout would cause constant rebalances for its group and coordinator work. A 2-hour timeout would hide dead members.
The defaults come from the broker documentation, so I would confirm them for the version I run.
- "How do I find the longest pause my service has?"
-
I measure it from the system, not from guesswork.
For garbage-collection pauses, I look at the GC logs, or the JVM pause metric, over at least a week and read the maximum, not the average. For network trouble, I look at latency spikes between the consumer and the brokers, and any times the client logged a disconnect. For container trouble, I check CPU throttling, because a throttled container can stall for seconds.
Then I add the worst of those together and leave a margin. The session timeout must be larger than the longest pause I expect, or else a normal event will remove a healthy member.
ruleruns offline# illustrative numbers longest GC pause seen 12 s, typical network blip 5 s session.timeout.ms = 30,000 (more than 2x the longest pause)The cost of a larger value is slower detection of a real crash, which is the trade I accept.
Q55. "What is static group membership and when does it help?"
Reveal answer
Strong answer With static membership, each consumer sets a stable group.instance.id. If it disconnects and returns within session.timeout.ms, the coordinator treats it as the same member and gives it back the same partitions, with no rebalance at all.
Without it, a restart looks like "member left, new member joined", causing two rebalances. With rolling deploys of many pods that adds up to repeated pauses.
The trade-off: because the coordinator waits for the member to return, a really dead instance keeps its partitions idle until the session timeout expires. So I raise the session timeout to cover the restart time and accept slower failover.
It fits well with Kubernetes StatefulSets, where each pod has a stable name to use as the instance id.
Picture it A pod restart with and without a static id.
The setup: Group of 4 pods; one restarts and takes 20 seconds to come back.
# illustrative output
DYNAMIC : pod-2 leaves -> rebalance #1 (partitions moved)
pod-2 returns -> rebalance #2 (partitions moved again)
STATIC : pod-2 leaves, session.timeout 60 s not reached
pod-2 returns with same group.instance.id -> keeps its partitions, no rebalanceMake the invisible visible: Configuration.
group.instance.id=billing-consumer-2
session.timeout.ms=60000 # longer than a pod restartWhy: The cost of a rebalance is paid per membership change. Static ids turn a quick restart into a non-event.
Land it I would use static membership with a session timeout longer than a normal restart, and I would state the cost in slower failure detection.
- "What if two consumers use the same instance id?"
-
The older one is fenced out. Two live consumers cannot share one
group.instance.id, because that id means "the same member".When a second consumer joins with an id that is already active, the broker keeps the newer one and tells the older one, through a
FencedInstanceIdException, that it has been replaced. The older consumer must stop working. Without that rule, two processes would both believe they owned the same partitions, and the one-reader-per-partition guarantee would be broken.It happens in practice in two ways. A copied configuration gives all replicas the same hard-coded id. Or a pod that looked dead was only slow, and its replacement started with the same name.
So each replica needs its own unique, stable id, and I treat a fenced exception as a signal to stop the process cleanly, not to retry. That also makes duplicate pods visible instead of silent.
- "How do I get a stable id in Kubernetes?"
-
The id must be the same after a restart and different between replicas, and a StatefulSet gives exactly that.
In a StatefulSet, pods are named with an ordinal, such as
billing-0,billing-1,billing-2, and a restarted pod keeps its name. A Deployment gives random names likebilling-7c9d5-x2k4q, which change on every restart, so the coordinator would see a new member each time and static membership would do nothing.I pass the pod name into the application through the Downward API and use it as the instance id.
id from pod nameruns offlineenv: - name: HOSTNAME_ID valueFrom: { fieldRef: { fieldPath: metadata.name } } # application: group.instance.id=${HOSTNAME_ID}If I must use a Deployment, I derive a stable id some other way, but this is the simplest route.
- "Does it help with scale-up and scale-down?"
-
No. Static membership only covers a member that goes away and comes back with the same identity.
If I add a new pod with a new id, the group has a new member and must rebalance to give it partitions. If I remove a pod for good, its partitions stay reserved for it until the session timeout runs out, and then a rebalance moves them. Neither case is helped.
Here is the effect in numbers. Scaling from 6 to 8 consumers still causes a rebalance. Restarting each of 6 existing pods during a deploy, with a session timeout longer than the restart, causes none.
One more thing to keep in mind is that the timeout now also decides how long a permanently removed member holds on to its partitions. A 5-minute timeout means up to 5 minutes of idle partitions after a scale-down, unless the member sends a leave request. I weigh that against the savings from skipped rebalances.
- "How does it compare with the new protocol?"
-
They solve different parts of the problem, so I can use both, with one caveat.
Static membership removes the rebalance when a known member restarts. The new protocol, KIP-848, makes each rebalance that does happen cheaper, because the broker updates assignments one member at a time and the whole group never stops.
A rolling deploy shows the difference. With static membership, a quick restart causes no rebalance at all. With KIP-848 only, a restart still causes a rebalance, but it moves only the affected partitions, so the damage is small.
I would not assume the two combine in every detail. Static membership exists in the new protocol, but the way it behaves with
group.protocol=consumerhas changed between releases, so I check the documentation for the version I run, and I test a rolling deploy before relying on it.
Q56. "What is KIP-848, the next-generation consumer rebalance protocol, and what does it change?"
Reveal answer
Strong answer KIP-848 moves partition assignment from the clients (a "group leader" consumer) to the broker-side group coordinator. It became generally available in Kafka 4.0, and a consumer opts in with group.protocol=consumer. The older protocol remains available as classic.
The key change: there is no group-wide "stop the world". Each member's assignment is updated individually and incrementally using a heartbeat-based exchange, so a join or leave moves only the affected partitions, and others keep working.
It also removes the need for clients to coordinate through a leader, and it makes large groups scale better, because the coordinator does the computation.
Assignors in the classic sense (partition.assignment.strategy) do not apply there; the server-side assignor decides, and uses a uniform or range strategy configured on the broker side.
Picture it Classic and next-gen side by side.
The setup: A group of 200 consumers; one more joins.
# illustrative output
CLASSIC : join -> all 200 sync through one leader -> new plan for everyone -> resume (seconds to a minute pause)
KIP-848 : join -> coordinator computes -> only the partitions that must move are revoked and given
the other members keep processing the entire timeMake the invisible visible: Opt in from the client.
group.protocol=consumer
# no partition.assignment.strategy here; the server-side assignor is used
# session timeout and heartbeat interval are decided by broker group configsWhy: Moving the coordination work to the server removes the need for stop-and-agree between clients, so rebalances stop being an outage.
Land it I would adopt the new protocol on Kafka 4.x clusters where the client version supports it, and test group behaviour under rolling deploys first.
- "Does the new protocol change my application code?"
-
Mostly no. The code you write stays the same, and what changes is configuration and a few behaviours underneath.
The poll loop, the commit calls and the listener methods are the same. You switch the protocol with
group.protocol=consumer, and the main configuration differences are these:- the client no longer picks an assignor, so
partition.assignment.strategydoes not apply, and the broker-side assignor decides; - session and heartbeat timeouts come from group settings on the broker, not from the client;
- rebalance callbacks always work incrementally, so
onPartitionsRevokedis called only for partitions that really leave.
The last point can matter if your code assumed "revoked means everything", for example by clearing all local state.
My plan is to run the existing integration tests with the new protocol on a test cluster, then a rolling deploy in staging, and only then production. I would not change protocol on a Friday.
- the client no longer picks an assignor, so
- "Can the two protocols coexist in one cluster?"
-
Yes. The protocol is chosen per group, from how its members are configured, so one cluster can serve both at once.
The practical rule is that one group should use one protocol at a time. If half the members say
classicand half sayconsumer, you are in a mixed state that exists only for migration. Kafka documents steps for moving a live group from one to the other, and I would follow them exactly, because the order of the rolling restarts matters.A safe approach goes like this:
- Check support: confirm the brokers are on a version that has the new protocol enabled, and the client libraries are recent enough.
- Move one low-risk group first: pick a non-critical group and compare rebalance times.
- Move the rest: follow the documented steps, one group at a time.
I would avoid accidental mixing, such as a forgotten old image in a deployment.
- "Is it the same for Kafka Streams?"
-
No, Kafka Streams is a separate case. It is a library on top of the consumer, with its own task assignment, and the consumer protocol alone does not cover it.
Streams has its own newer protocol, KIP-1071, which moves task assignment to the broker. It reached GA in Kafka 4.2, but with a limited feature set, so some features that the classic Streams protocol supports may not be there yet. I would read the current documentation and compare it with what my topology needs, for example standby replicas or particular assignors, before moving.
The way I explain it in an interview is that both KIP-848 and KIP-1071 follow the same idea, moving coordination from a client leader to the broker. KIP-848 has been GA longer and is the more mature of the two. For a Streams application I would stay on the classic protocol unless I had checked that the new one covers my case.
- "What would you measure to prove it helped?"
-
I would compare the same rolling deploy, before and after, with two numbers: how long the group is paused and how high the lag peaks.
The setup matters. I use the same traffic level, the same number of pods and the same rollout settings, and I change only the protocol. I record time spent in rebalance, the consumer's rebalance latency metric, and peak lag on the dashboard.
The kind of result I would expect is shown here, with made-up numbers to explain the reading:
before and afterruns offline# illustrative numbers, 24 pods, rolling restart classic : total paused time 24 x 6 s = 144 s of group-wide pauses, peak lag 3.1 M KIP-848 : paused only affected partitions, peak lag 0.4 MIf the numbers do not move, I look for the real cause, such as slow handlers or an unclean shutdown that makes members time out. The protocol is not a cure for those.
Q57 · Scenario. "Every rolling deploy of your 24-pod consumer deployment causes a lag spike and a flurry of rebalances. How do you reduce the impact?"
Reveal answer
Strong answer A rolling deploy replaces pods one at a time. With the classic eager protocol and dynamic membership, each pod leaving and each new pod joining triggers a rebalance: 24 pods mean up to 48 rebalances, each stopping the group.
Layers of fix, from cheapest: switch to the cooperative-sticky assignor; use static membership with a session timeout longer than a pod restart; limit surge (one pod at a time, with readiness gates); and move to the KIP-848 consumer protocol on Kafka 4.x.
Also make pods shut down cleanly: handle SIGTERM, stop polling, commit, and close the consumer so it leaves the group at once instead of timing out.
I would measure the peak lag during a deploy before and after each step so I know which change helped.
Picture it Rebalance counts per approach.
The setup: 24 pods, rolling update with one pod at a time.
# illustrative output
approach rebalances group pause each
eager + dynamic (baseline) 48 3-10 s for everyone
cooperative-sticky 48 only moved partitions pause
static membership (timeout 60 s) 0 to 2 near none, if restart under 60 s
KIP-848 48 (cheap) only moved partitions pauseMake the invisible visible: Clean shutdown in Spring.
spring.lifecycle.timeout-per-shutdown-phase=60s
server.shutdown=graceful
# container: terminationGracePeriodSeconds: 90, preStop hook not needed for consumers
# on SIGTERM the listener container stops polling, commits, and leaves the groupWhy: A rolling deploy is a sequence of membership changes. Each lever reduces either the number of rebalances or the cost of each.
Land it I would combine static membership for restarts with cooperative or KIP-848 for the cost, and make shutdown clean so pods leave the group immediately.
- "Why does leaving the group cleanly matter?"
-
Because it changes how fast the group learns the member is gone, and so how long its partitions sit idle.
When a consumer closes cleanly, it sends a leave-group request. The coordinator starts a rebalance immediately and the partitions are reassigned within a second or two.
When a pod is killed hard, nothing is sent. The coordinator waits until the session timeout passes with no heartbeat, which is up to 45 seconds with the default. For that time nobody reads those partitions and lag grows.
The numbers explain it. A partition receiving 500 records per second builds 500 x 45 = 22,500 records of extra lag during one slow failover, and a deploy repeats that for each pod.
So in the shutdown hook I stop polling, finish or hand back the current batch, commit, and call
close(). In Kubernetes I setterminationGracePeriodSecondslong enough for that to finish. With static membership the leave request is skipped on purpose, so the two settings go together. - "What is the downside of static membership during a deploy?"
-
The downside is that a pod which does not come back leaves its partitions idle until the session timeout expires.
Static membership works by telling the coordinator "wait for this member". That wait is the very thing that protects a quick restart from a rebalance, and it also delays failover for a pod that died for real.
Take a 60-second session timeout. If a pod crashes for good, its partitions, say 2 of 48, wait up to 60 seconds before moving. Lag builds on just those partitions, and the other 22 pods keep working.
Compare that with the alternative. Without static membership, a normal 24-pod roll causes dozens of group-wide rebalances. The group stops each time, and every partition is affected.
So I accept a slower failover for crashes in return for fewer pauses on every deploy, and I set the timeout just above the real restart time, not far above it. I also alert on pods that fail to come back.
- "Should I use maxSurge or maxUnavailable?"
-
The knobs differ between a StatefulSet and a Deployment, and the aim is that members never join in a crowd.
With a StatefulSet, I use the rolling update strategy, which replaces pods one at a time from the highest ordinal down, and waits for each to be ready before starting the next. Combined with static ids, each pod returns as itself.
With a Deployment,
maxUnavailable: 1andmaxSurge: 0mean one old pod goes away before one new pod appears, so membership changes by one at a time. A large surge, for examplemaxSurge: 50%, brings 12 new members in at the same moment and then removes 12 old ones, so churn is doubled.A readiness probe that waits until the consumer has joined and received its partitions also helps, because the rollout will not continue before the last pod is really working.
The cost of going slowly is a longer deploy, and for 24 pods that is usually a fair trade.
- "How do I confirm the deploy is smooth?"
-
I watch the deploy while it happens, with three measurements, and I compare them to limits I set beforehand.
- Lag per group: peak lag during the rollout, shown as seconds of traffic rather than raw records, so it stays meaningful when traffic changes.
- Rebalance count: how many rebalances the group had from the start of the rollout to the end. With static membership and cooperative or KIP-848 protocol, I expect very few.
- Time in rebalance: the total time the group spent not in the stable state.
deploy watchruns offline# illustrative thresholds peak lag during deploy < 30 s worth of traffic OK rebalances per deploy <= 2 OKI check these on every deploy for the first few weeks. After that I keep the alerts, because a new library version or a changed timeout can silently bring the problem back.
Q58. "Compare the Range, RoundRobin and Sticky assignors. How does the assignor affect the work each consumer gets?"
Reveal answer
Strong answer Range assigns, per topic, contiguous ranges of partitions to consumers sorted by name. With several topics of the same partition count, the first consumer gets the low partitions of every topic, which can overload it.
RoundRobin lays out all partitions of all subscribed topics and deals them out one by one, giving a more even count. Sticky aims for an even spread too, but tries to keep existing assignments when the group changes. CooperativeSticky is sticky plus the incremental protocol.
The default list in recent clients is Range and CooperativeSticky, so groups use the cooperative one when all members support it.
The assignor balances partition counts, not load. If one partition is hot, no assignor fixes that.
Picture it Three topics with 3 partitions each, two consumers.
The setup: Topics A, B, C each with partitions 0 to 2; consumers C1 and C2.
# illustrative output
RANGE C1: A0 A1 B0 B1 C0 C1 (6 partitions) C2: A2 B2 C2 (3 partitions) ❌ uneven
ROUNDROBIN C1: A0 A2 B1 C0 C2 (5) C2: A1 B0 B2 C1 (4) ✅ closerMake the invisible visible: Choosing in config.
partition.assignment.strategy=org.apache.kafka.clients.consumer.CooperativeStickyAssignor
# Range: fine for one topic, uneven across many; RoundRobin: even counts, but moves much on changeWhy: The assignor decides who does which share. Sticky variants minimize churn, and range is mainly historical.
Land it I choose cooperative-sticky, and I remember that balance in partition counts is not balance in work.
- "Why does Range cause trouble for co-partitioned topics?"
-
Range can be useful there, and that is the point of the question. It was designed so that the same partition number from several topics goes to the same consumer.
The reason is joins. If topics
ordersandpaymentsboth have 12 partitions and use the same key, then order 7001 lands in partition 5 of both. Range gives partition 5 of every topic to the same consumer, so that consumer sees both sides of the join locally. RoundRobin mixes the partitions of all topics into one deal, so partition 5 of each topic may land on different consumers, and the alignment is lost.The trouble people mean is the side effect: with many topics of few partitions, the first consumers in the sorted list get the low partitions of every topic and are overloaded.
In practice, Kafka Streams uses its own assignor for co-partitioning, so for plain consumers I choose Range only when I need that alignment.
- "Can I write a custom assignor?"
-
Yes. You implement the
ConsumerPartitionAssignorinterface and list the class inpartition.assignment.strategy.The assignor receives each member's subscriptions and user data and returns the plan. Reasons to write one are real placement rules, for example:
- keep partitions in the same availability zone as the consumer, to cut cross-zone traffic;
- give bigger machines more partitions, using a weight passed in the member's user data;
- pin specific partitions to specific members.
It is rare, and it comes with costs. You have to maintain a class that every member must support, and a bug in it can leave partitions unassigned. A rack-aware option already exists in the built-in assignors for some cases, so I would check that first.
With KIP-848 the server-side assignor makes the decision, so a client-side custom assignor does not apply there. I would not write one unless I had a placement rule that no built-in option can express.
- "How does the assignor handle different member subscriptions?"
-
The assignor only hands a member partitions of topics that member subscribed to. Members of one group can subscribe to different topics, and the assignor works out a plan that respects each member's list.
That is where unevenness appears. Suppose a group of 4 members reads topics A and B, but only 2 of them subscribe to B. B's partitions can go only to those 2, so they do more work than the other 2, even though the partition counts look even.
The balance the assignor aims for is also in partition counts, and it can be thrown off by different subscriptions.
My rule is one group, one purpose, one subscription list. When two jobs need different topics, they should be different groups with their own ids, so scaling and lag are visible per job. A group with members subscribed to different things is usually a mistake or a short-lived migration, and I would look at it closely.
- "What does sticky do when a member leaves?"
-
It moves only what it must. The leaving member's partitions are spread over the others, and every other partition stays where it was.
That is the point of the word "sticky". The assignor looks at the previous plan, removes the missing member, and gives each orphaned partition to the member with the fewest partitions, so counts stay even.
leave exampleruns offline# illustrative output before: C1[p0,p1] C2[p2,p3] C3[p4,p5] C3 leaves -> sticky: C1[p0,p1,p4] C2[p2,p3,p5] (p0..p3 never moved)A non-sticky assignor might redeal everything, so C1 could end with p0, p2, p4 and move partitions that did not need to move. Each moved partition means a lost cache and a new owner reading from the last commit.
With the cooperative version, the four unmoved partitions also never stop processing during the change.
Q59 · Design. "A topic has 48 partitions. Each record takes 40 ms to process, the peak input is 2,000 records per second, and per-key order matters. How many consumers and how do you configure them?"
Reveal answer
Strong answer Start with the arithmetic. One consumer thread handles 1 / 0.04 = 25 records per second. To process 2,000 per second I need 2,000 / 25 = 80 worker threads.
With one consumer thread per partition, 48 partitions give a ceiling of 48 × 25 = 1,200 per second: not enough. So I either make processing faster per record, or process several records in parallel inside one consumer while keeping per-key order.
The in-consumer approach: one poll thread per consumer, and a pool of workers where each key hashes to a fixed worker (Q77). With 48 partitions on 12 consumers and 8 workers each I get 96 workers, enough with headroom.
Commit only offsets that are fully processed, per partition, to avoid losing records when workers finish out of order.
Picture it Capacity numbers in a table.
The setup: Target 2,000 records/s at 40 ms each, 48 partitions.
# illustrative numbers
per thread : 1 / 0.040 = 25 records/s
needed threads : 2,000 / 25 = 80
1 thread x 48 partitions = 48 threads = 1,200 records/s ❌ short by 800
12 consumers x 8 key-ordered workers = 96 threads = 2,400 records/s ✅ 20% headroomMake the invisible visible: Key-ordered worker pool shape.
// one executor per worker, so records with the same key always run in order
ExecutorService[] workers = IntStream.range(0, 8)
.mapToObj(i -> Executors.newSingleThreadExecutor()).toArray(ExecutorService[]::new);
for (ConsumerRecord<String, Order> r : batch) {
int w = Math.floorMod(r.key().hashCode(), workers.length);
futures.add(workers[w].submit(() -> handle(r))); // same key -> same worker -> ordered
}
for (Future<?> f : futures) f.get(); // wait for the whole batch
consumer.commitSync(); // then commitWhy: Throughput is threads times rate per thread. The partition count caps consumer threads, so extra parallelism must come from inside each consumer.
Land it I would compute the thread count from the rate and the per-record time, then add key-ordered workers inside each consumer to get there while keeping order per key.
- "Why wait for the whole batch before committing?"
-
Because workers finish out of order, and Kafka's commit is a single number per partition. Committing offset 120 means "everything below 120 is done".
Suppose a batch holds offsets 100 to 149 and eight workers share it. Record 110 is a slow one. Record 120 finishes first, and I commit 121. Then the process crashes. On restart the group resumes from 121, and record 110, which never finished, is lost for good.
The two safe ways are these:
- Wait for the batch: collect the futures of all workers and commit only when every one of them has finished. This is simple and costs a little throughput when one record is slow.
- Track a watermark: per partition, remember which offsets are done and commit only the highest offset below which everything is finished. It is more efficient and a bit more code.
I start with the first, and move to the second only if the idle time is measurable.
- "What if one key is much busier than others?"
-
Then that key's records run one after another on one worker, while the other workers finish their keys and sit idle. The batch waits for the slowest worker, so the busy key sets the pace.
Take the numbers from the question. A record takes 40 ms, so one worker handles 25 per second. If one key sends 100 records per second, a single worker could never keep up with it, whatever the pool size. Order for that key forces one-at-a-time processing.
The options go like this:
- If order for that key is not really needed, route by a finer key such as the record id, so its records spread over all workers.
- If order is needed, make the handler faster for that key, for example by batching its writes.
- Find out why the key is hot, because a single customer producing most traffic may be a bot or a bug.
It is the hot-key problem again (Q24), just inside the consumer.
- "What if processing is mostly waiting on a remote service?"
-
Then the workers spend most of their time waiting, not computing, and a cheap kind of concurrency works well.
A platform thread costs an operating-system thread and about a megabyte of stack by default, so thousands of them are heavy. A virtual thread (Java 21) is a lightweight thread that the JVM parks while it waits for network or disk, so tens of thousands are fine. The same effect comes from async I/O.
The arithmetic changes in a nice way. If each record spends 40 ms waiting on a remote call, 80 in-flight calls give 2,000 records per second, and 80 virtual threads cost almost nothing.
The order rule stays the same. I keep one queue per key-hash bucket, each read by a single virtual thread, so records for one key still run in sequence. If the 40 ms is actual CPU work, virtual threads will not help and I need more cores or faster code.
- "Is it simpler to increase partitions?"
-
It is simpler in code, and there are three things to check before doing it.
First, order. Keys hash as murmur2(key) mod partition count, so changing the count sends existing keys to new partitions (Q22). Per-key order is broken at the moment of the change, and records for one key may be read by two consumers for a while.
Second, the capacity arithmetic. At 25 records per second per consumer thread, 96 partitions give 96 x 25 = 2,400 per second, which meets the 2,000 target with some headroom. 48 gives only 1,200.
Third, the cost: more partitions mean more files, more replication work and longer recovery on the brokers.
The safe route is to create a new topic with 96 partitions, migrate producers and consumers, and retire the old one. Compared with in-consumer workers, I would pick whichever has less risk for this team. If the processing can be made faster later, in-consumer workers keep that option.
Q60 · Scenario. "You scaled a consumer deployment from 4 to 10 pods to clear lag, but nothing improved. Why, and what next?"
Reveal answer
Strong answer Likely the topic has only 4 or 6 partitions, so the extra pods are idle. Check partition count and the group's member assignments. If assignments show idle members, parallelism is capped.
The second possibility is a shared bottleneck: a database, API or lock that all consumers wait on, so more consumers add contention instead of throughput. Check the dependency's latency and error rate as the pod count rose.
A third is a hot partition: if one partition holds most of the lag, one consumer works while the rest wait (Q24).
The fixes match the cause: add partitions (with order care), speed up each consumer, fix the dependency, or spread the hot key.
Picture it The evidence for each cause.
The setup: Topic events with 6 partitions, group scaled to 10 pods.
kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group events-worker --members --verbose
# illustrative output
MEMBER #PARTITIONS
pod-1 1
pod-2 1
...
pod-6 1
pod-7 0
pod-8 0
pod-9 0
pod-10 0 # four members idle: partition count is the capMake the invisible visible: What to look for if all pods are busy but throughput is flat.
# illustrative output
pods consume rate DB connection wait DB CPU
4 8,000/s 2 ms 40%
10 8,100/s 45 ms 98% ❌ database is the limit, not the consumersWhy: Capacity is the smallest of partitions, per-consumer rate and dependency capacity. Scaling the wrong one changes nothing.
Land it I would check assignments for idle members and then check whether a shared dependency is saturated, before adding anything else.
- "How do I decide how many partitions to add?"
-
I work from the rate I need to the rate one consumer delivers, and add headroom.
The formula is partitions needed = target throughput / per-consumer throughput, with a margin of 1.5 to 2 for growth and uneven keys. Per-consumer throughput must be measured, not assumed, as in Q20.
A worked case:
partition sizingruns offline# illustrative numbers target 6,000 records/s, one consumer handles 500 records/s 6,000 / 500 = 12 partitions needed x 1.5 headroom = 18 -> choose 18 or 24Then I check the side effects. Adding partitions changes which partition a key maps to, so key order breaks across the change, and I tell the owners of keyed data in advance. If order matters, I plan a new topic and a migration. If it does not, I add the partitions and watch the group.
What I avoid is doubling the count with no number behind it.
- "What if the dependency is the limit?"
-
Then more consumers cannot help, and I fix the dependency or reduce the load I put on it.
The cheapest improvement is almost always fewer round trips. A database that takes 2 ms per insert is slow when called 500 times per batch, and much faster when it receives one multi-row statement.
batching writesruns offline# illustrative numbers row-by-row: 500 records x 2 ms = 1,000 ms per batch one multi-row insert of 500 rows = 60 ms per batch (16x faster)After that, I consider adding capacity (connection pool size, read replicas, a bigger instance), caching reads that repeat, and putting a bounded queue in front so spikes do not crush it.
The trap is adding consumers that all open connections to a database already near its limit. Ten more pods with 20 connections each is 200 more connections, which may slow everyone down. I compare latency before and after the scale-up to see it.
- "Would autoscaling on lag help?"
-
Yes, up to a ceiling, and the ceiling is the partition count. Extra consumers beyond the number of partitions sit idle.
A tool such as KEDA can scale a Deployment on consumer lag. It watches the lag per group and adds pods when lag rises past a threshold, then removes them when it falls. The important detail is the maximum replica count: set it to the number of partitions, because pod number 13 on a 12-partition topic does nothing.
A few cautions apply:
- every scale event is a rebalance, so frequent small scalings create churn; a stabilisation period or larger steps help;
- scaling on lag only helps when the consumers are the bottleneck, and a saturated database makes lag worse when pods are added;
- the scale-down should leave the group cleanly.
So I use autoscaling for the predictable part, and I set the maximum from the partition count and the dependency's limits.
- "How do I prove the fix worked?"
-
By watching the numbers rather than trusting the change.
The first check is the rates. After the fix, the consume rate should be above the produce rate, and the lag should trend down toward zero. The gap between the two rates also gives a drain time: lag divided by the difference.
A worked check:
drain timeruns offline# illustrative numbers lag 1,200,000 records, produce 2,000/s, consume 4,000/s drain time = 1,200,000 / (4,000 - 2,000) = 600 s = 10 minIf lag takes 10 minutes as computed, the fix did what I thought. If it is flat or falling much more slowly, something else limits the rate, perhaps a dependency or a hot partition, and my explanation was incomplete.
I also check that no member is idle and that the oldest unprocessed record is getting younger, since lag in records alone can mislead.
These questions test whether you can say what each guarantee costs, where exactly-once stops, and what to do with a record that will never succeed.
Q61. "Define at-most-once, at-least-once and exactly-once delivery, and say which one Kafka gives you by default."
Reveal answer
Strong answer At-most-once: a record is delivered zero or one time; it may be lost, never repeated. At-least-once: delivered one or more times; never lost, but may repeat. Exactly-once: the effect happens once, with no loss and no repeat.
What you get depends on how the application commits. Commit before processing gives at-most-once. Process then commit gives at-least-once. With the idempotent producer, the producer side does not add duplicates from retries, so the producer to broker hop is exactly-once per session.
True end-to-end exactly-once needs cooperation: transactions when everything stays inside Kafka (Q62), or an idempotent consumer or transactional sink when the effect leaves Kafka.
The honest summary: Kafka gives you the building blocks, and at-least-once with idempotent handling is the default practical design.
Picture it Each guarantee as a crash test.
The setup: A consumer reads one record, does one side effect (charge a card), and commits. We crash at each point.
# illustrative output
at-most-once : commit -> charge -> crash between : charge never happens (lost)
at-least-once : charge -> commit -> crash between : charge happens twice (duplicate)
exactly-once : charge + commit in one atomic unit : charge happens once (needs a shared transaction or an idempotency key)Make the invisible visible: The idempotency key turns the second charge into a no-op.
// ✅ same key on retry -> payment provider returns the first result, charges once
paymentApi.charge(orderId, amountCents, /* idempotencyKey */ "order-" + orderId);
consumer.commitSync();Why: Exactly-once is a property of the effect, not of the message. It is built from at-least-once delivery plus a way to ignore repeats.
Land it I would say Kafka's practical default is at-least-once, and that exactly-once effects come from idempotent processing or transactions, not from the delivery itself.
- "Is "exactly-once delivery" possible in a distributed system?"
-
Not as a pure delivery guarantee over an unreliable network. What real systems offer is exactly-once processing, built from retries plus deduplication.
The reason is the two-generals problem. A sender transmits a record and waits for an acknowledgement, and the acknowledgement never arrives. The sender cannot tell whether the record was lost, or the record arrived and only the reply was lost. If it retries, the receiver may get two copies. If it does not, the receiver may get none.
So the network can give you at-most-once (no retry) or at-least-once (retry), and nothing in between.
What makes the effect happen once is that the receiver recognises a repeat and ignores it. Kafka's idempotent producer does that with sequence numbers, and an idempotent consumer does it with an event id.
In an interview I say "exactly-once effect through idempotence", because claiming exactly-once delivery invites a follow-up I would rather answer on my terms.
- "When is at-most-once the right choice?"
-
When a repeat is worse than a loss, and the action cannot be made safe to repeat.
A clear example is a one-time promotional SMS. If the same customer gets the offer twice, that is annoying and costs money. If one customer misses it, nobody notices. Another is a non-idempotent call to a partner system, with no idempotency key, where a second call would charge the customer twice.
At-most-once in Kafka means committing the offset before processing. If the process crashes in between, the record is skipped and never retried.
Even so, I would first try to remove the need. A partner API often offers an idempotency key, and a table of sent messages can turn the action into "send if not already sent". Those give you at-least-once delivery with at-most-once effect, and you lose nothing.
I choose at-most-once only after deciding that I cannot make the action safe, and I write that decision down.
- "Why is at-least-once the common choice?"
-
Because the two failures are not equal. A repeat can be made harmless, while a loss cannot be repaired.
A lost record is a missing fact. The order was placed, and nothing ever sees it, so no error appears and no one is alerted. You usually find out when a customer complains, and by then the data to rebuild it may be gone.
A repeated record is visible and fixable. The handler sees the same order id a second time, and the design decides what happens: a unique constraint rejects it, an upsert overwrites it with the same values, or a version check skips it.
Consider the cost of each:
- Loss: unknown size, found late, cannot be recovered without a source of truth.
- Repeat: known size, found at once, handled by a rule in code that you test.
That is the principle I follow: choose the failure that you can repair, and then do the repair work in the handler.
- "What does the producer-side idempotence guarantee exactly?"
-
It guarantees that a retry within one producer session does not put a second copy of a record into a partition. It does not guarantee anything beyond that.
The mechanism: the broker gives the producer a producer id, and the producer numbers every batch per partition. If a batch is sent twice because an acknowledgement was lost, the broker sees the same sequence number, recognises the repeat and discards it, while still replying "ok".
The limits are worth stating, because interviewers test them:
- if the producer process restarts, it gets a new producer id and the sequence starts again, so a record the application resends after restart is a new record;
- if application code sends the same business event twice, both are accepted;
- it covers one partition's sequence, not an atomic write across topics, which is what transactions add (Q62).
Since Kafka 3.0 it is on by default along with
acks=all. Details are in Q29.
Q62. "How do Kafka transactions work, and what do they give you?"
Reveal answer
Strong answer A transactional producer has a stable transactional.id. It can write to several partitions and topics and also commit consumer offsets in one atomic unit: either all of it becomes visible or none of it. This gives exactly-once for a consume-transform-produce loop that stays inside Kafka.
Mechanically, the producer registers with a transaction coordinator (a broker), writes records marked as part of the transaction, and calls commitTransaction(). The coordinator then writes commit markers to every partition involved. Consumers with isolation.level=read_committed only see records of committed transactions.
The transactional.id also fences zombies: if an old instance with the same id is still alive, the broker rejects its writes after a new instance starts (Q76).
It costs latency (a few extra round trips per transaction) and complexity, so I use it where a loop's output and its input offset must move together.
Picture it One transaction in steps.
The setup: Read order events from orders, write enriched events to orders-enriched, commit the input offset, all together.
# illustrative output
1 initTransactions() register transactional.id, fence older instances
2 beginTransaction()
3 send(orders-enriched, record) marked "in transaction 17"
4 sendOffsetsToTransaction(offsets, group) the input offset is part of the same unit
5 commitTransaction() coordinator writes COMMIT markers to all partitions
# crash anywhere before step 5 -> abort: outputs invisible, input offset not advanced, input re-readMake the invisible visible: The loop in code.
producer.initTransactions();
while (running) {
ConsumerRecords<String, Order> batch = consumer.poll(Duration.ofMillis(500));
if (batch.isEmpty()) continue;
producer.beginTransaction();
try {
for (ConsumerRecord<String, Order> r : batch) {
producer.send(new ProducerRecord<>("orders-enriched", r.key(), enrich(r.value())));
}
producer.sendOffsetsToTransaction(offsetsOf(batch), consumer.groupMetadata());
producer.commitTransaction();
} catch (Exception e) {
producer.abortTransaction(); // outputs invisible; batch will be re-read
}
}Why: The trick is that the output records and the input offset are written by one atomic commit, so the "process" and "commit" steps that cannot be joined normally are joined here.
Land it I would use transactions for consume-transform-produce loops inside Kafka and say clearly that they do not extend to a database or an HTTP call.
- "What config do the consumers need?"
-
Three settings, two on the consumer side and one on the producer.
Downstream consumers that must not see uncommitted or aborted records set
isolation.level=read_committed. The default isread_uncommitted, which returns everything including records from open and aborted transactions, so forgetting this one quietly removes the guarantee.The consumer that reads, transforms and writes sets
enable.auto.commit=false. Its offsets are committed as part of the transaction, using the producer'ssendOffsetsToTransaction, so that the offset and the output records commit together or not at all. If auto-commit also ran, it could advance the offset on its own and break that link.On the producer, I set a stable
transactional.idthat is unique per logical producer and the same after a restart. This id is what lets the broker fence an older instance.In Spring Kafka, the transaction manager and a
transactionIdPrefixset this up. - "What does a transaction cost?"
-
A transaction costs some extra requests, so each one adds a small, roughly fixed latency, and the way to make it cheap per record is to make it big.
The producer must register the partitions it writes to with the transaction coordinator, and the commit writes a marker into every partition involved. Those are extra round trips on top of the normal sends. The overhead is per transaction, not per record.
That is why batch size decides the cost:
cost shaperuns offline# illustrative numbers transaction per record : 10 ms overhead x 1 record = 10 ms per record -> ~100 records/s per producer transaction per 500 : 10 ms overhead / 500 = 0.02 ms per record -> negligibleSo I commit one transaction per poll batch, not per record. The trade-off is that a bigger transaction holds the last stable offset back for longer (Q63) and a failure repeats more work, so I keep batches moderate.
- "What is transaction.timeout.ms?"
-
It is the longest a transaction may stay open without being committed or aborted. The default is 60 seconds. When the time is over, the transaction coordinator aborts the transaction by itself.
The reason it exists is protection. A producer that crashed halfway through a transaction would leave it open, and the last stable offset would stop at its first record, blocking every
read_committedconsumer of that partition. The timeout is what frees them.The effect on a slow processing loop is hard. If the loop takes longer than the timeout between beginning and committing, the coordinator aborts the transaction, and the next call from the producer fails with a fenced or invalid-state error.
So I set it a bit above the longest normal batch, and I keep batches short. The broker caps the value with
transaction.max.timeout.ms(15 minutes by default), so a request above that is rejected. - "What happens to an aborted transaction's records?"
-
They stay in the log, and an abort marker is written after them. Nothing is erased, because Kafka logs are append-only.
What changes is who sees them. A consumer with
read_committedskips records from an aborted transaction, so the application never receives them. A consumer withread_uncommittedreturns them as ordinary records, and cannot tell that they were aborted.There are two side effects to know about. The aborted records and the transaction markers both occupy offsets, so a
read_committedconsumer sees gaps in offsets, and lag computed from offsets can look slightly off. That is normal and not a sign of lost data.The records also take disk space until retention or compaction removes them.
For a consumer, the point is simple: aborted data is invisible to correct readers, so I make sure every downstream group sets
read_committed.
Q63. "What is read_committed and the last stable offset? What happens to a consumer when a transaction stays open?"
Reveal answer
Strong answer With isolation.level=read_committed, a consumer only returns records that belong to committed transactions (and non-transactional records). The broker enforces this with the last stable offset (LSO): the offset below which every transaction is decided, committed or aborted.
If a transaction is open, the LSO stops at its first record. The consumer cannot read past that point, even if later records from other, finished transactions exist. The consumer waits, and lag grows.
So one slow or hung transaction can hold back all read_committed consumers of that partition until it ends or times out (transaction.timeout.ms).
That is the cost of isolation: readers share fate with the slowest open transaction.
Picture it An open transaction blocking the LSO.
The setup: Partition with records: offset 10 starts transaction T1 (still open), offsets 11 to 14 are from committed transaction T2.
# illustrative output
offset: 10 11 12 13 14
owner: T1 T2 T2 T2 T2 T1 open, T2 committed
LSO = 10 -> read_committed consumer can read up to offset 9 only (offsets 11..14 are held back)
read_uncommitted consumer reads all of it, including T1's uncommitted recordMake the invisible visible: After T1 commits or times out.
# illustrative output
T1 commits at 14:02:10 -> LSO moves to 15 -> consumer receives 10..14 in one go
T1 hangs -> coordinator aborts it after transaction.timeout.ms (60 s) -> LSO moves, 10 skippedWhy: To hide undecided data, Kafka must wait for decisions. Waiting is the price of seeing only committed results.
Land it I would monitor open transaction age and keep transactions short, because a stuck transaction delays every read_committed consumer behind it.
- "How do I see this as lag?"
-
Lag is usually computed against the high watermark, and a
read_committedconsumer can only read up to the last stable offset (LSO), so the two can disagree.The high watermark is the highest offset replicated to all in-sync replicas. The LSO is lower or equal: it stops at the first record of the oldest open transaction. A consumer waiting on an open transaction has no records to return, yet its measured lag to the high watermark stays the same or grows.
To see it, I compare three numbers for the partition: the committed offset of the group, the LSO, and the log end offset. If the group's committed offset is close to the LSO while the log end is far ahead, the consumer is not slow. It is waiting for the transaction.
It looks like a stuck consumer but is blocked by an upstream producer, so the right investigation goes to the producer side, and to open transactions on the broker.
- "How do I choose the transaction timeout?"
-
I choose it between two bounds. It must be longer than the longest legitimate transaction, and short enough that a stuck one does not hold readers for too long.
The default is 60 seconds, and I would measure the real distribution first. If a batch normally takes 2 seconds and the worst I have seen is 8, a timeout of 30 seconds leaves a safe margin and limits the damage of a hung producer to 30 seconds of delay for readers.
The trade-off runs both ways:
- too low, and healthy but slow transactions are aborted, and the producer is fenced and must restart its work;
- too high, and one crashed producer stalls every
read_committedconsumer of its partitions for that long.
The broker also limits the value with
transaction.max.timeout.ms, so a producer cannot ask for more than the cluster allows. I set the producer's value explicitly rather than relying on the default. - "Is read_committed needed if nobody uses transactions?"
-
No, it makes no difference. If no producer writes transactional records to a topic, every record is already committed and visible, and the setting has nothing to filter.
It starts to matter the moment any producer on that topic uses transactions. Then
read_uncommitted, the default, would show aborted records, andread_committedwould not.My habit is to set it on consumers whose topics might get transactional writers, such as the output topic of a Kafka Streams job with
exactly_once_v2. For topics that are certainly plain, I leave the default, becauseread_committedadds a small cost: the consumer can return only up to the last stable offset, and may wait for open transactions.Setting it everywhere by habit is harmless. I just do not count on it as a protection unless I have checked that the producers are transactional, and I write the reason in the config.
- "Do compacted topics and transactions mix?"
-
They work together, but the combination changes what offsets mean, so I test it instead of assuming.
Compaction keeps the latest record per key. With transactions, aborted records and the control markers are in the same log. Kafka handles them, and the cleaner removes the markers and aborted data eventually, but the cleaner's behaviour affects how soon, and offsets will have gaps.
Two practical points apply. A compacted topic that is also read by
read_committedconsumers still holds back readers during an open transaction, as any topic does. And a record that was aborted must never replace a good value for a key, which is the very thing the isolation level protects.I would not claim more than I have checked. For a real design I write a small test: produce committed and aborted records for the same keys, run the cleaner, and read with both isolation levels. Then I know exactly what the pattern does on the version I run.
Q64 · Scenario. "You enabled exactly-once with Kafka transactions, yet a downstream database shows duplicate rows. How?"
Reveal answer
Strong answer Transactions make Kafka writes atomic. They cannot cover a database write, an HTTP call or an email. If the consumer writes to a database inside the loop, a crash after the database commit and before the Kafka transaction commit repeats the batch, and the database gets the rows again.
Another way: a downstream service reads without read_committed and sees records from an aborted transaction as real.
The fix is to treat the database as a separate system: make the writes idempotent (unique key, upsert) or store the offset in the same database transaction. "Exactly-once" ends at the edge of Kafka.
I say that sentence directly in interviews, because it is the most common misunderstanding.
Picture it The boundary.
The setup: A transform reads orders, calls a database, and publishes to orders-enriched in a transaction.
# illustrative output
inside Kafka (atomic): input offset + output records
outside Kafka (not): INSERT INTO billing(...) <- repeats after an abort
crash after INSERT, before commitTransaction -> transaction aborts -> batch re-read -> INSERT again ❌Make the invisible visible: Idempotent insert.
insert into billing (order_id, amount_cents)
values (:orderId, :amount)
on conflict (order_id) do nothing; -- ✅ second attempt changes nothingWhy: Kafka's transaction coordinator only knows about Kafka. Anything else has to protect itself.
Land it I would explain that exactly-once covers reads and writes inside Kafka, and make every external write idempotent.
- "Can a database and Kafka be made atomic together?"
-
Not with a single commit, unless you use a distributed transaction, and most teams avoid those.
A two-phase commit across Kafka and a database would need both to take part in a coordinator's protocol, and Kafka is not an XA resource. Even where it can be done, it is slow, and a stuck coordinator leaves locks held in both systems.
The practical approach is to make one of them the source of truth, and derive the other.
- Outbox: write the business change and an event row to the database in one local transaction, then a relay or a CDC tool publishes the row to Kafka. This is covered in Q70, and in e07 under
#pat-outbox. - Idempotent consumer: for the other direction, the consumer applies each event once, using a unique event id stored with the effect.
Both settle for at-least-once delivery and remove the duplicates by design. That is the honest answer: atomicity across systems is replaced by safe repeats.
- Outbox: write the business change and an event row to the database in one local transaction, then a relay or a CDC tool publishes the row to Kafka. This is covered in Q70, and in e07 under
- "What if I use Kafka Connect to write to the database?"
-
Often it can, and that is one of the main reasons people use Connect, but I check each connector's behaviour rather than assume.
A sink connector reads from the topic and writes to the database. Many relational sinks support an upsert mode keyed on the record key, so a repeated record overwrites the same row and the duplicate disappears. That gives an exactly-once effect through idempotence, even though delivery is at-least-once.
Some connectors also advertise their own exactly-once support, and it works in different ways: some store offsets in the target system, some rely on the framework's support for exactly-once source connectors, which covers source connectors only. Support varies by connector and version.
My check is short. I read the connector's documentation for the delivery guarantee, set insert mode to upsert with the right key columns, and test a restart in the middle of a run to see that no duplicates appear. I never assume.
- "How do I prove duplicates are from replays and not from bugs?"
-
I match the duplicate rows with the events around them in time, because replays leave a recognisable pattern and logic bugs do not.
If the table stores the source topic, partition and offset with each row, the check is direct. Two rows with the same offset mean the same record was applied twice, which is a replay. Two different offsets with the same business key point to a producer that sent two events, which is a different problem.
Without offsets in the table, I look at the timing. Replays come after rebalances, restarts or transaction aborts, so the duplicates cluster at those moments.
diagnosisruns offline# illustrative output duplicates at 02:11, 02:43, 03:15 -> same times as pod restarts (rolling deploy) conclusion: replays after rebalance, not a logic bugOnce I know the cause is replays, the fix is idempotence in the consumer, not a change in Kafka settings.
- "What should be in the consumer's design doc?"
-
It should say, in plain words, what the consumer promises and how it keeps that promise, so a reviewer can check the design without reading the code.
I include four things:
- the delivery guarantee, stated honestly, for example "at-least-once delivery, idempotent by
order_idplusevent_type"; - the dedupe key and where it is stored, with a note that the check and the effect share one database transaction;
- the retention window of the dedupe data, tied to the topic's retention plus a margin, and the job that purges it;
- what happens on failure: retry count, dead-letter topic, who is alerted, and how a record is replayed.
I also list what the design does not promise, such as ordering across keys.
The value of this page shows during an incident. When duplicate rows appear at 3 a.m., the on-call engineer can compare what happened with what was promised, instead of guessing what "exactly-once" meant to the author.
- the delivery guarantee, stated honestly, for example "at-least-once delivery, idempotent by
Q65 · Design. "Design an idempotent consumer for payment events."
Reveal answer
Strong answer Every event carries a unique event id (or a business id like payment id plus version). The consumer records which ids it has processed and skips repeats. The record and the business effect must be written in the same database transaction, otherwise a crash between them breaks the guarantee.
The simplest form is a processed_events table with a unique constraint on the event id. Insert the id and apply the effect in one transaction; if the insert violates the constraint, the event is a repeat and the handler returns without doing anything.
The dedupe table needs a retention policy: keep ids for longer than the maximum possible replay window (for example, longer than topic retention plus a margin), then purge.
An alternative for state updates is a version check: apply an event only if its version is greater than the stored version.
Picture it The handler and its table.
The setup: Payment events have eventId, paymentId, amountCents.
create table processed_events (
event_id text primary key,
processed_at timestamptz not null default now()
);
create table payments (
payment_id text primary key,
status text not null,
amount_cents bigint not null
);Make the invisible visible: The handler in one transaction.
@Transactional
public void handle(PaymentEvent e) {
int inserted = jdbc.update(
"insert into processed_events(event_id) values (?) on conflict do nothing", e.eventId());
if (inserted == 0) {
return; // ✅ repeat: do nothing
}
jdbc.update("update payments set status = ?, amount_cents = ? where payment_id = ?",
e.status(), e.amountCents(), e.paymentId());
}Why: The processed-events row and the payment update commit together or not at all, so a crash cannot leave one without the other.
Land it I would use a unique event id recorded in the same transaction as the effect, and purge old ids after the replay window.
- "What if the effect is not in a database, such as calling an API?"
-
Then the idempotency has to come from the other system, or from a record I keep about my own calls.
The best case is that the API accepts an idempotency key. I send the event id as that key, and the API returns the first result for any repeat. Payment providers commonly offer this.
If it does not, I use a two-step record in my own database:
- Before the call: insert a row "event X, attempting" with a unique constraint on the event id.
- After the call: update it to "done", with the response.
- On a repeat: if the row says "done", skip. If it says "attempting", the earlier try may have succeeded or failed, so I query the API for the outcome, for example by looking up the charge by my reference, and then decide.
That "attempting" state is the ambiguous one, and it is what makes this closer to a small saga. See e07. I accept that I cannot get a perfect guarantee against a system that offers no lookup.
- "How long should I keep processed ids?"
-
At least as long as a duplicate could still arrive. That is the topic's retention window, plus the time a producer might retry, plus a margin.
The reasoning is about replay. If the topic keeps 7 days of data, then an operator can reset offsets and replay anything from the last 7 days. If my dedupe table had forgotten an id after 3 days, a replay of day 5 would apply the event again. So I keep ids longer than retention, say 10 days for 7-day retention.
A size check shows it is cheap:
sizingruns offline# illustrative numbers 2 million events/day x 10 days = 20 million rows x ~60 bytes = about 1.2 GB (manageable)I purge by age with a scheduled job, in small batches, so it does not lock the table. I also index the event id because that is the lookup on every message. If my consumers can replay from tiered storage for longer, the window should follow that.
- "Is a version number better than an id table?"
-
For "latest state" updates, yes, and it also solves a problem the id table cannot.
A version check applies an event only if it is newer than what is stored:
version checkruns offlineupdate account set balance_view = :v, version = :new where id = :id and version < :newIf zero rows change, the event is a repeat or arrived late, and it is dropped. That handles duplicates and out-of-order arrival together. An id table only recognises ids it has seen, so an old event that arrives after a newer one would still be applied and overwrite fresher data.
The id table fits one-off actions with no version, such as "send the receipt".
So I choose by the nature of the effect. State that converges to the latest value gets a version. An action that must happen once gets an id.
- "Where do event ids come from?"
-
The producer creates them, at the moment the business event happens, and where possible they are built from the business data, not drawn at random.
There are two common forms. A random UUID is easy, and works if it is created once and stored with the event, for example in the outbox row. A deterministic id is built from facts, such as
order-8841:PAYMENT_CAPTURED:1, order id, event type and sequence.The deterministic form is safer because it survives a retry of the whole producer-side action. Suppose a service crashes after publishing but before saving, and the retry builds the event again. A new random UUID makes the retry look like a different event, so the consumer applies it twice. A deterministic id gives the same value, and the dedupe works.
I never generate the id in the consumer: it would differ on every delivery.
Q66 · Scenario. "One malformed record at offset 1,204,000 makes the consumer throw an exception, retry forever, and block its partition. What do you do?"
Reveal answer
Strong answer This is a poison pill: a record that fails every time. Retrying the same record in place never succeeds, and because Kafka consumers read in order, everything behind it waits.
The immediate action: stop the loop from retrying forever. Bound the retries, then route the failed record to a dead-letter topic (DLT) with the error details, commit past it, and continue.
Then analyse the record from the DLT: fix the producer or the schema, and replay it if it is valid after a fix.
In Spring Kafka this is the DefaultErrorHandler with a DeadLetterPublishingRecoverer and a back-off, and for deserialization errors the ErrorHandlingDeserializer.
Picture it The stuck partition and the unstuck one.
The setup: Partition 4: offset 1,204,000 is malformed JSON.
# illustrative output
poll -> [1,203,999][1,204,000][1,204,001]...
handle(1,204,000) throws -> no commit -> poll returns same batch -> throws again ... ❌ lag grows foreverMake the invisible visible: The fix in Spring.
@Bean
DefaultErrorHandler errorHandler(KafkaTemplate<Object, Object> template) {
var recoverer = new DeadLetterPublishingRecoverer(template); // -> orders.DLT
var backoff = new FixedBackOff(1000L, 3); // 3 retries, 1 s apart
var handler = new DefaultErrorHandler(recoverer, backoff);
handler.addNotRetryableExceptions(JsonParseException.class); // retrying a parse error is pointless
return handler;
}What you see: After 0 retries for parse errors, the record is in orders.DLT with headers naming the exception and the original offset, and the partition continues at 1,204,001.
Why: A partition is a single lane. One record that never passes must be moved to a side lane so the lane keeps moving.
Land it I would bound retries, send the failure to a dead-letter topic with context, skip past it, and alert on DLT traffic.
- "Which errors should not be retried?"
-
Errors that cannot get better on a second try. Retrying them only delays the dead-letter topic and holds up the partition meanwhile.
I split errors into two groups, and I write the split down instead of leaving it to the default.
- Not retryable: a record that cannot be deserialized, a validation failure, an unknown enum value, a missing required field. The same bytes give the same error every time, so after the first failure I send the record to the DLT.
- Retryable: timeouts, deadlocks, a dependency that is briefly down, an optimistic-lock conflict. A later attempt can succeed, so I retry with a back-off and a limit.
In Spring Kafka,
DefaultErrorHandleralready treats some exceptions as fatal and skips retries for them, and I can add my own withaddNotRetryableExceptions. Its default for everything else is 10 attempts with no delay, which is fast and aggressive, so I normally set a real back-off.The test I apply is "if I run this record again an hour from now, would the result change?"
- "How do I handle a record that cannot even be deserialized?"
-
I wrap the real deserializer in
ErrorHandlingDeserializer, so a bad record becomes a failure the error handler can see, instead of an exception thrown from insidepoll().The problem it solves is subtle. Deserialization happens inside the client when it fetches records. If it throws,
poll()throws, the application cannot see which record failed, the position does not advance, and the nextpoll()fetches the same bytes and fails again. The consumer is stuck forever on that offset.With
ErrorHandlingDeserializer, the exception is caught, the record is delivered to the container with the raw bytes and the error stored in a header, and theDefaultErrorHandlerthen routes it, usually to the dead-letter topic throughDeadLetterPublishingRecoverer. The offset moves on.The setup is two properties: the error-handling wrapper as the deserializer, and a delegate class that names the real one. In Spring Kafka 4 the delegate may be the Jackson 3 based
JacksonJsonDeserializer. - "What goes into the dead-letter record?"
-
Enough to understand and replay it without going back to the source topic. I put it in headers, and the value carries the original payload bytes unchanged.
The useful items are these:
- the original topic, partition and offset, which tell you where it came from and let you find it in logs;
- the exception class and message, and a trimmed stack trace if it helps;
- the original key and timestamp, so a replay keeps its partitioning;
- the consumer group and, if I have one, a correlation or trace id.
Spring's
DeadLetterPublishingRecovereradds most of these as headers by default.DLT headersruns offline# illustrative output kafka_dlt-original-topic orders kafka_dlt-original-partition 4 kafka_dlt-original-offset 1204000 kafka_dlt-exception-fqcn com.fasterxml.jackson.core.JsonParseExceptionI keep the payload as raw bytes so a replay can send exactly what arrived.
- "How do I avoid silently losing data in the DLT?"
-
I make the DLT a place that people watch and can drain, with three habits.
First, an alert on arrival. Any message in the DLT of an important consumer should page or at least notify, and the rate should be on a dashboard. A DLT that no one looks at turns into a bin where data disappears slowly.
Second, retention that outlasts human reaction time. If the topic keeps 7 days and the failure happens on a Friday before a long weekend, the evidence may be gone on Tuesday. I use 14 to 30 days for DLTs.
Third, a replay tool, because a record in the DLT is only useful if it can go back. The tool reads the DLT, filters by cause or time, republishes to the original topic or a retry topic, and records what it replayed.
Replay happens after the cause is fixed, otherwise the record fails again and returns to the DLT. I treat the DLT as a work queue for humans, with an owner, not a storage area.
Q67 · Design. "Design a dead-letter topic strategy for a payments consumer: naming, retention, ownership and replay."
Reveal answer
Strong answer One DLT per source topic and group, named <topic>.DLT (or <topic>.<group>.DLT when several groups consume), with the same key as the original so related records stay together, and with the same number of partitions or fewer.
Retention is long enough for people to react, typically 14 to 30 days, longer than the on-call and holiday window. Records carry headers with the cause. Ownership: the team that owns the consumer owns the DLT, with a dashboard and an alert on any message arriving for payments.
Replay is a tool, not an ad hoc script: it reads DLT records, filters by cause, republishes to the original topic (or a retry topic), and marks what was replayed.
I also set a rule: records in the DLT are failed *after* retries, so replay only after the cause is fixed, or they loop back.
Picture it The flow and the ownership table.
The setup: Topic payments, group ledger, DLT payments.ledger.DLT.
# illustrative output
payments --> ledger consumer --(retry 3x, 1 s)--> success
\--(still failing / not retryable)--> payments.ledger.DLT
payments.ledger.DLT --> alert (any message) --> engineer inspects --> fix --> replay tool --> paymentsMake the invisible visible: Topic definition and the replay filter.
kafka-topics.sh --bootstrap-server localhost:9092 --create --topic payments.ledger.DLT \
--partitions 3 --replication-factor 3 --config retention.ms=1814400000 # 21 days
# replay tool (sketch): read DLT, keep records whose exception header = SchemaMismatch, resend to paymentsWhy: A dead-letter topic is only useful with an alert, a retention that outlasts attention, and a safe way to put records back.
Land it I would name, size, alert on and own the DLT explicitly, and provide a replay tool, so failed records end up fixed, not forgotten.
- "What if the failure is a transient dependency outage?"
-
Then I do not let it reach the DLT at all, because an outage is not a bad record. It affects every record, and sending all of them to the DLT would empty the main flow into a bin.
The order of defence is this:
- Back off and pause: catch the dependency error, pause the partitions, keep calling
poll(), retry the dependency with growing delays and resume when it answers (Q69). - Retry topics for the leftovers: records that still fail go through delayed retry topics, with attempts spread over minutes.
- DLT last: only records that failed after those steps, which really look bad, are dead-lettered.
A circuit breaker helps by failing fast while the dependency is known to be down.
If I see a flood of records going into the DLT during an outage, I treat it as a design fault. The replay of 500,000 records afterwards, with the possibility of out-of-order effects, costs far more than a short pause would have.
- Back off and pause: catch the dependency error, pause the partitions, keep calling
- "Should the DLT have the same partition count?"
-
It does not need the same count, because DLT traffic is small, but there is one trap I would mention because it breaks DLTs in practice.
By default, Spring's
DeadLetterPublishingRecovererpublishes to the same partition number as the original record. If the source topic has 12 partitions and the DLT has 3, a failed record from partition 7 asks for partition 7 of the DLT, which does not exist, and the publish fails. The failure then happens inside the error handling itself, so the record is not parked and the original problem comes back.There are two safe answers:
- create the DLT with at least as many partitions as the source, which is the simplest option;
- give the recoverer a destination resolver that returns a fixed partition, or a negative number to let the producer choose.
I also set
auto.create.topics.enableexpectations carefully, and create the DLT in the same pipeline as the main topic, so the two are never out of step. - "Is the order of DLT records important?"
-
Usually the order within the DLT does not matter, but the order of processing the business sees does, and that is a decision, not a technical detail.
When a record is dead-lettered, the consumer commits past it and carries on, so later records for the same key are processed first. By the time the failed record is replayed, the key may have moved through several newer states. Replaying the old record then applies old information on top of new, which can be wrong.
There are three ways to deal with it:
- make handlers tolerant, with version checks that drop an event older than the stored state;
- replay in order per key, and skip records that a later event has already replaced;
- for strict streams, stop the partition instead and use blocking, bounded retries, so nothing overtakes the failed record.
Which one to use depends on the cost of an out-of-order update. For payments I lean towards version checks, because they are cheap and always on.
- "What about sensitive data in the DLT?"
-
It must be protected like the source topic, because it holds the same data. A dead letter is a full copy of the payload, often with a stack trace that adds internal details.
For a payments consumer, that can mean card references, amounts, and customer identifiers. If the main topic is limited by ACLs to the payments team, and the DLT is readable by every developer, the DLT becomes the easiest way to read the data.
My checklist for the DLT:
- the same ACLs as the source topic, for both reads and writes;
- the same encryption and retention rules, and the same masking if the platform masks fields;
- no sensitive values in exception messages, which are copied into headers;
- a retention that fits the data policy, because longer DLT retention means longer exposure.
I apply the same security class to the DLT as to the main topic, and I check it in the review of the consumer, because teams often forget that the DLT exists.
Q68. "What are non-blocking retry topics and what do they cost you?"
Reveal answer
Strong answer Instead of retrying a failed record in place (which blocks the partition), the consumer publishes it to a retry topic with a delay, such as orders-retry-5s, orders-retry-1m, and moves on. Separate consumers read the retry topics after the delay and try again. After the last retry, it goes to the DLT.
The gain: the main partition keeps flowing even when some records fail slowly. In Spring Kafka this is @RetryableTopic.
The cost: ordering is lost for failed records. A later record for the same key may be processed before the retried earlier one. If per-key order matters, non-blocking retries are unsafe for that data; use blocking retries with a bound, or design handlers to be order-tolerant.
There are also more topics, more consumers and more to monitor.
Picture it Main flow and retry chain.
The setup: Order event key order-9 fails on a flaky call.
# illustrative output
orders : [order-9 e1] fails -> send to orders-retry-5s, commit, continue with [order-9 e2]
orders-retry-5s : after 5 s -> try e1 again -> fails -> orders-retry-1m
orders-retry-1m : after 1 min -> try again -> fails -> orders-dlt
# e2 was processed BEFORE e1: order for key order-9 broken ❌ (if order matters)Make the invisible visible: Spring annotation.
@RetryableTopic(attempts = "4",
backoff = @Backoff(delay = 5000, multiplier = 3.0),
dltStrategy = DltStrategy.FAIL_ON_ERROR)
@KafkaListener(topics = "orders", groupId = "billing")
public void handle(OrderEvent e) { service.process(e); }
@DltHandler
public void dlt(OrderEvent e) { log.error("gave up on {}", e.orderId()); }Why: Blocking retries protect order and stall throughput. Non-blocking retries protect throughput and give up order. Pick by what the data needs.
Land it I use retry topics when throughput matters and order is not needed for the failing records, and I keep blocking, bounded retries when per-key order is required.
- "Can I keep order with retry topics?"
-
Only with extra work, and I say so openly because there is no free option here.
The trouble is that a record in a retry topic is out of the main flow. Later records for the same key are processed on the main topic while the retry waits for its delay. The retried record then arrives after them, and the order is broken.
To keep order, the consumer has to hold back every later record for a key that has one in retry. That means three pieces of work:
- Per-key state: a store that says "key K is waiting on a retry".
- Parking: later records for K go to a holding place, not to the handler.
- Release: when the retry succeeds or reaches the DLT, parked records are processed in order.
This is complex and has its own failure modes. Most teams therefore choose between blocking and ordered, or non-blocking and unordered, and I decide per topic from how much order matters.
- "How is the delay implemented?"
-
It is done with timestamps and the pause call, so no scheduler is needed.
The retry consumer reads a record from a retry topic such as
orders-retry-5s. It compares the record's timestamp plus the delay with the current time. If the time has not come yet, it pauses that partition and keeps polling, so it stays in the group, and when the due time is reached it resumes and processes the record. All records in a retry topic have the same delay, so they are in due-time order, and waiting for the first is enough.In Spring Kafka,
@RetryableTopicbuilds this for you: the default is three attempts with a 1 second delay, and it creates the retry topics and the.DLTtopic from the main topic's name.The accuracy is approximate. The actual delay is the requested one plus poll timing and any queue in front, so I treat "5 seconds" as "at least 5 seconds".
- "How many attempts are sensible?"
-
Three to five, with delays that grow. After that, more attempts rarely help, because a failure that survives several rising delays usually is not transient.
The growth matters as much as the count. Short first delays recover from a blip such as a deadlock or a failover. Longer later delays give a restarting dependency time to come back, without hammering it.
backoffruns offline# illustrative numbers attempt 1 after 5 s, attempt 2 after 30 s, attempt 3 after 5 min, then DLT (total about 5.5 min)I pick the total from the question "how long can this record wait before a person must look?" and I match it to the downtime of the dependencies I use, for example a database failover of about a minute.
Adding jitter, a little random variation, stops many consumers from retrying at the same second after an outage.
Spring's default for
@RetryableTopicis 3 attempts with a 1 second delay, which I usually change to match my own numbers. - "How does it interact with idempotency?"
-
A retry means the handler runs on a record it may have started already, so the handler must be idempotent. This is the main way retries and idempotency are linked.
Consider a handler that writes an order row, then calls a shipping service, and the shipping call times out. The first attempt created the row. The retry runs the handler from the beginning. Without protection, it inserts the row a second time.
With the idempotent consumer from Q65, the retry checks the event id, sees the row exists, and continues only with the missing step, or the whole handler is a safe upsert that gives the same result when repeated.
The design rule I follow is that every retry path, in place or through a retry topic, assumes "the previous attempt may have partly succeeded".
Without that, retries create duplicates, so the same care that makes a rebalance safe also makes retries safe. It is one idea reused in several places.
Q69 · Scenario. "Your consumer writes to a database, which goes down for 20 minutes. What should the consumer do?"
Reveal answer
Strong answer It should stop pulling more data than it can handle, back off, and resume when the database returns, without sending thousands of good records to the DLT. A database outage is a transient fault, not a bad record.
Practical behaviour: catch the dependency error, pause the partitions (consumer.pause(...)), keep calling poll() so the consumer stays in the group, retry the connection with exponential backoff, and resume() when it works. Do not commit offsets for records that failed.
Alternatively, let the exception propagate to a blocking retry with a long backoff, as long as the total pause stays under max.poll.interval.ms, or use a circuit breaker around the call.
Lag will grow for 20 minutes and then drain; that is expected, and the drain time is computable.
Picture it Pause and resume.
The setup: Database outage from 10:00 to 10:20; input 1,000 records per second; consumer capacity 3,000 per second.
try {
repo.saveAll(batch);
consumer.commitSync();
} catch (DataAccessResourceFailureException e) { // dependency down: transient
consumer.pause(consumer.assignment()); // stop fetching, stay in the group
resumeAt = Instant.now().plus(backoff.next()); // exponential backoff
consumer.seek(firstFailedOffsets); // re-read from the first uncommitted record
}
// each loop: poll() (returns nothing while paused, but keeps the group membership alive)
// when Instant.now() > resumeAt and a health probe passes: consumer.resume(consumer.assignment());Make the invisible visible: Recovery arithmetic.
# illustrative numbers
backlog after 20 min = 20 x 60 x 1,000 = 1,200,000 records
net drain rate = 3,000 - 1,000 = 2,000 per s
time to catch up = 1,200,000 / 2,000 = 600 s = 10 minutes after the database returnsWhy: The records are fine, the dependency is not. Pausing preserves the records and the group membership while the dependency heals.
Land it I would pause, back off and resume without committing failed work, and I would tell the business that the lag will clear in about ten minutes after recovery.
- "Why keep calling poll() while paused?"
-
Because a paused consumer is still a group member, and the group judges it by the same clocks. The poll interval does not stop for paused partitions.
When you call
pause(), the consumer stops fetching records for those partitions, butpoll()must still be called. Each call returns an empty result for paused partitions, and it also resets themax.poll.interval.mstimer and keeps the group state fresh.If the code instead sleeps for 20 minutes, no
poll()happens. After 5 minutes the client sees that the interval has passed, leaves the group, and the partitions move. Worse, after the database returns, the consumer's first commit fails because it no longer owns them.So the loop during an outage is small: poll, which returns nothing, check whether the dependency is healthy with backoff, and resume when it is. The loop keeps running while the work is paused, which is the whole point of the pause call.
- "How is this different from the DLT?"
-
The two failures are different in kind, and the dead-letter topic is for only one of them.
A DLT is for a record that is bad: its content breaks the handler no matter how often you try, such as invalid JSON or an unknown type. Moving it aside lets the rest of the stream go on.
A database outage is the opposite. The records are fine, and the world is broken. Every record fails for the same reason, and every one would succeed in 20 minutes.
Look at the numbers. At 3,000 records per second, 20 minutes is 3,600,000 records. Sending them all to the DLT would put 3.6 million good records into a place meant for exceptions. Someone would then have to replay them in a way that respects order, and the replay itself could overload the recovering database.
Pausing leaves the records safely in the main topic, in order, and the consumer simply resumes where it stopped.
- "What does a circuit breaker add?"
-
It makes the failure cheap. Without it, each record waits for a connection timeout before failing, and the consumer spends the whole outage doing slow useless work.
A circuit breaker watches calls to the dependency. After a number of failures it opens, and then calls fail immediately without touching the network. After a wait it lets one probe call through, and if that succeeds, it closes again.
The arithmetic shows why. With a 5 second timeout per call, a worker thread can finish only 12 failed calls per minute. For 3,000 records per second, you would need hundreds of threads sitting blocked, and memory and connection pools run out. An open breaker answers in microseconds.
It combines naturally with pause and resume. When the breaker opens, the consumer pauses the partitions. A timer or the half-open probe decides when to resume.
A library such as Resilience4j provides the breaker, and I tune its thresholds from real failure data.
- "Is there a risk of rebalance during the pause?"
-
Only if the consumer stops polling for longer than the poll limit. While it keeps calling
poll(), a pause causes no rebalance, because the group sees a healthy member.The risks during an outage are indirect:
- a blocking retry in the handler, such as a 10-minute sleep, stops polling and breaks the 5-minute limit;
- a pod restarted by a health check that looks at the dependency, which removes a member and triggers a rebalance in the middle of the incident;
- memory growth from a queue that keeps filling, ending in an out-of-memory crash.
Static membership with a session timeout longer than a restart adds tolerance for the second case. A bounded internal queue and the pause call handle the third.
So my first rule is that the poll loop must stay alive whatever happens to the dependency, and everything else is built around that rule. I also test it by switching the database off in staging and watching rebalance counts.
Q70 · Design. "Design a way to update a database and publish an event reliably, without losing either. Use Kafka."
Reveal answer
The real test Whether you reach for the outbox pattern instead of "write DB then send to Kafka and hope".
Strong answer I use the transactional outbox: in the same database transaction that updates the business tables, I insert a row in an outbox table describing the event. A separate process publishes outbox rows to Kafka and marks them sent. Either both the business change and the outbox row commit, or neither.
The publisher can be a polling relay or a CDC connector (Debezium) that reads the database's transaction log and emits the outbox rows to Kafka. CDC avoids polling load and keeps order by commit.
Delivery is at-least-once, because the relay may publish and crash before marking the row. Consumers must therefore be idempotent, using the event id from the outbox row (Q65).
This answers the "dual write" problem: you cannot atomically write to a database and Kafka with one commit, so you write once, to the database, and derive the Kafka message from it. See e07 #pat-outbox for the base pattern.
Picture it The write path and what each failure leaves behind.
The setup: Place an order: update orders, then publish OrderPlaced.
begin;
insert into orders(id, customer_id, status) values (:id, :cust, 'PLACED');
insert into outbox(event_id, aggregate_id, type, payload)
values (gen_random_uuid(), :id, 'OrderPlaced', :json);
commit; -- both rows, or neitherMake the invisible visible: Failure cases compared.
# illustrative output
WITHOUT OUTBOX (dual write)
db commit ok, Kafka send fails -> order exists, no event ❌
Kafka send ok, db rollback -> event exists, no order ❌
WITH OUTBOX
crash before commit -> nothing happened ✅
crash after commit -> relay/CDC publishes later ✅ (at-least-once; consumer dedupes by event_id)What you see: The only moment two systems are written is inside the relay, where a repeat is safe because the event has a stable id.
Why: A single source of truth removes the need for atomicity across two systems.
Land it I would write the event to an outbox table in the same transaction, publish it with CDC or a relay, and make consumers idempotent on the event id.
- "Polling relay or Debezium?"
-
I choose by size and latency, and I start with the simpler one.
A polling relay is a small job that selects unsent outbox rows, publishes them to Kafka, and marks them sent. Its costs are extra load on the database, a delay of up to one poll interval, and care about ordering when several relay instances run, because two instances can take rows in a different order.
Debezium reads the database's transaction log, so it adds almost no query load, sees changes at once and keeps commit order. The price is operating Kafka Connect, the connector, and its offset and schema handling, and the need for the database to expose its log.
A rough guide:
- a few hundred events per second and a delay of a second or two is acceptable: polling is fine;
- high volume, tight latency or many services doing it: use CDC.
I start with polling for a small system and move to CDC when the limits show.
- "How is ordering kept per aggregate?"
-
I use the aggregate's id as the Kafka key, so every event of one order goes to one partition, and a partition keeps its records in the order written.
The reasoning is the usual keyed-order rule. Records with the same key hash to the same partition (murmur2 of the key, modulo the partition count), and a single partition is read in order by one consumer. If the key were random, events of one order could land in different partitions and arrive out of order.
With CDC, the outbox event router transformation does this work. It reads the outbox row and sets the key from a column holding the aggregate id.
key from outboxruns offlinetransforms=outbox transforms.outbox.type=io.debezium.transforms.outbox.EventRouter transforms.outbox.table.field.event.key=aggregate_idThe order inside one aggregate follows the commit order in the log. Across aggregates there is no order promise, and I do not rely on one.
- "How do I clean the outbox table?"
-
I delete rows once they have been published and a safety period has passed. An outbox that grows forever slows inserts and the relay's queries.
There are two usual patterns, depending on the publisher:
- Polling relay: keep rows after they are marked sent for a short period, such as a day, to help debugging and replays, then delete them by age in small batches.
- CDC: the log already captured the insert, so the row itself is no longer needed. Many teams insert and delete in the same transaction, or delete right after, and Debezium still sees the insert in the log.
A size check makes the case. At 1 million events per day and 500 bytes per row, the table grows by about 500 MB per day. Without cleaning, in a month it is 15 GB of mostly dead rows.
A scheduled purge by age is simple and enough. I do it in chunks, so it does not hold locks for long and does not create a large vacuum or replication burst.
- "Could Kafka transactions replace the outbox?"
-
No. A Kafka transaction covers writes to Kafka, together with consumer offsets. A database write is outside its boundary.
The transaction coordinator is a Kafka broker. It can make several partition writes atomic, but it cannot ask a database to hold its commit in step. So a service that updates a table and publishes an event still has two separate writes, and a crash between them leaves one without the other.
The outbox removes the problem by changing it. There is only one write, to the database, and the event row is part of that same local transaction. The Kafka message is derived from that row afterwards. If the relay crashes, the row is still there and the message is sent later, at-least-once.
So the two tools do different jobs. Kafka transactions keep a consume-transform-produce loop consistent inside Kafka. The outbox joins a database commit and a Kafka message.
That is the sentence I would give an interviewer: transactions end at the edge of Kafka.
These questions test the newer and harder corners: queue semantics, replaying safely, fencing, key-ordered parallelism and a whole pipeline designed from the ends.
Q71. "What are share groups (KIP-932, Queues for Kafka) and how do they differ from consumer groups?"
Reveal answer
Strong answer A share group lets several consumers read from the same partitions at the same time, with each record handed to one consumer and acknowledged individually. It was production-ready in Kafka 4.2. It gives queue-like semantics on top of the log.
In a classic consumer group, a partition has one reader, offsets move forward as a single bookmark, and one slow record holds everything behind it. In a share group, the broker tracks the state of each record: available, acquired (locked by a consumer for a time), acknowledged, or released for redelivery.
A consumer acknowledges each record with ACCEPT (done), RELEASE (give it back to be retried) or REJECT (unprocessable, archive it). Version 4.2 added RENEW, which extends the lock on a record that needs more time.
The trade-off: no ordering guarantee across a partition, because records can be processed by different consumers out of order. Use share groups for independent tasks and classic groups where order matters.
Picture it Two consumers sharing one partition.
The setup: Partition with records r1 to r4 and two members in a share group; r2 is slow.
# illustrative output
record state held by
r1 ACKNOWLEDGED C1 (ACCEPT)
r2 ACQUIRED C2 (processing, lock timer running)
r3 ACKNOWLEDGED C1 (ACCEPT)
r4 AVAILABLE - (next to be handed out)
# C1 keeps working while C2 is slow: no head-of-line blockingMake the invisible visible: The consumer API shape, in outline.
// outline only: names follow KIP-932 (KafkaShareConsumer); check the exact API for your client version
try (KafkaShareConsumer<String, Task> c = new KafkaShareConsumer<>(props)) {
c.subscribe(List.of("tasks"));
while (running) {
for (ConsumerRecord<String, Task> r : c.poll(Duration.ofMillis(500))) {
try { run(r.value()); c.acknowledge(r, AcknowledgeType.ACCEPT); }
catch (TransientException e) { c.acknowledge(r, AcknowledgeType.RELEASE); }
catch (Exception e) { c.acknowledge(r, AcknowledgeType.REJECT); }
}
c.commitSync();
}
}Why: Per-record state is what a work queue needs, and a single bookmark cannot express it. The broker now keeps that state.
Land it I would use share groups for independent tasks with many workers and a need for per-record retry, and keep classic groups where per-key order is the requirement.
- "What about ordering in a share group?"
-
There is none across the partition, and that is the main thing you give up. Order within a partition is the one guarantee of a classic group, and a share group trades it away.
In a classic group, one consumer reads a partition, so records come out in offset order. In a share group, several consumers hold records from the same partition at once. Consumer A may hold offsets 10 to 19 and consumer B 20 to 29, and B may finish first. A record that is released and redelivered also comes back later than newer ones.
Here is how I decide:
- tasks are independent, such as resize an image or send an email: share group;
- events for one key must be applied in sequence, such as account balance changes: classic group;
- order matters only for some records: classic group, or put those on a separate topic.
This is the main selection criterion, and I state it before talking about the benefits, so nobody thinks share groups replace ordered consumption.
- "How does a share group handle a consumer that dies?"
-
The broker takes the record back after a timer, and gives it to someone else.
When a consumer fetches a record from a share group, the broker marks it acquired and starts an acquisition lock with a time limit. If the consumer acknowledges the record before the lock ends, it is finished. If the consumer dies, hangs, or simply takes too long, the lock expires, and the record becomes available again for another consumer.
A delivery count limit protects against endless loops. A record that keeps timing out or being released is counted, and after the limit is reached the broker stops delivering it and marks it archived, so one bad record cannot circulate forever.
The consumer can say what it wants for each record: ACCEPT, RELEASE (retry it) or REJECT (unprocessable). Since 4.2 it can also RENEW, to ask for more time on a slow record.
The timeouts and the delivery limit are broker or group settings, so I would read the 4.2 documentation for exact names and values.
- "Is it a replacement for RabbitMQ or SQS?"
-
For simple work queues, it can replace them, and for rich messaging features I would check carefully first.
The attraction is queue behaviour in a system the team already runs: many workers on a few partitions, per-record acknowledgement, retry through release and a delivery limit, without a second broker to monitor, secure and upgrade.
What a mature queue broker has had for years is the extras. I would check the following list against my needs:
- delayed or scheduled delivery of individual messages;
- priorities between messages;
- a built-in dead-letter route and tools to inspect and redrive it;
- routing rules, such as exchanges or topics with filters.
The feature is new, production-ready since 4.2, and I hedge accordingly: client support and the feature list have been growing, so I read the current documentation, not older articles.
My position is that for a team already on Kafka with simple independent tasks, it removes a system. For complex routing, I would not force it.
- "How do I choose between 200 workers on 12 partitions via share group, or more partitions?"
-
I choose by what the real limit is. Both approaches reach 200 workers, but at different costs.
With a classic group, parallelism cannot exceed the partition count (Q42). To use 200 workers you need at least 200 partitions. With a share group, 200 consumers can all read the same 12 partitions, so worker count is no longer tied to partitions.
comparisonruns offline# illustrative output classic group, 12 partitions : max 12 workers classic group, 200 partitions: 200 workers, but 200 partitions x RF 3 = 600 replicas to run share group, 12 partitions : 200 workers, per-record ack, no per-key orderMore partitions also change key placement, so ordered data is disturbed. The price of the share group is that per-key order is gone.
So if order matters, I raise partitions or isolate slow work. If tasks are independent and slow work is the problem, the share group is the direct fit.
Q72 · Scenario. "You have a task topic with 12 partitions, 200 workers wanted, and a few tasks take 10 minutes while most take 50 ms. Classic consumers keep falling behind. What now?"
Reveal answer
Strong answer The slow tasks block the partition behind them, and the poll interval limit is under pressure. The three fixes in order of change size: isolate slow tasks by routing them to a separate topic and group; use pause/resume or a worker pool so polling continues during long tasks; or use a share group so per-record acknowledgement removes the head-of-line blocking.
Routing is easy to reason about: the producer or a first-stage consumer tags tasks as slow or fast, and sends slow ones to tasks-slow with its own consumers and its own max.poll.interval.ms. Fast tasks never wait behind slow ones.
If tasks are independent, the share group is the most direct fit. If they carry per-key order, classic groups with isolation remain the safe choice.
I would measure the task time distribution first, not guess which are slow.
Picture it The distribution and the isolation.
The setup: 10,000 tasks: 9,900 take 50 ms, 100 take 10 minutes.
# illustrative numbers
one lane : 100 slow x 600 s = 60,000 s of blocking spread over 12 partitions = 5,000 s per partition ❌ fast tasks wait up to 83 minutes
two lanes : tasks-fast: 9,900 x 0.05 s = 495 s total, done in seconds across 12 consumers
tasks-slow: 100 x 600 s = 60,000 s / 20 slow workers = 3,000 s (50 minutes), not blocking fast workMake the invisible visible: Routing in the producer.
String topic = task.estimatedSeconds() > 30 ? "tasks-slow" : "tasks-fast";
producer.send(new ProducerRecord<>(topic, task.id(), task));
// tasks-slow consumers: max.poll.records=1, max.poll.interval.ms=1800000Why: Waiting behind slow work is a property of one lane. Separate lanes keep the cheap work cheap.
Land it I would split slow and fast tasks into separate topics or move to a share group, depending on whether per-key order matters.
- "What if I cannot predict which task is slow?"
-
Then I stop trying to predict, and use mechanisms that do not need a prediction.
The cleanest is a share group. Every record is acknowledged on its own, so a slow task holds only itself, and the next record goes to another worker. Nothing needs to know in advance which task is slow.
The second is a worker with a timeout inside a classic consumer. The consumer hands each task to a worker pool and waits up to a limit, such as 2 seconds. If the task is not done, the consumer copies it to a slow-lane topic and moves on, and a dedicated group handles it with a larger poll interval.
The third is history. Even if a single task is unpredictable, the task type often is not: "generate report" is slow and "update status" is fast. Routing by type at the producer needs no runtime guess.
The unpredictable duration is the strongest argument for per-record acknowledgement, and I say so, since it removes the head-of-line blocking at its source.
- "What should the slow consumers be configured with?"
-
For the slow lane, I tune for few records per poll and a generous time limit, or I keep polling while a worker runs.
- One record at a time:
max.poll.records=1, so a single poll never takes more than one 10-minute task. - A long poll interval:
max.poll.interval.msabove the maximum task time, for example 15 minutes for a 10-minute task, so the consumer is not removed from the group. - Or pause and a worker: pause the partition, run the task in a worker thread, keep calling
poll(), then commit and resume.
The aim is that polling never stops for longer than the poll interval, while the heartbeat thread keeps the session alive.
Raising the interval weakens failure detection for that group only, which is an acceptable trade because it holds only slow tasks. The fast lane keeps its default of 5 minutes, so a hung fast consumer is still found quickly. That is one more benefit of separating the two kinds of work.
- One record at a time:
- "How do I avoid tasks being done twice when a consumer is evicted mid-task?"
-
I make a second run harmless, because I cannot stop it from happening. An evicted consumer loses its partition, the new owner starts from the last commit, and the task runs again from the start.
There are two protections, and they can be combined:
- Idempotent task: the result is written with the task id as a key, so a second run overwrites the first with the same content, or is skipped when the result already exists.
- Lease: before starting, the consumer inserts or updates a row in a database: task id, owner, expiry. A second consumer that sees an unexpired lease owned by someone else waits or skips.
The lease needs care. It should be renewed while the task runs, as a heartbeat, so a 10-minute task does not lose its lease at minute 5.
The rule behind all of it is that a task which can be interrupted must be safe to repeat.
- "How do I report progress on a ten-minute task?"
-
I keep progress outside Kafka, in a store keyed by the task id, because offsets cannot express it.
An offset only says "this record was consumed". It says nothing about how far into the 10-minute task the worker is. Committing the offset early to show progress would make the task look done and lose it on a crash. Committing it late leaves no progress information at all.
A small status table does the job well:
- Create: when the task starts, insert a row with the task id, status "running", and a start time.
- Update: the worker writes a percentage or a step name every few seconds.
- Finish: the status becomes "done" or "failed", with a result location.
Users or dashboards read the table, not Kafka. A status topic works too if consumers only need a stream of updates.
The offset commit stays what it should be: the mark that says the request was fully handled. The two have different meanings, so I keep them separate.
Q73 · Scenario. "A bug in the consumer corrupted data for the last 24 hours. You fixed the bug and need to reprocess. How do you do it safely?"
Reveal answer
Strong answer First confirm the log still holds 24 hours (retention). Then decide how the effects are undone: if the handler is an idempotent upsert, reprocessing overwrites bad data with good; if it appended or sent things, you need compensation or cleanup first.
Mechanically: deploy the fixed code, stop the group, reset offsets to a time 24 hours ago with the groups tool (use --dry-run first), then start the group. Watch downstream systems for load, because the replay may run much faster than live traffic.
Alternatively run the replay in a separate group id into a shadow table, verify it, and swap, which avoids overwriting live data while testing.
Throttle if downstream cannot take it, and tell consumers of downstream topics that duplicates are coming.
Picture it The command sequence.
The setup: Group ledger, topic payments, bug window 24 hours.
# 1. stop the group (scale to 0), then:
kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group ledger --topic payments \
--reset-offsets --to-datetime 2026-11-18T09:00:00.000 --dry-run
# illustrative output
TOPIC PARTITION NEW-OFFSET
payments 0 5,402,110
payments 1 5,398,764
# 2. same command with --execute, 3. start the fixed consumersMake the invisible visible: The risk to check beforehand.
# illustrative output
log start offset vs requested time: log starts 2026-11-12 -> 24 h is available ✅
handler idempotent (upsert by payment_id) ✅
downstream: emails sent per event? ❌ would resend -> suppress during replay
replay volume: 24 h x 20,000/s = 1.7 billion records at ~60,000/s = about 8 hours (plan capacity)Why: Replay is Kafka's superpower, but only if the consumer's effects can be repeated safely.
Land it I would check retention and idempotency first, dry-run the offset reset, and suppress non-repeatable side effects during the replay.
- "Why use a separate group for the replay?"
-
Because a separate group gives me a replay that cannot damage the live system, and I can check its result before it replaces anything.
The live group keeps its own committed offsets and goes on processing new records. The replay group, with a different
group.id, starts at the time I choose and has its own offsets. They never touch each other's progress.The replay writes to a shadow target, such as a new table. When it has caught up, I compare it with the live data, for example by counts and checksums on a sample, and look for differences I expected. If it is right, I swap the tables, or point the application at the new one. If it is wrong, I drop the shadow and nothing live changed.
The cost is double the work and a swap step for records that arrived meanwhile.
For a bug that touched 24 hours of money-related data, I accept those costs.
- "How do I replay only a subset, such as one customer?"
-
I read the time range with a small consumer that I control, and filter by key in my own code, because the broker cannot filter by key.
A Kafka fetch returns whole records in offset order. There is no "give me only key C-1042" request, and no index by key. So the technique is a scan.
- Assign: use
assignfor the partitions of interest, notsubscribe, so no group rebalancing is involved. - Seek: find the starting offsets with
offsetsForTimesfor the time 24 hours ago, thenseekto them. - Filter: read, skip records whose key does not match, and apply or republish the rest.
If I know the key, I can compute its partition with the same hash as the producer, murmur2 of the key modulo the partition count, and read only that one partition. That cuts the scan to a fraction.
It is still a scan, but a cheap one compared with a full replay.
- Assign: use
- "What if retention is already shorter than the bug window?"
-
Then Kafka alone cannot help, and I need another copy of the data. That is a sad moment, so I would rather prepare for it.
The possible sources, in the order I would check them:
- Tiered storage: if enabled (GA since 3.9), old segments live in object storage and the topic may hold much more history than local disks suggest (Q15);
- A sink copy: a Connect sink that writes the topic to object storage or a warehouse, which is the best protection and costs little;
- The upstream system: the database or service that produced the events, if it can regenerate them;
- Backups: a database backup from before the bug, and then replay only the newer events.
If none exists, I can only repair forward, correcting the data from other facts.
After the incident, I would add the sink, or raise retention for the topic, so the next replay is possible. Retention should be longer than the time it takes to find and fix a bug, including weekends.
- "How do I avoid overloading downstream during replay?"
-
I throttle the replay, because it will run much faster than live traffic, and downstream systems are sized for live traffic.
A consumer can read hundreds of thousands of records per second from the log. If each record causes a database write, the database sees a flood it never saw before. The ways to slow it down:
- lower
max.poll.recordsand add a pause between batches; - run fewer consumers for the replay group;
- add a rate limiter in the handler, as in the code below.
rate limitruns offline// illustrative RateLimiter limiter = RateLimiter.create(5_000); // 5,000 records/s during replay for (ConsumerRecord<String, Payment> r : batch) { limiter.acquire(); handle(r); }At 5,000 per second, 24 hours of 1,000 per second traffic (86.4 million records) takes about 4.8 hours. I slow down if downstream latency rises.
- lower
Q74 · Scenario. "A consumer sometimes needs 15 minutes for a single record (a report), but max.poll.interval.ms is 5 minutes. How do you handle it without being evicted?"
Reveal answer
Strong answer Keep the poll loop alive while the work runs elsewhere. Pause the partition, hand the record to a worker thread, and keep calling poll() (which returns nothing for paused partitions but keeps the consumer alive). When the worker finishes, commit the offset and resume.
The other route is to raise max.poll.interval.ms above 15 minutes and set max.poll.records=1. It is simpler, but it weakens failure detection: a truly hung consumer holds its partition for that long.
A third route is to not do long work in a consumer at all: the consumer accepts the request, records a job in a database or job queue, and acknowledges; a worker system runs the job.
I choose pause-and-worker when jobs are long and unpredictable, and the job-table route when they are very long or need status and retries.
Picture it The pause and resume loop.
The setup: A report job takes 15 minutes. Poll interval limit 5 minutes.
ConsumerRecords<String, Job> batch = consumer.poll(Duration.ofMillis(500));
for (ConsumerRecord<String, Job> r : batch) {
TopicPartition tp = new TopicPartition(r.topic(), r.partition());
consumer.pause(List.of(tp)); // stop fetching more for this partition
running.put(tp, executor.submit(() -> runReport(r.value())));
pendingOffset.put(tp, r.offset() + 1);
}
// every loop iteration, still calling poll() above, check for finished work:
running.forEach((tp, f) -> { if (f.isDone()) {
consumer.commitSync(Map.of(tp, new OffsetAndMetadata(pendingOffset.get(tp))));
consumer.resume(List.of(tp)); running.remove(tp);
}});Make the invisible visible: Why the consumer stays alive.
# illustrative output
t=0 poll -> job record, pause partition, worker starts
t=0.5s poll returns nothing (paused) -> poll interval clock resets
... poll every 500 ms for 15 minutes -> heartbeats and poll clock fine
t=15m worker done -> commit offset, resume partition ✅ no evictionWhy: The coordinator only needs to see poll() calls, not finished work. Pause stops new data while keeping the lease alive.
Land it I would pause the partition, process in a worker, keep polling, and commit when the work is done, and for very long jobs move to a job table.
- "What happens if the consumer crashes during the 15-minute job?"
-
The job is lost and repeated from the start by whoever gets the partition, because the offset was never committed. For a 15-minute job, that costs 15 minutes again, and it can happen more than once.
I reduce the damage with three things:
- Checkpoints: the job writes its progress to a store every minute or so, for example "processed 40,000 of 100,000 rows", and a new owner resumes from there.
- Idempotent steps: each step can be repeated without harm, so a half-finished run does not corrupt results.
- A lease: the owner record carries an expiry, so the new owner knows whether the old one is still working.
Without these, a crash costs the full job time, and a crash loop, for example from a bad record in the middle, can keep a partition busy and never finish.
The offset is committed only after the job is completely done, since it is the only thing that says "this request is handled".
- "What if a rebalance revokes the partition during the job?"
-
I use the revoke callback to stop cleanly, and I never commit for a partition I no longer own.
When a rebalance takes the partition away,
onPartitionsRevokedis called. At that point the code has two options. It can cancel the job and let the new owner start again, or let the job finish and discard the result if the work is no longer needed. In both cases, it must not commit for that partition, because the commit would fail or, worse, cause confusion.The new owner starts at the last committed offset, so it begins the same job. If the old job is still running, two runs write results at once. A lease or an idempotent write with the task id as the key makes sure only one result counts.
With cooperative rebalancing, my partition stays with me unless it must move, so a long job is less likely to be disturbed by a new member joining.
- "Why not just use a thread pool and keep polling without pause?"
-
Without pause,
poll()keeps handing back new records from the same partition while the first one is still running. That causes two problems.First, order. Records 2, 3 and 4 of the partition are now being handled in parallel with record 1, so they may finish earlier or later, and any order within the partition is gone.
Second, commits. Kafka stores one offset per partition. If record 3 finishes first, committing offset 4 would claim record 1 and 2 are done as well, and a crash would lose them. Tracking which ones are really complete needs extra bookkeeping.
Pause gives a clear rule: one job per partition at a time. The consumer pauses the partition when it hands out the job, keeps polling for liveness, and resumes when the job ends and the offset is committed. Other partitions of the same consumer can still run their own jobs, so I still get parallelism across partitions.
In short, pause is the throttle that keeps the model simple.
- "When is the job-table design better?"
-
When the jobs have a life of their own: status, progress, cancellation, retries with backoff, and users who want to see them.
Kafka is good at carrying a request, and bad at holding state about each job. It has no way to update one record, no query by job id, and no per-job retry timer. A table has all of these.
The design then splits in two. The consumer is short: it reads the request, inserts a job row with status "queued", commits the offset, and goes back to polling. Separate workers claim queued rows, run them, update progress and mark them done or failed. A failed job with attempts left is requeued with a delay.
job tableruns offlinecreate table jobs (id text primary key, status text, progress int, started_at timestamptz, result_url text);The poll loop never blocks, the consumer keeps its default timeouts, and a job lasting an hour is no problem. I choose it when jobs are very long or users ask "where is my report".
Q75. "Explain consumer-side backpressure. How do pause() and resume() help?"
Reveal answer
Strong answer Backpressure means slowing intake when downstream cannot keep up. A Kafka consumer pulls data, so it controls its own rate: it simply polls less or not at all. pause() stops fetching from chosen partitions without leaving the group, and resume() starts again.
The typical use: an internal queue between the poll thread and workers fills up. When it reaches a high mark, pause; when it falls below a low mark, resume. That keeps memory bounded and lets the poll loop continue so the consumer stays in the group.
Without backpressure, a fast poll loop and slow workers cause unbounded memory growth and eventually an out-of-memory crash, which causes a rebalance and repeat processing.
Settings that also limit intake: max.poll.records, fetch.max.bytes and max.partition.fetch.bytes.
Picture it A bounded queue with high and low water marks.
The setup: Queue capacity 1,000; pause at 800, resume at 200.
# illustrative output
queue size action
800 pause all assigned partitions (poll keeps running, returns nothing)
...workers drain...
200 resume partitions
# memory is bounded: at most about 800 + one poll batch records in memoryMake the invisible visible: The loop.
ConsumerRecords<String, Msg> batch = consumer.poll(Duration.ofMillis(200));
batch.forEach(queue::add);
if (!paused && queue.size() >= 800) { consumer.pause(consumer.assignment()); paused = true; }
if (paused && queue.size() <= 200) { consumer.resume(consumer.assignment()); paused = false; }Why: A pull-based consumer can apply pressure back to the log for free: the records just wait there, safely, until it is ready.
Land it I would bound the in-memory queue and use pause and resume with two thresholds, so a slow downstream slows the consumer instead of crashing it.
- "Why two thresholds rather than one?"
-
With one threshold, the consumer would flap. It would pause at the limit and resume one record later, and repeat that all the time.
Say the queue limit is 1,000 items. At 1,000 the consumer pauses. The workers finish one item, the queue is at 999, and the single rule "resume below the limit" resumes it. A poll then returns up to 500 records, and the queue is over the limit again, so it pauses again.
Two thresholds avoid this. I pause at a high mark such as 1,000, and I resume only when the queue has fallen to a low mark such as 400. The gap gives the workers a long stretch of work between pauses, and the consumer fetches in larger, more efficient batches.
It is the same idea as hysteresis in a thermostat.
- "Does Spring Kafka support it?"
-
Yes. The listener container has
pause()andresume(), and I use that API instead of the raw consumer, because the container owns the poll thread and the consumer is not thread-safe.Calling
consumer.pause()from another thread is unsafe.For dependency failures, Spring Kafka offers back-off handling that pauses the container between retries, so a failing record does not sit inside a long sleep that breaks the poll limit. For backpressure from a bounded queue, I call pause when it is full and resume when it drains, as in the code of Part B.
Some points I check for my version:
- whether the pause applies to all partitions or to one;
- how the container behaves across a rebalance, because assignments change;
The container API is what I would use in a Spring service.
- "Where does pressure go when the consumer pauses?"
-
It goes into lag, which means it stays in Kafka. That is the intended buffer, and the log is built to hold it cheaply on disk.
This is why lag is not automatically bad. When the downstream database is slow for 10 minutes, and the consumer pauses, producers keep writing and lag grows. When the database recovers, the consumer resumes, and lag drains.
An alert that fires on lag above a fixed number would fire for this healthy episode. A better alert looks at the direction and the age:
- lag growing for longer than expected (for example 15 minutes);
- the age of the oldest unprocessed record above the business limit;
- the consumption rate at zero while the group is supposedly running.
That is the same reasoning as in Q50. Backpressure moves the queue from memory, where it is dangerous, to disk, where it is cheap, and lag measures how much waits there.
The limit is retention: if lag outlasts the topic's retention, records are deleted unread.
- "What if memory is still a problem with big records?"
-
Then I shrink what one poll can bring in, since memory is a product of fetch settings and partition count.
In the worst case a consumer can hold about
max.partition.fetch.bytesfor every partition it owns, in one fetch round, and up tofetch.max.bytesin total for a fetch response.memory boundruns offline# illustrative numbers max.partition.fetch.bytes 1 MB x 12 assigned partitions = at most 12 MB per fetch roundThe steps I take are:
- Lower the fetch limits: smaller
max.partition.fetch.bytesandfetch.max.bytes. - Lower the batch: smaller
max.poll.records, so fewer parsed objects live at once. - Bound the queue: count it in bytes, not only in items, if sizes vary a lot.
Large records make these limits matter, because the client must hold at least one whole record. I check heap use under load, not only in theory.
- Lower the fetch limits: smaller
Q76 · Scenario. "You run a transactional consume-transform-produce service. After a pod hang and restart, both the old and new instances seem to be alive and writing. What protects you?"
Reveal answer
Strong answer Zombie fencing with the transactional.id and the producer epoch. When the new instance calls initTransactions(), the transaction coordinator bumps the epoch for that transactional id and aborts any open transaction of the old one. The old instance's next write carries the old epoch and is rejected with ProducerFencedException.
So two instances cannot both commit under the same transactional id. The old one must treat the fencing error as fatal: close the producer and stop.
On the consumer side, the group's generation id is also checked when offsets are sent in the transaction (sendOffsetsToTransaction with groupMetadata()), so a consumer that lost its partitions in a rebalance cannot commit offsets for them.
The design rule: the transactional id must be stable per logical worker (for example tied to the input partition, or to the stable pod name), not random per start, or fencing cannot work.
Picture it The epoch bump.
The setup: Instance A uses transactional.id=enricher-3, epoch 4, and hangs. Instance B starts with the same id.
# illustrative output
A: initTransactions -> epoch 4 ... hangs
B: initTransactions -> coordinator bumps epoch to 5, aborts A's open transaction
A wakes up: send(...) with epoch 4 -> ProducerFencedException ✅ A cannot write
B: runs normally with epoch 5Make the invisible visible: What A must do.
try {
producer.commitTransaction();
} catch (ProducerFencedException | OutOfOrderSequenceException | AuthorizationException e) {
producer.close(); // fatal: do NOT abort and continue; this instance is a zombie
throw e; // let the pod restart
} catch (KafkaException e) {
producer.abortTransaction(); // recoverable: abort and retry the batch
}Why: The id plus epoch is a lease: the newest holder wins, and older holders are refused at the broker.
Land it I would use a stable transactional id per worker, treat ProducerFenced as fatal, and rely on the epoch to stop a zombie from writing.
- "What should the transactional id be in Kubernetes?"
Use a stable name per logical worker, not a random one. In a StatefulSet the pods are called
orders-worker-0,orders-worker-1and so on, and a restarted pod keeps its name, so the pod name makes a good transactional id. In a plain Deployment the pod names change on every restart, so there I would build the id from something fixed, such as a configured worker number or the input partition the worker owns.The reason is how the broker remembers. It keeps one epoch counter per transactional id. A replacement pod that starts with the same id bumps the counter, and the hung pod's next write carries the old number and is refused. A random UUID per start gives the new pod a fresh id, so nothing is bumped and nothing is fenced.
In Spring the setting is
transaction-id-prefix. I give it a value that is the same across restarts of one logical worker and different between workers that run at the same time.- "Does the consumer need anything?"
Yes. The consumer must pass
consumer.groupMetadata()tosendOffsetsToTransaction, not just a group id string. That object carries the group id, the member id and the generation number, which is a counter that goes up on every rebalance.The broker compares that generation with the group's current one when it handles the offset commit. If a rebalance moved the partition to another member while this instance was hung, the old generation is out of date and the commit is refused.
A worked case: pod A owns partition 2 at generation 7 and hangs. A rebalance gives partition 2 to pod B at generation 8. Pod A wakes up and tries to commit offset 5001 for partition 2 at generation 7. The broker rejects it, so A cannot overwrite B's progress.
The producer epoch protects the output topic and the generation check protects the input offsets. I want both, because a zombie could do damage on either side. When either error appears, I treat it as fatal for that instance.
- "What if I see ProducerFencedException in a healthy deployment?"
It means the broker has already moved on from that producer. In a healthy-looking deployment I look for three causes.
- Shared id: two live instances use the same transactional id, for example a hard-coded id in a config file copied to every pod. Each
initTransactions()fences the other, and they take turns failing. - Timeout: a transaction ran longer than
transaction.timeout.ms(default 60 seconds). The coordinator aborted it and bumped the epoch, so the next call is fenced even though no second instance exists. A long GC pause or a slow downstream call inside the transaction causes this. - Restart overlap: a rolling update started the new pod before the old one stopped. That is fencing doing its job, not a fault.
My check is to list the transactional id per pod in the logs and compare transaction duration with the timeout. The fenced instance should close its producer and exit, not retry.
- Shared id: two live instances use the same transactional id, for example a hard-coded id in a config file copied to every pod. Each
- "Does idempotence alone fence zombies?"
No. Idempotence and fencing are related, but they protect against different things.
The idempotent producer gets a producer id from the broker and numbers each record per partition with a sequence number. If a retry sends the same record twice, the broker sees the repeated sequence and drops the copy. That removes duplicates caused by network retries, but only inside one producer session. If the process dies and a new one starts, it gets a new producer id and a fresh sequence, so the broker cannot tell that it replaces the old one.
A transactional id adds the missing link. It ties the old and new sessions together, and the epoch lets the broker refuse the old one. Setting
transactional.idturns idempotence on as well, which is why the two feel like one feature.So for a hung pod that wakes up and writes, idempotence does nothing. I need the transactional id plus the epoch.
Q77 · Design. "Design a consumer that processes records in parallel threads but preserves per-key order and commits offsets safely."
Reveal answer
Strong answer One consumer thread polls and commits. It routes each record to a worker chosen by hash of the key, so one key always lands on the same single-threaded worker. Per-key order holds because each worker handles its queue in sequence.
For commits, track per partition the highest offset such that every record below it is done (a contiguous watermark). Commit that value, not the highest finished offset, because workers finish out of order.
Backpressure: bounded worker queues with pause/resume (Q75). Rebalance: on revoke, wait for in-flight work of those partitions, commit their watermark and drop their queued records.
Cost: complexity. If a simple one-thread-per-partition design meets the throughput goal, I would not build this.
Picture it Routing and the commit watermark.
The setup: Partition 0 offsets 10 to 14; workers W0 and W1; keys A, B hash to W0, W1.
# illustrative output
offset key worker status
10 A W0 done
11 B W1 done
12 A W0 running <- blocks the watermark
13 B W1 done
14 B W1 done
watermark = 12 (everything below 12 is done) -> commit offset 12
# do NOT commit 15 even though 13 and 14 finished: a crash would lose offset 12Make the invisible visible: Core code.
class PartitionTracker {
private final TreeSet<Long> done = new TreeSet<>();
private long nextToCommit; // lowest offset not yet known done
PartitionTracker(long first) { this.nextToCommit = first; }
synchronized void markDone(long offset) {
done.add(offset);
while (done.remove(nextToCommit)) { nextToCommit++; } // advance over contiguous finished offsets
}
synchronized long committable() { return nextToCommit; } // value to commit
}Why: Parallelism makes completion order differ from log order, so the commit point must be computed, not assumed.
Land it I would hash keys to single-threaded workers for ordering, track a contiguous per-partition watermark for commits, and bound queues with pause and resume.
- "What happens on a rebalance?"
The risk on a rebalance is that a partition moves to a new owner while my workers are still busy with its records. I handle it in the revoke callback, in this order.
- Stop feeding: in
onPartitionsRevokedI stop routing new records from those partitions to the workers. - Drain: I wait, with a time limit, for the in-flight records of those partitions to finish, then compute the contiguous watermark and commit it.
- Drop: I discard records still waiting in worker queues and delete the tracking state for those partitions.
The dropped records are safe to throw away because they were never committed. The new owner starts at the committed offset and reads them again.
The wait must stay shorter than the rebalance timeout, or the member is removed anyway. If a record cannot finish in time, I accept that it may run twice, once here and once on the new owner, which is why the handlers must be idempotent. With cooperative rebalancing, only the partitions that move go through this path.
- Stop feeding: in
- "Does this give exactly-once?"
No, it gives at-least-once. The watermark only moves past records that are all finished, and it is saved after the work, so a crash always leaves a gap between what was done and what was committed.
A worked example: workers finish offsets 100 to 104, but offset 99 is still running, so the watermark is stuck at 99. The consumer crashes. On restart it begins at offset 99, and records 100 to 104, which were already processed, run again. The slower the slowest record, the bigger the repeat window.
The side effects of a handler can therefore happen twice, so I make the handler idempotent: a unique event id in a table, an upsert instead of an insert, or an idempotency key sent to an outside service.
Kafka transactions give exactly-once only for Kafka-to-Kafka work, and they are awkward with a worker pool. So the honest claim is at-least-once delivery plus idempotent handling, which gives an effect that happens once.
- "Is there a library for it?"
Yes, but I would treat it as a candidate to evaluate, not an automatic answer. Confluent's Parallel Consumer is the best-known open-source one. It lets you choose an ordering mode: by key, by partition, or unordered. It also tracks which offsets are done.
The part I do not want to write myself is the offset bookkeeping. Kafka stores one committed number per partition, but parallel workers finish out of order. So a library has to remember the gaps, for example by storing the set of finished offsets next to the commit, so that a restart does not repeat everything. It also has to cope with rebalances, retries and shutdown. These are the edge cases that cause real bugs.
Before adopting it I would check four things: when it last released, whether it supports the Kafka client version I run, how it behaves on a rebalance, and whether its tests cover failures. If it is not maintained, I would build the small design myself.
- "Where does this design fail?"
It fails in three places. The first is a hot key. All records of one key go to one worker, so if one customer sends 40% of the traffic, that worker is the ceiling and the other workers sit idle. Adding workers does not help that key.
The second is a shared bottleneck behind the workers: one database row, a lock, a rate-limited API or a small connection pool. The workers all wait on the same thing, so in practice they run one at a time.
speedup limitruns offline# illustrative numbers 8 workers, 40 ms each = ideal 200 records/s but all workers update the same DB row (lock) -> effective 25 records/s (no gain)The third is a stuck record. It blocks every later record of the same key in that worker, and it holds the watermark back, so commits stall and a crash would repeat a lot of work. Before building this, I would measure where the time goes. If handlers wait on one shared resource, more threads only add complexity, and the fix is on that resource.
Q78. "Which consumer fetch settings affect throughput and latency, and how would you tune them?"
Reveal answer
Strong answer fetch.min.bytes (default 1): the broker waits until at least this much data is ready. fetch.max.wait.ms (default 500): the longest the broker waits for fetch.min.bytes. max.partition.fetch.bytes (default 1 MB) and fetch.max.bytes (default 50 MB): size limits per partition and per request. max.poll.records (default 500): how many records one poll() returns to your code.
For lower latency, keep fetch.min.bytes at 1. For throughput on a busy topic, raise it (for example 64 KB to 1 MB) so each fetch returns more data, and accept up to fetch.max.wait.ms extra delay when traffic is light.
For backfills reading old data, raise max.partition.fetch.bytes so each fetch pulls larger chunks.
max.poll.records controls how much work each loop iteration must finish in time (Q53), so it relates to the poll interval, not to network efficiency.
Picture it Two profiles.
The setup: A real-time alerting consumer and a nightly backfill consumer.
# real-time: lowest latency
fetch.min.bytes=1
fetch.max.wait.ms=50
max.poll.records=100
# backfill: highest throughput
fetch.min.bytes=1048576
fetch.max.wait.ms=500
max.partition.fetch.bytes=4194304
max.poll.records=2000Make the invisible visible: Effect in illustrative numbers.
# illustrative numbers
real-time profile : end-to-end ~ 20-60 ms, requests/s high, CPU higher
backfill profile : ~ 200 MB/s, few big fetches, end-to-end delay up to 500 ms (irrelevant for a backfill)Why: Fetch settings trade request count against waiting. Pick the side that matches the job.
Land it I tune fetch size for throughput jobs and keep it minimal for latency jobs, and I keep max.poll.records tied to my processing time budget.
- "Does a bigger fetch use more memory?"
Yes, and the numbers add up faster than people expect. The consumer may receive up to
max.partition.fetch.bytes(default 1 MB) for each partition it owns, in one fetch response. The whole response is capped byfetch.max.bytes(default 50 MB), which is the real upper limit per request.memory arithmeticruns offline# illustrative arithmetic 100 partitions x 4 MB max.partition.fetch.bytes = 400 MB wanted fetch.max.bytes = 50 MB per response responses held at once: 1 being processed + 1 prefetched = about 100 MB rawThe raw bytes are only part of it. The Java objects built from them are often larger than the bytes. So I size the heap with margin and watch it in a load test with real traffic. When memory is tight, I lower
max.partition.fetch.bytesfirst, because it is the setting that grows with partition count. I also avoid raisingfetch.max.byteswithout first checking the pod's memory limit, since that is the other way to cause an out-of-memory kill.- "How does fetch tuning relate to lag?"
Lag is a symptom, and fetch tuning only cures one of its causes. Before touching a setting, I split the time into two parts.
- Fetching side: if
fetch-rateis high andrecords-per-request-avgis small, say 3 records per fetch, the consumer is making many tiny requests. Raisingfetch.min.byteshelps here. - Processing side: multiply time per record by records per poll. A handler that takes 20 ms with 500 records per poll needs 10 seconds per loop. Fetch settings cannot make that handler faster.
- Broker side: if fetch latency itself is high, the brokers are slow, and neither client setting is the fix.
A concrete case: a topic receives 2,000 records per second, and a single thread handles 5 ms per record, which is 200 per second at best. No fetch change can fix that. It needs more partitions and threads, or a faster handler.
- Fetching side: if
- "What does fetch.max.wait.ms do on a quiet topic?"
It makes the fetch a long poll. When the consumer asks for data and less than
fetch.min.bytesis ready, the broker does not answer at once. It holds the request open for up tofetch.max.wait.ms(default 500 ms) and answers as soon as enough bytes arrive. If nothing arrives in time, it sends an empty response and the consumer asks again.With the default
fetch.min.bytes=1, one new record is enough. So a record on a quiet topic reaches the consumer immediately, not after 500 ms. The wait is only a ceiling on how long the broker sits there empty-handed.The trap is the combination. If I raise
fetch.min.bytesto 1 MB for a throughput job and the topic goes quiet at night, a lone record can wait the full 500 ms. That is the price of bigger batches. Loweringfetch.max.wait.msonly creates more empty round trips, so I do it only after measuring a latency problem.- "Should I fetch from followers?"
Yes, with a trade-off. By default every fetch goes to the partition leader. If the consumer runs in another availability zone than the leader, every byte crosses a zone boundary, and cloud providers usually charge for that traffic. Fetch from followers (KIP-392) lets the consumer read from a replica in its own zone.
Two settings are needed: the consumer says where it is with
client.rack, and the brokers are told how to choose with a replica selector, plus each broker needs its ownbroker.rack.rack configruns offline# illustrative client.rack=zone-b # broker: broker.rack=zone-b # broker: replica.selector.class=org.apache.kafka.common.replica.RackAwareReplicaSelectorThe cost is a little extra latency, because a follower only serves data up to the high watermark, so it can be slightly behind the leader. For high-volume, cost-sensitive consumers I turn it on. For a latency-critical consumer I keep leader reads.
Q79 · Scenario. "A consumer group is stuck: members keep joining and leaving, the state flips between PreparingRebalance and Stable, and no records are processed. How do you diagnose?"
Reveal answer
Strong answer I look at the group state and member list first, then at the consumer logs for the reason members leave. The common causes are: processing slower than max.poll.interval.ms; session timeouts from long GC pauses or CPU starvation; a pod crash loop; a deserialization exception thrown from poll(); or a mismatch where members disagree on the assignor or subscription so the join fails.
The sequence of checks: describe the group with --state and --members; read the log lines about "leaving group" and the reason; check pod restarts and OOM kills; check GC logs; and check whether the exception is in the deserializer or in the handler.
The immediate relief is to stop the churn: scale the group to a smaller stable size or to one member, fix the cause, then scale up.
If the group is in a bad state and the cause is fixed, resetting by stopping all members lets the group go empty and rebuild cleanly.
Picture it The diagnostic commands and what each answer means.
The setup: Group billing flapping.
kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group billing --state
kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group billing --members --verbose
# illustrative output
GROUP STATE #MEMBERS
billing PreparingRebalance 3
# a state that never settles for minutes = members leave or fail to rejoin repeatedlyMake the invisible visible: Typical log clues and the cause each points at.
# illustrative output
"consumer poll timeout has expired ... max.poll.interval.ms" -> processing too slow (Q53)
"Member ... sending LeaveGroup ... because consumer was unresponsive (session timeout)" -> GC / CPU / network (Q54)
"Failed to deserialize ... " from poll() -> poison pill in deserializer (Q66)
"inconsistent group protocol" -> members disagree on assignor (Q52)
OOMKilled / CrashLoopBackOff in pod status -> application crash, not KafkaWhy: A rebalance loop has a reason on the member side almost every time. The group state only shows the symptom.
Land it I would read the state and member list, then the member logs for the leave reason, and calm the group down before fixing the cause.
- "How do I stop the churn quickly without losing data?"
I stop the churn first and find the cause second. Stopping is safe because offsets are committed only after processing, so no committed work is lost.
- Scale down: set the deployment to one replica. With one member there is nobody to disagree with, and it can take every partition.
- Freeze the autoscaler: pause any autoscaler and any rollout, or they will add pods back and restart the storm.
- Wait for Stable: describe the group and wait until the state is Stable. Lag grows meanwhile, but it is kept in Kafka and can be caught up later.
Then I fix the cause from the logs (a slow handler, an out-of-memory kill, a bad record) and scale up one pod at a time, watching the state stay Stable between steps. If the group looks damaged, stopping all members lets it go Empty, and it rebuilds cleanly when they return.
- "Could the broker side be at fault?"
Yes, though it is the less likely cause. Every group has a coordinator, which is the broker that leads one partition of the internal
__consumer_offsetstopic. Joins, heartbeats and offset commits all go to it. If that broker is overloaded, slow on disk, or its offsets partition is under-replicated, joins time out and members look like they are leaving.To check,
kafka-consumer-groups.sh --describe --group billing --stateshows which broker is the coordinator. Then I look at that broker's request latency, CPU, disk and under-replicated partitions.The clue that separates the two cases is scope. One group misbehaving points to the application. Many unrelated groups misbehaving at once points to the broker. Consumer logs help too: lines like "coordinator unavailable" or "not coordinator" point to the broker, while "leaving group because poll interval exceeded" points to the app. In the broker case, restarting consumers does not help.
- "What about a group stuck in Dead or Empty state?"
The two states mean different things.
Emptymeans the group exists but has no members. Its committed offsets are still stored, which is normal for a consumer that was stopped on purpose.Deadmeans the group's metadata has been removed, usually after the offsets expired (the defaultoffsets.retention.minutesis seven days, counted from when the group became empty).statesruns offline# illustrative output Empty : no members, offsets kept (until offsets.retention.minutes) Stable : members joined, assignments active PreparingRebalance : waiting for members to rejoin CompletingRebalance : waiting for the leader's assignment (classic) Dead : metadata removedIf a group that should be running shows Empty, no consumer is connected. I check the deployment, the network, the credentials and the ACLs. I also check for a typo in
group.id: a new group id starts fresh and followsauto.offset.reset, which can skip a backlog or re-read everything. A quick look at the group list for an unexpected new group name often finds this in seconds.- "How do I prevent a repeat?"
Prevention is mostly monitoring plus calmer defaults. I do four things.
- Alert: on rebalances per hour, and on a group that has not been Stable for more than five minutes.
- Time budget: processing time per poll, which is
max.poll.recordstimes time per record, must stay far belowmax.poll.interval.ms(Q53). For example 500 records at 40 ms is 20 seconds against a 300-second limit. I add this check to code review. - Calm restarts: static membership (
group.instance.id) with a session timeout long enough for a pod restart, so a quick restart keeps its partitions. Cooperative rebalancing, or the new consumer protocol (group.protocol=consumer, Kafka 4.0 and later), so a join does not stop everyone. - Resources: memory and CPU limits that avoid out-of-memory kills and long GC pauses.
Then I rehearse a rolling deploy in staging and count the rebalances.
Q80 · Design. "Design, end to end, an order-processing pipeline where orders must not be lost, payment events must not be double-charged, and the same customer's events must stay in order. Walk through producer, topic, consumer and failure handling."
Reveal answer
The real test Whether you chain the guarantees: outbox, key, replication, idempotent consumer, retry and DLT, and name where each protects you.
Strong answer I design it as a chain, one guarantee per link. Link 1, source of truth: the order service writes the order and an outbox row in one database transaction. Link 2, publish: CDC (or a relay) publishes outbox rows to Kafka, keyed by customer id, at-least-once.
Link 3, durable log: topic orders with replication factor 3, min.insync.replicas=2, unclean election off, producer acks=all and idempotence on. Link 4, ordering: key by customer id so a customer's events are on one partition, and one consumer thread (or a key-ordered worker pool) per partition.
Link 5, consumer: process then commit; the payment step is idempotent through a processed-events table plus the payment provider's idempotency key; transient errors use bounded blocking retries (to keep order), poison records go to a DLT with an alert.
Link 6, operations: alert on lag in seconds, under-replicated partitions, DLT traffic and rebalances; static membership and cooperative or next-generation rebalancing for calm deploys.
I name what I accept: slight latency from replication and CDC, writes failing if two brokers are gone (the outbox absorbs this), and blocking retries stalling one partition during an outage (which I handle with pause and backoff).
Picture it The whole chain as one picture, with the failure each link prevents.
The setup: Customer places an order; payment is charged; shipping is notified.
# illustrative output
link mechanism prevents
1 source of truth DB tx: order + outbox row lost event on crash (dual write)
2 publish CDC, key = customer_id order lost between DB and Kafka
3 durable log RF 3, min ISR 2, acks=all, idempotent broker loss, retry duplicates
4 ordering one partition per customer, 1 thread per key reordering of a customer's events
5 consumer process, then commit; idempotent payment double charge on replay
5b errors bounded retry; DLT + alert poison pill blocking the partition
6 operations lag-seconds, URP, DLT, rebalance alerts silent failureMake the invisible visible: Consumer handler tying links 4 and 5 together.
@KafkaListener(topics = "orders", groupId = "payments", containerFactory = "ackFactory")
@Transactional
public void on(OrderPlaced e, Acknowledgment ack) {
if (processed.insertIfNew(e.eventId()) == 0) { ack.acknowledge(); return; } // repeat: skip
gateway.charge(e.orderId(), e.amountCents(), "order-" + e.orderId()); // provider idempotency key
payments.save(Payment.charged(e.orderId(), e.amountCents()));
ack.acknowledge(); // commit AFTER the work
}What you see: A crash at any point either repeats work that is safe to repeat or leaves nothing half done.
Why: Each guarantee closes one gap. None is enough on its own, and exactly-once for the whole flow is the sum of at-least-once delivery and idempotent effects.
Land it I would chain outbox, replicated log, key by customer, process-then-commit with idempotent payment, bounded retries with a DLT, and monitor the whole chain, and I would state the costs I accepted.
- "Where are the remaining risks?"
Three risks remain, and I would name them rather than claim there are none.
The first is a poison record in the middle of one customer's stream. With blocking retries, that partition stops. If I skip to the dead-letter topic instead, later events for that customer run without it. For payments I usually choose to stop and alert, because skipping an order event can corrupt the state.
The second is a hot customer. One very busy key keeps one partition and one consumer thread busy while the others idle. I handle it with a rate cap or a dedicated lane (Q30).
The third is delay in the relay. If CDC falls behind or stops, orders stay safe in the outbox table, but events reach Kafka late. The outbox absorbs the outage, and I alert on the age of the oldest unsent row so that late events are noticed in minutes.
- "Would you use Kafka transactions here?"
Not for the payment step itself, because the payment provider lives outside Kafka. A Kafka transaction covers only Kafka writes and Kafka offsets. It cannot undo a card charge.
I would use one for a consume-transform-produce stage. For example, a service reads
PaymentRequested, calls the provider, then publishesPaymentCompleted. With a transaction, the output event and the input offset move together, so a crash cannot leave the event published but the input unmarked, or the reverse.The call to the provider stays protected on its own. If the service crashes after the charge but before the transaction commits, the input is read again and the provider is called again, with the same idempotency key. The provider returns the first result and does not charge twice.
The cost is a little latency, since read-committed readers wait for the commit. I would use transactions only where a duplicate event would really hurt. Otherwise, idempotent consumers on a plain producer are simpler.
- "What would you test?"
I would test failures, not the happy path. Each drill has one expected result, and I run them in staging against a real broker. A few are automated in CI, and the rest are run together as a game day before launch.
test matrixruns offline# illustrative output drill expected result kill consumer mid-batch charges == orders, no duplicates pass kill 1 broker no acked order missing pass poison record partition blocked or DLT + alert pass rolling deploy peak lag under 30 s pass replay 24 h no extra charges passThe drill I trust most is the replay: re-reading a full day of events and checking that the charge count does not change. It proves the idempotency end to end. I also compare counts at both ends, orders in the database against charges at the provider, because a matching total is the one result the business actually cares about. A failed drill is a finding, not an embarrassment: each one becomes a fix or an alert before real money moves through the pipeline.
- "How would this change at ten times the volume?"
The design stays the same and the numbers change. I scale in this order.
- Partitions and consumers: if 12 partitions carry 2,000 events per second, each handles about 170 per second. For 20,000 per second at the same cost per record, I need about 120 consumer threads, so 120 or more partitions (Q20).
- Producer batching: larger batches and compression (
linger.ms,compression.type) cut network and disk load. - Key-ordered workers: a pool inside each consumer (Q77) gives more parallelism than one thread per partition.
- Tiered storage: older segments move to cheap storage, so retention cost does not grow with volume.
I would also revisit CDC throughput and the database's write load, since the outbox is written for every order. And I would pick the partition count early, because adding partitions later changes which partition a key maps to, and order for a customer can break during the change.
10 · DrillSpring Kafka, Schemas, Connect & Streams — Q81–Q115
These thirty-five questions cover the ecosystem around the broker: how Spring Kafka sends and listens, what it does when a record fails, how schemas are allowed to change, how Connect moves data in and out of databases, and how Kafka Streams keeps state. Every answer is written to be said aloud, then backed by a picture and four follow-ups. Say yours first, then reveal.
These questions test whether you know what Spring does for you by default, what it quietly does not, and how it fails.
Q81. “KafkaTemplate.send() returns immediately. How do you know the record actually reached Kafka?”
Reveal answer
Strong answer send() is asynchronous: it puts the record into the producer's in-memory buffer and returns a CompletableFuture<SendResult> at once. The future completes only when the broker acknowledges the write (or the producer gives up).
So “the method returned” means nothing about delivery. You learn the outcome by attaching a callback with whenComplete, or by blocking on get(timeout) when you truly need to wait.
Which acknowledgement you get depends on acks. With the default acks=all, the future completes after the leader and all in-sync replicas have the record.
If you ignore the future, a failed send is silent. That is the single most common way an order event is “published” in the code and never exists in the topic.
Picture it Two versions of the same send, one that forgets the result and one that watches it.
The setup: An order service publishes OrderPlaced and then returns HTTP 201 to the customer.
// ❌ TRAP: fire and forget. Broker down for 30 s? The 201 is already sent.
kafkaTemplate.send("orders", orderId, event);
return ResponseEntity.status(201).build();
// ✅ watch the future, log and count failures
kafkaTemplate.send("orders", orderId, event)
.whenComplete((result, ex) -> {
if (ex != null) {
failedSends.increment();
log.error("send failed for order {}", orderId, ex);
} else {
RecordMetadata md = result.getRecordMetadata();
log.debug("stored at {}-{}@{}", md.topic(), md.partition(), md.offset());
}
});Make the invisible visible: What the future tells you once it completes.
# illustrative output
stored at orders-3@184220 -> success: partition 3, offset 184220
send failed ... TimeoutException: Expiring 1 record(s) for orders-3: 120000 ms has passed since batch creation
-> failure: the producer retried until delivery.timeout.ms ran outWhy: The offset and partition in the result are the broker's receipt. Without reading the future you hold no receipt at all, only a hope.
Land it I never treat send as done until the future completes, and for anything that must not be lost I tie the business step to that completion or use an outbox.
- “What exactly makes that future fail, and after how long?”
The producer retries transient errors by itself, so a short problem does not fail the future. The future fails only in two cases. One is when
delivery.timeout.ms(default 120,000 ms, two minutes) has passed since the record was queued. The other is a non-retriable error, such as a record that is too large or an authorization failure.So a broker outage of 30 seconds usually does not fail the future. It just completes late. An outage of three minutes does fail it, and the exception says that the record expired after the timeout.
timeoutsruns offline# illustrative delivery.timeout.ms=120000 # total budget for one record, including retries request.timeout.ms=30000 # one attempt waits this long for a reply # rule: delivery.timeout.ms >= linger.ms + request.timeout.msThe practical point is that a caller waiting on the future for a few seconds is not seeing failure, only slowness. If a web request must answer in two seconds, I do not wait on the future inside it. I record the intent safely and let the send finish in the background.
- “If I block with get() on every send, what do I lose?”
You lose batching. The producer groups records going to the same partition and sends them together. If you wait for each send to finish before the next, every batch holds exactly one record, and each record pays a full network round trip.
The arithmetic, with illustrative numbers: if one round trip takes 2 ms, a thread that blocks on every send can do at most 1,000 / 2 = 500 sends per second. Asynchronous sending lets the producer pack, say, 100 records into one request, so the same round trip carries 100 records and the same thread can reach tens of thousands per second.
Blocking also hides a second cost: with
linger.msset to wait for a fuller batch, a blocking caller sits through that wait on every single record.Blocking is fine for a low-volume path, such as an admin event once a minute, or in a test. On a hot path I send asynchronously and handle the result in a callback, counting failures in a metric.
- “Does a successful future mean the consumer will see the record?”
No. A successful future means the broker stored the record according to
acks. Withacks=allthat is the leader plus all in-sync replicas. It says nothing about the consumer.The consumer sees the record only when its poll reaches that offset. That can be seconds later if it is behind, or never if the group is stopped. With
isolation.level=read_committedit also waits until any surrounding transaction commits, and records from an aborted transaction are never shown.The future also says nothing about whether the consumer's own processing succeeds. The handler could throw, retry, or send the record to a dead-letter topic.
So there are three separate promises: stored (the future), delivered (the consumer polled it), and processed (the handler finished and the offset was committed). If a business step needs the third, I make it observable, for example with a status the consumer writes after it finishes, and I do not infer it from the producer side.
- “Where does this interact with a database write in the same request?”
That is the dual-write problem: the database commit and the Kafka send are two systems with no shared transaction. There are two bad outcomes. If the commit works and the send fails, the order exists and nobody hears about it, so the event is lost. If the send works and the commit rolls back, a phantom event announces an order that does not exist.
Reordering does not fix it: send first and commit after, and you just swap which failure you get.
The fix is the outbox: write the event to a table in the same database transaction as the order, and let a separate relay publish the rows to Kafka. Then the order and the event commit or roll back together, and the relay delivers at least once. See the outbox pattern in Chapter E7.
For anything that must not be lost, such as orders or payments, I use the outbox. For a best-effort metric, a plain send with a callback is enough.
Q82. “How does @KafkaListener concurrency relate to partitions?”
Reveal answer
Strong answer concurrency is the number of consumer threads Spring starts inside one listener container. Each thread owns its own KafkaConsumer instance, and each is a separate member of the consumer group.
A partition can be read by only one member of a group at a time. So if a topic has six partitions and you set concurrency=10, six threads work and four sit idle.
The real parallelism limit is therefore min(concurrency × instances, partitions). Adding threads beyond the partition count helps nothing.
Ordering is kept per partition, because one thread handles one partition's records one after another.
Picture it Six partitions shared by three threads on one pod, then by two pods.
The setup: Topic orders has 6 partitions. The listener uses concurrency = 3.
@KafkaListener(topics = "orders", groupId = "billing", concurrency = "3")
public void on(OrderPlaced e) { billing.charge(e); }Make the invisible visible: Assignment with one pod, then two pods, then ten threads total.
# illustrative output
1 pod x 3 threads : t1=[p0,p1] t2=[p2,p3] t3=[p4,p5] 6 of 6 busy
2 pods x 3 threads : 6 members, one partition each 6 of 6 busy
2 pods x 5 threads : 10 members, 6 partitions 4 members idle ✗Why: Group membership counts threads, not pods. Past the partition count, extra members are spare tires.
Land it Concurrency is capped by partitions, so I choose the partition count for the parallelism I will need and then size threads to match.
- “Is the listener method thread-safe then?”
The container is thread-safe, but your bean is not automatically safe. With
concurrency=3, Spring starts three consumer threads, and all three call the same listener bean instance, each for its own partitions. So your method runs at the same time on different threads.Anything shared inside the bean must be safe for that. A plain
int count++loses updates, and aHashMapcan corrupt itself under concurrent writes. I useAtomicLong,ConcurrentHashMap, or I keep the bean free of mutable state and put state in a database or a thread-safe service.Within one partition there is no overlap. One thread handles that partition's records one at a time, in offset order. That is why per-key logic stays simple: all records of one key come through one partition, so two threads never handle the same key at the same moment.
- “How do I raise throughput if I am already at one thread per partition?”
I use three levers, in this order, because each costs more than the one before.
- Make each record cheaper: batch the database writes, remove a blocking call, cache a lookup. Suppose each record costs 50 ms, so one thread does 20 per second, and 6 threads do 120. If I cut the cost to 10 ms, the same threads do 600.
- Use a batch listener: one poll's records are processed together, so a bulk insert replaces 500 single inserts.
- Add partitions: only when the first two are exhausted.
Adding partitions is a one-way door. A topic's partition count can grow but never shrink, and a key maps to a partition by hash modulo the count. When the count changes, existing keys can move to a different partition, so per-key order breaks for a short time while old and new records mix. I plan it at a quiet moment, and I do not do it in a panic during an incident.
- “What if one record takes ten seconds? Do other partitions on that thread wait?”
Yes. A thread that owns two partitions, p0 and p1, handles them in one loop: poll, then process p0's records, then p1's records, then poll again. A ten-second record on p0 delays everything behind it, including p1, for those ten seconds.
An example: a thread polls 100 records from p0 and 100 from p1. If each p0 record is slow, p1's 100 records wait until all of p0's are done. The lag of p1 grows even though p1 itself is healthy.
The fix is to remove the sharing. Set concurrency so each partition has its own thread, for example 6 threads for 6 partitions. Then a slow p0 holds only its own thread.
I also watch
max.poll.interval.ms. If one poll returns 500 records and each takes ten seconds, the loop needs more than an hour, and the member is evicted after five minutes. A slow handler needs a smallermax.poll.records, or a pause and resume design.- “Can I scale threads without scaling pods?”
Yes, up to the partition count. Three threads in one pod and one thread in each of three pods have the same group capacity. The thread version uses less memory because the threads share one JVM, one set of caches and one connection pool.
The cost is blast radius. If the pod crashes, all its threads leave at once and all their partitions move together. A pod with 4 threads that crashes takes 4 partitions away from the group, and those partitions stay idle until the rebalance finishes. The more partitions one pod owns, the more work moves and the longer the delay.
There is a second cost: threads in one pod share its CPU limit and the garbage collector, so one pod under memory pressure slows all of its threads together.
Many teams run a few threads per pod and several pods. They trade a little memory for smaller failures and easier rolling deploys. I pick the numbers from the partition count and the resource limits.
Q83 · Scenario. “One record in your listener keeps throwing an exception. With default Spring Kafka settings, what happens?”
Reveal answer
Strong answer With a plain Spring Boot setup, the container uses a DefaultErrorHandler. Its default back-off is a FixedBackOff with zero delay and 9 retries, so the failing record is attempted 10 times in a row, immediately.
After the tenth failure, the default recoverer just logs the record at error level and moves on. The offset is committed past it, so that record is effectively dropped, and the log line is all that remains.
During those retries the partition is blocked: nothing behind the bad record is processed. With no delay, the retries burn through in milliseconds, so you may not notice the block, but with a back-off of seconds you would.
So the default is “retry fast, then lose it with a log line”. For anything that matters you configure a dead-letter recoverer so the record is parked, not discarded.
Picture it The same bad record under default handling versus a dead-letter recoverer.
The setup: Partition 2 holds offsets 100, 101, 102. Offset 101 contains a value your code cannot process.
Make the invisible visible: Default handler timeline.
# illustrative output
off 100 processed ✓ committed 101
off 101 attempt 1 ✗ ... attempt 10 ✗ (0 ms apart)
log: Backoff FixedBackOff{interval=0, currentAttempts=10, maxAttempts=10} exhausted
❌ record skipped, offset 102 committed
off 102 processed ✓The fix: Add a recoverer that publishes the failing record to a dead-letter topic.
@Bean
DefaultErrorHandler errorHandler(KafkaTemplate<Object,Object> template) {
var recoverer = new DeadLetterPublishingRecoverer(template);
return new DefaultErrorHandler(recoverer, new FixedBackOff(1000L, 3L)); // 4 attempts, 1 s apart
}Why: The record now lands in orders-dlt with headers naming the exception, so someone can inspect and replay it.
Land it By default it retries ten times instantly and then logs and skips, so I always configure a dead-letter recoverer for anything I cannot afford to lose.
- “Why does Spring commit past the failed record at all?”
Because the alternative is worse. If the container refused to move past a failing record, one bad record would freeze its partition forever. Everything behind it would wait, and lag would grow without limit while the application kept looking busy.
So the framework follows a simple rule: after the retries are used up, the recoverer decides what happens, and then the offset moves on. The default recoverer only logs the record at error level. That is a policy choice, and it is the weakest one, because the log line is the only evidence that the record ever existed.
Parking the record in a dead-letter topic is the same choice with a receipt. The partition still moves on, but the record, its key, and the reason it failed are stored where someone can inspect and replay them later.
For data I cannot afford to lose, I want that receipt. For a stream where a lost event is harmless, such as a click counter, the default logging may be acceptable.
- “Which exceptions should not be retried at all?”
The ones that cannot succeed on a second try. A malformed message, a missing required field, a validation failure and a class cast error will fail the same way every time. Retrying them just burns attempts and delays the move to the dead-letter topic.
DefaultErrorHandleralready treats some exceptions as not retryable, for exampleDeserializationExceptionandMessageConversionException. These go straight to the recoverer on the first failure. The exact list can change between versions, so I check the reference for mine.I add my own with
addNotRetryableExceptions, for the business errors that I know are permanent.not retryableruns offline// illustrative DefaultErrorHandler handler = new DefaultErrorHandler(recoverer, new FixedBackOff(1000L, 2)); handler.addNotRetryableExceptions(InvalidOrderException.class);The opposite case matters too: a timeout calling another service is worth retrying, because the next try may work. I keep a short list of permanent errors and let everything else retry.
- “How many blocking retries are reasonable?”
Blocking retries hold the partition, so I keep them short. My default is two or three attempts with about a second between them. That is enough to absorb a blip, such as a database failover that takes a few seconds, without stalling the partition for long.
The arithmetic shows why. The default is 10 attempts. With a 1-second delay between them, one bad record blocks its partition for about 9 seconds. With 10 attempts and a 30-second delay, it blocks for about 4.5 minutes, which is close to the default
max.poll.interval.msof 5 minutes, and the consumer may be removed from the group.So the total blocking time must stay far below the poll interval, and it should also stay small compared with how much lag the business can tolerate.
For waits longer than that, such as a downstream outage that lasts minutes, I stop retrying in place. I use retry topics, covered in the next question, so the main partition keeps moving while the failed record waits its turn.
- “What does the dead-letter record contain?”
It holds the original key and value, plus headers that say where the record came from and why it failed. The recoverer adds the original topic, partition, offset and timestamp, and the exception class, message and stack trace.
headersruns offline# illustrative output kafka_dlt-original-topic orders kafka_dlt-original-partition 2 kafka_dlt-original-offset 101 kafka_dlt-exception-fqcn java.lang.IllegalStateException kafka_dlt-exception-message order 4711 has no itemsKeeping the original key matters, because a replay should land on the same partition as the first attempt. Keeping the original coordinates matters too, because an operator can find the exact record in the source topic and look at its neighbours.
The stack trace can be large, so a dead-letter topic may need a higher
max.message.bytesthan the main topic. I check that before the first real failure. The header names can differ between versions, so I read them from the reference.
Q84. “What are Spring Kafka's AckModes, and what is the default?”
Reveal answer
Strong answer Spring turns off the client's auto-commit and commits offsets itself. The AckMode decides when. The default is BATCH: after the listener has processed every record returned by one poll(), Spring commits once.
RECORD commits after each record. TIME and COUNT commit after an interval or a number of records. MANUAL and MANUAL_IMMEDIATE hand you an Acknowledgment object and you call acknowledge() yourself.
All of them are “commit after process”, which gives at-least-once: a crash between processing and commit replays some records.
The trade is commit traffic versus replay size. BATCH commits least often but replays up to a whole poll's worth after a crash.
Picture it Commit points for the same eight records under BATCH and RECORD.
The setup: One poll returns records at offsets 10–17. The process crashes while handling offset 14.
# illustrative output
BATCH : process 10 11 12 13 14 💥 committed offset = 10 (nothing in this poll yet)
restart -> replay 10..14 and onward 5 duplicates
RECORD : process 10 ✓c11 11 ✓c12 12 ✓c13 13 ✓c14 14 💥
restart -> replay 14 only 1 duplicate, but 4 extra commit callsWhy: Smaller commit steps shrink the duplicate window and cost more broker round trips. Either way the handler must tolerate repeats.
Land it The default BATCH commits after each poll's records are done, it is at-least-once, and I pick MANUAL only when the commit must wait for something asynchronous.
- “When do I really need MANUAL?”
I need it when the work finishes later than the listener method returns. Two common cases: I hand the record to an async executor, or I collect records and write them to a database in one batch, and I want to commit offsets only after that flush succeeds.
manualruns offline// illustrative spring.kafka.listener.ack-mode=manual @KafkaListener(topics = "orders") void on(OrderPlaced e, Acknowledgment ack) { repo.save(e); ack.acknowledge(); // commit only after the save succeeded }There are two flavours.
MANUALqueues the acknowledgement and commits after the poll's records are handled.MANUAL_IMMEDIATEcommits as soon as you callacknowledge(), which means more commit calls.The danger is forgetting to call it on some path: the offset is never committed, and the records come back after a restart. Acknowledgements normally have to come in order. Recent versions have an option for out-of-order acknowledgement, which I would check in the reference. If the listener is synchronous, I keep the default BATCH.
- “What happens to ack if the listener throws?”
Nothing is committed for that record at that moment. The container catches the exception and hands it to the error handler, and the handler decides: retry the record, send it to a recoverer such as a dead-letter topic, or skip it. The commit then follows the handler's decision.
By default, the error handler seeks the consumer back to the failed record's offset, so the same record is delivered again on the next poll. That is how a blocking retry works. Once the retries are used up and the recoverer has handled the record, the offset moves past it and the commit includes it.
In MANUAL mode, an exception before
acknowledge()means the same thing: the offset is not advanced. If you swallow the exception yourself and return without acknowledging, the container does not know that anything went wrong, and the record is redelivered only after a seek or a rebalance. That silent half-state is hard to debug, so I let exceptions leave the method.- “Does the commit go to Kafka or to my database?”
The commit goes to Kafka, into the internal
__consumer_offsetstopic. It does not go to my database. If my processing writes to a database, I have two systems again, and a crash between the database commit and the Kafka commit repeats the record.There are two standard answers. The first is to make the handler idempotent: a unique event id in a table, or an upsert, so a repeat has no effect. The second is to store the offset in the same database transaction as the business write, and on startup tell the consumer to seek to that stored offset instead of Kafka's. Spring has a seek-aware listener for this.
The second approach gives true exactly-once effects in the database. It also means Kafka's committed offset is no longer the truth, so monitoring tools that read lag from Kafka will look wrong.
I choose the idempotent handler in most cases because it is simpler to run. The idempotent-consumer pattern in the primer is the usual answer.
- “Would you ever turn auto-commit back on?”
Almost never. The danger depends on where the processing happens. Kafka's auto-commit runs inside
poll(): when the interval has passed (default 5 seconds), the next poll commits the offsets that the previous poll returned. If the handler processes everything on the same thread before polling again, that is acceptable.It breaks in two common cases. If the handler passes records to another thread, the next poll commits offsets for records that are still queued or running, and a crash then loses them. If the handler catches an exception and moves on, the offset is committed for a record that was not handled.
Either way, a record that was never processed is marked done, and it is not redelivered. That turns at-least-once into at-most-once for the unlucky records.
The one tolerable case is a metrics-style stream where losing a few records is acceptable. For everything else I let Spring commit, with BATCH or MANUAL.
Q85 · Design. “Design the dead-letter flow for an orders consumer. What goes in the dead-letter topic and who looks at it?”
Reveal answer
Strong answer I would use DeadLetterPublishingRecoverer inside the DefaultErrorHandler. After the retry budget is spent, the original record plus failure headers is published to orders.DLT.
Two details bite people. By default the recoverer publishes to the same partition number as the original, so the dead-letter topic needs at least as many partitions, or you supply a resolver that returns partition -1 to let the producer choose.
Second, the dead-letter topic is a normal topic: give it a long retention (say 14 days), an alert on its message rate, and an owner. A dead-letter topic nobody watches is a slow data-loss channel.
Finally, a replay tool: a small job that reads the dead-letter topic and republishes to the original topic after the bug is fixed, preserving the key.
Picture it The whole flow from failure to replay.
The setup: Orders consumer, four attempts, 1 s apart; then dead-letter.
orders (p2@101) --fail x4--> DeadLetterPublishingRecoverer
--> orders.DLT (p2) + headers {orig topic, partition, offset, exception}
--> alert: DLT rate > 0 for 5 min -> on-call opens the record
--> fix deployed -> replay job: DLT -> orders (same key)Make the invisible visible: Configuration with a destination resolver.
var recoverer = new DeadLetterPublishingRecoverer(template,
(rec, ex) -> new TopicPartition(rec.topic() + ".DLT", -1)); // -1: any partition
var handler = new DefaultErrorHandler(recoverer, new FixedBackOff(1000L, 3L));
handler.addNotRetryableExceptions(IllegalArgumentException.class);Why: Partition -1 avoids failing when the dead-letter topic has fewer partitions. The headers make each parked record self-explaining.
Land it A dead-letter topic is only useful if it has headers, retention, an alert and a replay path, so I design all four, not just the publish.
- “Should replay preserve the original key?”
Yes, because the key decides the partition, and the partition decides the ordering for that entity. If I replay with a null key, the records scatter across partitions, and the per-order ordering that the producer worked to create is gone.
The original key is stored on the dead-letter record, so the replay tool reads it and publishes with the same key. It is also worth copying the original headers, so the consumer sees the same trace and event ids.
There is a catch that no tool can remove: replayed records are late. By the time I fix the bug and replay, later events for the same key may already have been processed. For example, the dead-lettered
OrderPaidmay arrive afterOrderShipped.So the consumer must tolerate out-of-order arrival: compare version numbers or timestamps and ignore an older event, or park an event until its predecessor is seen. I test this with a replay in staging before the first real incident.
- “What if the dead-letter publish itself fails?”
The recoverer throws an exception. The error handler then treats the record as still failing, so the container retries it or seeks back to it, and the record is not lost. The partition stays blocked until the dead-letter topic accepts the write.
That is the right default, because stopping is safer than dropping. A record that cannot be parked must not be silently thrown away.
The common reasons for the failure are an unreachable broker, a missing topic with auto-creation off, or a record that is too large for the dead-letter topic. The partition mismatch from the main answer also shows up here: if the dead-letter topic has fewer partitions than the original, publishing to the same partition number fails.
The downside is that a broken dead-letter path blocks a healthy stream. So I alert on dead-letter publish failures and on lag that grows with no progress. I also create the dead-letter topic in advance with the right partition count, rather than trusting auto-creation in production.
- “Dead-letter topic per consumer group or per topic?”
I prefer one per topic and per consuming service, for example
orders.billing.DLTandorders.shipping.DLT. Different consumers fail for different reasons. Billing may reject an order for a missing tax code, while shipping rejects it for a bad address. Each has a different owner who knows how to fix it.A single shared dead-letter topic is simpler to create and to monitor in one place. But it mixes the failures, so nobody knows whose job it is to look. The alert goes to everyone, which in practice means no one.
The default name in Spring is the original topic plus
.DLT. That is fine when one service reads the topic. When two groups read the same topic, I supply a destination resolver that adds the service name, or the two groups write into the same dead-letter topic and confuse each other.The cost of many topics is more topics to create and to give retention. I accept it for the clearer ownership.
- “How do you stop the dead-letter topic becoming a graveyard?”
A dead-letter topic becomes a graveyard when nobody owns it. I use four habits to prevent that.
- Age alert: if the oldest unprocessed record in the topic is older than a day, page the owner. A rate alert catches spikes, but an age alert catches the slow trickle that people stop noticing.
- Triage: a weekly item for the owning team to look at every record, in a short meeting or a ticket queue.
- Classify: each record is given a cause: bad data, a bug on our side, or a downstream outage.
- Act on the class: bug and outage records are replayed once the cause is fixed; bad-data records are reported back to the producing team, then discarded on purpose.
The aim is that every record leaves the topic by a decision. A record that sits there for months is a business event that was lost without anyone choosing to lose it.
Q86. “How does @RetryableTopic work, and how is it different from the error handler's retries?”
Reveal answer
Strong answer With the error handler, retries happen in place: the same thread, the same partition, blocked until the record succeeds or is parked. With @RetryableTopic, a failed record is published to a separate retry topic and the main partition moves on.
A retry topic is consumed by another listener that waits until the record's delay has passed before delivering it. The default is three attempts in total, starting at one second, and the last failure goes to a dead-letter topic.
This is non-blocking retry: the main stream keeps flowing while one record waits. The cost is that ordering for that key is gone, since later records for the same key overtake the failed one.
Use it when delays are long (seconds to minutes) and strict per-key ordering is not required; use in-place retries when order matters more than speed.
Picture it Timelines for a downstream that is down for two minutes.
The setup: Five orders arrive; the second needs a payment API that is down.
@RetryableTopic(attempts = "4",
backoff = @Backoff(delay = 5_000, multiplier = 3.0), // 5 s, 15 s, 45 s
dltStrategy = DltStrategy.FAIL_ON_ERROR)
@KafkaListener(topics = "orders", groupId = "billing")
void on(OrderPlaced e) { payments.charge(e); }
@DltHandler
void dead(OrderPlaced e) { alerts.notifyOps(e); }Make the invisible visible: Where each record is over time.
# illustrative output
t=0s orders: o1 ✓ o2 ✗ -> copy to orders-retry-0 o3 ✓ o4 ✓ o5 ✓ (main flow never stops)
t=5s orders-retry-0: o2 ✗ again -> orders-retry-1
t=20s orders-retry-1: o2 ✗ again -> orders-retry-2
t=65s orders-retry-2: o2 ✓ (API is back)
order seen by billing: o1 o3 o4 o5 o2 ❌ o2 arrived lastWhy: Nothing blocked, and nothing was lost, but o2 now arrives after o3–o5. Anything that depends on order for one key has to cope.
Land it Retry topics let the main stream keep moving while a failed record waits, at the price of per-key ordering.
- “How does the delayed delivery work without a timer in the broker?”
Kafka itself has no delayed delivery. A record in a topic is readable as soon as it is written. So Spring builds the delay on the consumer side.
Each retry record carries headers, including the time when it is due. The retry listener reads the record and checks that time. If it is too early, the container pauses that partition and resumes it when the time comes, then delivers the record. While paused, the consumer keeps polling and heartbeating, so it stays in the group.
A record due in 30 seconds holds up the records behind it in the same retry partition, which is why one retry topic is used per delay level.
The cost is that each retry topic gets its own listener container, which uses a thread and a connection even though it is idle most of the time.
- “What topics does it create?”
It creates one retry topic per delay step, plus the dead-letter topic. For four attempts in total, that is the main topic, three retry topics and one dead-letter topic. With a growing back-off the retry topic names carry the delay, for example
orders-retry-1000,orders-retry-2000andorders-retry-4000, and the last stop isorders-dlt. With a fixed delay, a single retry topic may be reused. The exact names depend on the version and settings, so I check what my version creates.Spring can create these automatically. That is fine for a test, but in production I create them in advance. I choose the partition count, which should match the main topic so a record can keep its partition number, and I set the retention.
Each topic is also something to monitor. The retry topics should be nearly empty, and a retry topic with a growing backlog tells me a downstream system is down, long before the dead-letter topic fills.
- “What about records that must stay in order per key?”
For those listeners I do not use it. Retry topics and strict per-key order are opposites: while the failed record waits in a retry topic, later records of the same key flow through the main topic and get processed first.
I have three options, depending on how much order matters.
- Blocking retries: use the error handler's in-place retries with a short budget of a few attempts. The partition waits, so order is kept. I accept the head-of-line block and alert on it.
- Tolerant state machine: design the consumer so that order does not matter. A
PaymentCompletedevent that arrives beforeOrderCreatedis parked, or ignored until its predecessor is seen. Version numbers on events make this checkable. - Per-key block: after the first failure for a key, send all later events of that key to the retry topic too. It keeps order but needs custom code, so I rarely build it.
For payments I choose option one and a loud alert.
- “Does the retry copy duplicate the offset commit risk?”
Yes, there is a gap. Moving a record to a retry topic is two actions: publish it to the retry topic, then commit the offset of the original. A crash between them leaves the original uncommitted, so it is read again and published to the retry topic a second time. Now two copies are waiting.
The same gap exists with in-place retries, where a crash after the work but before the commit repeats the handler. So no mechanism removes it. What changes is only how the duplicate shows up.
That is why I treat duplicate handling as a requirement of every consumer, not an extra for the retry design. The handler records an event id in the same database transaction as its effect, so a second copy hits a unique constraint and does nothing.
Q87 · Scenario. “A malformed message arrives and your consumer crashes in a loop on every restart. What is happening and how do you fix it?”
Reveal answer
Strong answer That is a poison pill that fails at deserialization, before your listener runs. The consumer's poll() throws, the offset is not advanced, the app restarts, polls the same record, and throws again.
Because it fails inside the client, the error handler never sees a record to retry or dead-letter. Lag grows behind it while the pod flaps in CrashLoopBackOff.
The Spring fix is ErrorHandlingDeserializer: it wraps the real deserializer, catches the exception, and hands the container a record with a marked failure instead. Now the normal error handler can send it to the dead-letter topic and move on.
Short-term rescue if it is already looping: seek the group past that offset with the CLI, after saving the bytes for analysis.
Picture it The loop, and the break in the loop.
The setup: Offset 5000 holds bytes that are not valid JSON.
# illustrative output
poll -> offset 5000 -> SerializationException (no listener call, no handler)
pod restarts -> poll -> offset 5000 -> SerializationException ✗ repeats every 20 s
consumer lag: 5000 stays, others growThe fix: Wrap the deserializers.
spring.kafka.consumer.key-deserializer=org.springframework.kafka.support.serializer.ErrorHandlingDeserializer
spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.ErrorHandlingDeserializer
spring.kafka.consumer.properties.spring.deserializer.value.delegate.class=org.springframework.kafka.support.serializer.JsonDeserializer
spring.kafka.consumer.properties.spring.json.trusted.packages=com.shop.eventsWhat you see now: The bad record becomes a dead-letter entry.
# illustrative output
off 5000 DeserializationException -> not retryable -> orders.DLT
off 5001 processed ✓ ✓ stream moves onWhy: The failure moves from the client's poll to the container's error path, where recovery policy lives.
Land it A poison pill at deserialization crashes poll itself, so I wrap deserializers with ErrorHandlingDeserializer to turn the crash into a dead-letter record.
- “How do I skip it right now, in production, if I cannot deploy?”
The group must be stopped first, because the CLI refuses to reset offsets for a group that has active members. Then I do three things, in order.
- Find the offset: the exception message names the topic, partition and offset of the failing record, for example partition
orders-2at offset 5000. - Save the bytes: I copy that record out with a console consumer, from that offset with a count of 1, so engineers can study it later.
- Move past it: I reset the group to the next offset, 5001, and start the consumers again.
skipruns offline# illustrative kafka-consumer-groups.sh --bootstrap-server b1:9092 --group billing \ --topic orders:2 --reset-offsets --to-offset 5001 --dry-run # check the plan, then repeat with --executeI run it with
--dry-runfirst and only then with--execute. This is a rescue, not a design. The permanent fix isErrorHandlingDeserializer, so the next bad record goes to the dead-letter topic by itself.- Find the offset: the exception message names the topic, partition and offset of the failing record, for example partition
- “Why not just catch the exception in my listener?”
Because the listener is never called. The failure happens earlier, inside
poll(), when the deserializer turns the bytes into an object. The container never receives a record, so there is nothing to pass to your method. A try/catch in the method body cannot see the error.There are two honest ways around it. One is
ErrorHandlingDeserializer: it wraps the real deserializer, catches the exception, and gives the container a record that carries the failure. The normal error handler then sees it, retries or not, and sends it to the dead-letter topic. This is the standard answer, and it needs only configuration.The other is to consume the value as a
byte[]and deserialize it yourself inside the listener. Then your catch works. But every listener must repeat the same boilerplate, and it is easy to forget it in one of them.I use the wrapper, because it fixes the whole application in one place.
- “How do I prevent bad data at the source?”
I stop it at the source with a contract, and I keep a second defence at the consumer.
- Schema registry: the producer's serializer checks the object against a registered schema before sending, and the registry refuses an incompatible new schema. Well-behaved producers can no longer produce malformed bytes.
- Access control: a rogue or buggy producer can still write raw bytes straight to the topic, ignoring the registry. ACLs that limit who may produce to a topic close that door.
- Consumer defence:
ErrorHandlingDeserializerand a dead-letter topic, because no source check is perfect.
I also add a producer-side test in CI that serializes a sample event and reads it back with the consumer's code. It catches the common failure, a changed class on one side, before it reaches the topic.
- “Does this relate to the trusted-packages setting?”
Yes, it is the same family of problem: bytes in a topic are untrusted input. With the JSON deserializer and type headers, the producer writes the Java class name into a header, and the consumer creates an object of that class. Spring limits this to trusted packages.
If I set
spring.json.trusted.packagesto*, any producer, or anyone able to write to the topic, can name any class on my classpath to be created. That is a deserialization security risk, because some classes do harmful things in their constructors or setters.I use one of two safer settings, shown here.
safe json settingsruns offline# illustrative # option 1: allow only my event package spring.json.trusted.packages=com.example.orders.events # option 2: ignore type headers, always use one class spring.json.use.type.headers=false spring.json.value.default.type=com.example.orders.events.OrderPlacedIn Spring Kafka 4 the class is named
JacksonJsonDeserializer, and I check that the property names are unchanged.
Q88. “How do you test Kafka code: @EmbeddedKafka or Testcontainers?”
Reveal answer
Strong answer Both start a real broker so your code talks to something that behaves like Kafka. @EmbeddedKafka runs a broker inside the test JVM; Testcontainers' KafkaContainer runs the real Kafka image in Docker.
I prefer Testcontainers for integration tests that must mirror production: same image, same KRaft mode, real network. It needs Docker on the CI machine and starts in a few seconds.
@EmbeddedKafka needs no Docker and starts fast, so it suits quick listener tests and builds without Docker access. The catch is that it is in-process, so it can drift from the version and settings you run.
In either case, never use Thread.sleep to wait for the consumer; use Awaitility to poll for the expected outcome with a timeout.
Picture it Choosing and the shape of one test.
The setup: Test: publish an order, assert the listener wrote one row.
@SpringBootTest
@Testcontainers
class OrderIT {
@Container @ServiceConnection
static KafkaContainer kafka = new KafkaContainer(DockerImageName.parse("apache/kafka:4.3.0"));
@Autowired KafkaTemplate<String, OrderPlaced> template;
@Autowired OrderRepo repo;
@Test void storesOrder() {
template.send("orders", "o1", new OrderPlaced("o1", 1999));
await().atMost(10, SECONDS).untilAsserted(() ->
assertThat(repo.count()).isEqualTo(1)); // ✅ poll, do not sleep
}
}Make the invisible visible: Comparison.
| Option | Pick it when | Cost or catch |
|---|---|---|
@EmbeddedKafka | No Docker on CI; many fast listener tests | In-process; may differ from production version and config |
| Testcontainers | Integration tests that mirror production | Needs Docker; seconds to start; share one container across tests |
Mock KafkaTemplate | Pure unit tests of the service logic | Proves nothing about serialization, partitioning or commits |
Why: Mocks test your logic, embedded tests your wiring, containers tests your assumptions about the real broker.
Land it I use Testcontainers for the tests that must mirror production, embedded for fast wiring tests, and Awaitility instead of sleeps in both.
- “What do you assert on besides the happy path?”
The unhappy paths, because that is where real consumer bugs live. I write three tests for every consumer, and they catch most of what goes wrong in production.
- Failure test: publish a malformed or failing record and assert that it arrives in the dead-letter topic with the right headers, while the good records around it are still processed.
- Duplicate test: publish the same event twice and assert there is exactly one effect, one row in the database or one charge at a fake provider.
- Order test: publish events out of order, for example
OrderShippedbeforeOrderCreated, and assert that the final state is still right.
I add one more when the service uses retry topics: assert that a record that fails twice and then succeeds ends up processed once. All of these use Awaitility to wait for the outcome, with a timeout, instead of a sleep.
- “How do you keep tests from interfering with each other?”
Isolation is the main danger, because a Kafka test shares state that most tests do not: topics, group offsets and leftover records. I use three habits.
First, each test gets its own topic name or its own
group.id, built with a random suffix. If two tests share one group, the second inherits the committed offsets of the first and may skip its own records.Second, I clean up. When a topic is reused, I delete and recreate it between tests, or I use a fresh container for each test class.
Third, I balance speed and isolation. Starting a container takes several seconds. Starting one for each test is slow. So the usual compromise is one container for the whole suite and new topics per test. Records written by a previous test are then never seen, since they sit in other topics.
A test that passes alone but fails in the full suite almost always shares a topic or a group.
- “How do you test the transaction behaviour?”
I use a real broker, either option, because the transaction coordinator and the commit markers are broker behaviour. A mock cannot show them. A single broker needs the transaction log settings lowered, such as a replication factor of one. Container images and the embedded setup usually do this, but I check.
The test has three parts. First, consume the output topic with
isolation.level=read_committed. Second, force a failure after the produce call but before the commit, for example by throwing in the handler. Third, assert that nothing is visible downstream, because the aborted records are hidden from read-committed readers.I also run the opposite check once: consume the same topic with
read_uncommittedand confirm that the aborted record is visible there. It proves the test is real and not just an empty topic.A last test covers a crash and restart with the same transactional id. It asserts that the old producer is fenced and the new one continues.
- “What about Spring Boot 4 specifics?”
Spring Boot 4 split its auto-configuration into focused modules, so Kafka support needs
spring-boot-starter-kafkadeclared explicitly. Having onlyspring-kafkaon the classpath compiles fine, but nothing configures it.The same applies to tests. The test slice and its support classes come from the matching test dependency, and I check the Boot 4 documentation for the exact artifact names, since they changed with the split. The Testcontainers integration also has its own module, and with a recent Boot I can use a service-connection annotation so the container's address is wired into the app without manual properties.
The symptom is the confusing part. A missing starter does not say anything about Kafka. It appears as a missing bean, for example no
KafkaTemplateor no listener container factory, and the context fails at startup.So when a Kafka test fails with a missing bean after an upgrade, I check the dependencies first, then the versions. A single smoke test that only starts the context catches this early.
Q89 · Scenario. “After upgrading to Spring Boot 4 the app fails at startup with no KafkaTemplate bean, though the code did not change. What do you check?”
Reveal answer
Strong answer First the dependency. Spring Boot 4 split its auto-configuration into focused modules, and Kafka support now comes from spring-boot-starter-kafka. If the build only has spring-kafka, the library is on the classpath but nothing configures it, so there is no KafkaTemplate bean.
Second, the versions must line up: Spring Boot 4.0 pairs with Spring for Apache Kafka 4.0 and Spring Boot 4.1 with Spring for Apache Kafka 4.1. Overriding the Kafka version by hand against the wrong Boot version causes odd failures.
Third, read the auto-configuration report with --debug: it lists which Kafka auto-configurations matched and which were skipped and why.
Fourth, look for property renames in the migration notes, though in this case the missing starter is the usual cause.
Picture it Find the cause with one run.
The setup: Startup stops with No qualifying bean of type KafkaTemplate.
# illustrative output
$ java -jar app.jar --debug | grep -i kafka
Negative matches:
KafkaAutoConfiguration:
Did not match: @ConditionalOnClass did not find required class 'org.springframework.boot.kafka.autoconfigure.KafkaAutoConfiguration' The fix: Declare the starter.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-kafka</artifactId>
</dependency>Why: The auto-configuration class lives in the starter's module now; without it Spring has nothing to build the template from.
Land it I check that spring-boot-starter-kafka is declared, confirm Boot and Spring Kafka versions match, and read the auto-configuration report.
- “How do I confirm the versions match?”
I print the dependency tree and read the resolved
spring-kafkaversion. The Boot dependency management should choose it, so Boot 4.0 gives Spring for Apache Kafka 4.0 and Boot 4.1 gives 4.1. If the tree shows a version that someone pinned by hand in the build file, I remove that pin unless I can name a reason for it.treeruns offline# illustrative output ./mvnw dependency:tree | grep -E "spring-kafka|kafka-clients" [INFO] +- org.springframework.boot:spring-boot-starter-kafka:jar:4.0.x:compile [INFO] | +- org.springframework.kafka:spring-kafka:jar:4.0.x:compile # Gradle: ./gradlew dependencyInsight --dependency spring-kafkaTwo things in that output tell me the setup is right. The starter itself is present, not just the library. And
kafka-clientsis the version that spring-kafka expects, not an older one pulled in by another dependency.If an old
kafka-clientsshows up, some other library has forced it. I then use the build tool's insight command to see who asked for it, and fix it there.- “Why did this not fail at compile time?”
Because your own code compiles against
spring-kafkaclasses such asKafkaTemplateand@KafkaListener, and those are still on the classpath.What is missing is the auto-configuration, which creates the beans from the properties file when the application starts. Auto-configuration is found and applied at runtime, so the error only appears when the Spring context starts. It does not appear when the code is built.
That is a general pattern: an upgrade can break wiring that no compile step checks. Three habits catch it. A startup smoke test in CI, which only boots the context and fails if any bean is missing. Running the full integration suite on the upgrade branch before merging. And running the app once with
--debug, which prints the auto-configuration report, so a skipped Kafka configuration is visible as a line saying why it did not match.I make the smoke test mandatory for any framework upgrade.
- “What else commonly breaks on a major upgrade?”
Four things break most often on a major upgrade, and I check them in this order.
- Removed APIs: methods and classes that were deprecated in the old major version are gone in the new one. The compiler finds these, so they are the cheapest to fix.
- Changed defaults: a setting that kept its name but changed its value, for example in retry or error handling. Nothing fails; behaviour just differs. I compare the effective config before and after.
- Serialization: serializer classes, header names and the JSON library may change, which can make old and new instances disagree about the bytes on the topic.
- Client version: the Kafka client jar moves with the framework, and its release notes list changed defaults and protocol options.
I test the upgraded consumer in staging against a copy of production topic data and compare its outputs with the old version's.
- “How do you keep the upgrade safe for a consumer group in production?”
I roll out one pod first as a canary and watch four numbers: lag, error rate, rebalance count and processing time per record. Only if they stay flat for a while do I continue.
A new client version joins the same group as the old pods, so for a time both versions are members at once. They must be compatible with the assignment protocol in use. With the classic protocol and a cooperative assignor, mixed versions are normally fine, but I read the release notes before relying on it, and I avoid changing the assignment strategy and the framework version in the same release.
Rollback is simple. Offsets are stored in Kafka, not in the pod, so a rolled-back pod resumes from the committed offsets and nothing is lost. Records processed since the commit are processed again, which is why the handler is idempotent.
These questions test the pieces beyond hello-world: what exactly a transaction covers, how to survive duplicates, and how to tune a consumer.
Q90. “How do Kafka transactions work in Spring Kafka for a consume-transform-produce service?”
Reveal answer
Strong answer You set a transaction-id-prefix on the producer factory. Spring then creates transactional producers, and the listener container wraps each record (or batch) in a transaction: begin, run the listener, produce the output records, send the consumed offsets to the transaction, commit.
The offsets are committed inside the same transaction as the output records. So either the output appears and the input is marked consumed, or neither happens and the input is redelivered.
Downstream consumers must use isolation.level=read_committed to hide records from aborted transactions. Without that setting they see everything, including aborted writes.
This gives exactly-once for the Kafka-to-Kafka hop only. A database write or an HTTP call inside the listener is outside the transaction.
Picture it One transaction around one input record.
The setup: Input topic orders, output topic invoices. One order produces two invoice lines.
spring.kafka.producer.transaction-id-prefix=billing-tx-
spring.kafka.consumer.properties.isolation.level=read_committed
spring.kafka.consumer.enable-auto-commit=falseMake the invisible visible: What the broker holds when the service crashes between the two sends.
# illustrative output
invoices p0: [line-A (txn 77, open)] [line-B (txn 77, open)]
crash before commit -> broker aborts txn 77 after transaction.timeout.ms
read_committed reader sees: nothing from txn 77 ✓
read_uncommitted reader sees: line-A, line-B ✗ phantom invoices
restart -> order redelivered -> txn 78 writes line-A, line-B, commit ✓Why: The aborted records stay in the log but are filtered out. The re-run writes them once, committed.
Land it Spring's transaction-id-prefix puts produce and offset commit in one Kafka transaction, which is exactly-once between topics and nothing more.
- “What is the transactional.id for and why must it be stable?”
It identifies the producer across restarts. The broker keeps an epoch counter per transactional id. When a new instance starts with the same id and calls
initTransactions(), the broker raises the epoch, aborts any open transaction, and refuses any later write from the old epoch. A zombie that was only paused, say by a long GC, wakes up and finds that it cannot commit.For this to work, the same logical worker must get the same id after a restart. A random id on every start fences nobody, because the new instance looks like a stranger.
The other rule is the reverse: two producers that are alive at the same moment must not hold the same id, or each start fences the other and both keep failing.
Spring builds each producer's id from the
transaction-id-prefixplus a suffix. How the suffix is chosen depends on the exactly-once mode, so I read the reference for my version.- “What does it cost?”
It costs extra round trips and extra waiting. A transaction adds calls to register the partitions, to send the offsets and to commit, and then the broker writes a commit marker into every partition touched. Readers using
read_committedcannot see the records until that marker arrives.Here is a worked example with assumed numbers: about 6 ms of overhead per transaction in total.
transaction costruns offline# illustrative arithmetic, assumed 6 ms overhead per transaction 1 record per transaction : 6 ms per record -> at most about 166 records/s per producer 100 records per transaction: 0.06 ms per record -> overhead nearly goneSo a transaction per record is expensive, and a transaction per batch is cheap. The container does one transaction per record by default, or per batch when it is a batch listener.
The price in latency is that end-to-end delay rises by the commit wait, usually tens of milliseconds. I accept that when a duplicate would hurt, and I measure it in staging with real batch sizes.
- “What if my listener also writes to Postgres?”
Then the database write is not covered. The Kafka transaction only knows about Kafka. A crash after the database commit but before the Kafka commit repeats the record, and the database is written twice.
There are three ways to deal with it.
- Idempotent write: use an upsert, or record the event id with a unique constraint in the same database transaction, so the repeat does nothing.
- Outbox: write the output event into the database in the same transaction as the data, and publish it from there. Kafka transactions are then not needed for that hop.
- Synchronised transactions: Spring can commit the database transaction and the Kafka transaction one after the other. This shrinks the window, but it is a best effort, not a guarantee, because a crash between the two commits still leaves a gap.
I choose the first, since it is the simplest and the safest.
- “What is transaction.timeout.ms and why does it matter?”
It is the time the broker waits for a transaction to finish before it aborts it. The producer setting is
transaction.timeout.ms, default 60 seconds, and the broker has a ceiling for it (transaction.max.timeout.ms, 15 minutes by default).When the timeout passes, the coordinator aborts the transaction and bumps the epoch. The producer's next call fails with a fenced or invalid-epoch error, and the work is redone.
A worked example: a batch listener polls 500 records, and each takes 150 ms to process. That is 500 x 0.15 = 75 seconds, which is more than 60. The transaction is aborted before the commit, and the same batch is processed again, fails again, and loops.
The fix is to keep each transaction short: fewer records per poll, a faster handler, or a larger timeout set deliberately. I keep processing per transaction well below the timeout, around a third of it, and I never do a slow remote call inside a transaction.
Q91 · Design. “Design an idempotent consumer in Spring for payments, where a duplicate must never charge twice.”
Reveal answer
Strong answer Idempotent means that processing the same message twice has the same effect as processing it once. Kafka delivers at least once, so the dedup has to live in the consumer's own database.
I give every event a unique id (the producer sets it, for example the payment id plus a version). The consumer inserts that id into a processed_events table with a unique constraint in the same database transaction as the business write.
If the insert hits a duplicate-key error, the event was already handled: roll back nothing, skip, and let the offset commit. If the transaction fails any other way, nothing was recorded and a retry is safe.
Clean the table by age, keeping it longer than the topic's retention plus the longest replay window.
Picture it One listener method, one transaction, one unique constraint.
The setup: Event PaymentRequested carries eventId and amountCents.
CREATE TABLE processed_events (
event_id text PRIMARY KEY,
processed_at timestamptz NOT NULL DEFAULT now()
);@KafkaListener(topics = "payments")
@Transactional
void on(PaymentRequested e) {
try {
processed.insert(e.eventId()); // unique constraint
} catch (DuplicateKeyException dup) {
return; // ✅ already done, skip
}
ledger.charge(e.paymentId(), e.amountCents()); // same transaction
}Make the invisible visible: The same event delivered twice.
# illustrative output
delivery 1: insert e-77 ok, charge 19.99, commit db, crash before kafka commit
delivery 2: insert e-77 -> duplicate key -> skip, kafka commit ✓ charged onceWhy: The dedup record and the charge commit or roll back together, so a crash cannot leave one without the other.
Land it I store the event id in the same database transaction as the effect, so a replay hits a unique constraint and does nothing.
- “Why not check with a SELECT first?”
Because a check and an insert are two steps, and another thread can slip in between them. Both threads run
SELECT ... WHERE event_id = ?, both see no row, and both go on to charge the customer. This is the classic check-then-act bug.It is not rare. A redelivered record after a rebalance can reach a second consumer while the first is still working on it, so two copies run at the same time in different processes. A lock inside one JVM cannot stop that.
The unique constraint moves the decision into the database, which sees all writers. Whoever inserts first wins, and the other gets a duplicate-key error. That error is the answer to the question "was this already handled?"
dedup insertruns offline-- illustrative BEGIN; INSERT INTO processed_events(event_id, processed_at) VALUES (?, now()); -- unique(event_id) -- duplicate key error here means: already handled, skip UPDATE accounts SET balance = balance - ? WHERE id = ?; COMMIT;The insert and the charge sit in one transaction, so they succeed or fail together.
- “What if the event has no natural id?”
I use the record's own coordinates: topic, partition and offset, which are unique for each stored record. It is better than nothing, and it needs no cooperation from the producer.
The catch is that it identifies a record in the log, not the business event. Suppose the producer sends an event and the acknowledgement is lost, so it retries, and Kafka stores both copies at offsets 100 and 101. The consumer sees two different coordinates and treats them as two events. The idempotent producer prevents that duplicate at the source.
A business key is more robust. For example, the payment id plus a version, or an id generated once when the command was first created, and carried in a header or the value. It survives producer retries and replays into a new topic, where offsets would differ.
- “How long do I keep dedup rows?”
Longer than any plausible redelivery. A duplicate can only arrive as long as the old record can still be read, or as long as someone can rewind offsets and replay. So the rule is: topic retention plus the longest replay window I would allow.
dedup retentionruns offline# illustrative arithmetic, assumed numbers topic retention 7 days + replay window 7 days = keep 14 days at least 1,000 events/s x 86,400 s = 86.4 million rows per day 14 days = about 1.2 billion rows -> partition the table by day, drop old partitionsThe numbers show the real concern: at high volume this table is big. Deleting rows one by one with
DELETE ... WHERE processed_at < ?is slow and bloats the table. Partitioning by day and dropping a whole partition is cheap.The trap is cleaning too early. If the table forgets an event that is still in the topic, a replay charges again. I choose the retention from the topic's, and I add an alert if the oldest topic offset is older than the oldest dedup row.
- “What if the effect is an external API, not a database?”
The idea is the same, but the dedup has to live on the other side of the call, and the way to do that depends on what the API offers.
- Idempotency key: if the API accepts one, I send the event id as the key. The provider remembers it and returns the first result for a repeat. Payment providers usually offer this, so I use it first.
- Two-step record: if there is no such feature, I write a row marked started before the call and done after it. On a retry, a row stuck in started means the earlier attempt may or may not have worked.
- Query first: for that unclear state, I ask the API whether the thing exists, for example by looking up the charge by my own reference, before calling again.
If the API lets me attach no reference at all, I flag it as a risk. See the idempotency discussion in Chapter E7.
Q92 · Scenario. “Consumers keep getting kicked out of the group with 'max.poll.interval.ms exceeded', and the group rebalances constantly. Fix it.”
Reveal answer
Strong answer The consumer must call poll() again within max.poll.interval.ms (default 5 minutes). If processing one poll's records takes longer, the coordinator decides the member is stuck, removes it, and gives its partitions to others.
The processing then finishes, the offset commit fails because the member is gone, the consumer rejoins, and the same records are delivered again. That loop is the rebalance storm.
There are three honest fixes: process fewer records per poll (max.poll.records), make each record faster, or raise the interval. Raising the interval alone only hides it and slows failure detection.
Never do the long work on another thread while the poll thread idles, unless you pause the partitions and keep polling.
Picture it The arithmetic that shows the problem.
The setup: Default max.poll.records=500. Each record calls a slow API taking 800 ms.
500 records x 0.8 s = 400 s = 6 min 40 s > 5 min (300 s) ✗ kicked out
fix A: max.poll.records=100 -> 80 s ✓
fix B: parallelise calls 8-wide -> 500 x 0.8 / 8 = 50 s ✓The fix: Settings for fix A.
spring.kafka.consumer.max-poll-records=100
spring.kafka.consumer.properties.max.poll.interval.ms=300000Why: Time per poll equals records times cost per record. Keep that product well under the interval, with a 3x margin for slow days.
Land it The time to process one poll's records exceeded max.poll.interval.ms, so I shrink the batch or speed up the record, not just raise the limit.
- “How is this different from session.timeout.ms?”
They watch different things. The session timeout is about heartbeats. A background thread sends them every few seconds. If the broker hears none for
session.timeout.ms(default 45 seconds), it assumes the process is dead and removes the member.The poll interval is about the application thread. The heartbeats may continue perfectly while the thread is busy, but if it does not call
poll()again withinmax.poll.interval.ms(default 5 minutes), the consumer decides it is stuck and leaves the group.Setting Detects Default session.timeout.msa dead or frozen process, no heartbeats 45 s max.poll.interval.msa live process whose loop is stuck 5 min So the first detects dead processes and the second detects stuck ones. A long GC pause can trigger the first. A slow handler triggers the second. The cure differs, so I read the log message to see which one fired.
- “Does KIP-848 change this?”
It helps, but it does not remove the cause. With the new protocol (
group.protocol=consumer, Kafka 4.0 and later) the broker computes assignments, and rebalances are incremental. Members not affected keep working. So the damage from one kicked member is smaller than before, when a whole group could stop and wait.The poll-interval rule still applies. The client still expects the application to keep calling
poll(), and if the loop stalls pastmax.poll.interval.ms, the consumer leaves the group. Its partitions move to others, and its own commit may fail.So with a 10-minute handler and a 5-minute limit, the same loop appears: kicked, rejoined, same records again. The difference is that fewer other members are disturbed while it happens.
I would adopt the new protocol for its calmer rebalances, but I would still fix the slow processing. It lowers the blast radius, and the cause stays in my code.
- “What if I cannot make records faster?”
I move the slow work off the polling thread while keeping the poll loop alive. There are two ways.
- Queue inside the process: the listener hands records to a bounded executor. When the queue reaches a high-water mark, I pause the partitions. When it drains below a low-water mark, I resume. Polling continues the whole time, so the member stays in the group. Offsets are committed only for records that are finished.
- Scale out: more partitions and more consumers, so each member handles fewer records. If one record takes 10 seconds and 500 records arrive per poll, one thread needs over an hour. Ten partitions with ten threads cut it to a tenth.
The queue approach gives up simple ordering and commit rules, so I use the watermark design from Q77. Scaling out keeps the simple model. If I can choose, I scale out first and add the queue only when the work cannot be split.
- “How do I see that this is happening?”
I watch two signals. One is the rebalance count per hour for each group:
rebalance-totalandrebalance-rate-per-houron the consumer, or the broker's group state. A stable group should rebalance only at deploys. The other is the warning in the consumer log.logruns offline# illustrative output WARN consumer poll timeout has expired. This means the time between subsequent calls to poll() was longer than the configured max.poll.interval.msThat line tells me exactly which rule fired, so I do not have to guess between the poll interval and the session timeout.
The consumer also publishes
last-poll-seconds-ago. I alert when it rises above half ofmax.poll.interval.ms, which warns me before the member is removed, not after. And I alert when a group that should be stable rebalances more than a couple of times per hour.With those three alerts, a slow handler shows up as a warning on a dashboard hours before it becomes a storm.
Q93. “How do you apply backpressure in a Spring Kafka consumer when the downstream is slow?”
Reveal answer
Strong answer Kafka consumers pull, so backpressure is natural: you just poll less. The trick is to stop fetching without being kicked out of the group, which means you must keep calling poll().
The tool is pause() and resume(). A paused partition returns no records from poll, but the consumer keeps heartbeating and stays a member. Spring exposes it through the MessageListenerContainer.
The pattern: hand records to a bounded queue; when the queue passes a high-water mark, pause; when it falls under a low-water mark, resume.
Using two marks, not one, avoids flapping on and off every few records.
Picture it Queue depth against pause state.
The setup: A database accepts 500 writes per second. The topic delivers 2,000 per second.
@Autowired KafkaListenerEndpointRegistry registry;
void check(int depth) {
var c = registry.getListenerContainer("billing");
if (depth > 800 && !c.isContainerPaused()) c.pause(); // high-water mark
if (depth < 200 && c.isContainerPaused()) c.resume(); // low-water mark
}Make the invisible visible: What happens over a few seconds.
# illustrative output
t=0 depth 0 fetching 2000/s
t=1 depth 1500 pause() polls return empty, heartbeats continue
t=3 depth 100 resume()
group stays stable; lag grows in Kafka, not in the JVM heap ✓Why: The backlog waits in the broker, which is built for it, rather than in your heap, which is not.
Land it I pause partitions when my queue is full and resume when it drains, so the backlog stays in Kafka and the consumer stays in the group.
- “Why not just sleep in the listener?”
Because sleeping stops the calls to
poll(), and aftermax.poll.interval.ms(default 5 minutes) the member is evicted. Its partitions move away, the commit fails, and the group rebalances, which is exactly the storm I wanted to avoid.Pause keeps polling alive. A paused partition returns no records, but the loop keeps going, so the consumer stays a member and heartbeats and the interval check are satisfied. When the downstream recovers, I resume.
The loop still runs, so it also keeps reacting to rebalances. A sleeping thread cannot, so a rebalance can leave it waiting with stale partitions.
A short sleep is fine as long as the total stays far below the poll interval. For example, a 200 ms pause between batches when the limit is 5 minutes is harmless. The trouble starts when the sleep length depends on a slow downstream and has no upper bound. I use pause when the wait can last seconds or more, and a short sleep only for tiny back-offs.
- “Does pause lose records already fetched?”
No records are lost. Pausing changes what the consumer fetches from now on, not what it has already committed. The committed offset does not move, and the consumer's position stays where it was, so on resume it continues from the same place.
In Spring, a pause requested on the container usually takes effect on the next pass of the loop, after the current poll's records have been handled. So records already returned by the last poll are still processed. There is an option for pausing sooner, and I read the reference for my version before relying on it.
What can happen is that fetched data is held by the client while paused, and it is returned after the resume. The same bytes are not fetched twice and not skipped.
If the process crashes while paused, the committed offsets decide the restart point, as always. Records processed but not yet committed repeat, so the handler must be idempotent. Pausing adds no new risk in that respect.
- “How does this appear in monitoring?”
While a pause is active, the consumer lag rises, and that is expected. The records are waiting in Kafka as intended. So a lag alert alone would page for a healthy back-pressure event. I make the alert smarter.
I alert on lag that rises while no pause is active, because that means the consumer is slow for another reason. I also alert on a pause that lasts longer than a set limit, say 10 minutes, because that means the downstream is down and a human should look.
To make both visible, I add three metrics of my own: a gauge for queue depth, a gauge for whether the container is paused (one or zero), and a counter for pause events. A counter that climbs every few seconds shows the water marks are too close together.
With these, a dashboard shows the story: queue full, paused, drained, resumed. Without them, back-pressure looks like an unexplained lag graph.
- “When is scaling out better than pausing?”
When the downstream can actually take more load. Pausing protects a system with fixed capacity. Scaling out only helps if capacity exists behind the consumer.
- Check the ceiling: suppose the sink database can do 400 writes per second. Each consumer pod sends 300 per second when running flat out.
- Do the arithmetic: two pods offer 600 per second, which is already over the limit. A third pod offers 900, and the database is hit by more than twice what it can take, so errors and slowness grow for everyone.
- Choose: pausing holds the surplus in Kafka at no harm. Scaling out would make the incident worse.
If the sink is an elastic service, or the slowness is inside my own CPU-bound code, more pods help. I look at where the saturation is, and I scale only the part that is saturated.
Q94. “What is a batch listener, and how do you handle one bad record in a batch?”
Reveal answer
Strong answer A batch listener receives a List of all records from one poll in a single method call. It suits bulk writes such as a JDBC batch insert, which is much faster than one insert per record.
The problem is failure: if the call throws, the container does not know which record was bad, so by default it retries the whole batch.
Throw BatchListenerFailedException with the index (or record) that failed. Spring commits the records before it, and handles the failing one with the error handler, then redelivers the rest.
Make the handler idempotent anyway, since a retried batch repeats the earlier records.
Picture it One batch of five with the third record bad.
The setup: Batch listener enabled, bulk inserts.
@KafkaListener(topics = "orders", batch = "true")
void on(List<ConsumerRecord<String, OrderPlaced>> recs) {
for (int i = 0; i < recs.size(); i++) {
try { repo.save(recs.get(i).value()); }
catch (Exception ex) {
throw new BatchListenerFailedException("bad record", ex, i); // ✅ tell Spring which
}
}
}Make the invisible visible: What the container does with the index.
# illustrative output
batch: r0 r1 r2(bad) r3 r4
r0 r1 saved; r2 throws index 2
container commits offsets for r0, r1
r2 -> retries, then dead-letter
r3 r4 redelivered as a new batch ✓
without the index: whole batch retried, r0 r1 written twice ✗Why: The index lets Spring commit partial progress instead of replaying everything.
Land it Batch listeners trade simplicity for speed, and BatchListenerFailedException is what stops one bad record from replaying the whole batch.
- “How big is a batch?”
It varies, and I never assume a fixed size. A batch is whatever one
poll()returns, up tomax.poll.records(default 500). If the topic is quiet it may hold 3 records. If there is a backlog, it hits 500.What the poll returns depends on the fetch settings: the broker answers when
fetch.min.bytesare ready orfetch.max.wait.mshas passed. With an average record of 1 KB andfetch.min.bytesof 64 KB, a busy partition gives about 64 records per fetch before the wait runs out.If I want larger bulk inserts, I raise three settings together:
max.poll.recordsfor the ceiling,fetch.min.bytesso the broker collects more before answering, andfetch.max.wait.msas the longest I accept waiting for it. The last one adds latency when traffic is light.The code must also work with a batch of one. I test with a tiny batch and a full one, because both occur in production.
- “Are batch listeners compatible with retry topics?”
I would not count on it. As far as I know, the annotation-based
@RetryableTopicdoes not support batch listeners, and the reference says so. Versions change, so I read the reference for the version I run before deciding.For a batch listener I would use the error handler path.
- Identify: throw
BatchListenerFailedExceptionwith the failing record's index, so Spring knows which record failed. - Recover: let
DefaultErrorHandlerwith a dead-letter recoverer park that record after its retries. The records before it are committed, and the rest are redelivered. - Replay: read the dead-letter topic with a small job when the bug is fixed.
If I truly need non-blocking retries with batches, I would split the work. A batch listener reads and bulk-writes, and records that fail are published by hand to a retry topic that a record-based listener consumes.
- Identify: throw
- “How do I do a real bulk insert safely?”
The bulk insert must be fast and repeatable. Fast means sending many rows in one statement or one JDBC batch. Repeatable means a replay does no harm. The batch listener will, sooner or later, receive the same records again after a crash or a retry.
bulkruns offline-- illustrative INSERT INTO orders(id, total) VALUES (?, ?) ON CONFLICT (id) DO NOTHING; -- run as one JDBC batch; for PostgreSQL add reWriteBatchedInserts=true to the URLThe conflict clause is keyed by the event or entity id, so a row that already exists is skipped silently. The whole batch then succeeds even when half of it is a repeat.
The speed difference is large. With assumed numbers, 500 single inserts at 2 ms each take about 1 second, while one batched statement may take 30 to 50 ms. I measure on my own database.
If one row can be invalid, I validate before the insert. Otherwise one bad row makes the statement fail, and the whole batch fails with it.
- “What about ordering in a batch?”
A batch contains records from several partitions, and within each partition they are in order. It does not give one global order across partitions. Kafka never promised that, and the batch shape does not change it.
If processing depends on per-key order, I group the batch by key first, and I process each key's records in the order they appear. For example,
OrderCreated, thenOrderPaid, thenOrderShippedfor order 7 run as one sequence. Different keys can run in any order.If I parallelise inside the batch, the unit of parallel work is the key group, never a single record. Two threads on the same key would swap the order and create exactly the bugs ordering was meant to prevent.
A simpler way is to avoid parallelism and let the batch run sequentially, since the speed gain comes from the bulk write, not from threads. I add threads only after measuring that the handler, not the database, is the bottleneck.
Q95 · Scenario. “A team wants synchronous request-reply over Kafka with ReplyingKafkaTemplate. Is that a good idea?”
Reveal answer
Strong answer It can be done: the requester sends a record with a correlation id and a reply-topic header, and the responder publishes the answer to that topic. The template matches replies to waiting requests by correlation id.
But it fights the grain of Kafka. Latency is higher and less predictable than HTTP because of batching, polling and commits. Every requester instance needs its own reply topic or partition, and a reply for an instance that restarted is lost.
I would use it only when the request must flow through Kafka for another reason, such as audit or routing, and the caller can tolerate delays. For plain synchronous queries I use HTTP or gRPC.
If it must be asynchronous, return 202 Accepted and let the client poll or receive a callback.
Picture it Where the reply goes, and where it can be lost.
The setup: Pod A sends a request; pod A restarts before the reply arrives.
A --req(corr=9, reply=replies-A)--> requests --> responder
responder --reply(corr=9)--> replies-A
A restarts at t=2s; new A has a new member id, still reads replies-A
the waiting future for corr=9 died with the old JVM ✗ reply is orphanedMake the invisible visible: Comparison of options.
| Option | Pick it when | Cost or catch |
|---|---|---|
| HTTP or gRPC | Caller needs an answer in milliseconds | Caller and callee must both be up |
ReplyingKafkaTemplate | Kafka routing/audit is required, delays tolerable | Slow, reply topic management, lost futures on restart |
| Async event + callback | Work takes seconds or more | Client must handle “not yet” state |
Why: Kafka is a log, not a call stack. Forcing call semantics onto it brings timeouts and orphan replies.
Land it I would push back: Kafka is great for events, not for synchronous calls, so I would use HTTP or an async event with a status endpoint.
- “What is the correlation id for?”
It ties a reply to the specific request that is waiting for it. When the requester sends, the template creates a random correlation id, puts it in a header, and keeps a map of pending futures keyed by that id. The responder copies the header onto its reply. When the reply arrives, the template looks up the id and completes the matching future.
Without it, a requester that has ten calls in flight could not tell which answer belongs to which.
If no reply comes, the future fails with a timeout after the configured reply timeout. I believe the default is five seconds, and I set it explicitly instead of trusting that. A timeout does not mean the request failed. The responder may be finishing it at that moment, so the caller must treat the result as unknown.
The pending map is in memory, so a requester restart loses every waiting call.
- “How do multiple requester instances share one reply topic?”
It needs care, and that care is part of the cost. A reply topic is shared, so if two requester instances both read all of it, instance B receives instance A's reply, finds no pending request with that id, and discards it. Instance A never gets its answer and times out.
There are two ways to prevent it. One is a separate reply topic for each instance. The other is a shared topic where each instance reads only its own partition. In both cases the request carries a header telling the responder where to send the reply.
Each way has a price. A topic per instance means creating and cleaning up topics as pods come and go, and it does not fit autoscaling well. Partition ownership means the number of partitions limits the number of requesters, and instances must agree on who owns which.
- “Is there a case where it is justified?”
Yes, in a few narrow cases. One is a legacy integration where Kafka is the only shared bus between two systems, and nothing else can connect them. Another is a path across data centres or networks where traffic already goes through Kafka because direct connections are not allowed.
A third is when the request must pass through Kafka for audit or routing, and the reply is a convenience for one caller.
Even then I set a short timeout, and I treat a timeout as unknown, not as failed. The responder may have processed the request, so the caller must be able to ask again safely. That means the request carries an idempotency key, or the operation is a read.
That rule is the same for any remote call. The network gives no certainty, and Kafka adds more delay and more moving parts between the question and the answer.
- “What would you build instead for a long operation?”
I would build an asynchronous job with a status endpoint. It has four steps, and each is simple to explain and to test.
async job flowruns offline# illustrative POST /exports -> 202 Accepted, Location: /jobs/42 (a worker consumes the job from a Kafka topic and updates the row) GET /jobs/42 -> {"status": "running"} GET /jobs/42 -> {"status": "done", "result": "/files/42.csv"}The state of the job lives in a database row, not in memory, so it survives restarts of both the requester and the worker. The client gets an id immediately and never holds a connection open.
If waiting is awkward, I offer a webhook as an alternative: the worker calls a URL the client registered when the job finishes.
Kafka does what it is good at: it carries the work to workers and absorbs bursts. The request and the answer are separate events, and the status row is the only thing the caller needs.
Q96. “JSON, Avro or Protobuf for Spring Kafka messages, and what is the type-header risk?”
Reveal answer
Strong answer JSON is readable and needs no schema tooling, but it is large, loose and lets fields drift unnoticed. Avro and Protobuf are compact binary formats with a schema, so a consumer knows exactly what shape to expect and compatibility can be checked automatically.
With Spring's JsonSerializer, the producer adds a type header with the Java class name. The consumer's JsonDeserializer uses it to create the object. That ties consumers to producer class names and, if packages are not restricted, lets a message pick any class to instantiate.
I restrict spring.json.trusted.packages to my event package, or turn off type headers and give the consumer a fixed default type.
For a company-wide event backbone I pick Avro or Protobuf with a schema registry.
Picture it The same event in three encodings.
The setup: Event: order o1, total 1999 cents, currency EUR.
# illustrative output
JSON {"orderId":"o1","totalCents":1999,"currency":"EUR"} about 55 bytes, names repeated every record
Avro 00 <schema id> 04 6f 31 ... about 12 bytes, names live in the registry
Protobuf 0a 02 6f 31 10 8f 0f 1a 03 45 55 52 about 12 bytes, field numbers not namesMake the invisible visible: The safe consumer settings for JSON.
spring.kafka.consumer.properties.spring.json.trusted.packages=com.shop.events
spring.kafka.consumer.properties.spring.json.use.type.headers=false
spring.kafka.consumer.properties.spring.json.value.default.type=com.shop.events.OrderPlacedWhy: Without the restriction a message decides which class gets built, which is the shape of a deserialization attack.
Land it Binary formats with a registry for shared topics, JSON only for small local ones, and always restrict the type header.
- “Why is JSON worse for evolution?”
Because nothing enforces anything. JSON is just text, so the producer and the consumer agree only by habit. A field can be renamed, retyped or dropped, and nobody is told.
A concrete case: the producer renames
customerIdtocustomer_id. The producer's tests pass, and it deploys. The consumer still looks forcustomerId, finds nothing, and silently sets the field to null. No exception, no alert. The first sign is a wrong report days later.With a schema registry the same rename is a schema change, and the registry checks it against the compatibility rule before any record is written. A rename looks like removing one field and adding another, so under most rules it is refused, and the producer's deploy fails in CI.
You can add JSON Schema to a registry to get these checks for JSON as well. But then you carry the schema tooling and still pay JSON's size, so teams usually move to Avro or Protobuf at that point.
- “When would you still pick JSON?”
I still pick JSON for low-volume topics, for debugging convenience, and for consumers in many languages where schema tooling is a burden. A topic with a few hundred events a day, read by one team, does not need a registry. Anyone can inspect it with a console consumer, which is a real benefit during an incident.
The cost is size and weak contracts. Field names repeat in every record, numbers are text, and nothing checks the shape.
size arithmeticruns offline# illustrative, assumed sizes one event: about 1,000 bytes as JSON, about 300 bytes as Avro 10 million events/hour: 10 GB vs 3 GB of payload per hour x 3 replicas, kept for 7 days: the gap becomes terabytesThat gap shows up in disk, network and cross-zone transfer bills. Compression narrows it, because repeated field names compress well, but it does not close it, and compression costs CPU.
My rule: JSON for small and local, binary with a registry for shared and large.
- “Avro or Protobuf?”
Both are good, and the choice is mostly about the ecosystem.
Avro Protobuf Fits best Kafka and big-data tools teams already using gRPC How it evolves reader and writer schema are resolved together numbered fields, unknown ones are skipped Code generation available, often optional strong, standard Avro needs the writer's schema to read a record, which the registry provides. The reader resolves differences by matching field names and using defaults. Protobuf identifies fields by number, so a field can be renamed freely, but a number must never be reused for something else.
If the organization already has Protobuf messages and tooling for gRPC, I would stay with Protobuf and avoid a second toolchain. If the data flows into Spark or a warehouse, Avro is the smoother path. Pick one per organization.
- “What does the consumer need besides the class?”
It needs three things besides the class.
- Registry address: the URL, set with
schema.registry.urlin the deserializer config, and the matching Avro or Protobuf deserializer class. - Credentials: if the registry requires them, a username and password or a token, and TLS trust settings. These are easy to forget in a new environment.
- Specific or generic type: a setting that tells the deserializer whether to build the generated class or a generic record. The wrong choice gives generic maps where the code expects typed objects.
At runtime, each record starts with the schema id. The consumer fetches the schema for that id once, caches it, and decodes with it, so later records of the same id cost nothing extra.
A registry outage therefore affects only cold starts and new schema ids. A running consumer with a warm cache keeps working, but a new pod that cannot reach the registry cannot start reading.
- Registry address: the URL, set with
Q97 · Scenario. “After a deploy, consumer throughput halves although the code is the same. Where do you look in the consumer config?”
Reveal answer
Strong answer I diff the effective config first, since a Spring Boot upgrade can change defaults or a property rename can silently disable a setting and fall back to a default.
Then the usual suspects: max.poll.records too low (more polls per record), fetch.min.bytes and fetch.max.wait.ms (small fetches), concurrency lower than before, and compression or deserializer changes that cost CPU.
Next, outside the config: a slower downstream, a new synchronous call added in the listener, or a pod CPU limit throttling the JVM.
I compare two numbers per instance before and after: records per poll and time per poll. They show whether the cost moved in fetching or in processing.
Picture it Two metrics that separate fetching from processing.
The setup: Before: 8,000 records/s. After: 4,000 records/s.
# illustrative output
before after
records per poll 480 35 <- fetch got small ✗
time per poll 60 ms 55 ms <- processing unchanged
polls per second 16 80
cause: max.poll.records default lost in a renamed propertyThe fix: Set the properties explicitly and verify.
spring.kafka.consumer.max-poll-records=500
spring.kafka.consumer.fetch-min-size=65536
spring.kafka.consumer.fetch-max-wait=200msWhy: Per-poll numbers point at the layer that changed.
Land it I diff the effective consumer config and compare records-per-poll and time-per-poll before and after to find which layer slowed.
- “How do I print the effective config?”
The consumer logs its full
ConsumerConfig valuesat startup, at INFO level, with every setting and its effective value. That includes defaults I never wrote, which is exactly what I want to see. So I compare the startup line from before the deploy with the one after.diffruns offline# illustrative diff <(grep -A60 "ConsumerConfig values" before.log) <(grep -A60 "ConsumerConfig values" after.log) # a changed max.poll.records or fetch.min.bytes shows up as one differing lineThe logged block spans many lines, one per setting, so I select enough lines after the marker to cover them all. A key renamed in the upgrade shows as a value that has fallen back to the default, for example
max.poll.records = 500where I had set it to 2000.If logs are not kept, I compare the property files and the Spring Boot version's migration notes. I also keep the old startup log with the release, so the comparison is always possible.
- “What does fetch.min.bytes do?”
It is the smallest amount of data the broker will return for one fetch request. The broker holds a fetch until at least that many bytes are ready or
fetch.max.wait.mspasses, whichever comes first.The default is 1 byte, so the broker answers as soon as any data exists. At a low rate that means many tiny fetches. If a topic receives 50 records per second, the consumer may make close to 50 requests per second, each carrying one record, and each paying for a full round trip and a handful of small network packets.
Raising it to 64 KB makes the broker wait to collect a bigger chunk. The fetches become fewer and more efficient, and the CPU on both sides drops. The price is latency: on a quiet topic a record can wait up to the full
fetch.max.wait.ms.That is why a changed or lost value matters after a deploy. A property that silently returned to 1 byte can double the request rate and halve throughput.
- “Could it be the broker, not the consumer?”
Yes. If every service reading from the same brokers slowed down at once, I suspect the brokers. A slow broker lowers all of its consumers together. If only one service slowed, the cause is on its side.
- Request latency: the broker metric
kafka.network:type=RequestMetrics,name=TotalTimeMs,request=Fetchshows how long fetches take. A rise there points to the brokers. - Thread idle ratios: if the request handler threads or the network processor threads are close to fully busy, the broker is saturated.
- Disk and network: disk wait, and replica fetching from followers that saturates the network after a broker restart or a new topic.
I also check whether the consumers' own broker connection changed, for example a different zone or a proxy added in the deploy. A consumer moved to a remote zone gets slower fetches without any broker fault.
- Request latency: the broker metric
- “How do I keep this from happening again?”
I do three things, in the order of cheapness.
- Explicit settings: I write the important consumer settings in code or config, instead of relying on defaults that can change between versions.
max.poll.records,fetch.min.bytes,fetch.max.wait.msand the concurrency are all listed in the repository, so a change shows up in review. - Load test with a gate: staging runs a recorded or generated workload and compares throughput with a stored baseline. A drop of more than, say, 10 percent fails the pipeline.
- Dashboard: records per poll, time per poll and lag per group, shown for the old and new version side by side during a rollout.
The aim is to catch a halved throughput in staging, or in the first canary pod, not in the middle of a traffic peak.
- Explicit settings: I write the important consumer settings in code or config, instead of relying on defaults that can change between versions.
Q98 · Design. “Design the order service so it saves an order and publishes OrderPlaced without ever losing or inventing an event, in Spring Boot.”
Reveal answer
Strong answer The save and the publish are in two systems, so one transaction cannot cover both. The robust design is the transactional outbox: the service writes the order and an outbox row in one database transaction, and a separate relay publishes the outbox rows to Kafka.
The relay can be a poller or, better, Debezium reading the database's change log and routing outbox rows to topics. Either way the publish is at-least-once, so consumers are idempotent.
The event id is the outbox row's id, the key is the order id (so all events of one order stay in order), and consumers dedup on the event id.
No event is lost, because the row is committed with the order. No event is invented, because a rolled-back order has no row.
Picture it The write path and the relay.
The setup: POST /orders inserts into orders and outbox together.
@Transactional
public Order place(NewOrder in) {
Order o = orders.save(Order.from(in));
outbox.save(new OutboxEvent(UUID.randomUUID(), "order", o.getId(),
"OrderPlaced", json(o))); // same transaction
return o;
}Make the invisible visible: The two crash points and what survives.
# illustrative output
crash before commit : no order, no outbox row, no event ✓ consistent
crash after commit, before relay: order + outbox row exist; relay publishes on restart ✓
relay publishes, crashes before marking sent: published twice -> consumer dedups ✓Why: The database transaction is the only source of truth; Kafka is fed from it, never in parallel with it.
Land it I write the event to an outbox table in the same transaction as the order and let Debezium or a poller publish it, with idempotent consumers.
- “Debezium or a polling relay?”
I choose by volume and by how much database load I can accept. The two relays have different shapes.
A poller is simple: select unsent rows, publish them, mark them sent. It adds query load to the database, and it needs care. Two poller instances must not publish the same row, and rows must be taken in order, with attention to gaps caused by transactions that commit out of id order.
Debezium reads the database's write-ahead log, so it adds no query load and sees changes in commit order. It is another system to run, with its own connector, offsets and monitoring, and the database must allow log reading with the right settings.
I start with a poller for a small system, because it is a few dozen lines and easy to debug. I move to Debezium when the event rate, the latency target or the database load calls for it. The event contract does not change between them. See the outbox pattern.
- “How do you keep the outbox table small?”
How I clean up depends on the relay.
With Debezium, I delete the row right after inserting it, in the same transaction. The connector reads the insert from the log, so the event is not lost even though the row is already gone. The table stays almost empty, and it never grows.
With a poller, the row has to remain until it is published, so I delete or archive it after publishing. A cleanup job removes rows marked sent that are older than, say, a day. Keeping a short history helps debugging a stuck event.
A growing outbox table is not harmless. The poller scans for unsent rows, and a large table with a poor index makes that scan slow, which delays every event. I keep an index on the unsent status and the id, and I alert when the oldest unsent row is older than a minute. That one alert catches a stopped relay, a slow relay and a bloated table.
- “What guarantees ordering of one order's events?”
The key. Every event of order o1 is published with key o1. The key decides the partition, so all events of that order land in one partition, and Kafka keeps the order inside a partition. Consumers then see them in the order they were published.
That order is only as good as the relay's order. The relay must publish an order's events in the order they were committed, which means by outbox id for each key. Debezium does this naturally, since it follows the commit log. A poller with several instances can break it, so I run one poller per key range, or one instance at a time.
The producer settings matter as well. With idempotence on, retries cannot reorder records in a partition. I keep that default.
Order across different orders is neither guaranteed nor needed. Order o1 and order o2 are independent, so they may be interleaved freely. I only fix the order where a consumer would break without it.
- “Could Kafka transactions replace the outbox here?”
No. A Kafka transaction covers Kafka writes and Kafka offsets. It does not include the database, so it cannot make an order row and an event commit together. The outbox is the part that joins the database to Kafka.
There is a tempting idea: write to the database, then send inside a Kafka transaction. That still leaves a gap. If the database commits and the process crashes before the Kafka transaction commits, the event is lost. Nothing connects the two commits.
Transactions are useful later in the pipeline. When a consumer reads one topic, transforms the record and writes to another topic, the output and the input offset can move together, so a crash leaves neither half done. That is the consume-transform-produce case.
So the two tools do different jobs. The outbox gives me a reliable first publish from a database. Transactions give me exactly-once between topics. A pipeline can use both, and I only add the second when a duplicate between topics would really hurt.
These questions test whether you can keep data changing safely across teams, and move data between databases and Kafka without losing or doubling it.
Q99. “What does a schema registry do, and what is actually on the wire?”
Reveal answer
Strong answer A schema registry is a small service that stores schemas and gives each one a numeric id. Producers register the schema of what they send; consumers look up the schema by id to decode it.
On the wire, each record starts with one magic byte (zero), then a four-byte schema id, then the encoded payload. So the schema itself is never repeated in the record.
The registry also enforces compatibility rules: a producer who registers a new version that breaks the rule is refused before any bad data is written.
Consumers cache schemas by id, so the registry is only asked once per id per process.
Picture it Bytes of one record.
The setup: An Avro order event with a 4-byte id, schema id 42.
# illustrative output
byte 0 : 00 magic byte
bytes 1-4 : 00 00 00 2a schema id 42 (big-endian)
bytes 5-... : avro-encoded fields (no field names)
consumer: id 42 -> ask registry once -> cache -> decode every later record locallyMake the invisible visible: What the registry rejects.
# illustrative output
POST /subjects/orders-value/versions (adds required field "coupon", no default)
-> 409 Conflict: schema being registered is incompatible with an earlier schema
(compatibility = BACKWARD) ✗ refused before productionWhy: The refusal happens at registration time, in CI or at producer start, not at 3 a.m. in a consumer.
Land it The registry maps schema ids to schemas and checks compatibility, so records carry only a five-byte prefix and breaking changes are refused early.
- “What happens if the registry is down?”
The effect depends on what the process has already cached, so I look at four situations.
- Running producers: they already know the schema id for the schemas they use, so they keep sending without calling the registry.
- Running consumers: they have cached the schema for each id they have seen, so they keep reading.
- New schema or new id: a producer registering a new version, or a consumer meeting an id it has not seen, needs the registry, and fails or retries until it returns.
- Cold start: a new pod starts with an empty cache, so it cannot decode its first record. During a registry outage, scaling up or a rolling deploy can fail.
So an outage hurts at the edges, not in the steady state. I run the registry replicated, behind a load balancer, and I treat it as critical infrastructure for startup. I also avoid deploying while it is unhealthy.
- “Where does the registry store schemas?”
In a Kafka topic, usually called
_schemas. It has a single partition and is compacted, so the latest entry for each key is kept. Every registered schema is a record in that topic.That makes the registry a client of Kafka. On startup, an instance reads the topic and rebuilds its state in memory. If an instance is lost, a new one recovers everything from Kafka.
In a registry cluster, one instance is the leader and takes all writes, which avoids conflicting ids. The others serve reads.
There is a dependency loop to remember: the registry needs Kafka to run, and the applications need both. So the topic needs the same care as any critical data: a replication factor of 3, a sensible
min.insync.replicas, and a backup or a mirror. Losing it would lose the mapping from schema ids to schemas, and the records could no longer be decoded.- “What is a subject?”
A subject is a named scope under which the registry keeps the versions of a schema. Compatibility is checked between versions inside one subject.
By default, the subject name is the topic name plus
-keyor-value. So the schemas for the value of the topicordersgo under the subjectorders-value, as versions 1, 2 and 3.subjectsruns offline# illustrative orders-value v1 -> v2 -> v3 each new version checked against the earlier ones orders-key v1 payments-value v1 -> v2Other naming strategies exist. A record-name strategy uses the schema's full name instead of the topic, which allows several event types in one topic, each with its own evolution. I would use that when a topic carries a family of related events.
The subject is also the unit I set the compatibility mode on, and the unit that access control can protect.
- “Does the registry validate the data itself?”
No, the registry never sees the data. It stores schemas and answers questions about them. The checking of a value happens in the client, in the serializer.
When the producer calls the serializer, it tries to encode the object with the schema. A wrong type, such as a string where a number is required, or a missing required field, fails right there, before anything is sent. So bad data from a well-behaved application stops at the producer.
Then it writes the magic byte, the four-byte schema id and the encoded payload, and the consumer reverses the steps.
The weak point is that none of this is forced on the topic. The broker does not check that a record follows a schema. A producer that writes raw bytes, or uses a plain serializer by mistake, bypasses everything, and the consumers then fail at deserialization. Two defences help: ACLs on who may produce, and the poison-pill handling from Q87 on the consumer side.
Q100. “Explain BACKWARD, FORWARD and FULL compatibility, and which side you upgrade first.”
Reveal answer
Strong answer BACKWARD means a consumer with the new schema can read data written with the old schema. FORWARD means a consumer with the old schema can read data written with the new one. FULL is both.
BACKWARD is the registry's default. Under it you upgrade consumers first, because they must be able to read old data still in the topic, and then producers.
Under FORWARD you upgrade producers first, since old consumers will see new data. The _TRANSITIVE variants check against all earlier versions, not just the latest.
In Avro terms: adding a field with a default is safe both ways; removing a field with a default is safe both ways; adding a required field without a default breaks BACKWARD.
Picture it Three changes against the rules.
The setup: Version 1 has orderId, total.
| Change | BACKWARD | FORWARD |
|---|---|---|
Add coupon with default null | ✓ | ✓ |
Add coupon, no default | ✗ new reader cannot fill it from old data | ✓ |
Remove total (no default) | ✓ | ✗ old reader needs it |
Rename total to amount | ✗ | ✗ |
Make the invisible visible: Upgrade order under BACKWARD.
1. deploy consumers with schema v2 (can read v1 and v2 data)
2. deploy producers writing v2
if you flip it: producers write v2 first, old consumers see unknown data ✗ (only safe under FORWARD)Why: The data in the topic outlives the code. The rule is about who has to understand whose bytes.
Land it BACKWARD lets new readers read old data, so consumers go first; FORWARD is the mirror; FULL needs both, and adding fields with defaults is the safe move.
- “Which mode should I pick for a shared topic?”
I would first ask who deploys in what order, and who may replay old data. I lean to FULL_TRANSITIVE for a shared topic, if I can live with its limits. Then any producer version and any consumer version can work together, and the deploy order stops mattering. For many teams that is the least stressful rule, because no one has to coordinate.
The limits are real. FULL means each change must be safe in both directions, so the allowed changes shrink to adding or removing fields that have defaults. A change that is natural for the business, such as making a field required, is refused, and I have to do it in several steps.
BACKWARD, the default, is fine when consumers reliably upgrade before producers. That needs discipline, and on a topic with many teams it tends to slip. Then a producer deploys first and breaks someone.
So I weigh the discipline I trust against the freedom I need, and I write the choice down.
- “What does transitive add?”
It checks the new schema against every earlier version in the subject, not only the latest one. The non-transitive modes compare with the previous version alone, and that leaves a gap.
why transitiveruns offline# illustrative, BACKWARD, new reader checked against older data v1: id, region v2: id, region, tier (default "basic") v3: id, tier (no default) v3 reads v2 data: ok (tier is present) v3 reads v1 data: FAILS (tier is missing, no default) BACKWARD checks v3 only against v2 -> passes BACKWARD_TRANSITIVE checks v3 against v1 and v2 -> refusedEach step looks safe on its own, yet v3 and v1 are not compatible. The gap stays hidden while only new records are read. It shows up when a consumer replays the topic from the beginning, or a new consumer group starts at the earliest offset, and meets old v1 records. The failure then arrives months after the schema change, far from whoever caused it.
The price is stricter rules, because every new version must fit all the old ones. If I ever replay a topic from the start, or keep records for a long time, or rely on compacted topics where old records stay forever, I use a transitive mode.
- “How do I rename a field safely?”
I never rename in one step. A rename looks like removing one field and adding another, so the registry rejects it under most rules, and any consumer reading the old name breaks. I use the expand-and-contract approach.
- Add the new field: add
customer_idwith a default, next to the oldcustomerId. This version is compatible both ways. - Write both: for a while the producers fill both fields, with the same value.
- Migrate readers: consumers switch to the new field, team by team.
- Remove the old one: when no reader uses the old field, a later version removes it. The old field must have had a default for this removal to be compatible.
Avro aliases can help on the reader side, since a reader can declare that an old name is an alias of a new one. I use them as a bridge, not instead of the steps above.
- Add the new field: add
- “Where is the check run?”
In two places. In CI, I call the registry's compatibility endpoint with the new schema before the merge, so a breaking change fails the pull request and not the production deploy. And at registration time, when the producer registers its schema, as the last line of defence.
ciruns offline# illustrative curl -s -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \ --data @new-order.avsc \ http://registry:8081/compatibility/subjects/orders-value/versions/latest # {"is_compatible": true}The call returns whether the schema is compatible, and CI fails the build on
false. The check uses the subject's current compatibility mode, so it applies the same rule the registration will.I turn off automatic registration of schemas in production applications. Otherwise a service can register any schema at startup, and the check moves from the pull request to the deploy. With that setting off, schemas are registered by the pipeline only after the check has passed.
Q101 · Scenario. “A producer team added a required field, deployed, and every consumer crashed. What went wrong and how do you stop it happening again?”
Reveal answer
Strong answer The new schema had a field with no default, which is a breaking change under BACKWARD (and for any consumer still on the old schema, under FORWARD). Either the registry was set to NONE, or the team bypassed it.
Consumers on the old schema hit data they cannot decode, or consumers on a new schema choked on old records missing the field. Then the poison record stops the partition, as in the earlier deserialization question.
Immediate fix: roll back the producer so new records use the old schema, and dead-letter the bad ones. Longer-term: set compatibility on every subject, check in CI, and block registration from application credentials.
The cultural fix: schema changes get a review like database migrations.
Picture it Timeline and gate.
The setup: The compatibility level for orders-value is NONE.
# illustrative output
10:02 producer v2 deployed, adds required "coupon"
10:03 consumers: org.apache.avro.AvroTypeException ... missing field coupon
10:04 lag 0 -> growing on all partitions
10:09 producer rolled back; bad records dead-lettered; lag drains by 10:20The fix: The gate.
curl -X PUT -H "Content-Type: application/vnd.schemaregistry.v1+json" \
--data '{"compatibility":"FULL_TRANSITIVE"}' http://registry:8081/config/orders-value
# CI step: POST new schema to /compatibility/..., fail the build if "is_compatible": falseWhy: One failed build is cheaper than an incident. The registry is the shared referee.
Land it The schema change broke the compatibility rule because nothing enforced it, so I set a compatibility level per subject and run the check in CI.
- “Who should be allowed to register schemas in production?”
Only the CI pipeline's credentials, never the running application. The registry is the contract between teams, so adding to it should go through the same review as a database migration.
The mechanism is two producer settings. With
auto.register.schemas=false, the serializer will not create a schema when it meets an unknown one; it fails instead. Withuse.latest.version=true, it looks up the newest registered version and uses that.So a developer who adds a field in code gets a loud error in a test, not a silent new schema in production. The pipeline registers the schema first, after the compatibility check passes, and only then deploys the producer.
On the registry side, give application accounts read-only access to subjects. Then even a copied config with the wrong flag cannot write. I would also keep an audit log of who registered what, because the first question after an incident is "who changed it".
- “How do I introduce a truly breaking change?”
You do not make it on the same subject. A breaking change on a live subject is not a change, it is an outage with a delay, because every consumer on the old schema fails the moment it reads a new record.
The safe path is a new topic or a new major version of the subject, with a migration:
- Create: make
orders.v2with the new schema, next toorders.v1. - Dual publish: the producer writes every event to both topics for a set period. Consumers can move one at a time.
- Migrate: each consumer team switches to v2 and confirms its lag on v1 is zero.
- Retire: stop writing to v1, wait out retention, delete it.
The cost is real: two topics, double the write traffic, and a deadline that someone has to chase. That cost is the price of a breaking change, and it is the reason to avoid breaking changes by adding optional fields with defaults wherever possible.
- Create: make
- “How do I clean up the already-bad records?”
I do it in four steps, and I keep the originals the whole time. The goal is to repair the data without losing the evidence of what went wrong.
- Stop the damage: roll back the producer so no new bad records arrive, and move the stuck consumers past the poison records by sending them to a dead-letter topic.
- Keep the raw bytes: a record that cannot be decoded is stored in the dead-letter topic as plain bytes, with a header naming the topic, partition, offset and error. Nothing is thrown away.
- Repair: write a small job that reads the dead-letter topic, decodes with the schema the producer really used, fills the missing field with a sensible default, and writes the fixed record back.
- Replay: the consumers read the repaired records. Because the key is the same, ordering per key is mostly preserved.
Then I check the count: records in the dead-letter topic must equal records repaired plus records deliberately dropped.
- “What alert would have caught this early?”
The pattern to look for is everything breaking at once, right after a deploy. Lag and error rate rise on every partition together, within a minute or two of the producer release. A hot key would hit one partition; a slow database would slow processing but not raise errors. Errors on every partition at once point at the data itself.
The sharpest signal is a counter for failed deserialization, because it names the cause directly. Most clients expose an error metric for this; if yours does not, wrap the deserializer and count failures yourself.
I would set up three things:
- Alert: deserialization failures above zero for two minutes, per consumer group.
- Deploy marker: a vertical line on the dashboard for every producer release, so cause and effect sit on one screen.
- Dead-letter growth: an alert when the dead-letter topic grows faster than a trickle.
With these, the page arrives while the bad producer is still being rolled out, not after the consumers have been down an hour.
Q102. “Avro, Protobuf or JSON Schema for Kafka: how do you choose?”
Reveal answer
Strong answer I choose by team and tooling first. Avro is the native choice in the Kafka and data-warehouse world, with good schema evolution and a tight registry integration. Protobuf suits organizations already using gRPC. JSON Schema suits teams wanting readable data with checks.
Avro needs the writer's schema to decode, which the registry provides; fields are matched by name, so renames are hard. Protobuf matches by field number, so renames are free but numbers must never be reused.
Size and speed: Avro and Protobuf are both compact; JSON is several times bigger.
Pick one for the company. Mixed formats multiply tooling, library and review costs.
Picture it The decision as a table.
The setup: A company with Java services, a data lake, and some gRPC.
| Option | Pick it when | Cost or catch |
|---|---|---|
| Avro | Data lake / Kafka-first, many consumers | Names matter; needs registry to decode; limited code-gen ergonomics |
| Protobuf | gRPC already used, many languages | Field numbers must never be reused; unknown fields need care |
| JSON Schema | Human-readable, debugging by eye | Big, slow, weaker evolution guarantees |
Make the invisible visible: Evolution rule of thumb.
Avro: add field WITH default; never rename without alias
Protobuf: add field with new number; mark removed numbers "reserved"; never reuse a number
JSON: add optional property; do not change a typeWhy: The wire format decides how change is possible. Choose it for how you will change things in three years.
Land it I pick the one my organization's tooling already speaks, usually Avro for Kafka-first shops and Protobuf where gRPC already lives.
- “What is the biggest Protobuf trap?”
The biggest trap is reusing a field number for a different meaning. Protobuf identifies a field on the wire by its number, not its name. If you delete the field
coupon = 3and later addcurrency = 3, old stored records and old producers still send number 3 with coupon data, and new readers decode it as a currency. No error is raised, because the types may even match. You get wrong data silently.The cure is to retire the number explicitly. A
reservedline makes the compiler refuse any later use of it, so the mistake fails at build time rather than in production.order.protoruns offline// illustrative message Order { reserved 3; // was "coupon", never reuse reserved "coupon"; // also block the old name string order_id = 1; int64 total_cents = 2; }I would also make this a review rule: no field number is ever edited, only added or reserved.
- “What is the biggest Avro trap?”
Adding a field without a default. Avro decodes by comparing two schemas: the one the writer used and the one the reader expects. When the reader's schema has a field that the old record does not contain, the reader must fill it from a default. With no default, decoding old data fails, so the change breaks BACKWARD compatibility.
The usual way to add an optional field is a union with null listed first and a null default. The union says "a string or nothing", and the null default says "if absent, use nothing".
order.avscruns offline{"name": "coupon", "type": ["null", "string"], "default": null}Two related traps. The default must match the first branch of the union, so writing
["string","null"]with a null default is invalid. And renaming a field is a break unless you add an alias, because Avro matches by name.- “Does the format affect Kafka Streams or Connect?”
Yes, and all three are well supported, so the format is a team-tooling choice, not a blocker. Each piece of the ecosystem just needs the right adapter.
In Kafka Streams, every stream and table needs a serde, a pair of functions that turn a Java object into bytes and back. The Confluent-compatible schema registry libraries ship serdes for Avro, Protobuf and JSON Schema, and they fetch the schema from the registry by the id at the start of each record.
In Connect, the equivalent is a converter, set per worker or per connector with
key.converterandvalue.converter. Again, each format has one.The practical trap is mixing them. If the source connector writes Avro and a downstream sink is configured for JSON, the sink reads bytes it cannot parse and the task fails. I keep one converter setting across a whole pipeline and write it down next to the topic's owner, so nobody changes one end alone.
- “Can I change format later?”
Yes, but it is a migration project, not a setting. Records already in a topic are bytes in the old format, and every consumer is built to read them. You cannot flip a switch and have both worlds agree.
The path I would follow is the same as any breaking change:
- New topic: create
orders.v2in the new format, with its own subject in the registry. - Bridge: a small stream job or a Connect transform reads the old topic and writes the new one, so both stay in step while teams move.
- Move consumers: each team switches and verifies lag, then the producer writes only to the new topic.
- Retire: drop the bridge and the old topic after retention has passed.
This takes weeks across several teams, which is why I say it is far cheaper to choose well at the start. If an organization is unsure, the format its existing tools already speak is the right default.
- New topic: create
Q103 · Design. “Design the schema governance for forty topics owned by ten teams.”
Reveal answer
Strong answer Three layers. Naming and subjects: use the default TopicNameStrategy (one schema type per topic) so each subject maps to one topic, and name topics by domain, like orders.order-placed.v1.
Compatibility: FULL_TRANSITIVE by default, changed only with a review. Registration: only CI can register, with auto.register.schemas=false in applications.
Process: schemas live in a shared repository or the owning team's repo, reviewed like code, with a check that runs the registry's compatibility endpoint. Each topic has a named owner and a documented consumer list.
Breaking change path: new versioned topic, dual publish, consumer migration deadline, retire.
Picture it The pipeline from a schema file to production.
The setup: Team Orders wants to add currency.
PR changes orders/order-placed.avsc
-> CI: lint + POST /compatibility ... FULL_TRANSITIVE -> ✓ or ✗ build fails
-> review by owner + one consumer team
-> merge -> CI registers version 5 (service account only)
-> apps run with auto.register.schemas=false, use.latest.version=trueMake the invisible visible: Responsibilities.
| Item | Owner | Rule |
|---|---|---|
| Schema file | Producing team | Reviewed, versioned in git |
| Compatibility level | Platform team | FULL_TRANSITIVE default; exceptions documented |
| Topic and retention | Producing team | Created by GitOps, not by apps |
| Consumer list | Each consuming team | Registered in a catalogue |
Why: Governance is a lightweight pipeline that makes the safe path the easy path.
Land it One naming rule, FULL_TRANSITIVE by default, registration only from CI, and a versioned-topic path for breaking changes.
- “Why TopicNameStrategy and not RecordNameStrategy?”
It depends on whether you need several kinds of event on one topic, and ordering is the deciding reason. TopicNameStrategy ties the subject to the topic name, such as
orders-value. That gives one schema per topic, which is easy to understand and to govern. It fits most topics.RecordNameStrategy ties the subject to the record's own name, such as
com.shop.OrderPlaced. TopicRecordNameStrategy combines both. These let one topic carry OrderPlaced, OrderPaid and OrderShipped, each with its own schema and compatibility history.Why would you want that? Kafka only orders records inside one partition of one topic. If all events of one order sit in separate topics, a consumer can see "shipped" before "paid". Putting them in one topic, keyed by order id, preserves the true sequence.
So my rule is the simple strategy by default, and the record-name strategies only on topics where cross-event ordering for one key matters, and I document that choice on the topic.
- “How do you discover who consumes a topic?”
You find consumers from three sources, and no single one is complete, so I use all three.
- Brokers: every consumer group has an id and a list of topics it reads. The admin tools list them and show lag per topic.
- ACLs: on a secured cluster, a group needs permission to read a topic. The ACL list shows which principals are allowed.
- A catalogue: a short record per topic with the owner, the purpose and the known consumers. This captures intent, which the broker cannot.
who reads itruns offline# illustrative kafka-consumer-groups.sh --bootstrap-server b1:9092 --list kafka-consumer-groups.sh --bootstrap-server b1:9092 --describe --group billing # output lists: TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAGThe broker view tells you who is reading today. A group that reads once a month will not show up between runs, which is why the catalogue matters before you retire anything.
- “What do you do when a team will not migrate off v1?”
I turn it from a request into a dated plan that the team's manager can see. Asking nicely rarely works against a team's own backlog.
First, set a retirement date when v2 launches, and announce it to every consumer owner. A date gives the work a priority.
Second, make the progress visible. A dashboard shows lag on the old topic per consumer group. A group that is still reading v1 on the day before the deadline stands out in red.
Third, keep dual publish until that date, and then stop. Dual publish costs double the writes and keeps two code paths alive, so it is the price of being polite, and it must have an end.
If the team still has not moved, the owner of the topic and the team's manager decide together: extend with a new date, or switch off the old topic and accept the break. I would never extend silently, since "temporary" dual publish tends to last for years.
- “How do you stop schema sprawl?”
Sprawl is near-duplicate schemas: three teams each defining their own
MoneyorAddress, with small differences, so no consumer can reuse another team's code. I fight it in three ways.- Shared types: a common library or common schema file for the types everyone uses, such as Money, Address and Timestamp. Teams import them instead of redefining them.
- Review for reuse: the schema pull request has a checklist line "does this type already exist?". A reviewer from another team is cheap insurance.
- Tidy-up: a quarterly job lists subjects with no producer in 90 days and no consumer group, and the owner confirms deletion.
The registry should be treated as an inventory with named owners, not a dumping ground. Each subject records an owner and a purpose in a naming convention or a metadata field, so an orphan is easy to spot.
The goal is not fewer schemas, it is fewer accidental ones.
Q104. “Explain Kafka Connect: workers, connectors, tasks, converters and transforms.”
Reveal answer
Strong answer Kafka Connect is a framework for moving data between Kafka and other systems without writing a consumer or producer. A worker is a JVM process; a connector is a configuration that says what to copy; a task is the unit of work that does the copying, many tasks per connector.
A source connector reads from an outside system into Kafka; a sink connector writes from Kafka out. Converters turn bytes into Connect's internal format and back (Avro, JSON). SMTs, single message transforms, modify one record at a time, for example dropping a field.
In distributed mode, workers form a cluster, configs and offsets live in internal Kafka topics, and if a worker dies the tasks move to others.
You configure it by posting JSON to its REST API.
Picture it One source connector's shape.
The setup: Copy a Postgres table to a topic.
{
"name": "orders-source",
"config": {
"connector.class": "io.debezium.connector.postgresql.PostgresConnector",
"database.hostname": "pg",
"table.include.list": "public.orders",
"tasks.max": "1",
"key.converter": "io.confluent.connect.avro.AvroConverter",
"value.converter": "io.confluent.connect.avro.AvroConverter",
"transforms": "unwrap",
"transforms.unwrap.type": "io.debezium.transforms.ExtractNewRecordState"
}
}Make the invisible visible: Where the pieces sit.
Postgres --source task--> [converter] --> [SMT chain] --> Kafka topic
Kafka topic --> [SMT chain] --> [converter] --sink task--> Elasticsearch
internal topics: connect-configs, connect-offsets, connect-statusWhy: Connect gives restart, scaling and offset tracking for free; you write config, not code.
Land it Workers run tasks for connectors; converters handle format, transforms tweak records, and state lives in Kafka topics.
- “Standalone or distributed?”
Standalone for a laptop or a single small job, distributed for anything that must survive a failure. I use distributed from the moment a pipeline matters.
Standalone mode runs one worker process. Connector configs come from a file at startup, and offsets are kept in a local file. If the machine dies, so does the job and its position. It is fine for trying a connector, or for a log shipper on one host.
Distributed mode runs several workers that form a cluster through Kafka's group mechanism. Configs, offsets and status are stored in three internal Kafka topics, so any worker can pick up any task. If one worker dies, its tasks move to the others. You manage connectors by REST calls rather than by editing files and restarting.
The extra effort is small, and the failure behaviour is far better, so even small jobs go distributed once someone depends on them.
- “What does tasks.max mean?”
It is an upper limit on how many tasks the connector may run in parallel, not a promise. The connector itself decides how many tasks it actually needs, up to that limit, based on how the work can be split.
Examples help:
- CDC source on one table: a change log is a single ordered stream, so the connector uses one task however large
tasks.maxis. - JDBC source on ten tables: it can give each task a subset of the tables, so up to ten tasks are useful.
- Sink on a ten-partition topic: sink tasks are consumers in a group, so at most ten tasks do work. An eleventh would sit idle.
So for sinks I set
tasks.maxto the partition count of the input topic, or lower if the target database cannot take that many parallel writers.Setting it higher than the work allows wastes nothing but also gains nothing, which is a common source of "I raised it and nothing changed".
- CDC source on one table: a change log is a single ordered stream, so the connector uses one task however large
- “When should I write a custom transform?”
Rarely, and only for small edits to a single record. A Single Message Transform sees one record at a time, with no memory of earlier records and no way to call another system. That is exactly why it is safe to run in the middle of a connector.
Good uses: rename a field, drop a column that must not leave the database, mask an email, add a timestamp, or route a record to a topic by a field value.
A custom one is justified when the standard set cannot do a small edit that you need in many connectors, such as company-specific masking of a field format. Write it as a tiny, well-tested Java class.
Anything bigger belongs elsewhere. Joins, aggregation, lookups against a service and error-prone business rules need testing, metrics and state. A Kafka Streams app or a normal service has all of those, a connector transform chain has none.
My warning sign is three or four chained SMTs with nested conditions. That is business logic hiding in configuration, where it is hard to test and review.
- “How do I see a failing connector?”
Start with the REST status endpoint, which shows the state of the connector and of each task separately. The connector can say RUNNING while one of its tasks is FAILED, so you must look at the tasks.
statusruns offline# illustrative curl -s localhost:8083/connectors/orders-source/status # illustrative output: {"name":"orders-source","connector":{"state":"RUNNING"}, # "tasks":[{"id":0,"state":"FAILED","trace":"org.apache.kafka.connect.errors..."}]}A failed task includes the stack trace in the response, which usually names the cause: a bad record, an unreachable database, a missing permission.
After fixing the cause, a failed task does not restart by itself. You restart it with a POST to
/connectors/orders-source/tasks/0/restart, or restart the whole connector. Recent versions can also restart only the failed tasks in one call.For monitoring, I alert on any task not RUNNING for more than a few minutes, and on a sink's lag growing.
Q105 · Scenario. “Your Postgres disk is filling up and the cause is a Debezium connector. What happened?”
Reveal answer
Strong answer Debezium on Postgres uses a replication slot: a marker that tells Postgres to keep the write-ahead log (WAL) until the connector confirms it has read it. If the connector stops, or lags, WAL files pile up and the disk fills.
Causes: the connector is down or paused, it is stuck on a bad record, Kafka is unreachable, or the captured tables are quiet while other tables are busy, so the slot position does not advance.
Immediate: get the connector running, or if it cannot be saved quickly, drop the slot to free the disk, knowing you will need a new snapshot afterwards.
Prevention: alert on slot lag in bytes, set max_slot_wal_keep_size in Postgres so a runaway slot is invalidated instead of killing the database, and enable heartbeats.
Picture it Check the slot.
The setup: Disk is 92% full. The WAL directory is huge.
SELECT slot_name, active,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained
FROM pg_replication_slots;# illustrative output
slot_name | active | retained
debezium_1 | f | 312 GB <- connector down, slot holds 312 GB of WAL ✗The fix: Guard rails.
max_slot_wal_keep_size = 50GB # slot is invalidated beyond this
# connector: heartbeat.interval.ms=10000 (advances slot on quiet tables)Why: A slot is a promise to keep data. An unmonitored promise eventually costs a database.
Land it The replication slot kept WAL because the connector stopped confirming, so I restore the connector, cap slot retention, and alert on slot lag.
- “Why do quiet tables cause growth?”
Because the slot only moves forward when the connector confirms a position, and the connector only sees changes for the tables it watches. Postgres writes one shared log for the whole database. If your captured tables are quiet while other tables are busy, the log grows, but the connector has nothing to confirm.
Picture a database where one busy table writes 5,000 log entries a minute and your small captured table changes once an hour. The connector reads past all the busy table's entries, finds nothing to emit, and so confirms nothing. The slot stays at the old position for up to an hour, and Postgres keeps every entry written since.
The fix is heartbeats. With
heartbeat.interval.msset, Debezium produces its own small event at regular intervals, and for Postgres you can also point it at a heartbeat table that it updates, so the position moves forward even when nothing real changed.I switch heartbeats on for every Postgres connector, by default.
- “What if I drop the slot?”
Dropping the slot frees the disk, because Postgres can recycle the log files it was holding, but it throws away the connector's place. That is the emergency lever, not the plan.
What happens next:
- Disk frees: the WAL files are removed at the next checkpoint. The database is safe.
- Position is lost: when the connector restarts it finds no slot. It creates a new one and, depending on the snapshot setting, takes a fresh snapshot of all captured tables.
- Gap or burst: any changes made while there was no slot are not seen as individual events. The snapshot covers current state, but intermediate changes are lost.
Downstream consumers then see a burst of "read" events for every row, which may be millions. They must be idempotent, and the sink must be able to absorb the load.
The decision is about which failure is worse: a database that stops accepting writes, or a connector that repeats a snapshot. The second is recoverable. I only drop a slot when the alternative is the database going down, and I tell the downstream owners first.
- “How big should the guard be?”
Size it from the longest outage you will accept, multiplied by your WAL rate, and keep it below the free disk. The setting is
max_slot_wal_keep_sizein Postgres.The worked example:
guard sizeruns offline# illustrative arithmetic, measure your own WAL rate WAL rate = 10 GB per hour (assumed) tolerated outage = 4 hours minimum guard = 10 x 4 = 40 GB disk size = 100 GB, data takes 40 GB, so 60 GB free chosen guard = 50 GB (above 40, below 60 free)When the slot passes that limit, Postgres invalidates it. The connector then needs a new snapshot, but the database stays up, which is the trade I want: lose the connector's position, not the primary database.
Measure the WAL rate over a busy day, including batch jobs and migrations, since those are the peaks. I also alert at about 60 percent of the guard so someone acts early.
- “Is there an equivalent in MySQL?”
MySQL has no slot, but the same kind of risk exists in a different form. Debezium reads the binary log, remembering a file name and position, or a GTID set, which is a global transaction id range.
Nothing in MySQL waits for the connector. Binary logs are deleted by their own retention, for example
binlog_expire_logs_secondsor the older day setting. So the failure is the opposite: the disk does not fill, but if the connector is down longer than the retention, the log file it needs is gone.On restart the connector asks for a position that no longer exists and fails. The only repair is a new snapshot, as with a dropped Postgres slot.
So the lesson is the same, with a different measure:
- Postgres: watch slot lag in bytes against the guard.
- MySQL: watch connector lag in time against binlog retention. Keep retention longer than your longest tolerated outage.
In both cases, the alert is about the connector falling behind, not just about its state.
Q106. “What delivery guarantee do Connect source and sink connectors give?”
Reveal answer
Strong answer By default, at-least-once in both directions. A source connector commits its offsets periodically, so after a crash it may re-read and re-publish some records. A sink commits consumer offsets after writing, so after a crash it may rewrite some.
Newer Connect versions support exactly-once for source connectors (KIP-618) when the specific connector supports it and the feature is enabled; check your connector's documentation.
For sinks, the practical route is idempotent writes: upsert by primary key, so a repeat overwrites with the same value.
So the question to ask is what the target does with a duplicate.
Picture it Why a duplicate appears and how an upsert absorbs it.
The setup: Sink to Postgres, batch of three records, crash after the write but before the offset commit.
# illustrative output
write batch o1 o2 o3 to DB ✓ committed
crash before offset commit
restart: re-read o1 o2 o3
INSERT mode : 3 duplicate rows ✗
UPSERT mode : same 3 rows overwritten ✓ (insert.mode=upsert, pk.mode=record_key)Make the invisible visible: Sink config.
{
"connector.class": "io.confluent.connect.jdbc.JdbcSinkConnector",
"topics": "orders",
"insert.mode": "upsert",
"pk.mode": "record_key",
"pk.fields": "order_id"
}Why: With a key, a repeat writes the same value into the same row, so the end state is identical.
Land it Both sides are at-least-once by default, and I make sinks safe with upserts keyed by the record key.
- “Where does a source connector keep its offset?”
In an internal Kafka topic, by default named
connect-offsets(the name is a worker setting,offset.storage.topic). The offset is whatever "position" means for that source: a WAL position for Postgres, a binlog file and offset for MySQL, a file name and byte count for a file source, a timestamp or id for a polling source.It is not written per record. The worker flushes offsets on an interval,
offset.flush.interval.ms, which is 60 seconds by default.That interval is the size of the replay window. After a crash, the connector restarts from the last flushed position, so records produced during the final stretch before the crash are read again and published again.
A shorter interval narrows the window but adds writes to the offsets topic. I leave it alone and instead make sure the sink is idempotent, because duplicates can also come from the sink side, and an idempotent target covers both.
A sink connector's position is different: it is an ordinary consumer group offset.
- “What about deletes in a sink?”
Deletes do not flow through unless you plan for them. A delete in the source database appears in Kafka as a delete event, and Debezium then follows it with a tombstone: a record with the same key and a null value. A sink only acts on that if it is configured to.
For the JDBC sink connector, the settings are:
sink.propertiesruns offline# illustrative insert.mode=upsert pk.mode=record_key pk.fields=order_id delete.enabled=truedelete.enabled=trueturns a tombstone into aDELETEstatement, and it requirespk.mode=record_key, since the null value has no fields to take a key from. Other sinks, such as search or object storage, have their own switch or none at all. Check the connector's documentation.If you skip this, the target slowly collects rows that the source has already removed. That is a quiet data-quality bug, so I test deletes explicitly, not only inserts.
- “Do SMTs change the guarantee?”
A transform does not change the delivery guarantee, but a failure inside it can stop the task. By default,
errors.tolerance=none: the first record that fails to convert or transform fails the task, and the task stays FAILED until someone restarts it. That is safe, because no record is lost, but it halts the pipeline.For sink connectors you can change this:
sink.propertiesruns offline# illustrative errors.tolerance=all errors.deadletterqueue.topic.name=orders-sink-dlq errors.deadletterqueue.context.headers.enable=true errors.log.enable=trueNow a bad record is copied to the dead-letter topic, with headers that say why, and the task carries on. Source connectors do not have a dead-letter topic option.
The danger is that
allalso hides problems. If every record is failing, the task looks healthy while the target stays empty. So I always alert on dead-letter topic growth, and I choose tolerance on purpose, per connector.- “How do you check for duplicates in the target?”
With a reconciliation query that compares the source and the target for the same slice of time. Duplicates and missing records are two ends of the same check, so one job finds both.
A simple version, run each hour for the previous hour:
- Count: count the rows per key range in the source, and the rows in the target for the same range.
- Compare: if the target has more, look for duplicates by grouping on the key. If the target has fewer, you have lost records.
- Alert: raise an alert when the difference exceeds a small threshold, because in-flight records make an exact match impossible at the very edge of the window.
If the sink upserts by primary key, true duplicates cannot exist in the target, and the check mostly finds gaps. If the sink appends, as in a warehouse event table, then duplicates are expected, and the view on top of it should pick the latest version per key.
The key point: the check must run on a schedule, not only after an incident.
Q107 · Design. “Design a pipeline that keeps a search index and a data warehouse up to date from an orders database.”
Reveal answer
Strong answer Use change data capture (CDC) with Debezium into Kafka, then sink connectors to each target. One captured table becomes one topic, with the primary key as the record key, so all changes to a row land in one partition in order.
Each target gets its own sink connector and its own consumer group, so a slow warehouse load never delays search. Search uses upserts by document id; the warehouse appends change events and builds the current view in a query.
Handle three special cases: the initial snapshot (a burst of existing rows), deletes (tombstones), and schema changes (registry plus compatibility).
Add monitoring: connector status, lag per sink, and a reconciliation count.
Picture it The pipeline picture.
The setup: Orders in Postgres; two consumers of change.
Postgres --WAL--> Debezium source --> topic dbserver.public.orders (key=order_id)
|--> sink A: Elasticsearch (upsert by id, delete on tombstone)
|--> sink B: warehouse loader (append changes, build view)
Schema Registry: Avro, FULL_TRANSITIVE Monitoring: lag per sink, slot lagMake the invisible visible: One update and one delete as they appear in the topic.
# illustrative output
key=o1 value={before:{status:NEW}, after:{status:PAID}, op:"u"}
key=o2 value={before:{...}, after:null, op:"d"}
key=o2 value=null <- tombstone so compaction can drop o2Why: Separate groups isolate failures; the key preserves per-row order; the tombstone lets deletes propagate.
Land it CDC into one topic per table, keyed by primary key, with independent sinks per target so one slow target does not hold the others.
- “Why not dual-write from the application?”
Because two separate writes without a shared transaction will eventually disagree. Suppose the app saves the order to the database and then publishes to Kafka. If the process crashes between the two, the order exists with no event. Reverse the order of the writes and the event exists with no order. A retry can add a third case: the event is sent twice.
Wrapping both in one transaction is not possible, because a database and Kafka do not share a transaction manager. Two-phase commit across them is rarely available and fragile.
CDC removes the problem by having one writer. The application writes only to the database. Debezium reads the database's own commit log, which holds exactly what was committed and in the commit order. So Kafka reflects the database, with a short delay.
The price is that events are shaped like table rows, not business events. When that matters, I add an outbox table in the same transaction and capture that instead.
- “How is the initial snapshot handled?”
Debezium first reads the existing rows and emits them as events with operation type "r", meaning read. Then it switches to streaming the log from the position it noted when the snapshot began, so there is no gap between the old rows and the new changes.
The costs are real. A large table can take hours to read, it adds load on the database, and while it runs the consumers see a burst of events.
I plan for it in four ways:
- Timing: run it off-peak, or from a replica when the connector supports it.
- Incremental snapshots: Debezium can snapshot in chunks while streaming continues, so no long pause. Check the version's documentation.
- Consumers: make search upserts idempotent, and let the warehouse accept repeated rows.
- Capacity: check the topic's partition count and retention, because millions of records land at once.
The same burst returns whenever a snapshot is repeated, so the sinks must tolerate it every time.
- “What if the schema of the table changes?”
Debezium notices the change in the log, updates its internal copy of the table structure, and emits later events with a new schema, which the schema registry stores as a new version. Whether the downstream breaks depends on the kind of change.
Compatible changes are usually safe: adding a nullable column, or one with a default. Older consumers ignore the field, and new consumers see it.
Risky changes include dropping a column, renaming it, changing its type, or making a nullable column required. These can fail the registry's compatibility check or break a sink that writes into a table with a fixed shape.
I make the process explicit:
- CI check: a migration that touches a captured table must pass the registry's compatibility check against the topic's subject before it is merged.
- Order of rollout: update the sinks first for additions, so they accept the new field, then migrate the database.
- Breaking changes: use a new topic version, as with any breaking schema change.
- “How do I prove the index matches the database?”
By reconciliation: a scheduled job that compares the two sides and alerts when they differ by more than a small margin. It works the same for the index and the warehouse.
A practical design:
reconcile.sqlruns offline-- illustrative -- run on both sides, for rows updated in the last full hour SELECT date_trunc('hour', updated_at) AS bucket, count(*) AS n, sum(hashtext(order_id::text)) AS checksum FROM orders WHERE updated_at < now() - interval '5 minutes' GROUP BY 1;The five-minute cushion lets in-flight changes land. If the count or checksum for a bucket differs, I alert, and a repair job re-snapshots just that bucket by re-emitting the rows.
Choose the bucket size by how fast you need to notice: hourly buckets find a gap within an hour, and a small bucket makes the repair cheaper. The index may use a different engine, so I compare ids and a version number rather than full documents. An on-demand incremental snapshot is the repair tool, and I rehearse it before I need it.
These questions test whether you understand state, time and partitioning, the three things that make stream processing different from request handling.
Q108. “KStream, KTable and GlobalKTable: what is the difference?”
Reveal answer
Strong answer A KStream is an unbounded sequence of events where every record is an independent fact: “order o1 placed”, “order o1 paid”. A KTable is a changelog read as a table, where each key has only its latest value: the current status of o1.
Same topic, two readings. Read as a stream, five records for key o1 are five events. Read as a table, they collapse to the last one.
A GlobalKTable is a KTable fully copied to every instance rather than split by partition, so joins against it need no co-partitioning. It suits small reference data such as country codes.
Use a stream for events and counting, a table for current state and lookups.
Picture it The same three records read two ways.
The setup: Topic status receives, for key o1: NEW, PAID, SHIPPED.
# illustrative output
KStream view: (o1,NEW) (o1,PAID) (o1,SHIPPED) 3 events, count by key = 3
KTable view: o1 -> SHIPPED 1 row, latest wins
GlobalKTable: same as KTable, but all partitions present on every instanceMake the invisible visible: Code for each.
StreamsBuilder b = new StreamsBuilder();
KStream<String,String> events = b.stream("status");
KTable<String,String> current = b.table("status");
GlobalKTable<String,String> countries = b.globalTable("countries");Why: A table is a stream plus the rule “newest per key wins”. Compaction in the topic matches that rule.
Land it A stream is every event, a table is the latest value per key, and a global table is a table copied to every instance for small lookups.
- “When do I pick GlobalKTable?”
Use a GlobalKTable for small, slowly changing reference data that many keys need to look up, such as currency rates, country names or a product category list. Its advantage is that the join does not need the stream and the table to be co-partitioned, and it can join on any field of the stream record, not only the key.
The reason is the full copy. Every Streams instance loads the whole topic into its local store. So a lookup is always local, whatever the stream's key.
The cost is that every instance holds all the data. Memory, disk and start-up time all grow with the table, and a restart must read the full topic again. A table with ten thousand rows is trivial. One with a hundred million is a problem multiplied by your instance count.
My rule: if it fits comfortably in each instance's memory and changes rarely, it is a GlobalKTable. Otherwise it stays a partitioned KTable with co-partitioning.
- “What is the stream-table duality?”
It is the idea that a stream and a table are two views of the same data, and you can convert in either direction.
From table to stream: every change to a table row is an event. A series of updates to one key, "o1 PLACED", then "o1 PAID", is a stream of changes, which is what a changelog topic records.
From stream to table: keep only the latest value per key. Replay the same events into a table and you get the current state, "o1 PAID".
dualityruns offlinestream: (o1,PLACED) (o2,PLACED) (o1,PAID) table: o1 -> PAID, o2 -> PLACED (latest per key) changes of the table, replayed: gives the same stream backThis is why Kafka Streams can store state safely. The state store is a table, its changelog topic is the matching stream, and rebuilding a lost store is just replaying the stream back into a table.
- “How does a null value behave in a KTable?”
In a KTable, a record with a null value is a tombstone, meaning "delete this key". The key is removed from the table, and a downstream consumer of the table sees a deletion. In a compacted topic, the tombstone also tells the log cleaner that the key can be dropped completely after
delete.retention.ms, 24 hours by default.So producing a null value into a table topic is the standard way to delete.
In a KStream the same record means nothing special. It is just an event whose value is null, and most processing code would fail on it with a NullPointerException. So I usually filter nulls out of a stream right after reading, unless I am deliberately handling deletes.
The practical trap: aggregations and joins on a table treat null differently from an empty value. If a delete must reach a downstream search index or database, I check that each step passes the tombstone along and the sink acts on it.
- “Can a KTable be queried from outside?”
Yes, with interactive queries: a read API over the state store that Kafka Streams keeps for the table. You wrap it in your own REST endpoint, since Streams does not ship an HTTP server.
The catch is that state is split by partition, and each instance holds only its own share. A key may live on another instance, so a query needs two steps:
- Find the owner: ask Streams which instance holds the key. It knows the partitioning rule and the assignment, and returns the host and port, which you set with
application.server. - Route: if the owner is this instance, read the store. Otherwise forward the request to the owner over HTTP.
During a rebalance or restore, the store may be unavailable for a short time, so the endpoint must handle "not ready, try again".
The store gives reads by key and range, nothing more. For richer queries, such as search by another field, I write the table into a database or index, as a separate sink.
- Find the owner: ask Streams which instance holds the key. It knows the partitioning rule and the assignment, and returns the host and port, which you set with
Q109. “What are state stores and changelog topics, and why are they needed?”
Reveal answer
Strong answer Aggregations such as a count per key need memory between records. Kafka Streams keeps this in a local state store, by default RocksDB on disk with a cache in memory, one store partition per input partition.
Local disk can be lost, so every update is also written to a changelog topic in Kafka, compacted by key. If an instance dies, another rebuilds the store by reading the changelog from the start.
That makes state durable without a database: the topic is the truth, the store is a fast local copy.
The cost: rebuilding takes time proportional to the store size, which is the main operational pain.
Picture it How one count update flows.
The setup: groupByKey().count() over card ids.
record (card=c9) -> read store: c9=41 -> write c9=42 -> changelog topic app-count-changelog (key=c9, value=42)
instance dies -> new owner reads changelog: c9=42 restored, continuesMake the invisible visible: Why compaction makes this cheap.
# illustrative output
changelog before compaction: c9=40 c9=41 c9=42 c7=3 c9=43
after compaction: c7=3 c9=43 restore reads 2 records, not 5Why: Compaction keeps only the latest value per key, so restore cost follows the number of keys, not the number of updates.
Land it State lives in a local store backed by a compacted changelog topic, so any instance can rebuild it after a failure.
- “Is the store a database I can query?”
Not in the usual sense. The state store supports reads by key and by range through interactive queries, but it is processing state, not a general database. There are no secondary indexes, no ad hoc queries, and no access except through the Streams instance that owns that partition.
The ownership point matters. Each store partition lives on one instance at a time. When a rebalance moves the partition, the store moves, or is rebuilt elsewhere, and while that happens it cannot be read.
The store is also tied to the processing logic. If you change the topology, for example the key or an aggregation, the old store may no longer match, and you may need to reset the application.
My rule is to use the store as the engine's working memory. If other services need to query the data in flexible ways, I write the output topic into a proper database or search index, which can then be the system of record for readers.
- “What if the store is huge?”
Huge state makes three things slow: a restore after a restart, a rebalance that moves a partition, and any change to the topology. The forty-minute restart in the earlier scenario is the typical symptom.
The options, from cheapest to most work:
- Persistent volumes: keep each instance's state directory on a disk that survives restarts, so only the tail of the changelog has to be replayed.
- Standby replicas: set
num.standby.replicasso another instance keeps a near-current copy and can take over quickly. - Make the state smaller: use windows with a retention, drop fields you do not need, and store ids rather than full objects.
- Bound the key space: check that the number of keys cannot grow forever, for example one key per session id with no expiry.
The last point is the one people forget. An unbounded key space eventually defeats every other plan, because the store only grows. If the business needs unlimited history, the data belongs in a database, not in a Streams store.
- “Can I turn off the changelog?”
You can, per store, by calling
withLoggingDisabled()on the store builder. The store then has no changelog topic. It saves the write traffic and the topic's disk, but you give up recovery: if the instance loses its local disk, the state is gone and the store starts empty.That is acceptable in one case: the store is a cache or helper that can be rebuilt another way, for example from the source topic by reprocessing, and a brief gap in results is tolerable.
It is wrong in every case where the state is the answer. A counter, a running total or a deduplication table that silently resets after a failure produces wrong output with no error. With
exactly_once_v2it also removes the guarantee, since state is no longer part of the transaction.So I leave the changelog on by default and count the cost, topic storage, as the price of correctness. If a team asks to disable it, I ask how they would detect an empty store, and what the downstream does with the answer.
- “Where does the data physically sit?”
In two places, and you must plan capacity for both. First, on each instance's local disk, under
state.dir. It holds the RocksDB files, one directory per task, and it is the fast copy used while processing. Second, in the changelog topics on the brokers, one per store, compacted by key and replicated like any other topic.The cost adds up. If a store holds 20 GB and its changelog has replication factor 3, the brokers store about 60 GB for it, in addition to the 20 GB on the instance and any standby copies.
Two settings to check:
- State directory: the default is under the system temp directory in older setups, which may be wiped on reboot. Point it at a durable volume.
- Internal topics:
replication.factorin the Streams config defaulted to 1 in older versions, and newer ones may defer to the broker default, so check yours. Set it to 3 explicitly in production, so the changelog survives a broker loss.
I also set aside disk headroom for restores, which can temporarily need extra space.
Q110 · Scenario. “A Streams pod restarts and takes 40 minutes before it processes anything. What is happening and what are your options?”
Reveal answer
Strong answer It is restoring its state stores. After a restart on a new machine or with an empty disk, the instance reads each store's changelog topic from the beginning to rebuild the store, and until that completes the task does not process input.
Forty minutes means the stores are large, perhaps tens of gigabytes. Options: keep the store directory on a persistent volume so a restart reuses it and replays only the tail of the changelog; add standby replicas so another instance already holds a near-current copy; and shrink the state.
Standby replicas are set with num.standby.replicas. On failover the standby takes over with only a small gap to catch up.
On Kubernetes, run Streams as a StatefulSet with a persistent volume per pod.
Picture it Where the time goes.
The setup: Store of 60 GB, restore speed of about 25 MB/s (illustrative).
60 GB = 61,440 MB
61,440 MB / 25 MB/s = 2,458 s = about 41 minutes <- matches
with persistent volume: replay only the delta since shutdown, a few seconds
with 1 standby: failover in seconds, cost = 2x disk and 2x changelog readThe fix: Settings.
num.standby.replicas=1
acceptable.recovery.lag=10000 # assign active only to instances within 10k records of the log end
max.warmup.replicas=2
state.dir=/var/lib/streams # persistent volume mountWhy: Restore time is store size divided by read speed. Persistence and standbys remove the read from the critical path.
Land it It is restoring state from the changelog, so I keep state on persistent volumes and add standby replicas.
- “What does acceptable.recovery.lag do?”
It tells the task assignor how far behind an instance can be, in records, and still be given an active task. The default is 10,000 records. The aim is to stop a new or empty instance from being given a task it cannot process yet.
Without it, the assignor could hand an active task to a fresh instance that has an empty store. That instance then spends many minutes restoring, and the task, which could have kept running on the old owner, sits idle.
With it, the assignor sees that the new instance is more than the acceptable lag behind. It places a warm-up replica on it instead. The warm-up copies the changelog in the background while the old owner keeps processing. Once the lag is under the threshold, the active task moves, with a very short pause. The number of warm-ups running at once is capped by
max.warmup.replicas, 2 by default.The effect: scaling out no longer causes a long processing pause. It needs the cooperative rebalancing that recent versions use.
- “Does a rolling deploy restore every time?”
Not if the deployment is set up for it. Whether a restart restores everything depends on whether the local state survives and whether the shutdown is clean.
The two cases:
- Ephemeral disk: each rolling restart starts a new pod with an empty directory. Every pod restores its full state from the changelog, one after the other. A 40-minute restore times ten pods is a very long deploy.
- Persistent volume, graceful stop: on a clean shutdown Streams writes a checkpoint file with the changelog offset the store is up to. After restart, it reads the checkpoint and replays only the records written since, usually seconds.
The failure case is a hard kill. A
kill -9, an out-of-memory kill or a node loss leaves no fresh checkpoint, so the instance must replay from an older point or, with exactly-once, restore from scratch.So I set the pod's termination grace period long enough for Streams to close cleanly, and run it as a StatefulSet with a volume per pod.
- “Does the cost grow with the number of instances?”
Yes, and the cost is easy to calculate. Each standby is a full extra copy of the store, kept up to date by reading the changelog. With
num.standby.replicas=1, every task has one active copy and one standby.standby costruns offline# illustrative arithmetic, assumed numbers store size = 30 GB, 12 tasks standbys = 1 local disk, total = 12 x 30 GB x (1 + 1) = 720 GB across the instances changelog reads = doubled (each standby also reads every update)So local disk and read traffic scale by one plus the number of standbys. The broker's changelog is unchanged, because standbys read it, they do not add to it.
What you buy is failover time. Without a standby, a lost instance means a full restore, which may take tens of minutes. With one, the standby takes over with a small gap to catch up.
I use standbys for services with a strict recovery target and leave them off elsewhere.
- “How do I see restore progress?”
Streams shows restore progress in three ways, and I use all of them, because a long restore looks like a hung application from the outside.
- Listener: register a
StateRestoreListeneron the Streams object. It is called when a restore starts, after each batch, and when it ends. I log the store, the records restored and the records remaining. - Metrics: Streams exposes restore rates and the application state as metrics, which a dashboard can chart. The state moves REBALANCING, then RUNNING, once restore completes.
- Lag: the changelog consumer's lag is a good estimate of the remaining work. Divide it by the restore rate to get time left.
The alert I would add is simple: the application has been in REBALANCING for longer than a threshold, such as ten minutes, or longer than your recovery target.
A tile on the service dashboard showing the state, with the restore percentage, saves an on-call engineer from guessing whether to wait or to intervene.
- Listener: register a
Q111. “Explain windows in Kafka Streams: tumbling, hopping, session, sliding, and grace.”
Reveal answer
Strong answer A window groups records by time for an aggregation. Tumbling: fixed, non-overlapping, such as every 5 minutes. Hopping: fixed size that moves by a smaller step, so windows overlap (5 minutes, every 1 minute). Session: grouped by activity, closing after a gap of inactivity. Sliding: a window anchored on each record's time within a size.
Time is the record's event time by default (its timestamp), not the clock. Records can arrive late, so each window accepts them for a grace period after its end; after that, late records are dropped.
Without grace you must decide explicitly: modern APIs make you write ofSizeWithNoGrace or ofSizeAndGrace.
To emit only one final result per window, use suppress(untilWindowCloses); otherwise you get an update on every record.
Picture it Counting per 5-minute tumbling window with a late record.
The setup: Window 10:00–10:05, grace 1 minute.
# illustrative output
10:01 e1 -> window[10:00,10:05) count=1
10:04 e2 -> count=2
10:06 e3 (next window opens)
10:05:40 e4 with timestamp 10:03 arrives late -> within grace, count=3 ✓
10:07 e5 with timestamp 10:03 arrives -> after grace -> dropped ✗Make the invisible visible: Code.
events.groupByKey()
.windowedBy(TimeWindows.ofSizeAndGrace(Duration.ofMinutes(5), Duration.ofMinutes(1)))
.count()
.suppress(Suppressed.untilWindowCloses(Suppressed.BufferConfig.unbounded())) // one final result
.toStream();Why: Grace trades completeness for latency: longer grace catches more late data and delays the final answer.
Land it Windows group by event time, grace admits late records for a while, and suppress turns many updates into one final result per window.
- “Which window for which question?”
Match the window to the shape of the question. The window type is not a style choice, it changes the answer.
- Tumbling: "orders per 5 minutes". Each record belongs to exactly one window, so totals add up cleanly. Good for reports and billing.
- Hopping: "the last 15 minutes, updated every minute". Windows overlap, so each record is counted in several windows (15 of them here). Good for smooth rolling numbers on a dashboard.
- Session: "one visit by a user", closing after, say, 30 minutes of silence. The window length depends on the data. Good for user activity.
- Sliding: "any 5-minute span around an event". Good for thresholds such as "more than five in any five minutes".
Session windows are the hardest to reason about. A late record can arrive in the gap between two sessions and merge them into one, changing a result you already emitted.
When two types would both work, I pick the one whose result a business person can explain in one sentence.
- “What does event time mean when producers have wrong clocks?”
Event time is the timestamp the producer put on the record, so a wrong clock gives wrong windows. Streams does not look at the wall clock. It tracks "stream time", the largest timestamp it has seen so far. A window closes when stream time passes its end plus the grace period.
The trap: a producer with a clock set a day ahead sends one record. Stream time jumps forward a day. Now every correct record that arrives afterwards looks a day late, falls outside its grace period, and is dropped. One bad device can silence a whole stream.
Two defences:
- Timestamp extractor: write a custom
TimestampExtractorthat checks the timestamp against the record's broker-append time. If it is far in the future, fall back to the broker time or reject the record. - Edge validation: reject or clamp implausible timestamps at the producer or gateway, so they never enter the topic.
I also count dropped late records as a metric, because a sudden jump is the first sign that the stream time was pushed forward.
- Timestamp extractor: write a custom
- “What is the cost of suppress?”
suppressholds results in a buffer until the window closes, so it trades memory and latency for fewer updates. Without it, an aggregation emits an update on every incoming record. With it, you get one final result per window, but only after the window end plus the grace period.So the costs are:
- Delay: the answer for a 5-minute window with a 1-minute grace arrives six minutes after the window starts, at the earliest.
- Memory: every open window for every key sits in the buffer. Many keys times many windows can exhaust the heap.
- Loss risk: an in-memory buffer is lost on a crash. Streams rebuilds it by replaying, so it is correct but slow.
The configuration is
Suppressed.BufferConfig. A bounded buffer, with a maximum number of records or bytes, forces a choice about what happens when it fills:shutDownWhenFull()stops the app,emitEarlyWhenFull()sends partial results.I choose between them on purpose. If a duplicate or early result is harmless, emit early. If an early result would be wrong, shut down and alarm.
- “How long are window stores kept?”
A window store keeps each window's data for the window size plus the grace period plus a retention period, and after that its old segments are deleted. The idea is that you need the window around while late records may still arrive, and for queries.
A worked example with assumed numbers:
window retentionruns offline# illustrative arithmetic, assumed numbers window size = 5 minutes grace = 1 minute retention = 1 hour (set on the store) a window ends at 10:05, can still take late records until 10:06, and stays readable by interactive queries until about 11:05Retention must be at least the window size plus grace, or Streams refuses to start. Beyond that minimum, it is a choice. Longer retention helps dashboards and replays, but costs disk, and the changelog topic is sized to match.
I set retention from the longest time anyone needs to query a past window, not larger. It is configurable per store with
Materialized.withRetention(...).
Q112. “Why do Streams joins need co-partitioning, and what is a repartition topic?”
Reveal answer
Strong answer A join matches records with the same key. For that to work in a distributed setting, the records for key X from both inputs must be handled by the same instance. That requires both topics to have the same number of partitions and the same partitioning rule, so key X sits in the same partition number in both.
If the key is changed before the join (for example you re-key a stream with selectKey), Streams does not know where the records belong. It writes them to an internal repartition topic, keyed by the new key, and reads them back so same-key records end up together.
That extra topic adds latency, disk and network cost. Avoid unnecessary re-keying.
GlobalKTable joins skip all this, at the cost of copying the table everywhere.
Picture it A bad and a good arrangement.
The setup: orders has 6 partitions, customers has 4.
orders(6 partitions) JOIN customers(4 partitions)
-> TopologyException: Topics not co-partitioned ✗
fix: recreate customers with 6 partitions, same default partitioner ✓
or: use a GlobalKTable for customers (small data) ✓Make the invisible visible: A repartition appears when the key changes.
orders
.selectKey((k, v) -> v.customerId()) // key changed -> marks for repartition
.join(customers, (o, c) -> enrich(o, c)); // Streams adds orders-repartition topicWhy: Same key, same partition number, same instance: that single rule is what makes distributed joins correct.
Land it A join needs same-key records on the same instance, which means equal partition counts and partitioning; changing the key triggers a repartition topic.
- “Does Streams check the partition counts?”
Partly. Streams checks what it can see, which is the partition counts, and cannot check what it cannot see, which is how the producers chose the partition.
At startup, Streams compares the number of partitions of every topic that must be co-partitioned for a join. If a stream has 12 and a table has 6, it fails with a clear error naming the topics. That check is cheap and catches the most common mistake.
What it cannot know is how each record's partition was picked. The default producer partitioner uses a hash of the key. If another team's producer uses a custom partitioner, or a different client library hashes differently, then key X lands on partition 3 in one topic and partition 5 in the other. Counts match, the join runs, and matches are silently missed.
My defence is a rule: every producer of a joined topic uses the default partitioner, and I include a small test that joins known keys across the two topics.
- “How do I avoid repartition costs?”
The best saving is to choose the key when you produce, so the data arrives already keyed by the join field. Then Streams never needs to re-key it.
Inside the topology, there are smaller rules:
- Keep the key: use
mapValues,filterandflatMapValueswhere the key is not changing. They keep the partitioning knowledge.map,selectKeyandgroupBywith a new key mark the stream as needing repartition. - Re-key once: if you must change the key, do it once, early, and do all the later joins and aggregations on that new key.
- Read the topology: print the description and look for names ending in
-repartition. Each one is a topic written and read back.
The cost of a repartition topic is a full write and read of every record, with network, broker disk and added latency. For a high-volume stream, that can double the load. I treat an accidental repartition like an accidental extra database query: find it in review.
- Keep the key: use
- “Where can I see the topology?”
Call
describe()on the built topology, and print it. It lists each sub-topology with its sources, processors, state stores and sinks, and it names the internal topics that Streams will create.Describe.javaruns offline// illustrative Topology topology = builder.build(); System.out.println(topology.describe()); // illustrative output, abbreviated: // Sub-topology: 0 // Source: KSTREAM-SOURCE-0 (topics: [orders]) // Sink: KSTREAM-SINK-5 (topic: app-KSTREAM-KEY-SELECT-repartition)A line like that last one tells you that a repartition topic exists, and which operation caused it.
I use this in two ways. First, as a review habit: paste the printed topology in the pull request when the topology changes, so reviewers see new repartitions and state stores. Second, as a regression test: compare the printed text to a saved file, so an accidental change fails the build.
There are also visualizer tools that draw the same text as a graph.
- “Stream-stream joins?”
A stream-stream join is windowed: two records join only if their timestamps are within a chosen time difference, such as 5 minutes. The reason is that both streams are infinite, so without a time limit the join would have to remember every record forever.
Each side keeps recent records in a state store, so the other side can find them. The memory is roughly the window length times the event rate, for both sides together.
join memoryruns offline# illustrative arithmetic, assumed numbers orders 200 records/s, payments 200 records/s, 1 KB each join window = 5 minutes = 300 s state = (200 + 200) x 300 x 1 KB = 120,000 KB, about 120 MB a 1-hour window would hold about 1.4 GBSo the cost grows directly with the window, and I keep it as small as the business case allows. Grace and retention add to it.
Also, a stream-stream inner join only emits when a match is found within the window, so a missing partner produces nothing unless I use a left join.
Q113 · Scenario. “A Streams counter shows too-high numbers after an instance crashed. What setting is missing?”
Reveal answer
Strong answer The default processing guarantee is at_least_once. After a crash, the instance restarts from the last committed offsets, which may be behind the last processed record, so some records are processed again and counted twice.
Setting processing.guarantee=exactly_once_v2 wraps the work for each batch (read input, update state, write changelog, write output, commit offsets) in one Kafka transaction. A crash aborts the whole thing, and the replay yields each count once.
Consumers of the output must use read_committed.
It costs latency (commit interval drops to 100 ms by default in this mode) and some throughput, and requires brokers at a compatible version with three or more brokers for transaction state defaults.
Picture it The same crash under both modes.
The setup: Counting events for key k; record 7 was processed, then crash before offset commit.
# illustrative output
at_least_once: count(k)=7 written; offsets committed through 6; crash
restart replays record 7 -> count(k)=8 ✗ double counted
exactly_once_v2: count, changelog, output and offsets in one txn; crash aborts it
restart replays record 7 -> count(k)=7 ✓The fix: The setting.
processing.guarantee=exactly_once_v2
# downstream readers: isolation.level=read_committedWhy: State and output are Kafka data too, so they can share one transaction with the offsets.
Land it Counts doubled because at_least_once replays after a crash; exactly_once_v2 puts state, output and offsets in one transaction.
- “Does exactly_once cover my database write in a processor?”
No. Exactly-once in Streams covers a closed loop: read from Kafka, update state kept in Kafka, write to Kafka. A call to a database, an HTTP API or an email service from inside a processor is outside that loop, and Kafka's transaction cannot undo it.
Here is what goes wrong. The processor calls the payment service, then the instance crashes before the transaction commits. The transaction aborts, and on restart the same input record is processed again. The processor calls the payment service a second time. The Kafka output is correct and the payment is doubled.
The options are:
- Idempotent call: send an idempotency key, such as the record's topic, partition and offset, or an order id, so the other system ignores repeats.
- Move it out: let the stream write a result topic, and have a separate idempotent consumer or sink connector make the external call.
The second is cleaner, since it keeps the stream's exactly-once promise honest.
- “What about the extra latency?”
Exactly-once mode delays results, because downstream consumers using
read_committedsee an output record only after its transaction commits. Streams commits on a timer, and in this mode the defaultcommit.interval.msfalls to 100 ms, from 30 seconds in at-least-once mode.So the added end-to-end delay is bounded by the commit interval plus the time to finish the transaction. With the default, that is typically a small fraction of a second.
The trade-off runs in both directions:
- Lower interval: fresher results, but more small transactions, each with its own overhead on the brokers' transaction coordinator.
- Higher interval: bigger batches, better throughput, and results that arrive later.
I tune
commit.interval.msfrom the delay the business can accept. A fraud alert may need 100 ms. A nightly report can use 5 seconds or more and gain throughput.Measure before you change it, because the right number depends on your record rate and transaction size.
- “Is there a version I should name?”
Yes:
exactly_once_v2. It is the only exactly-once mode in current Kafka. The earlier valuesexactly_onceandexactly_once_betawere deprecated in Kafka 3.0 and removed in 4.0, so a config that still names them fails when you upgrade.The reason v2 replaced them is scale. The first version used one transactional producer for every task, which meant many producers, many connections and many transaction ids per instance. In v2 (KIP-447) there is one producer per stream thread, and the consumer group's metadata lets the broker fence a zombie, an old instance that has been replaced but is still running. That cut the load on brokers heavily.
It needs brokers at version 2.5 or later, and for production at least three brokers, since the transaction state topic has a replication factor of 3 by default.
In an interview I name it as
exactly_once_v2, and mention the removal, since people still write the old name.- “How do I test it?”
I test it by breaking it on purpose. A normal unit test cannot show exactly-once, because the failure only appears when a crash lands between the steps.
The approach:
- Known input: send a numbered sequence, for example 1 million events across 1,000 keys, so the correct counts can be computed offline.
- Inject failures: while it runs, kill instances with
kill -9at random times, restart them, and also kill a broker once. - Compare: read the output topic with
read_committed, take the latest count per key, and compare with the offline answer. They must match exactly.
Run the same test with
at_least_oncefirst. You should see inflated counts. If you do not, the test is not hitting the failure window, so it proves nothing.I do this in staging before relying on the guarantee, and I keep the script, so it runs again after a Streams upgrade.
Q114 · Design. “Design a streaming job that flags a card with more than five transactions in five minutes.”
Reveal answer
Strong answer Key the stream by card id, so all of a card's transactions go to one partition. Count in a 5-minute window per key, and write an alert event when the count passes five.
A hopping window (size 5 minutes, step 1 minute) gives a rolling check; a tumbling window can miss a burst split across two windows. Sliding windows are the most accurate for “any five-minute span”.
The store holds one counter per card per window. Scale by adding instances up to the partition count. Output goes to fraud-alerts, keyed by card.
Give the topic a retention matching how long investigators need alerts, and make the alert handler idempotent.
Picture it The topology.
The setup: Input transactions, key = card id, 12 partitions.
builder.stream("transactions", Consumed.with(Serdes.String(), txSerde))
.groupByKey()
.windowedBy(SlidingWindows.ofTimeDifferenceAndGrace(Duration.ofMinutes(5), Duration.ofSeconds(30)))
.count()
.toStream()
.filter((w, n) -> n != null && n > 5)
.map((w, n) -> KeyValue.pair(w.key(), new Alert(w.key(), n)))
.to("fraud-alerts", Produced.with(Serdes.String(), alertSerde));Make the invisible visible: What the numbers look like.
# illustrative numbers: 3,000 tx/s total, 2 million active cards
store: 2,000,000 keys x ~80 bytes x a few windows = a few hundred MB, spread over 12 partitions
instances: 3 (each owns 4 partitions); max useful instances = 12Why: The key chosen at the start decides ordering, state locality and scaling limit all at once.
Land it Key by card, use a sliding window count, emit an alert event over the threshold, and scale to the partition count.
- “Why not a database counter?”
A database counter works at modest volume, but it makes a shared database sit in the path of every transaction. At scale the design costs more than it looks.
Each transaction becomes a synchronous read-modify-write: read the card's count, add one, write it back, with locking or a retry on conflict. Cards that are active at the same moment contend on rows, and the database's latency becomes the fraud system's latency. Expiring old events needs a cleanup job too.
The Streams version keeps the counter in a local store, partitioned by card id. Each instance handles its own cards with no remote call, the counts are rebuilt from the changelog after a failure, and windows expire by themselves. Because the input topic is a log, you can replay history to test a new rule.
Scale decides it. At a few hundred transactions a second, a database counter is simpler, and I would use it. At tens of thousands a second, or when replay matters, I use Streams.
- “How do I avoid sending the same alert repeatedly?”
With a sliding or hopping window, a burst of seven transactions produces an alert on the sixth, then again on the seventh. A noisy alert stream floods the investigators. I add a cool-down.
The idea is a second small keyed store, card id to the time of the last alert:
- Check: when the count passes five, look up the card in the cool-down store.
- Emit or skip: if there is no entry, or the last alert was more than ten minutes ago, emit an alert and write the current time. Otherwise skip.
- Expire: entries older than the cool-down are removed, so the store stays small.
This needs the lower-level Processor API, or a transform with a state store, since the DSL has no built-in "once per period".
The alert handler still must be idempotent, because a replay or a crash can resend one alert. An alert id built from the card and the window start lets the handler ignore repeats.
- “What if one card is extremely hot?”
A card is a very unusual hot key. One person cannot make thousands of transactions a second, so a card that does is itself the finding: a bot, a test script, or a bug in an upstream service. All of its records still go to one partition, which is correct and cannot be split without breaking the count.
What I do:
- Measure skew: chart records per second by partition. One partition far above the rest means a hot key.
- Rate-limit upstream: a card submitting hundreds of transactions a second should be blocked at the payment gateway, before it reaches Kafka.
- Quarantine: route the offending card to a side topic and an alert for investigators, so it stops burdening the main partition.
I would not salt the key and spread this card, because the whole job is counting per card. Splitting the card's records across partitions gives several partial counts, and none of them reaches five.
Partition skew is a monitoring item, and I alert on it.
- “How do I test it without waiting five minutes?”
With
TopologyTestDriver, which runs the topology in memory, with no broker and no waiting. Time inside a Streams topology comes from the record timestamps, so the test sets them itself.FraudTopologyTest.javaruns offline// illustrative var in = driver.createInputTopic("tx", new StringSerializer(), new StringSerializer()); var out = driver.createOutputTopic("fraud-alerts", new StringDeserializer(), new StringDeserializer()); Instant t0 = Instant.parse("2026-01-01T10:00:00Z"); for (int i = 0; i < 6; i++) in.pipeInput("card-1", "tx" + i, t0.plusSeconds(i * 30)); // 6 in 2.5 minutes assertEquals(1, out.getQueueSize()); // one alertSix transactions at 30-second spacing fall within five minutes, so the test expects one alert. The driver does not wait for real time: it only moves time forward when records carry later timestamps, so the whole test finishes in milliseconds. That also means a window will not close in a test unless you send a later record to push stream time past the window end, which is a common surprise.
I then add cases for the edges: exactly five, six spread over ten minutes, and records arriving late within and beyond the grace period. The edges are where window bugs live.
Q115. “Kafka Streams, Flink, or a plain consumer: how do you choose?”
Reveal answer
Strong answer A plain consumer with some code is the simplest and enough when each record is handled alone, or with a small database table for state. Kafka Streams is a library inside your own app, giving windows, joins and managed state over Kafka with no extra cluster.
Flink is a separate cluster and framework with richer event-time features, many sources and sinks beyond Kafka, and larger scale analytics, at the cost of running and learning it.
I choose Streams when the data is Kafka to Kafka and the team wants to ship as a normal service. I choose Flink when jobs are bigger, need many sources, or have a dedicated platform team.
I choose a plain consumer when there is no real need for state across records.
Picture it The decision table.
The setup: Three jobs: enrich orders, count fraud, big multi-source analytics.
| Option | Pick it when | Cost or catch |
|---|---|---|
| Plain consumer + DB | Per-record work, simple state in a database | You write windowing and recovery yourself |
| Kafka Streams | Kafka-to-Kafka, joins and windows, normal service deployment | Kafka only; state restore is your ops concern |
| Flink | Large jobs, many sources, advanced time handling | Separate cluster to run; more to learn |
| ksqlDB / SQL layer | Analysts want SQL on streams | Less control; check current support for your environment |
Make the invisible visible: The question that decides.
Does the job need state across records? no -> plain consumer
Is input and output Kafka only? yes -> Kafka Streams
Many sources, huge state, platform team? yes -> FlinkWhy: Pick the least machinery that covers the state you need.
Land it Plain consumer for per-record work, Streams for Kafka-to-Kafka stateful jobs, Flink when scale or sources outgrow a library.
- “What does Streams give that a consumer does not?”
Streams gives you the stateful building blocks as library calls, so you do not write them yourself. With a plain consumer, each of these is your own code to write, test and debug.
- Windows: grouping by time, handling late records and closing windows correctly.
- Joins: matching records from two topics by key, with co-partitioning checks.
- State with recovery: local stores backed by changelog topics, so state survives a crash without a hand-built database.
- Exactly-once: one setting that wraps read, state update, output and offset commit in a transaction.
- Scaling and rebalancing: tasks per partition, standby replicas and assignment of state.
A plain consumer can do all of these, with a database for state and careful commit logic. It is simply more code, and subtle bugs live in the commit and recovery parts.
The cost of Streams is learning its model: tasks, state stores, repartition topics and restore. A team that does not need windows, joins or aggregation should not pay it, and a plain consumer is the better choice there.
- “When does Streams hurt?”
Streams hurts when the state is large, when restoring is slow, or when the team wants to run and deploy the job separately from the application it lives in.
The main problems:
- Large state: a store of hundreds of gigabytes means long restores after a restart, and a rebalance that moves a partition can pause that partition for a long time.
- Deploys: it is a library inside your application, so every application deploy restarts the stream job and triggers a rebalance. A frequently deployed service therefore restarts its stream job often.
- Kafka only: it reads and writes Kafka. Other sources and sinks need Connect or custom code.
None of these is a reason to avoid it, but each is a reason to treat the job as a stateful service. That means persistent volumes, standby replicas, graceful shutdown, restore monitoring and a deploy process that restarts one pod at a time.
If a team cannot invest in that operational care, a simpler design, or a dedicated platform with Flink, may fit better.
- “Why might a team prefer Flink?”
Teams usually pick Flink for four reasons, and each one needs a clear need behind it.
- Event-time features: richer windows, watermarks and handling of late and out-of-order data.
- Checkpoints and savepoints: a savepoint is a snapshot of a whole job, so you can stop, upgrade the code and resume without losing state. That is a smoother upgrade path for very large state.
- Many connectors: it reads from and writes to files, databases, message systems and object storage, not only Kafka.
- Scale and SQL: large analytics jobs, with a SQL layer that analysts can use.
The price is a separate cluster to run, which means a resource manager, job deployment, upgrades and monitoring, plus the effort of learning its model.
That price is worth it when a platform team runs Flink once for many jobs. For one or two Kafka-to-Kafka services, with no such team, the cluster is overhead, and Streams as a library is the lighter choice.
- “What would you tell a team that wants to start?”
I would tell them to start with a plain consumer and a database table, and to move up only when the code tells them to. The first version should be boring and easy to run.
A plain consumer that reads a record, does the work and writes to a database covers a large share of real use cases. It has no new concepts and the whole team can debug it.
The signs that it is time for Streams:
- Windows or joins: they are writing their own time-bucket or matching logic.
- Recovery code: they are building checkpoints or a state table that must be rebuilt after a failure.
- Exactly-once: they need results that must not be doubled and are all in Kafka.
When two of these appear, Streams will save more code than it costs. Flink comes later still, if scale or sources outgrow a library.
Choosing a framework for a problem you do not have yet is the usual mistake. A simple design that works can be moved to a heavier tool later, because the topics stay the same.
11 · DrillProduction Scenarios & Design — Q116–Q150
The last thirty-five questions are the ones a senior round saves for the end: incidents you must diagnose from symptoms, and systems you must design from a blank page. Name the first three things you would look at, give real numbers, and say what you would give up. Say yours first, then reveal.
These questions test how you reason from symptoms to causes with few facts, and whether you give numbers and a first action, not a lecture.
Q116 · Scenario. “Consumer lag grows to 2 million after a deploy. Walk me through it.”
Reveal answer
Strong answer First I ask whether lag grows on every partition or on one. Every partition means the consumers got slower or stopped; one partition means a hot key or a stuck record.
Second, I compare consumption rate to production rate. Lag is just the gap: if producers write 5,000 records per second and consumers now handle 3,000, lag grows by 2,000 per second, which is 2 million in 1,000 seconds, about 17 minutes.
Third, I look at what the deploy changed: a new slow call, a config default, a smaller concurrency, a rebalance storm, or crashing pods. I check rebalance count and pod restarts first, since those are quickest to see.
Then I act: roll back if the deploy is clearly the cause, otherwise scale out (up to the partition count) while I find it.
Picture it The arithmetic and the decision tree.
The setup: Lag was near 0 before the deploy at 10:00; now 2,000,000.
produce rate 5,000 rec/s
consume rate 3,000 rec/s (after deploy)
lag growth 2,000 rec/s -> 2,000,000 / 2,000 = 1,000 s = about 17 min
to catch up at 8,000 rec/s capacity: 2,000,000 / (8,000 - 5,000) = 667 s = about 11 minMake the invisible visible: Per-partition lag, the first thing I look at.
# illustrative output: kafka-consumer-groups.sh --describe --group billing
PARTITION LAG
0 250000
1 248000
2 251000 <- all even: whole group slowed (rate problem)
3 249000
vs one partition at 2,000,000 and the rest at 0: hot key or stuck recordWhy: Even lag points at rate or availability; skewed lag points at data.
Land it I split lag by partition, compute produce versus consume rate, check rebalances and restarts, and roll back or scale out while I find the cause.
- “What do you check when the lag is even across partitions?”
If lag is even across partitions, the whole group is slower or has stopped, so I look for something that affects every consumer at once. I go through five things in order, quickest first.
- Restarts and rebalances: pod restarts, crash loops, and the rebalance count. A group that keeps rebalancing spends its time not consuming.
- Time per record: the handler's processing time. If it rose from 2 ms to 8 ms, throughput fell to a quarter.
- Dependencies: latency of the database or API the handler calls. A slow dependency shows up as more time per record, with low CPU.
- Resources: CPU throttling, memory pressure or long garbage collection pauses in the consumers.
- Config changes: the deploy diff, such as
max.poll.records, concurrency, or a new library.
The most effective step is one chart: lag with a deploy marker, and processing time on the same time axis. If the processing time rose at the deploy, the cause is the change. If it rose a little later, suspect a dependency.
- “What if scaling out does not help?”
Then the limit is not the number of consumers, it is either the partition count or something the consumers depend on. Adding pods past those limits only adds cost.
The two usual cases:
- Already one consumer per partition: in a group, a partition goes to only one consumer. With 12 partitions and 12 pods, the thirteenth pod gets nothing. More parallelism needs more partitions, which has its own cost, including changing key placement.
- Downstream is the bottleneck: if every handler waits on one database that is already at its limit, more consumers send more concurrent queries, which slows each one down. Throughput may even fall.
I check which case I am in by looking at consumer CPU, and at the dependency's own latency and saturation. Idle consumers waiting on a busy database point to the database.
The fix then is on that side: add capacity or caching, batch the writes, or make the call cheaper. Increase partitions only when the consumers are busy and already one per partition, and I warn the team that ordering for existing keys changes.
- “How long to drain, and how do you tell the owner?”
The time to drain is the lag divided by the spare capacity, where spare capacity is what the consumers can process minus what producers still send.
drain timeruns offline# illustrative arithmetic, assumed rates lag = 2,000,000 records incoming = 5,000 records/s capacity (fixed) = 8,000 records/s spare = 8,000 - 5,000 = 3,000 records/s drain time = 2,000,000 / 3,000 = about 667 s, roughly 11 minutesIf the capacity is only 5,500, spare is 500, and drain takes over an hour. So a small change in capacity moves the answer a lot. If capacity is below incoming, the lag never drains.
I tell the owner the estimate with the assumption, for example "about 11 minutes if the fix holds", and I update it every ten minutes from the real lag curve, because both rates move.
A number with a time stamp beats "soon". It lets them decide on a customer message, or on whether to scale out.
- “Should I just skip the backlog?”
Only if the business owner agrees, and the answer depends on what the records mean.
Where skipping is fine: data where only the latest value matters, such as live price updates, location pings or a "current status" feed. A record from twenty minutes ago has already been replaced by a newer one, so processing it is wasted work. Jumping to the end of the log loses nothing useful.
Where it is not: orders, payments, ledger entries and anything where each record is a fact someone relies on. Skipping means those facts never reach the downstream system, so customers are not billed or shipped.
How to skip, if allowed, is to stop the group and reset offsets to the latest, or to a chosen timestamp, with the reset tool. I record the offsets I skipped, and the time range, so the gap can be repaired later from the topic while retention still holds it.
I get the decision from the owner in writing, because it is a data decision, not a technical one.
Q117 · Scenario. “One partition has all the lag and the others are at zero. What are the causes?”
Reveal answer
Strong answer Three causes. A poison or stuck record: the consumer retries or hangs on one record at the head of that partition. A hot key: one key sends far more traffic than others, so one partition is overloaded. Or a slow or dead consumer that owns that partition.
To tell them apart, I look at the consumer's current offset: if it is not moving at all, a stuck record; if it moves slowly while the end offset moves fast, a hot partition; if the member is not heartbeating, a dead owner.
Fixes: for a stuck record, dead-letter or skip it; for a hot key, change the key or add a salt for non-order-sensitive work; for a dead owner, fix the instance and let the rebalance move the partition.
I also check for a bad partition leader on a struggling broker.
Picture it Three signals from one command.
The setup: Partition 7 shows lag 1.9 million; the rest are near 0.
# illustrative output
CASE A stuck record : CURRENT-OFFSET 880100 unchanged for 20 min, LOG-END grows slowly
CASE B hot key : CURRENT-OFFSET advances 900/s, LOG-END advances 4,000/s -> 3,100/s deficit
CASE C dead owner : CONSUMER-ID shows "-" (no active member for partition 7)Make the invisible visible: Find the hot key by sampling.
kafka-console-consumer.sh --bootstrap-server b1:9092 --topic orders \
--partition 7 --offset latest --max-messages 5000 --property print.key=true \
| cut -f1 | sort | uniq -c | sort -rn | head -3
# illustrative output: 4210 customer-9 <- one key is 84% of the partitionWhy: One command and one sample separate the three causes and each has a different fix.
Land it A single lagging partition means a stuck record, a hot key or a dead owner, and the offset movement tells me which.
- “How do I fix a hot key without breaking ordering?”
If order per key matters, you cannot spread that key over several partitions. Spreading it would let two records of the same key be processed by different consumers in the wrong order. So the options are all about making the work cheaper, or changing what the key means.
- Cheaper work: batch the handler's database writes, cache lookups, or move slow side work to an asynchronous step, so one partition's consumer keeps up.
- Finer key: if ordering is only needed within a smaller unit, use that as the key. Customer plus region, or customer plus order id, splits one hot customer into many ordered streams.
- Salt: if no ordering is needed, append a small random number to the key, such as
cust-42#3, spreading it over several partitions. Then merge the partial results downstream.
The salt works well for counts and sums, which are commutative, and badly for anything sequence-dependent.
First I check whether the hot key is legitimate. A single "unknown" or null-like key, such as an empty customer id, is often a bug, and fixing it removes the skew.
- “Why not just add partitions?”
Because adding partitions does not change where the hot key goes: it still hashes to exactly one partition. The new partitions get some of the other keys, and the one overloaded partition remains overloaded.
There is also a harm. The partition for a key is murmur2 of the key, modulo the partition count. Change the count from 12 to 24, and many existing keys map to a different partition than before. Records for the same key now sit in two partitions, one before the change and one after. A consumer can then process a new record before the old ones, which breaks ordering at the moment of the change.
partition moveruns offline# illustrative: hash(key) = 1000 partitions 12: 1000 mod 12 = 4 partitions 24: 1000 mod 24 = 16 key moved from partition 4 to 16So partition count fixes lack of parallelism, not skew. I add partitions to scale many keys, and I handle skew by changing the key or the work.
- “How do I prevent poison records?”
I stop a single bad record from being able to block a partition, at several layers. No one layer is enough alone.
- At the producer: validate the record before sending, and fail the request if it is malformed. It is cheaper to refuse one bad record than to clean a topic.
- Schema registry: serialize with a registered schema, so a record that does not match fails at the producer, not at the consumers.
- Safe deserialization: wrap the deserializer, for example with Spring's
ErrorHandlingDeserializer, so a failure becomes a handled error instead of an exception that repeats forever. - Dead-letter topic: after a few attempts, publish the record, with the error and its position, to a dead-letter topic and move on.
- Time limit: put a limit on a handler's time per record, so a record that triggers an infinite loop or a stalled call cannot hold the partition indefinitely.
The dead-letter topic then needs an alert and an owner, or it becomes a place where problems quietly go to wait.
- “How would you alert on skew?”
A total lag number hides a stuck partition, because eleven healthy partitions with zero lag and one with a million average to a modest figure. So I alert on the shape of lag, not only the sum.
- Skew ratio: the maximum partition lag divided by the median, for each group. Alert when it stays above about 10 for several minutes. The exact number depends on your baseline.
- Stalled offset: a partition whose committed offset has not changed for N minutes while its end offset keeps increasing. This catches a stuck record and a dead owner even when lag is still small.
- Throughput per partition: producer rate by partition, to spot a hot key at the source.
For the first two, the data comes from the consumer-group lag metrics, which most monitoring setups can export per partition.
The stalled-offset alert catches the first minutes of a poison record, long before the lag number looks scary. With an alert on the stall, the on-call engineer sees the message in time to dead-letter the record before a backlog forms.
Q118 · Scenario. “A broker dies at 3 a.m. What happens, what do you check, and what do producers see?”
Reveal answer
Strong answer The controller notices the broker is gone, and for every partition whose leader was on it, picks a new leader from the in-sync replicas. Producers and consumers get a metadata error, refresh, and continue against the new leaders, usually within seconds.
With replication factor 3, min.insync.replicas=2 and acks=all, writes continue as long as two replicas are in sync. Each affected partition now has two replicas, so it is under-replicated until the broker returns or is replaced.
I check under-replicated and offline partition counts, whether any partition has fewer than min.insync replicas (writes fail there), the cause of the crash (disk, memory, host), and recovery time as the broker catches up.
I do not wake anyone for a single broker down if no partition is offline; I do for offline partitions or a second failure.
Picture it Before and after for one partition.
The setup: Partition orders-3: leader on broker 1, replicas 1, 2, 4, ISR = {1,2,4}.
# illustrative output
broker 1 dies
orders-3: leader 2 (elected), ISR {2,4}, replicas {1,2,4} under-replicated, writes OK (2 >= min.isr 2)
a second broker (2) dies as well
orders-3: leader 4, ISR {4} (1 < min.isr 2) producers: NotEnoughReplicas ✗, reads still OKMake the invisible visible: What I run first.
kafka-topics.sh --bootstrap-server b2:9092 --describe --under-replicated-partitions
kafka-topics.sh --bootstrap-server b2:9092 --describe --unavailable-partitionsWhy: The ISR plus min.insync.replicas decides whether a partition accepts writes. One failure is tolerated by design; two is a page.
Land it Leaders move to in-sync replicas in seconds; with RF 3 and min ISR 2 one broker loss is safe, and I check under-replicated and offline partitions.
- “Why does a producer sometimes see errors for a few seconds?”
Because for a short time the partition has no leader, so there is nobody to accept a write. Clients see this as a retriable error, not a loss.
The sequence is:
- Detection: the broker's session with the controller expires, or its connection drops, and the controller marks it as gone. This takes up to the session timeout, a few seconds to some tens of seconds, depending on settings.
- Election: the controller picks a new leader for each affected partition from the in-sync replicas and publishes the change.
- Client refresh: a producer gets
NOT_LEADER_OR_FOLLOWER, refreshes its metadata, and resends the batch to the new leader.
The producer keeps retrying within
delivery.timeout.ms, 2 minutes by default, so a gap of seconds is absorbed. With idempotence on, the retry cannot duplicate the batch.What the application sees is a brief latency spike for that partition, and no errors unless the outage outlasts the delivery timeout.
- “What if the dead broker had the only up-to-date copy?”
That happens when the in-sync set shrank to just one broker, and that broker was then the one that died. The other replicas are behind, so the new leader would be missing acknowledged records.
The setting that decides what happens is
unclean.leader.election.enable, which is false by default.- False (default): the partition stays offline until a replica from the in-sync set returns. Producers get errors and consumers wait. No acknowledged record is lost, but the partition is unavailable.
- True: Kafka promotes an out-of-sync replica. The partition is available again quickly, and every record that replica never received is gone, even though producers were told it was written.
This is the clearest example of choosing consistency over availability. For orders and payments I keep it false and accept the outage.
For a metrics or logging topic where losing a few seconds of data is harmless and downtime is worse, setting it true on that topic can be a reasonable choice. Document it as a decision.
- “How long does catch-up take when it returns?”
Catch-up time is the amount of data the replica missed divided by how fast it can fetch. It is bounded by the network, the disks and any replication throttle.
catch-up timeruns offline# illustrative arithmetic, assumed numbers data missed = 200 GB (about 2 hours of writes at 28 MB/s, for this broker's partitions) fetch rate = 100 MB/s time = 200,000 MB / 100 MB/s = 2,000 s, about 34 minutes with a 50 MB/s throttle: about 67 minutesDuring that period, every partition on the broker is under-replicated, so a second failure in the same window could cost a write: with
min.insync.replicas=2, losing another replica of any of those partitions stops writes on it.So the catch-up window is the riskiest time. A throttle protects the network and latency for clients but lengthens that window. I decide how to balance it by looking at the load at the time, and I watch the under-replicated count falling to zero.
- “How do you stop a restart from causing a traffic storm?”
When the broker is back and caught up, leadership does not move back by itself at once. The surviving brokers keep the leaders they took, so the cluster runs unbalanced until leadership is restored to the preferred replica, the first replica in each partition's list.
By default
auto.leader.rebalance.enable=true. The controller checks everyleader.imbalance.check.interval.seconds(300 s) and moves leaders back when a broker has more thanleader.imbalance.per.broker.percentage(10 percent) imbalance.The concern is the timing of the move. Each leader change causes a short pause for that partition and a burst of client metadata refreshes. Moving hundreds of partitions at once, at peak, shows as a latency spike.
Options:
- Let it run: acceptable on a quiet cluster, and the default.
- Control it: turn auto rebalance off for large clusters, and run
kafka-leader-election.sh --election-type preferredgradually, off-peak.
I watch request latency and under-replicated partitions while it happens.
Q119 · Scenario. “Customers report duplicate orders. How do you find where the duplicate was created?”
Reveal answer
Strong answer Duplicates can be created at four places: the producer retried and wrote twice, the consumer re-processed after a rebalance or crash, the upstream client called twice, or a replay or reprocessing job ran.
I take one duplicated order id and trace it: how many times is it in the topic (with partition and offset)? If twice in the topic, the duplicate is upstream of the consumer; if once in the topic but twice in the database, the consumer reprocessed.
If twice in the topic, I check producer settings (idempotence off? acks=1 with retries?) and whether the HTTP client retried the request, creating two orders with different ids.
The fix depends on where: idempotent producer, idempotent consumer, or an idempotency key on the API.
Picture it The investigation as a short decision.
The setup: Order o-5512 charged twice.
# illustrative output
count of o-5512 in topic: 1 (partition 4, offset 90211)
count of o-5512 in DB table: 2 (rows at 10:02:11 and 10:07:44)
-> consumer reprocessed; 10:07 matches a rebalance in the group log
fix: unique constraint on event_id in the same transaction as the chargeMake the invisible visible: The other branch.
count in topic: 2 (offsets 90211 and 90217, different order ids "o-5512","o-5513", same cart)
-> client retried POST; no idempotency key
fix: Idempotency-Key header, stored with a unique constraint on the API sideWhy: Counting the id at each hop localizes the duplicate to one hop in a few minutes.
Land it I follow one duplicated id through the topic and the database, which tells me whether the producer, the consumer or the client created it.
- “What producer settings can produce duplicates?”
Duplicates from the producer come from a retry after a lost acknowledgement, and whether that can happen depends on the settings and on what the application does.
With idempotence off, the sequence is: the producer sends a batch, the broker writes it, the acknowledgement is lost on the network, the producer times out and sends the same batch again. The topic now has the batch twice.
Since Kafka 3.0,
enable.idempotence=trueandacks=allare the defaults. Each batch carries the producer id and a sequence number, and the broker drops a repeated sequence. So client-library retries cannot duplicate.Two situations remain:
- Producer restart: a new instance gets a new producer id, and an application that resends "what it was not sure about" will duplicate.
- Old settings: a config that sets
enable.idempotence=falseoracks=1explicitly turns the protection off. Check the effective config in the producer logs.
And an HTTP client that retried the API call creates two different orders, which no Kafka setting can detect.
- “How do rebalances cause duplicates?”
A rebalance moves a partition from one consumer to another, and the commit position is the line between what the old owner is known to have finished and what the new owner will start with. Anything the old owner processed after its last commit is processed again by the new owner.
A small example, with auto-commit every 5 seconds: consumer A processes records 100 to 140. Its last commit said "next is 120". A rebalance happens. Consumer B takes the partition and starts at 120. Records 120 to 140 are processed twice, once by A and once by B.
That is normal at-least-once behaviour, and it is the reason handlers must be idempotent. How often it happens depends on how often the group rebalances, and how long the uncommitted window is.
The two fixes are to reduce the window and the frequency:
- Commit more precisely: commit after processing, and also in a rebalance listener when partitions are revoked.
- Fewer rebalances: cooperative assignment, static membership, and stable pods.
- “Can I prevent all duplicates in Kafka?”
No, not end to end, and it is worth being plain about where the guarantee stops.
Inside Kafka you can reach exactly-once. An idempotent producer prevents duplicates from retries, and transactions make a read, a write and an offset commit atomic. Kafka Streams offers this with
exactly_once_v2.Outside Kafka, the guarantee cannot extend by itself. An email, a card charge or a database row is written by code that Kafka's transaction does not control. If the consumer sends an email and then crashes before committing, the email goes out again.
So the reliable design is:
- Inside Kafka: use idempotent producers, and transactions where a stream job needs exact counts.
- At the edges: make each external action idempotent, with an idempotency key such as the order id, a unique constraint, or an upsert.
The accurate phrase is "effectively once": the action may be attempted twice, but the second attempt changes nothing.
The primer's delivery-guarantee section shows the same idea in more detail.
- “What do I tell the customer service team?”
Customer service needs facts and a next step, not an explanation of Kafka. I give them four things.
- Who is affected: a query that lists duplicated orders, such as orders with the same cart id and customer within a few seconds. They can run it themselves to find more.
- What we do for them: the duplicate is cancelled or refunded, with a clear owner and a date, so agents can tell the customer what happens and when.
- What happened, in one line: "a retry created two copies of some orders between 14:00 and 16:30". No jargon.
- What has been fixed: the producer or consumer change, and when it went live, so they know new duplicates should stop.
I also give them a way to ask for help, like a channel and an on-call name, and I update them when the count changes.
The aim is for the agent to answer the customer in the first minute, with accurate details. A specific, honest message beats a general apology, and I follow up when the fix is verified.
Q120 · Scenario. “Some messages never arrived at the consumer. Where could they have been lost?”
Reveal answer
Strong answer Seven places, from producer to consumer. Producer: acks=0 or acks=1 and the leader died; the send future ignored and the buffer dropped on shutdown; delivery.timeout.ms expired. Broker: unclean leader election; ISR too small. Retention: the data was deleted before the consumer read it. Consumer: auto-commit committed before processing; auto.offset.reset=latest skipped data; dead-letter missing.
I check them in order with evidence. Is the record in the topic (console consumer from the offset)? If yes, the loss is on the consumer. If no, the loss is on the producer or broker.
Then I check metrics: producer error counters, offset-out-of-range logs, an auto.offset.reset in the consumer logs showing a reset.
Each fix is a setting: acks=all, min.insync.replicas 2, manual commit after process, retention above the maximum downtime.
Picture it The seven places.
The setup: Orders o-1 to o-100 sent; the consumer saw 97.
| Where | Cause | Fix |
|---|---|---|
| Producer | acks=1, leader died; ignored failed future | acks=all, check futures, flush on shutdown |
| Broker | Unclean leader election | unclean.leader.election.enable=false, min.insync.replicas=2 |
| Retention | Consumer down longer than retention | Retention above worst downtime; alert on lag age |
| Consumer commit | Auto-commit before processing finished | Commit after processing |
| Offset reset | Lost offsets with auto.offset.reset=latest | Use earliest for must-not-lose data |
| Handler | Exception swallowed in code | Dead-letter topic, no empty catch |
| Wrong topic | Producer wrote to a different topic or partition | Check config per environment |
Make the invisible visible: Is it in the topic at all?
kafka-console-consumer.sh --bootstrap-server b1:9092 --topic orders --from-beginning \
--property print.key=true | grep -c "o-42"
# 1 -> in the log, loss is consumer-side; 0 -> producer/broker/retentionWhy: Splitting the path at the log cuts the search space in half with one command.
Land it I first check whether the missing record is in the log; if it is, the consumer lost it, otherwise the producer, broker or retention did.
- “How does acks=all with min.insync.replicas=2 prevent the broker-side loss?”
Because a write is only acknowledged once enough replicas hold it, so one broker failing cannot take an acknowledged record with it.
The settings work together. With replication factor 3,
acks=allmeans the leader waits for every replica in the in-sync set.min.insync.replicas=2sets a floor: if fewer than two replicas are in sync, the write is refused with an error instead of being accepted on a single copy.Take a leader that dies right after acknowledging record 500. At least one other in-sync replica also has record 500, and only an in-sync replica can be elected leader, so the new leader has it too.
The price is availability: if two of the three brokers are down, writes to that partition fail. That is the trade I choose for important topics.
With
min.insync.replicas=1, the in-sync set can shrink to just the leader. Thenacks=allmeans only the leader, and a leader crash can lose acknowledged writes. So the two settings must be set together.- “What does auto.offset.reset do exactly?”
It decides where a consumer starts when it has no valid committed offset for a partition. It is not used on an ordinary restart, where the committed offset is simply followed.
When there is no offset:
- New group: a group id that has never committed anything.
- Expired offsets: the group was inactive longer than the offsets' retention.
- Out of range: the committed offset no longer exists in the log, because retention deleted that data.
The values are:
- earliest: start at the oldest record still in the log. It reads everything available, so duplicates are likely after expiry.
- latest: start at the end, and ignore everything produced before this moment. This is the default, and it is where silent loss hides.
- none: throw an error. I like it for critical consumers, since it turns a silent skip into a visible failure.
If a consumer logs "resetting offset" at an unexpected time, that is the evidence of where the records went.
- “How long do committed offsets survive?”
Group offsets are not kept forever. When a group has no active members, its committed offsets expire after
offsets.retention.minutes, which is 7 days by default (10,080 minutes). The clock starts when the group becomes empty, in current versions.The failure case looks like this. A weekly batch consumer or a service switched off for a long holiday stays down for ten days. When it comes back, the broker has deleted its offsets. The consumer finds no position and falls to
auto.offset.reset. Withlatest, it skips everything produced while it was away. Nothing was deleted from the topic, but the consumer never reads it.There are three defences:
- Raise the retention: set
offsets.retention.minutesabove the longest expected gap, for batch-style groups. - Use none: set
auto.offset.reset=noneso a missing offset fails loudly. - Track offsets yourself: store the last processed offset alongside your data, if you must be exact.
- Raise the retention: set
- “How do I prove the pipeline loses nothing?”
You prove it by measuring both ends and comparing, and then by trying to break the pipeline on purpose.
The steady-state check is a reconciliation job. The producer side attaches a sequence number, or you count by key and time bucket; the sink side counts the same. Compare regularly, and alert on any difference above a small threshold that covers in-flight records.
reconcileruns offline# illustrative bucket 10:00-10:05 produced = 120,430 delivered = 120,430 ok bucket 10:05-10:10 produced = 118,902 delivered = 118,897 MISSING 5 -> alertThe second check is a chaos test in a staging environment:
- Send a known sequence: numbered records, so any gap or repeat is visible.
- Break things: kill a broker, kill consumers mid-batch, restart the producer, and force a rebalance.
- Compare: every number must appear, and the count of repeats must be what you designed for.
A pipeline that has never been tested with failures has not been shown to be lossless.
Q121 · Scenario. “After enabling autoscaling, the consumer group rebalances constantly and throughput collapses. Why?”
Reveal answer
Strong answer Autoscaling adds and removes pods in response to load. Every join or leave triggers a rebalance. Under the classic eager protocol, every member gives up all partitions and the group stops until reassignment finishes.
Scaling up because lag is high causes a rebalance that pauses consumption, which raises lag, which triggers more scaling. That is a feedback loop.
Fixes: use cooperative-sticky assignment or the KIP-848 group.protocol=consumer so only the moving partitions pause; use static membership with a stable group.instance.id so a restart does not trigger a rebalance; slow the autoscaler with a stabilization window; and never scale past the partition count.
Scale on lag per partition, not on CPU alone.
Picture it The loop and its break.
The setup: 6 partitions, autoscaler min 2, max 20, scales on CPU at 60%.
# illustrative output
t=0 2 pods, lag rising -> CPU 80% -> scale to 6 rebalance #1 (eager: all stop 15 s)
t=1 lag spikes during the pause -> scale to 12 rebalance #2, 6 pods idle (only 6 partitions) ✗
t=3 CPU low -> scale to 4 rebalance #3
fix: max replicas = 6; cooldown 10 min; cooperative protocolThe fix: Consumer and autoscaler settings.
group.protocol=consumer # KIP-848, or partition.assignment.strategy=CooperativeStickyAssignor
group.instance.id=${HOSTNAME} # static membership: restart within session timeout = no rebalance
session.timeout.ms=45000Why: The cure is fewer and cheaper rebalances, plus a cap that matches the partition count.
Land it Eager rebalances plus a lag-driven autoscaler form a feedback loop, so I use incremental rebalancing, static members and a capped, slow autoscaler.
- “What exactly does static membership change?”
It lets a restarting consumer keep its partitions, so a restart does not cause a rebalance at all. The key is a fixed identity that the consumer carries across restarts.
Without it, a member gets a new random member id each time it connects. The broker sees "old member left, new member joined", and the whole group rebalances twice. With
group.instance.idset to something stable, such as the pod nameorders-consumer-2, the broker recognises the returning member as the same one.If that member returns within
session.timeout.ms, it simply gets its old partitions back, and the rest of the group never notices. A rolling restart becomes a series of quiet swaps.The trade-off is slower failure detection. If a static member really dies, its partitions sit unassigned until the session timeout runs out, since the broker assumes it may come back. With the 45-second default, that is up to 45 seconds of no consumption on those partitions.
It needs stable pod names, so I use a StatefulSet, not a Deployment, for the consumers.
- “Why cap replicas at the partition count?”
Because consumers beyond the partition count have nothing to do. In a group, each partition goes to exactly one consumer. With 12 partitions, the first 12 consumers each get one, and a thirteenth gets none and sits idle.
An idle member is not free. It costs money for the pod, it takes part in every rebalance, and it triggers one when it joins or leaves. In a feedback loop with an autoscaler it makes things worse: scaling from 12 to 16 pods pushes no extra work through, but causes rebalances that pause the 12 working pods.
A small example of the loop:
- Lag rises: the autoscaler adds pods, up to 20.
- Rebalance: each addition pauses consumption, so lag rises further.
- Repeat: more pods are added, with no benefit.
The fix is a hard maximum in the autoscaler equal to the partition count, and a plan for what to do when that ceiling is hit: increase partitions, or make processing faster.
I write the maximum as a number next to the topic's configuration, so it is changed with it.
- “What should the autoscaler look at?”
It should look at how much work is waiting, per unit of capacity, not at CPU alone. CPU is a poor signal for many consumers, because a consumer that waits on a database or an HTTP call has a low CPU use even when it is badly behind. A CPU-based autoscaler sees a calm pod and does nothing, while lag grows.
Better signals:
- Lag per partition: total lag divided by the number of partitions, or the maximum lag, with a target such as 10,000 records per partition.
- Time to drain: lag divided by the current consumption rate, with a target of a few minutes.
A tool like KEDA has a Kafka scaler that reads lag from the brokers and sets the replica count. You set the lag threshold, the minimum and the maximum, and the maximum is the partition count.
The other half is damping. A scale-down window of 10 to 15 minutes stops it removing pods the moment lag dips, only to add them again.
- “How do I observe it?”
I watch four things, and a healthy group looks quiet.
- Rebalance rate: the number of rebalances per hour for the group. A healthy group rebalances at deploys and almost never otherwise.
- Assigned partitions per member: an even spread, and no member with zero unless there are more members than partitions.
- Time with no assignment: the total time the group spends rebalancing. This is the real cost, because during it the group consumes nothing, on the eager protocol.
- Autoscaler events: a chart of replica count next to lag. Zig-zag replica counts mean flapping.
The Java client exposes metrics such as
rebalance-total,rebalance-latency-avgandlast-rebalance-seconds-ago. The brokers' group coordinator logs show the cause, such as a member timing out or a join.My alert: more than a few rebalances per hour outside deploy windows. That points straight at an unstable member, a long processing time exceeding
max.poll.interval.ms, or an autoscaler out of tune.
Q122 · Scenario. “A broker's disk is 95% full. What do you do, in what order?”
Reveal answer
Strong answer Stop the bleeding first: find which topics and partitions are growing and why. A producer stuck in a loop, a retention change, or a traffic spike are the usual causes.
Then free space safely: lower retention.ms or retention.bytes on the offending topic, or delete a topic whose data is disposable. Retention deletes whole closed segments, so space frees in steps, not at once.
If a broker fills completely it stops, so do not wait. Move partitions to emptier brokers with the reassignment tool, throttled, or add disk.
After the incident, alert at 70 and 85 percent, set quotas, and size retention from rates.
Picture it Find the largest topics, then act.
The setup: Broker 2 at 95% of 2 TB.
kafka-log-dirs.sh --bootstrap-server b1:9092 --describe --broker-list 2 | \
python3 -c "..." # or: du -sh /var/kafka/data/* | sort -h | tail -5
# illustrative output
1.1T clickstream-4
210G orders-2 <- clickstream is the culpritMake the invisible visible: Reduce retention on the culprit, then watch.
kafka-configs.sh --bootstrap-server b1:9092 --alter --entity-type topics \
--entity-name clickstream --add-config retention.ms=21600000 # 6 hours
# segments older than 6 h are deleted at the next retention check (log.retention.check.interval.ms)Why: Retention is the safe lever, since it removes the oldest closed segments and never touches what consumers are reading right now.
Land it I find the topic that is growing, cut its retention to free closed segments, rebalance partitions if needed, and add alerts and quotas afterward.
- “Why does space not free instantly?”
Because Kafka deletes data in whole segment files, and only closed ones. A topic's log is a series of files, each up to
segment.bytes(1 GiB by default). A segment is deleted only when it is closed and when the newest record in it is older than the retention.Three consequences:
- The active segment stays: the file being written to is never deleted, however old its first records are. It closes only when it reaches the size limit or
segment.ms, 7 days by default. - The newest record decides: a segment holding records from hour 1 to hour 20 is kept until hour 20 is older than the retention.
- The checker runs on a timer: the log cleaner checks every
log.retention.check.interval.ms, 5 minutes by default.
So after I lower retention, space falls in steps over several minutes, and on a quiet topic with big segments it may not fall at all.
If I need it faster, I lower
segment.msorsegment.bytesfor the topic as well, so the active segment rolls and becomes deletable.- The active segment stays: the file being written to is never deleted, however old its first records are. It closes only when it reaches the size limit or
- “How do I move partitions safely?”
Moving partitions is safe if you throttle it and verify it, since the copy adds load at the moment the cluster is already stressed. I use the reassignment tool in three steps.
- Plan: generate or write a JSON plan listing which brokers should hold each partition, choosing the emptiest brokers. Check it by eye for replica placement across racks.
- Execute with a throttle: start the move with a limit on the replication bandwidth, so client traffic keeps priority.
- Verify and remove the throttle: check for completion, then clear the throttle, or it stays in place for later replication.
reassignruns offline# illustrative kafka-reassign-partitions.sh --bootstrap-server b1:9092 --reassignment-json-file plan.json --execute --throttle 50000000 # 50 MB/s kafka-reassign-partitions.sh --bootstrap-server b1:9092 --reassignment-json-file plan.json --verifyOn a very full disk I free space by retention first, and move data only when the target has room.
- “What if the broker already crashed on a full disk?”
Then the broker is down, and it will not start until it has space to write. The order of work changes: first make space, then start it, then deal with the cause.
- Make space offline: with the broker stopped, remove the data directories of a topic that is disposable and already known to be safe to lose, or attach a larger volume. Never delete files of a topic you need.
- Start and let it recover: on startup, Kafka checks the logs after an unclean shutdown. This can take a while, so I watch the logs for corruption messages and let recovery finish.
- Catch up: the broker's replicas fetch what they missed from their leaders, which needs space too. If the disk fills again, repeat with more room.
- Fix the cause: only now lower retention, find the producer that grew, and move partitions.
The other brokers took over the leaders meanwhile, so with replication factor 3 clients usually see only a short blip.
- “How do I prevent a repeat?”
I prevent it in four layers, since each one catches what the others miss.
- Alerts early: disk usage at 70, 85 and 90 percent, plus an alert on the rate of growth, such as "full in 12 hours at this rate", which gives lead time that a plain threshold does not.
- Right-sized retention: set per topic from rate times time. A topic that writes 2 MB/s for 7 days with 3 replicas needs about 2 x 604,800 x 3, roughly 3.6 TB across the cluster, so I check that against the disks.
- Quotas: byte-rate quotas per client id, so a runaway producer is slowed, not allowed to fill the brokers.
- Tiered storage: for topics that need long retention, keep recent data on local disk and older segments in object storage. Tiered storage has been generally available since Kafka 3.9.
And capacity planning each quarter: current rate, growth trend, and the date at which the disks fill. The goal is to buy disk on a schedule, not during an incident.
Q123 · Scenario. “Producer p99 latency jumped from 5 ms to 2 seconds. Where do you look?”
Reveal answer
Strong answer I split the time into the producer's own stages: waiting in the buffer, waiting for a batch to fill (linger.ms), network, broker processing, and replication wait for acks=all. The producer metrics show each part.
A two-second tail often means a replica is slow or out of sync, so acks=all waits for it until it is removed from the ISR (replica.lag.time.max.ms, default 30 seconds). Other causes: a full buffer (buffer.memory) blocking send, a broker overloaded or doing long GC, retries after a leader change, or a changed linger.ms.
I check broker request latency percentiles and ISR shrink events at the same timestamp as the spike.
Fix depends on the cause: replace the slow broker or disk, increase buffer, or tune batching.
Picture it Producer metrics by stage.
The setup: Spike at 14:10 for 8 minutes.
# illustrative output
metric normal at 14:10
record-queue-time-avg 1 ms 1 ms
request-latency-avg 3 ms 1900 ms <- broker round trip
buffer-available-bytes ok ok
broker 3 log: ISR shrink at 14:10, follower on broker 5 fell behind (slow disk)Make the invisible visible: Why a slow follower hurts.
acks=all waits for every replica in the ISR.
Broker 5 disk stalls -> its fetch lags -> leader waits (up to the ISR timeout) -> producer waits
after the follower is dropped from ISR, latency recovers; min.insync.replicas=2 still holdsWhy: Tail latency under acks=all is the latency of the slowest in-sync replica.
Land it I read the producer's per-stage metrics, then check broker request latency and ISR changes at the same time; a slow follower under acks=all is the classic cause.
- “Should I drop to acks=1 to fix it?”
No, it hides the symptom and removes the safety. With
acks=1, the leader acknowledges as soon as it has the record itself, without waiting for any follower. Latency drops because the slow follower no longer matters. But if the leader then dies before the followers copy the record, the record is gone, even though the producer was told it was safe.The slow replica is still there, and still behind. Now nothing warns you, because the producer no longer feels it. The next leader failure may have a stale replica to take over.
The real fix is on the replica side:
- Find it: broker request latency and the per-replica fetch lag show which follower is slow.
- Cause: a failing disk, a saturated network link, a noisy neighbour, or a long GC pause.
- Repair: replace the disk or move partitions off the broker.
I accept
acks=1only as a deliberate per-topic choice, for example for clickstream data where losing a few records on a crash is harmless.- “What does buffer.memory do to latency?”
It is the memory the producer uses to hold records waiting to be sent, 32 MB by default. Records are appended to it by
send(), grouped into batches, and a background thread sends them. When the broker is slow, the batches wait and the buffer fills.When the buffer is full,
send()blocks the calling thread for up tomax.block.ms, which is 60 seconds by default. If space does not appear in that time, it throws an exception.This shows up as a stall in your own request threads. A web request that calls
send()takes 2 seconds, not because Kafka is slow for that record, but because it is waiting for space.buffer fill timeruns offline# illustrative arithmetic, assumed rate producing 20 MB/s, broker stalls buffer 32 MB / 20 MB/s = 1.6 s until send() starts to blockI watch the producer metric for time spent waiting for buffer space, and for the available bytes in the buffer. A buffer that is often near empty-available is a warning before latency appears.
- “Could linger.ms be the cause?”
Not at its defaults, but it is worth checking, because a configuration change can turn it into the cause.
linger.msis a deliberate wait: the producer waits that long for more records, so it can send a bigger batch. Since Kafka 4.0 the default is 5 ms, earlier it was 0.So a delay of 5 ms cannot explain 2 seconds. But a value of 1000, left in a config after a throughput experiment, would add up to a second to every send on a quiet topic. Combined with other waits, the p99 would reach two seconds.
My check:
- Effective config: the producer logs its full config at startup. Compare it to the previous version's.
- Batch metrics: average batch size and records per request. If batches are tiny and linger is large, the producer is waiting for records that do not come.
- Deploy diff: look at whether
linger.ms,batch.sizeor compression changed with the deploy.
It is a throughput versus latency trade, set on purpose per use. For a request-path producer, I keep it low.
- “What about GC pauses in the producer app?”
They can, and they look just like a slow broker from the outside, so I rule them in or out with the GC logs. The producer's JVM runs the network thread, which sends batches and handles acknowledgements. A long stop-the-world pause freezes it, so the time between sending and noticing the response grows, and the measured latency includes the pause.
The evidence:
- GC log at the same timestamp: a pause of hundreds of milliseconds or more at the moment the latency spikes points at the application.
- Broker-side latency: if the broker's own request latency percentiles are normal, the delay is outside the broker.
- Other threads: if unrelated work in the same app is also late, the process is paused as a whole.
Fixes are to reduce allocation, for example by reusing buffers or avoiding large temporary objects, to set heap sizes properly, or to change the collector.
Seeing a healthy JVM and a slow broker round trip puts the cause back on the broker side.
Q124 · Scenario. “Someone reset the consumer group's offsets to the beginning in production. What happens and how do you do a safe replay?”
Reveal answer
Strong answer After a reset to earliest, the group reprocesses every record still in the topic. If handlers are idempotent, the result is wasted work and a load spike; if not, you get duplicate emails, charges and rows.
The group must be stopped (no active members) for a reset to be accepted. Before the reset, I do a dry run to see what the new offsets would be, then execute.
A safe replay is deliberate: choose a timestamp, not the beginning (--to-datetime), run it in a separate group id into a separate sink, or make sure side effects are disabled. Throttle consumption so the downstream is not flooded.
If someone already did it by mistake, stop the group and reset forward to the committed offset recorded before, which good monitoring has saved.
Picture it Dry run first, then reset to a time.
The setup: Group billing, bug fixed, need to reprocess from 14:00.
# stop all consumers first
kafka-consumer-groups.sh --bootstrap-server b1:9092 --group billing --topic orders \
--reset-offsets --to-datetime 2026-11-19T14:00:00.000 --dry-run
# illustrative output: p0 new offset 120044, p1 new offset 118010 ...
# same command with --execute when the list looks rightMake the invisible visible: The safer side-by-side.
| Option | Pick it when | Cost or catch |
|---|---|---|
| Reset the live group | Handlers idempotent, downstream can take the load | Duplicates if not idempotent; production load spike |
| New group id, separate sink | You want to compare or rebuild a view | Needs space and a second sink |
| Replay from a dead-letter topic | Only failed records need redoing | Ordering relative to newer records changes |
Why: Offsets are just a number per partition; the danger is the side effects behind them.
Land it I stop the group, dry-run a timestamp-based reset, and replay only with idempotent handlers or into a separate sink.
- “Why must the group be inactive?”
Because the group coordinator on the broker only accepts an offset reset for a group that has no active members. If members were running, they would overwrite the new offsets with their own on their next commit, so the reset would silently vanish. The tool refuses with an error.
That gives a simple sequence:
- Stop: scale the consumer deployment to zero, and wait until the group shows no members. The group goes to the Empty state.
- Reset: run the reset tool, first as a dry run to see the result.
- Start: scale back up. Consumers read from the new position.
The group may take up to the session timeout to be considered empty, 45 seconds by default, so I check with
--describe --state, not just assume it.The same logic explains why you should never edit offsets with another tool while consumers run. And it is the reason for the cost: replay means downtime for that group, while it is stopped.
- “How do I record the offsets before changing them?”
I save the current position before changing anything, because the reset tool changes it with no undo. The saved copy is my rollback plan, and I prepare it first.
Two ways, and I use both for critical groups:
- Describe: run
kafka-consumer-groups.sh --describe --group billing, and store the output, with the date, in the incident or change ticket. - Export: run
--reset-offsets --exportwith the target spec, which prints the offsets in CSV form. A saved CSV from before the change can be applied again with--from-file.
offsetsruns offline# illustrative kafka-consumer-groups.sh --bootstrap-server b1:9092 --group billing --topic orders --reset-offsets --to-datetime 2026-11-24T10:00:00.000 --dry-run # illustrative output: GROUP TOPIC PARTITION NEW-OFFSET (nothing applied yet)Only after reading the dry-run output do I replace
--dry-runwith--execute. If I need to roll back, I apply the saved file.- Describe: run
- “How do I protect the downstream during a replay?”
I limit how fast the replay reads, and I tell the owners of everything it touches. A replay brings in a lot of work at once, and the systems at the end of the pipeline were sized for normal traffic.
- Throttle the reader: a rate limiter in the handler, a lower
max.poll.records, or fewer consumers than partitions. Start slow and raise it while watching the target. - Watch the target: database latency, connection pool use and error rates. Slow down at the first sign of strain.
- Timing: run it off-peak, so replay does not compete with live users.
- Tell people: downstream teams, support, and anyone who gets emails or alerts from the pipeline. A heads-up avoids a flood of tickets.
For anything with side effects, I replay into a separate group id and a separate sink, so the production target is not touched, or I switch the side effects off.
A replay that has no throttle is a self-inflicted load test on production.
- Throttle the reader: a rate limiter in the handler, a lower
- “What if the data is already past retention?”
Then Kafka cannot give it back, and the recovery source is somewhere else. Retention deleted the segments, so no offset reset can reach them.
The ways to rebuild:
- Source of truth: the original database. A fresh CDC snapshot re-emits every current row as an event, which rebuilds the current state, though not the history of changes.
- Tiered storage: if enabled for the topic, with a long remote retention, older segments are in object storage and are still readable. Tiered storage has been generally available since Kafka 3.9.
- Another copy: a mirror cluster or a sink, such as object storage, that holds an archive of the topic.
Rebuilding from a snapshot restores state but not the sequence of events, so an audit trail is lost.
That is the argument for setting retention longer than the longest incident you are willing to plan for, and for archiving topics whose history has value. Disk is cheaper than an irrecoverable gap.
These questions test whether you decide the key first, state the numbers, and name what you give up.
Q125 · Design. “Design the event backbone for an e-commerce company: topics, keys, partitions, retention.”
Reveal answer
Strong answer I start from the entities: orders, payments, inventory, shipments. Each gets a topic per event family, keyed by the entity id, so all events of one order are in one partition in order. Names follow domain plus event: orders.events.v1.
Partitions: sized from peak throughput and the slowest consumer's rate (see the sizing question), with headroom, commonly 12 to 48 for a mid-size topic. Replication factor 3, min.insync.replicas=2.
Retention: seven days for most event topics, so a consumer down over a weekend recovers; compacted topics for “current state” such as customer profile; long or tiered retention for audit.
Producers use idempotence and acks=all; events are published through an outbox; schemas are Avro with a registry and FULL_TRANSITIVE compatibility.
Picture it The topic map.
The setup: Peak 3,000 orders per minute, many consumers.
| Topic | Key | Partitions | Retention / cleanup |
|---|---|---|---|
| orders.events.v1 | orderId | 24 | 7 d, delete |
| payments.events.v1 | orderId | 24 | 7 d, delete |
| inventory.events.v1 | sku | 12 | 3 d, delete |
| customers.state.v1 | customerId | 12 | compact, keep latest |
| *.dlt | same as source | same | 14 d, delete |
Make the invisible visible: Why payments is keyed by orderId.
Key = orderId on orders AND payments:
both topics place order o1 in partition hash(o1) mod 24 -> same number in both
a stream join of orders and payments is co-partitioned ✓
Key = paymentId on payments would break that join and the per-order ordering ✗Why: The key is the most expensive decision, so it follows the question consumers will ask: “what happened to this order?”
Land it One topic per event family, keyed by the entity id, 3-way replication, seven-day retention, compaction for state, and registry-checked schemas.
- “Why one topic for all order events instead of one per type?”
Because of ordering. Kafka orders records only within one partition of one topic. OrderPlaced, OrderPaid and OrderShipped for the same order must be processed in that sequence, and keying by order id sends them to the same partition, in the order they were produced.
If each event type had its own topic, the three events would live in three different logs, and there is no ordering between logs. A consumer reading all three could see "shipped" before "paid", depending on timing and lag.
orderingruns offline# illustrative one topic, key o1: [o1 PLACED] [o1 PAID] [o1 SHIPPED] -> always read in this order three topics: placed: [o1] paid: [o1] shipped: [o1] -> read order not definedTo carry several event types in one topic, use a union schema, or the record-name or topic-record-name subject strategy, so each type has its own schema, with its own compatibility history.
The cost is that consumers who care about one event type read and skip the others. For order events, which are all small and related, that cost is worth the ordering.
- “How do you choose retention?”
I choose retention from two things: the longest outage a consumer can have, and how long we may need to replay. Then I check the cost.
For event topics, seven days is a common starting point. It covers a long weekend plus a slow Monday, so a consumer that failed on Friday evening can still catch up. Topics that feed jobs which run only monthly need longer, or an archive.
Anything that must be kept for years, such as audit data, does not belong in local broker disk. It goes to a warehouse or object storage, or to a topic with tiered storage.
The cost is straightforward arithmetic:
retention costruns offline# illustrative arithmetic, assumed rate rate = 3 MB/s, retention = 7 days = 604,800 s, replicas = 3 disk = 3 x 604,800 x 3 = about 5.4 TB across the clusterIf that is too much, I shorten retention, compress, or tier the data. I would not drop below the longest outage I have to survive.
- “What would make you split a topic?”
I split a topic when the data in it has very different volume, consumers, or retention needs, so that forcing them together hurts the common case.
A typical example is a click and tracking event that produces a hundred times more records than orders. If both sit in one topic, every order consumer has to read and discard the tracking records, wasting network and CPU, and the lag of the order consumers rises with a tracking spike. Retention is also shared: orders may need seven days, while tracking is useless after one.
My checks before splitting:
- Ordering need: does any consumer need these events in order with the others? If yes, they stay together.
- Volume ratio: is one stream far larger than the rest?
- Audience: do different teams read them, with different access rules?
- Retention and cleanup: do they need delete versus compact, or different lengths?
The rule is to isolate noisy streams and keep related, ordered ones together.
- “How do new teams get topics?”
Through a pull request to a topic repository, applied by automation, not by someone running commands by hand or an application creating it on first use.
The pull request asks for:
- Name: following the domain naming rule, such as
orders.order-placed.v1. - Owner: a team and an on-call contact.
- Key and schema: what the record key is and its subject in the registry.
- Sizing: partitions from the expected rate and consumer speed, replication factor 3,
min.insync.replicas=2, and retention.
A reviewer from the platform team checks these, and a pipeline creates the topic, with its ACLs, in each environment from the same file. That gives one reviewed record of what exists and why, and it is easy to audit.
Auto-creation of topics is turned off on the brokers with
auto.create.topics.enable=false. Otherwise a typo in a topic name quietly creates a new topic with default settings, and a producer writes into a place nobody reads.- Name: following the domain naming rule, such as
Q126 · Design. “A topic must carry 50,000 messages per second of 2 KB each. How many partitions?”
Reveal answer
Strong answer Two limits decide: bytes per partition and consumer processing rate. Bytes: 50,000 × 2 KB is about 100 MB/s. If one partition comfortably takes about 10 MB/s (an illustrative figure to measure), that needs 10 partitions.
Consumers: if one consumer thread processes 500 records per second, 50,000 per second needs 100 threads, so at least 100 partitions. The consumer limit dominates here.
I take the larger number and add headroom for growth, since partitions cannot be reduced and increasing them moves keys: 100 × 1.5 = 150, rounded to 160 or 192 for even spread over brokers.
Then check broker load: 192 partitions × 3 replicas is 576 partition replicas, fine over 6 brokers.
Picture it The arithmetic.
The setup: Illustrative numbers: measure your own.
ingress 50,000 msg/s x 2 KB = 100 MB/s
by bytes 100 / 10 MB/s per partition = 10 partitions
by consumer 50,000 / 500 msg/s per thread = 100 partitions <- larger wins
headroom 100 x 1.5 = 150 -> choose 192 (divides evenly over 6 and 8 brokers)
cluster replicas 192 x 3 = 576; network in = 100 MB/s x 3 = 300 MB/s across brokersMake the invisible visible: What to measure instead of guessing.
kafka-producer-perf-test.sh --topic perf --num-records 5000000 --record-size 2048 \
--throughput -1 --producer-props bootstrap.servers=b1:9092 acks=all
# read MB/s per partition on your hardware, and time one consumer's per-record workWhy: Partitions buy parallelism, and the slowest stage sets how much parallelism you need.
Land it I compute partitions from both bytes and consumer rate, take the larger, add headroom, and check the cluster can hold the replicas.
- “Why not just use 1,000 partitions to be safe?”
Because partitions are not free, and the cost is paid on every broker whether or not you use the capacity. Each partition is a directory of log segment files, so 1,000 partitions with replication factor 3 on six brokers is 500 partition replicas per broker, each with open file handles, index memory and a replica fetcher doing work.
The costs that hurt most come at failure time. When a broker dies, every partition it led needs a new leader, and every partition it held must catch up when it returns. More partitions mean longer recovery and more metadata for the controller to move around. Consumer groups also rebalance more slowly, because there are more assignments to hand out.
Our calculation gave 150 to 192. A thousand is five times that, for no measured reason. I size from the two limits, add headroom for growth, and revisit the number when the traffic changes.
- “What if I need to increase later?”
Yes, you can add partitions to an existing topic, but it changes where keyed records go. The rule is murmur2(key) mod the partition count, so when the count goes from 192 to 256, many keys map to a different partition than before.
Two things break. First, per-key ordering: old records for a key sit in partition 17, new ones land in partition 203, and a consumer can read the new record before it has finished the old ones. Second, anything that depends on co-partitioning, such as a Streams join of two topics with the same partition count, now finds matching keys in different places.
Reducing the count is not possible at all. The safe route is a new topic with the larger count, copying the old data across, and moving consumers over. Because that is a project, I pick the count with margin up front: about 1.5 times the calculated need, as in the answer.
- “What if the consumer is the real bottleneck?”
I would make each consumer thread faster before adding partitions, because partitions only help when the code is already efficient. The 100-thread figure came from an assumption of 500 records per second per thread, which is 2 ms per record. That is slow enough that the work itself is probably the problem.
- Batch the writes: if each record does one database insert, a bulk insert of 100 rows can be many times cheaper per record.
- Parallel calls: if each record waits on a remote call, issue the calls for a whole poll batch at once.
- Cheaper decoding: JSON parsing can dominate the time; a binary format with a reused decoder is lighter.
Example: if bulk inserts lift one thread from 500 to 2,500 records per second, then 50,000 per second needs 20 partitions, not 100. Fewer partitions means less broker overhead. I measure first, then size.
- “How does replication change the numbers?”
Replication multiplies the write load, so I size the brokers for the multiplied figure, not the producer figure. With replication factor 3, every byte a producer sends is stored three times: once on the leader and once on each of two followers.
replication arithmeticruns offline# illustrative producers to leaders 100 MB/s follower fetch (2 extra copies) 200 MB/s disk writes, whole cluster 300 MB/s spread over 6 brokers 50 MB/s eachNetwork follows the same logic. The leader sends each byte to two followers, so internal traffic is twice the ingress, before any consumer reads. If three consumer groups each read everything, add 300 MB/s of egress. Per broker that is modest on 10 Gb/s links (about 1,250 MB/s), but disk and cross-zone cost scale with the multiplier.
Consumers that keep up read from the page cache, so they add little disk load. I check write rate and network per broker against hardware limits, with headroom.
Q127 · Design. “Design disaster recovery across two data centers for a Kafka-based platform.”
Reveal answer
Strong answer Decide the targets first: how much data may we lose (RPO) and how fast must we be back (RTO). A stretched single cluster across distant sites suffers from latency on acks=all, so the common design is two separate clusters with asynchronous replication.
A replicator such as MirrorMaker 2 (or a vendor linking feature) copies topics and consumer-group offset translations from the primary to the standby. Because it is asynchronous, a failover loses whatever had not yet been copied: the RPO is the replication lag.
Active-passive is simplest: producers and consumers use the primary; on disaster, switch clients to the standby, using translated offsets. Active-active needs per-region topics and conflict handling.
Practise the failover with a game day; an untested plan is a hope.
Picture it The two-cluster shape.
The setup: Primary in site A, standby in site B.
Site A (primary) Site B (standby)
producers -> cluster A --MirrorMaker 2--> cluster B (topics prefixed "A.orders")
consumers <- cluster A checkpoint topic: translated group offsets
disaster: clients flip to B; consumers resume from translated offsets
lost data = records not yet mirrored (RPO = replication lag, e.g. 2-5 s, illustrative)Make the invisible visible: Decision table.
| Option | Pick it when | Cost or catch |
|---|---|---|
| Async mirror to standby cluster | Normal RPO of seconds is acceptable | Some data loss; failback needs care |
| Stretch cluster across close sites | Near-zero RPO needed and latency under about 10 ms | Latency on every write; quorum issues with two sites |
| Dual write to two clusters | Rarely; you control the producers | Inconsistency risk; avoid unless forced |
Why: Distance costs time on every synchronous write, so most designs accept a small, known loss in exchange.
Land it Two clusters with asynchronous mirroring and offset translation, known RPO equal to replication lag, and a rehearsed client switch.
- “What happens to consumer offsets on failover?”
The copied records get new offsets in the standby cluster, so a group's committed offset in cluster A means nothing in cluster B. A record at offset 5,000 in A may sit at offset 4,973 in B, because copying started later or compaction removed some records.
MirrorMaker 2 solves this with checkpoints. A checkpoint connector periodically records, for each group and partition, the pair "offset in A, matching offset in B" in a topic on the standby. On failover, the consumers start from the translated offset. How the translation is applied depends on the version (a translation utility, or automatic group offset sync in recent releases), so check the docs for yours.
The translation is approximate and slightly behind, because checkpoints run on an interval. A group restarts a little earlier than where it stopped. That produces duplicates, never gaps. With idempotent consumers a few repeated records are harmless, and I would always rather have duplicates than lose records.
- “How do I fail back?”
Failback is harder than failover, because after the switch the two clusters have diverged. B has accepted new writes that A never saw, and A may still hold records that were never copied before the outage.
- Reverse and catch up: start replication from B back to A, wait until lag is near zero, pause producers briefly, switch clients to A, then resume the original direction.
- Or promote B: declare B the new primary and rebuild A as the standby by replicating into a clean cluster. This is simpler and often the better choice.
- The unreplicated tail: records that were on A but never reached B must be reviewed with the business, because replaying them could duplicate or reorder events.
I never point clients back just because A is reachable again. I rehearse failback like failover and treat it as a planned change window.
- “Why not one stretched cluster?”
A stretched cluster is one Kafka cluster whose brokers and controllers sit in different data centers. It is attractive because replication is synchronous, so data loss can be zero. It works only under specific conditions.
The first is quorum. The KRaft controllers need a majority. With two sites, one site always holds the majority, and if that site is lost, the survivor cannot elect a controller. You need three sites, the third holding at least a controller vote.
The second is latency. With acks=all, every produce waits for the in-sync followers to copy the record. If the other site is 40 ms away, each acknowledged write waits at least 40 ms, and follower fetching slows too. Within one metro area at 2 to 5 ms that is acceptable; across a continent it is not.
So I use a stretched cluster only for three close sites when zero data loss is a hard requirement. Otherwise I choose two clusters with asynchronous mirroring and a known RPO.
- “How do you test it?”
I test it with a scheduled game day, and the measured numbers are the result, not whether it "worked". The question is whether the measured RPO and RTO meet the targets.
- Before: write down the targets, for example RPO 60 seconds and RTO 30 minutes, and record the current replication lag.
- Cut: block the primary from the clients the way a real outage would, not with a polite shutdown. Start a timer.
- Switch: follow the runbook to move producers and consumers using translated offsets. Stop the timer when traffic is healthy; that is the measured RTO.
- Measure loss: compare the last event ids written on the primary with those present on the standby. The gap is the measured RPO.
Then fail back, and write down what surprised you: a hard-coded bootstrap address, an expired certificate, a group with no translated offset. Fix those and repeat, for example twice a year.
Q128 · Design. “Design GDPR erasure for personal data in an immutable log.”
Reveal answer
Strong answer Kafka records cannot be edited, so the strategy is to keep personal data out of the log, or make it unreadable. Best: put only an opaque id in events and keep personal details in a database where deletion is easy.
If personal data must be in events, use crypto-shredding: encrypt each person's data with a per-person key held in a key store. To erase, delete the key. The records remain but cannot be read.
For compacted topics, publish a tombstone (null value) for the key; compaction removes older values after delete.retention.ms and cleaning.
Also bound retention so delete-style topics expire on their own, and remember copies: downstream stores, warehouse, logs, backups.
Picture it Crypto-shredding in one picture.
The setup: Customer c1 asks to be erased.
event: {customerId:"c1", payload: ENC(key_c1, {name, email})}
key store: c1 -> key_c1
erase c1: delete key_c1 from the key store
result: old events still in topic, payload cannot be decrypted ✓
consumers get an error for c1 events -> treat as "erased", skipMake the invisible visible: Choices.
| Option | Pick it when | Cost or catch |
|---|---|---|
| Opaque ids only, data in a DB | You can design events freely | Consumers need lookups |
| Crypto-shredding | Personal data must be in the log | Key management; cached keys must be purged |
| Compaction + tombstone | State topics keyed by person | Delay until compaction; older copies elsewhere |
| Short retention | Data is not needed long | Does not satisfy an immediate request alone |
Why: The log is append-only, so erasure has to happen at the key, the topic policy, or by never storing the data.
Land it I keep personal data out of the log where I can and otherwise encrypt per person so that deleting the key erases the data.
- “Why not rewrite the topic?”
Because rewriting is slow, risky and incomplete. To remove one person's records, you would read the whole topic, write every other record to a new topic, point all consumers at it, and delete the old one. For 90 days of data that is a large copy.
The risks are real. Offsets change, so every consumer group's position becomes wrong and must be translated or reset. Timing and ordering can shift during the cutover, and a mistake loses other people's data.
It is also not complete. The person's data still lives in follower replicas until the old topic is deleted, in broker backups, in the object store if tiered storage is on, and in every downstream copy such as the warehouse, search index and caches.
So rewriting is an emergency tool for one bad incident, such as a leaked secret. For routine erasure I design so it is never needed: opaque ids in the log, and crypto-shredding where personal data must be in the event.
- “How long does a tombstone take to take effect?”
It can take hours or days, and I cannot give an exact figure, because compaction runs in the background. Three things set the time.
- Dirty ratio: the cleaner only picks a log when the share of not-yet-cleaned data passes
min.cleanable.dirty.ratio(default 0.5), so a quiet topic may wait. - Segment rolling: the active segment is never compacted, so the tombstone and old values must first sit in a closed segment. Segments roll at about 1 GiB or at
segment.ms(default 7 days). - Tombstone retention: after cleaning, the tombstone stays for
delete.retention.ms(default 24 hours) before it is removed.
So with defaults, a quiet topic could take over a week to physically drop the old value. If the legal deadline is 30 days, I lower
segment.msto a day and the dirty ratio to about 0.1 on that topic, then test with a dummy key and measure the real delay.- Dirty ratio: the cleaner only picks a log when the share of not-yet-cleaned data passes
- “What about derived data?”
The log is only one copy. Erasing from Kafka while a search index, a warehouse table and a cache still hold the person is not erasure. So I treat erasure as a flow that follows the data.
- Catalogue: keep a register of every system where each personal field lands, with an owner. Build it from schemas that tag personal fields, so it is not from memory.
- One erasure event: publish a "subject erased" event carrying the opaque id. Each downstream consumer deletes or anonymises its copy and reports back.
- Prove it: collect the confirmations with dates, because a regulator may ask for evidence within a month.
Backups are the awkward part, since they cannot be edited. Keep them short-lived, for example 35 days, and re-run erasure for known subjects after any restore. Crypto-shredding helps here too, because a deleted key makes even backed-up copies unreadable.
- “What do the consumers do after the key is deleted?”
They should treat "key deleted" as a normal business outcome, not a failure. With crypto-shredding, a consumer that reads an old record asks the key store for the person's key and gets "deleted". If the code treats that as a transient error, it retries forever and blocks the partition, or fills the dead-letter topic with records that can never succeed.
So I define one error type, say
SubjectErasedException, and handle it explicitly: skip the record, increment a counter, and move on. I register it as non-retryable in the error handler. A key store that is down is different: that is transient and is retried.Replay needs the same care. Rebuilding a read model from offset 0 will meet many such records. They are skipped, and the rebuilt table correctly has no row for that person.
I alert on the rate of the counter. A steady trickle is erasure working; a sudden spike means keys were deleted wrongly.
Q129 · Design. “Order created, paid, shipped: how do you keep events of one order in order across services?”
Reveal answer
Strong answer Order is guaranteed only inside one partition. So all events of one order must be written with the same key, order id, to topics whose partitioning agrees, ideally the same topic.
If services publish to different topics, ordering across them is not guaranteed. A consumer may see “shipped” before “paid”. Then the consumer needs a state machine: if an event arrives for a state it cannot reach yet, park it or ignore until the predecessor arrives.
Use a version or sequence number in each event so consumers can detect gaps and out-of-order delivery.
For multi-step business flows spanning services, a saga with explicit steps is clearer than relying on arrival order.
Picture it Same key, same partition.
The setup: Orders emits Placed, Payments emits Paid, Shipping emits Shipped, all for order o1.
Single topic order-events, key=o1: Placed -> Paid -> Shipped one partition, order kept ✓
Separate topics orders / payments / shipping:
consumer may read Shipped (from shipping) before Paid (from payments) ✗
mitigation: version numbers + state machine ("Shipped needs Paid first, wait")Make the invisible visible: A consumer that tolerates arrival order.
void on(OrderEvent e) {
Order o = repo.load(e.orderId());
if (e.version() <= o.version()) return; // duplicate or old
if (e.version() > o.version() + 1) { parking.add(e); return; } // gap: wait for predecessor
o.apply(e); repo.save(o); parking.releaseNext(o);
}Why: Ordering is a property you either buy with a shared key or rebuild with versions.
Land it I give every event of one order the same key in the same topic when I can, and add version numbers with a tolerant state machine when I cannot.
- “When is a shared topic wrong?”
A shared topic is wrong when different teams own the events. One topic for "order events" where the order service writes created, payments writes paid and shipping writes shipped means three teams write into one schema, one retention setting and one set of access rules.
That couples them. A schema change by payments needs agreement from the others. Retention is one number, though payments may need seven years and shipping seven days. ACLs cannot easily say "payments may write only paid events". And one bad record from one producer hurts every consumer of the topic.
So in that case each service gets its own topic, keyed by order id, and I accept that arrival order across topics is not guaranteed. Consumers then use version numbers and a tolerant state machine. Ordering still holds inside each service's topic, since the same key always goes to the same partition. I choose ownership first and ordering second.
- “What does the version number come from?”
It comes from the aggregate that owns the data, not from Kafka and not from a clock. In the order service, the order row has a
versioncolumn. Each change increments it inside the same database transaction that updates the order and writes the outbox row.version in the outboxruns offline-- illustrative UPDATE orders SET status = 'PAID', version = version + 1 WHERE id = 42 AND version = 2; INSERT INTO outbox (aggregate_id, type, version, payload) VALUES (42, 'OrderPaid', 3, '...');The consumer stores the last version it applied per order and per source service. Next is 3 and it holds 2: apply. It sees 5 while holding 3: version 4 is missing, so park it. It sees 2 or lower: a duplicate, so drop it.
A timestamp is weaker, because clocks drift between machines and two changes can share a millisecond. A version has no gaps by construction, so a gap means something is truly missing.
- “How long do you park an event?”
Only until a bound I choose, and the bound is part of the design. A parked event is waiting for a predecessor that may just be delayed, or may never come because it was lost or failed.
- Hold: keep it in a small table keyed by order id, with its arrival time, rather than in memory, so a restart does not lose it.
- Release: when the missing event arrives, apply it, then check the table for the next version and apply that too.
- Timeout: if it waits longer than, say, ten minutes (cross-topic delay is normally seconds), send it to the dead-letter topic with the reason "gap" and raise an alert.
An unbounded park grows without limit when a producer has a bug, eats memory or table space, and hides the real problem. With a timeout, a gap becomes a visible, countable event that someone can fix and replay. I also expose the count of parked events as a metric, because a rising number is an early warning.
- “How does this relate to sagas?”
They solve the same problem differently. Relying on event order is choreography: each service watches events and reacts, and the flow is implicit, spread across many services. It works while the happy path arrives in order, and hurts when order, timing or failure matter.
A saga makes the flow explicit. An orchestrator sends a command such as "reserve stock", waits for the reply, then sends "take payment", and so on. If a step fails, it runs compensations in reverse, such as "release stock". Because it moves on only after a reply, it does not depend on events from different topics arriving in a particular order. The flow state lives in one place.
The cost is an orchestrator to build and operate, and commands and replies to design. My rule: when a flow has three or more steps with compensation, or "paid before shipped" is a business rule, I use a saga. For simple notifications, versioned events are enough. See the saga chapter.
Q130 · Design. “Design the retry and dead-letter strategy for a payments consumer with a 30-second business deadline.”
Reveal answer
Strong answer Separate failures by kind. Permanent failures (invalid data, business rule) are not retried: they go straight to the dead-letter topic. Transient failures (downstream timeout, deadlock) are retried.
Within a 30-second deadline, retrying is short: two or three in-place attempts with 200 ms, 1 s and 3 s waits (about 4 seconds total), blocking the partition, because payment order per customer matters.
If the downstream is still down after that, I do not hold the partition for minutes. I pause consumption (circuit breaker) so the backlog waits in Kafka, rather than dead-lettering a flood of good payments.
Records that exhaust attempts go to payments.DLT with headers, an alert, and a replay tool. Handlers are idempotent so replay is safe.
Picture it The decision flow.
The setup: Payments service calls a card processor.
record -> handler
permanent error (invalid card number) -> DLT now, no retry
transient error -> retry 200 ms, 1 s, 3 s (in place)
still failing for 5 records in a row -> breaker OPEN: pause partitions, backlog stays in Kafka
breaker half-open after 30 s -> one probe record; success -> resume
exhausted single record -> payments.DLT + alertMake the invisible visible: Spring wiring.
var handler = new DefaultErrorHandler(
new DeadLetterPublishingRecoverer(template), new FixedBackOff(1000L, 2L));
handler.addNotRetryableExceptions(InvalidCardException.class); // permanent: straight to DLT
// breaker around processor.charge(): on OPEN call container.pause()Why: Retrying a permanent error wastes the deadline; dead-lettering during an outage creates a mess to replay. Classification avoids both.
Land it Permanent errors go straight to the dead-letter topic, transient ones get a few quick in-place retries, and an outage pauses consumption instead of dead-lettering everything.
- “Why not use retry topics here?”
Retry topics break ordering, and for payments ordering is a correctness issue. With a retry topic, a failed record is moved to another topic and the consumer carries on with the next one. If customer 42 has "charge 50" fail and then "refund 50" succeed, the refund is processed first. The charge is retried later and the customer ends up charged.
The second reason is time. Retry topics are built for delays: 1 second, then 10 seconds, then a minute, each a hop through another topic. A 30-second deadline leaves almost no room for those hops, and the extra complexity buys nothing.
Third, each hop is another place for duplicates and another thing to monitor.
So for payments I block the partition for a few quick in-place retries, which preserves order, and pause consumption if the downstream stays down. Retry topics suit notifications and enrichment, where order is unimportant and delay is acceptable.
- “What if the processor times out but may have charged?”
A timeout means "unknown", not "failed". The processor may have charged the card and the reply was lost. A blind retry may charge twice; a blind give-up may leave a charged customer with no order.
Two controls handle it. First, send an idempotency key with every charge, for example the payment id. The processor treats a repeated request with the same key as the same charge and returns the original result, so retrying is safe. Most payment providers support this; check yours.
Second, reconcile. If retries still end in doubt, mark the payment "pending review", and let a job query the processor for the status of that key, then complete or cancel the order.
idempotent retryruns offline# illustrative POST /charges Idempotency-Key: pay_8841 amount=50 -> timeout (unknown) POST /charges Idempotency-Key: pay_8841 amount=50 (retry) -> 200 charge ch_77 (same charge, not a second one)I never show a timeout to the customer as "declined".
- “How do you handle the backlog after the outage?”
Draining a backlog needs a controlled rate, because the load that arrived over minutes now arrives all at once. If the processor rate-limits at 200 requests per second and live traffic is 100, the spare capacity is only 100 per second.
drain timeruns offline# illustrative (assumptions: 10 min outage, 100 payments/s) backlog 10 min x 60 s x 100 = 60,000 spare capacity 200 - 100 = 100 per second drain time 60,000 / 100 = 600 s (10 min)So I resume with a rate limiter below the processor's limit, in order per customer, and watch error and latency rates. If rejections climb, I slow down rather than push harder, because failures turn into new retries.
Some payments will miss the 30-second deadline because they waited ten minutes. I tell the business and support, and mark those payments so they are handled by policy, not hidden. The deadline is for normal operation; outage rules are a separate agreement.
- “Who gets paged?”
The rule is page for harm happening now, ticket for harm that can wait. For this consumer that gives three levels.
- Page on-call: the circuit breaker has been open for more than about five minutes, or lag on the payments topic is growing past the time-to-drain target. Customers are charged late or not at all, so someone acts now.
- Notify the payments team channel: the DLT is growing faster than a small threshold, for example 20 records in ten minutes. It may be a bad deploy or bad upstream data, but money is not stuck.
- Ticket: a single dead-lettered record. A person looks at it in working hours and decides to fix and replay, or reject.
The tiers matter because a pager that fires for every poison record trains people to ignore it. I add a short "for" duration to skip blips, and every page links to the runbook entry for that cause. Each month I review pages that needed no action and lower or delete them.
Q131 · Design. “Design a shared Kafka cluster for ten teams so one team cannot hurt the others.”
Reveal answer
Strong answer Isolation comes from four controls: naming and ACLs (who can touch what), quotas (how much throughput each may use), resource limits per topic, and automation for provisioning.
Naming: team.domain.event.v1 with prefixed ACLs, so team A has rights only on teamA.* and its consumer group prefix. Authentication with TLS or SASL gives each team its own principal.
Quotas: per-principal producer and consumer byte rates and a request-percentage quota, so a runaway job is throttled instead of starving others.
Provisioning: topics created through reviewed pull requests, with limits on partitions and retention, and a showback report of cost per team.
Picture it Per-team setup.
The setup: Team billing onboarding.
# ACLs: prefixed topic and group rights
kafka-acls.sh --bootstrap-server b1:9093 --command-config admin.properties --add \
--allow-principal User:billing --operation Read --operation Write --operation Describe \
--topic billing. --resource-pattern-type prefixed
kafka-acls.sh ... --allow-principal User:billing --operation Read --group billing- --resource-pattern-type prefixed
# quotas
kafka-configs.sh --bootstrap-server b1:9093 --alter --add-config 'producer_byte_rate=20971520,consumer_byte_rate=41943040' \
--entity-type users --entity-name billingMake the invisible visible: What a quota does to a runaway producer.
# illustrative output
team search starts a bulk load at 300 MB/s
broker throttles the principal at 20 MB/s by delaying responses (produce-throttle-time-avg 800 ms)
other teams' latency unchanged ✓Why: Shared infrastructure survives when every shared resource has a limit and an owner.
Land it Prefixed ACLs, per-principal quotas, reviewed topic provisioning and cost showback keep ten teams from hurting each other.
- “What do quotas protect that ACLs do not?”
ACLs say who may do something; quotas say how much. A team with fully legitimate access can still hurt the others by producing too fast, and ACLs cannot stop that, because every request is allowed.
Kafka quotas are set per principal or client id: a producer byte rate, a consumer byte rate, and a request quota expressed as a percentage of the broker's request-handler time. When a client goes over, the broker delays its responses, which slows it down without errors. The delay shows in the client's throttle-time metrics.
set quotas for team Aruns offline# illustrative values kafka-configs.sh --bootstrap-server b1:9092 --alter --add-config 'producer_byte_rate=10485760,consumer_byte_rate=20971520,request_percentage=20' --entity-type users --entity-name teamAThe request quota matters because bytes are not the only resource. A client sending thousands of tiny requests a second can use up broker CPU while staying under its byte limit. I pick values from measured need plus headroom, and use both ACLs and quotas.
- “Shared cluster or one cluster per team?”
It is a trade between cost and blast radius. A shared cluster is cheaper per message, because brokers are pooled and one team runs them. But a bad upgrade, a controller problem or an overloaded broker hits all ten teams at once.
Separate clusters isolate failure and let teams upgrade on their own schedule and choose their own settings. The price is ten sets of brokers, each with spare capacity, ten things to patch, and cross-cluster copying whenever teams need each other's data.
The middle path I prefer: one shared cluster for ordinary workloads, governed by quotas and ACLs, plus dedicated clusters for two kinds of tenant. The first is the loudest, whose volume would dominate the shared one. The second is the most critical, such as payments, where another team's mistake must never matter.
To decide, I ask what an hour of outage costs each team, and whether the platform group has the people to run more than one cluster well.
- “How do you stop topic sprawl?”
Sprawl starts when creating a topic is free and deleting one is nobody's job. So I make creation deliberate and retirement routine.
- Stop accidental creation: set
auto.create.topics.enable=false, so a typo in a topic name fails instead of creating a new topic with default settings. - Review at creation: topics come from a pull request naming an owner, partition count, retention and purpose, with automated maximums.
- Find the unused: a topic with no reads for ninety days is a candidate. Tell the owner, cut retention, and delete after a grace period.
Then I report topic and partition counts per team, because partitions per broker is the real limit. For example, a team with 400 topics of 12 partitions at replication factor 3 holds 400 x 12 x 3 = 14,400 partition replicas, a large share of one cluster. Numbers like that change behaviour.
- Stop accidental creation: set
- “How do you charge back cost?”
I charge back from three measurable things: bytes written per principal, bytes read per principal, and bytes stored per topic. They map to the three real costs of a cluster: ingest with replication, egress, and disk.
monthly showbackruns offline# illustrative, with assumed unit prices bytes in 2 TB x $20 per TB = $40 bytes out 6 TB x $10 per TB = $60 stored (avg) 5 TB x $50 per TB = $250 team A total = $350The unit prices come from dividing the cluster's monthly cost between these three parts. The inputs come from broker metrics (per-topic bytes in and out, mapped to a team by the topic's naming prefix or by the principal) and from log size on disk.
Perfect accuracy is not the goal. Showing each team a number every month makes it ask why its test topic keeps 30 days of data at 12 partitions. Visibility alone changes behaviour; real billing can come later.
Q132 · Design. “Design an exactly-once pipeline from a Kafka topic to a database and on to another topic.”
Reveal answer
Strong answer I would not claim end-to-end exactly-once. I would make the effect happen once: at-least-once delivery plus idempotent writes. The consumer writes to the database with the event id in a unique constraint, in one transaction.
The next topic is fed through an outbox row written in that same transaction, and a relay (Debezium or a poller) publishes it. A duplicate input finds its event id already recorded, does nothing, and produces no second output.
That keeps both writes in the database's transaction, which the Kafka transaction cannot join. Kafka transactions would only help if both input and output were Kafka and the state in Kafka.
Result: input may be redelivered, output may be published twice by the relay, and consumers of the output also dedup on event id.
Picture it One transaction, three writes.
The setup: Input payments, output ledger-events.
@Transactional
void on(PaymentCaptured e) {
if (!processed.insertIfAbsent(e.eventId())) return; // unique constraint
ledger.apply(e); // business write
outbox.add("ledger-events", e.accountId(), LedgerUpdated.from(e)); // outbox row
} // commit: all three or noneMake the invisible visible: Crash points.
crash before commit : nothing written; input redelivered, redone ✓
crash after commit : all three written; input redelivered -> id found -> skipped ✓
relay crash after publish : row republished -> downstream dedups on eventId ✓Why: Exactly-once effect is at-least-once delivery plus a dedup record committed with the effect.
Land it I get exactly-once effect with idempotent writes and an outbox in one database transaction, not with a claim of end-to-end exactly-once.
- “When would Kafka transactions be the right tool?”
When the input, the state and the output all live in Kafka. A Streams job, or a consume-transform-produce service with no external store, is the case. Then Kafka can make three things one atomic step: the output records, the state changelog writes, and the consumer's offset commit. They become visible together or not at all.
The mechanism: the producer begins a transaction, writes the output, sends the consumed offsets into the transaction, and commits. Downstream consumers using
isolation.level=read_committedsee only committed output. In Streams, you turn it on withprocessing.guarantee=exactly_once_v2.The boundary is where Kafka's transaction stops. A database write is outside it. A crash between the database commit and the Kafka commit leaves one done and the other not, and Kafka cannot roll the database back. That is why our pipeline uses a unique constraint and an outbox. I use Kafka transactions for Kafka-to-Kafka steps and do not stretch them further.
- “What does the dedup table cost?”
It costs one insert per event, plus storage for as long as you must be able to recognise a duplicate. That window is the key choice: it should be longer than the longest plausible redelivery or replay, for example seven days.
dedup table sizeruns offline# illustrative (assumed: 1,000 events/s, 7 days, 60 bytes per row with index) rows 1,000 x 86,400 x 7 = 604,800,000 size 604.8M x 60 B = about 36 GBThat is manageable but not small. Two tricks keep it cheap. Partition the table by day, so expiry means dropping a partition, which is instant, rather than deleting 86 million rows, which is slow and leaves bloat. And keep the key compact: a 16-byte id, not a long string.
A cache of recent ids in front can skip the database for common duplicates, but the unique constraint stays the authority. The insert is in the same transaction as the business write, so it adds no extra round trip.
- “Can I put the dedup in Redis instead?”
Only as a shortcut, never as the source of truth. The reason is atomicity. The database transaction can commit the business change and the dedup row together. Redis is a different system, so writing there is a second write that is not part of that transaction.
Look at both orders. If I write Redis first and crash before the database commit, Redis says "done" but nothing was done, so the redelivered event is skipped and data is lost. If I write the database first and crash before Redis, the redelivery is not recognised there, and the effect could happen twice. Either order has a failure window.
So the dedup record lives with the effect, in the same transaction. A Redis check can sit in front to answer "have I seen this?" quickly and avoid a database call for most duplicates. If Redis is empty after a restart, the unique constraint still catches the duplicate. It is an optimisation I can lose without harm.
- “How do I test it?”
I test it by forcing the failures that real systems have, because the happy path proves nothing about duplicates. The key fault is the gap between the database commit and the offset commit.
- Crash after the database commit: process an event, kill the consumer before it commits the offset, restart. The event is redelivered. Assert one row in the effect table and one outbox row.
- Crash before the commit: kill it mid-transaction. Assert nothing was written, and that the redelivered event then succeeds exactly once.
- Relay duplicate: make the relay publish the same outbox row twice and assert the downstream consumer applies it once.
I repeat the fault at every step boundary and run the suite in CI against a real database and a real Kafka in containers (Testcontainers is one common way), because mocks hide transaction behaviour. A final check: count input event ids and output event ids at the end of the run. They must match, with no extras.
Q133 · Design. “Design a notification system that fans out one event to a million users across email, push and SMS.”
Reveal answer
Strong answer One event, three channels, a million recipients. Fan-out is a job, not a loop in one consumer. Publish the event once, then a fan-out service reads it and writes per-channel messages in batches.
One topic per channel (notify.email, notify.push, notify.sms), each with its own consumer group, partition count and rate limiter, since channels differ hugely in speed and cost. Key by user id to keep one user's messages ordered.
Add priority: a separate high-priority topic for security alerts so marketing bulk never delays them. Dedup with a notification id so a retry does not text someone twice.
Use backpressure and provider rate limits; SMS providers allow maybe a few hundred per second, so lag is expected and planned.
Picture it The fan-out shape.
The setup: Campaign event for 1,000,000 users.
campaign.events (1 record)
-> fan-out service: reads user segments in pages of 10,000
-> notify.email (48 partitions) -> email workers (provider limit 2,000/s)
-> notify.push (24 partitions) -> push workers (10,000/s)
-> notify.sms (12 partitions) -> sms workers (300/s) 1,000,000 / 300 = 3,333 s = 56 minMake the invisible visible: Priority lanes.
| Topic | Used for | Rule |
|---|---|---|
| notify.sms.high | Security codes, fraud alerts | Dedicated consumers, tight limit alerts |
| notify.sms.bulk | Marketing | Rate limited, can lag for an hour |
| notify.*.dlt | Provider rejects | Triage; suppress bad numbers |
Why: Different channels have different bottlenecks, so each gets its own topic and its own pace.
Land it Publish once, fan out in batches to one topic per channel with priority lanes, and let the slowest provider's rate set the pace.
- “Why not one consumer that loops over a million users?”
Because one consumer looping over a million users is a single point of failure with no way to resume. If it crashes at user 600,000, you do not know which users were sent, so you either start over and double-send, or skip some.
It also cannot go fast. One thread sending 200 messages a second needs 5,000 seconds, about 83 minutes, for a million, and adding threads inside it is hand-made parallelism.
Fan-out through a topic fixes both. The campaign becomes many small messages, each one page of users or one notification, spread across partitions. Several consumers work in parallel, each bounded by its channel's rate limiter. The committed offset is the saved place: after a crash the consumer resumes from the last commit, and the dedup key stops the overlap from sending twice.
The campaign becomes restartable, parallel, and visible through lag.
- “How do I avoid sending twice?”
I assume every step can repeat, then make the repeat harmless. A notification gets an id built from the campaign, the user and the channel, for example
cmp_903:user_5521:sms. The same triple always gives the same id.- Claim before sending: insert the id into a dedup table with a unique constraint. If the insert fails, someone already handled it, so skip.
- Pass the key on: give the id to the provider as an idempotency key where it supports one, so a retried call is not delivered again.
- Record the outcome: mark sent or failed, so a retry after a crash can tell "claimed but unknown" from "done".
The hard case is a provider timeout, since the SMS may have gone out. Without provider idempotency, I check its delivery status for that id before retrying. For SMS, where a duplicate costs money and annoys users, I would accept a rare missed message over a double send, and state that choice in the design.
- “How do I respect user preferences and quiet hours?”
I check preferences twice, because they change while a campaign is in flight. The first check is when the audience is expanded: users who opted out of marketing are removed before any message is created, which saves work. The second is at send time, just before calling the provider, because someone may have unsubscribed during the hour the message waited in the queue. The send-time check is the one that counts.
Quiet hours work the same way, using the user's own time zone. If it is 02:00 for a user, the message must wait until 08:00 there.
Kafka has no delayed delivery, so waiting is not built in. I use a scheduler table of "send at" times with a poller that re-publishes due messages to the channel topic. It is simple and easy to inspect. Do not hold the message in the consumer by sleeping, because that blocks the partition and risks a poll timeout.
- “What do I watch?”
I watch per lane, not the whole system, because a number that is normal for one lane is an incident for another.
- Lag and time to drain: consumer lag per channel divided by its send rate. One hour of drain time on bulk marketing is expected; five minutes on security codes is an incident.
- Provider health: error and throttling rates from the email, push and SMS providers, so I see a provider problem before the queue shows it.
- DLT counts: records that exhausted retries, per channel, with a cause breakdown.
- End-to-end latency: time from event creation to provider acceptance, and where possible to delivery receipt, for the high-priority lane.
Alert thresholds belong to each lane. I page when the security lane's latency passes a minute or two, and open a ticket for bulk lag only if the drain estimate passes the campaign's deadline. I also track sends per user per day, to catch a bug that spams someone.
These questions test operational judgment: sizing, alerts, upgrades, security, and when Kafka is the wrong tool.
Q134. “How do you size a Kafka cluster's disk and brokers?”
Reveal answer
Strong answer Start from the write rate, retention and replication factor. Disk needed is bytes per second times retention seconds times replicas, plus headroom, since a full disk stops a broker.
Example: 50 MB/s ingress, 7-day retention, RF 3 is 50 × 604,800 × 3, about 90.7 TB. With 40 percent headroom for growth and rebalancing, plan for about 127 TB of raw disk.
Brokers: network is usually the limit. Ingress 50 MB/s becomes 150 MB/s of replication writes across the cluster, plus consumer egress; six brokers on 10 Gb/s links handle that comfortably.
Keep partitions per broker reasonable (a few thousand at most) and watch request handler idle percent.
Picture it The arithmetic.
The setup: Illustrative inputs: 50 MB/s, 7 days, RF 3.
per day 50 MB/s x 86,400 s = 4,320,000 MB = 4.32 TB
7 days 4.32 TB x 7 = 30.2 TB (one copy)
RF 3 30.2 TB x 3 = 90.7 TB
headroom x 1.4 = 127 TB raw
brokers 127 TB / 6 brokers = about 21 TB each (e.g. 6 x 24 TB disks, or 12 x 2 TB)
network ingress 50 MB/s; replication adds 100 MB/s; consumers read 3 groups = 150 MB/sMake the invisible visible: With compression.
producer compression ratio 3:1 (illustrative, measure your own) -> ingress to disk 16.7 MB/s
disk drops from 127 TB to about 42 TB; the cost moves to producer CPUWhy: Retention and replication multiply the ingress rate into disk, so a small change in either is a large change in cost.
Land it Disk is rate times retention times replicas plus headroom, brokers follow network and partition count, and compression changes both.
- “Why headroom of 40 percent?”
Because a disk that is nearly full is an outage waiting for one bad hour, and several normal operations need free space. At 90 percent used, a traffic spike or a retention change can fill a broker. A full disk stops that broker from writing, and its partitions fail over to brokers that are almost full too.
Moving partitions is the second need. Reassigning a partition to a new broker copies the whole partition before the old copy is deleted, so for a while you hold both. Growth between planning cycles is the third: if traffic grows 5 percent a month, six months of growth is 1.05 to the sixth power, about 34 percent.
Forty percent is a rule of thumb, not a law. I alert at 70 percent used, act at 80, and treat 90 as an incident. The right figure depends on how fast I can add disk or brokers: with cloud volumes that can be resized in minutes, I can run tighter.
- “SSD or HDD?”
Both work, and the choice is mostly cost against access pattern. Kafka writes sequentially to the end of a log and serves recent reads from the operating system's page cache, a pattern hard disks handle well. A set of HDDs in a sensible layout, for example several disks per broker each holding some partitions, gives plenty of throughput at the lowest cost per terabyte.
SSDs help when access is not sequential: thousands of partitions all appending, consumers reading old data at random offsets, or many lagging consumers at once. They also recover faster after a broker restart or a rebalance copy.
At large retention, cost per terabyte decides. 127 TB on SSD costs far more than on HDD, which is where tiered storage helps: a small SSD window, and the long tail in object storage.
I do not guess. I benchmark a representative workload with the perf-test tools on both, including lagging consumers, and compare p99 latency.
- “How much RAM?”
Mostly for the page cache, not the heap. Kafka writes records into the operating system's page cache and leaves it to the OS to flush to disk. A consumer that keeps up reads the same pages straight from memory, with no disk read at all.
So the JVM heap is modest. A typical figure is around 6 GB, which I would check against the current docs and my workload, and the rest of memory is left to the OS. A broker with 64 GB of RAM and a 6 GB heap leaves roughly 50 GB for cache after the OS itself.
How much cache you need follows from how far behind your consumers read. A broker taking 20 MB/s of writes holds ten minutes of data in 20 x 600 = 12,000 MB, about 12 GB, so 50 GB covers consumers that are up to about 40 minutes behind.
A lagging consumer reading data from hours ago misses the cache and hits the disk, and it also pushes out pages other consumers need. That is how a few lagging groups can slow a whole broker.
- “What would make you add brokers rather than disks?”
I add brokers when the limit is anything a disk cannot fix: network, CPU or the number of partitions. Adding disks to a broker adds space only. It adds no network bandwidth, no request-handler threads, and no relief from too many partitions.
The signals come from metrics. Network utilisation regularly above about 60 percent of the link leaves too little room for a failure, because when one broker is down the others take its traffic. Request-handler idle percent under about 30 means the threads that process requests are mostly busy and queues are building. Partitions per broker above a few thousand means slow recovery after a failure.
The order is: add brokers, then reassign partitions, because a new broker starts empty and takes no load until partitions move. I use the reassignment tool, or Cruise Control, with a throttle so the copying does not hurt live traffic.
Q135. “Which broker and client metrics do you alert on, and why?”
Reveal answer
Strong answer I alert on symptoms of lost safety first: offline partitions (data unavailable), under-replicated partitions (redundancy lost), and active controller count not equal to one.
Then performance: request latency percentiles for produce and fetch, request handler idle percent (low means CPU-saturated), network processor idle percent, and disk usage.
On the client side: consumer lag and its trend (offset not advancing), producer error and retry rate, rebalance count, and dead-letter topic growth.
I page on user-visible harm and ticket on trends.
Picture it The short list.
The setup: Dashboard for the on-call engineer.
| Metric | Alert when | Means |
|---|---|---|
| OfflinePartitionsCount | > 0 | Some data is unavailable: page |
| UnderReplicatedPartitions | > 0 for 5 min | Lost redundancy; one more failure hurts |
| ActiveControllerCount | not 1 in total | No or split controller |
| RequestHandlerAvgIdlePercent | < 30% | Brokers CPU-bound |
| Produce/Fetch p99 latency | above SLO | Clients feel it |
| Consumer lag (and offset not moving) | above drain-time SLO | Consumers behind or stuck |
| Disk used | > 70% ticket, > 85% page | Capacity |
Make the invisible visible: Reading one in the CLI.
kafka-topics.sh --bootstrap-server b1:9092 --describe --under-replicated-partitions
# JMX: kafka.server:type=ReplicaManager,name=UnderReplicatedPartitions (0 is healthy)Why: Alerts are tied to the question: can clients still read and write safely, and are they keeping up?
Land it Offline and under-replicated partitions and controller count first, then request latency and handler idle, then lag, errors and disk.
- “Why alert on lag trend and not just a number?”
Because the same number means different things. A lag of 10,000 records on a group that processes 5,000 a second is two seconds of work and no concern. The same 10,000 on a group that has stopped is a disaster in progress.
So I look at direction and speed. Time to drain is lag divided by the rate at which the group catches up. If lag is rising, or the committed offset has not moved while new records keep arriving, the group is falling behind.
lag as timeruns offline# illustrative lag 10,000; consume 5,000/s; produce 1,000/s catch-up rate 5,000 - 1,000 = 4,000/s -> drains in 2.5 s lag 10,000; consume 0/s (stuck) never drains -> alertTools such as Burrow judge lag over a window of history instead of one snapshot. I alert when lag has grown across several consecutive checks, or when the offset is not advancing while the log end is. That catches a stuck consumer early and ignores a harmless spike after a rebalance.
- “What does a low request-handler idle mean?”
It means the threads that process requests are busy most of the time, so new requests wait in a queue. A broker has a pool of request-handler threads (
num.io.threads) that run the produce and fetch work. The metric reports the fraction of time they are idle, so 100 percent is free and 0 percent is saturated.Under about 30 percent idle is where I get concerned. Queueing starts, and request latency rises sharply, because waiting time grows quickly as utilisation nears full. It shows first in p99 produce and fetch latency.
Typical causes are heavy per-request CPU work such as TLS or recompression, a very large number of partitions, or clients sending many small requests. To find which, I look at request rates by type and at per-client request quota usage.
Then I either reduce the load (fix chatty clients, batch more, apply a request-percentage quota) or add brokers and move partitions. Raising the thread count helps only if CPU cores are idle.
- “How do you avoid alert fatigue?”
I deal with alert fatigue by making every page mean "a human must act now", and moving everything else off the pager.
- Classify: page only on user-visible or imminent harm, such as offline partitions, no controller, or lag past a deadline. Everything else becomes a ticket or a dashboard.
- Add durations: an alert must stay true for, say, five minutes before it fires, so a rebalance blip or one broker restart in a rolling upgrade does not wake anyone.
- Group by cause: one broker failing should give one alert, not forty for its partitions and every lagging client.
- Review: each month list the alerts that fired and ask whether anyone acted. If not, fix the threshold or delete the alert.
Every remaining page links to a runbook entry, so the person woken knows the first three commands. A quiet pager that is trusted is worth more than a complete one that is ignored.
- “What would you add for a transactional or exactly-once service?”
For a service that uses transactions, I add three things, because transaction problems show up as stuck readers, not as errors.
- Abort rate: the share of transactions that abort. A few are normal under retries; a sudden rise points to a crash loop or a downstream failure.
- Producer fenced errors: they appear when two instances use the same
transactional.idand the older one, a zombie, is kept out. A burst after a deploy is expected; a steady stream is a configuration problem. - Age of the oldest open transaction: an open transaction holds the last stable offset back, so
read_committedconsumers cannot read past it.
The third matters most. One hung producer with an open transaction stalls every read_committed consumer of that partition, though no record is lost and the broker looks healthy. Lag grows while data sits behind the stuck transaction. So I watch last stable offset lag next to ordinary lag. The producer's
transaction.timeout.ms(60 seconds by default) bounds how long a hung transaction can block.
Q136. “How do you do a rolling upgrade of a Kafka cluster with no downtime?”
Reveal answer
Strong answer Upgrade one broker at a time and wait until the cluster is healthy before the next. For each broker: do a controlled shutdown (it hands leadership off cleanly), replace the software, start it, and wait for under-replicated partitions to return to zero.
Read the release notes first for incompatibilities and for the order of steps. With KRaft, upgrade controllers and brokers according to the guide, then raise the cluster's metadata version (feature level) only after all nodes run the new software. That last step is the point of no easy return.
Upgrade clients separately and later; brokers stay compatible with older clients. Test in staging with production-like load first.
Keep a rollback plan: before raising the metadata version you can roll back the binaries.
Picture it The loop and the gate.
The setup: Six brokers, three controllers.
for each node (controllers first, then brokers; follow the release notes):
1. controlled shutdown (leaders move away cleanly)
2. install new version, start
3. wait: under-replicated partitions == 0 and node caught up
4. pause 5 minutes, check request latency
after the LAST node runs the new version:
5. kafka-features.sh ... upgrade --metadata 4.x (raises the feature level; hard to undo)Make the invisible visible: Why wait for under-replicated to reach zero.
broker 1 restarting: partitions it hosted have 2 of 3 replicas
if broker 2 is also restarted now: some partitions have 1 of 3 < min.insync.replicas 2 -> writes fail ✗
waiting for zero under-replicated keeps at least 2 in sync at every moment ✓Why: The wait is what keeps min.insync.replicas satisfied during the whole upgrade.
Land it One node at a time, controlled shutdown, wait for zero under-replicated partitions, and raise the metadata version only at the very end.
- “What if a broker does not come back healthy?”
Stop the rollout and do not touch the next broker. The design tolerates one broker being down: with replication factor 3 and min.insync.replicas=2, one missing replica still allows acks=all writes. A second broker down could make partitions unwritable, so a bad signal on broker one is the moment to hold.
- Look: read the broker's startup log, and check whether under-replicated partitions are shrinking or stuck. A broker catching up on a long backlog is healthy but late.
- Decide: if the new version is at fault, stop the broker and reinstall the old binaries. That is possible as long as the metadata version has not been raised.
- Record: write down the cause before retrying, and reproduce the fix in staging.
I tell "slow" from "broken" by watching replica lag fall. Pressure to finish tonight is how a one-broker problem becomes a cluster outage, so I pause.
- “Why upgrade clients later?”
Because the brokers are built to stay compatible with older clients, and the reverse is not guaranteed. A new broker understands old protocol versions, so existing clients keep working during and after the upgrade. A new client may use protocol versions that an old broker does not have, and then it can fail.
The order also keeps the change small. I roll the brokers first and confirm health. Then each team upgrades its clients when it is ready, with its own rollback. Two moving parts are never changed at once, and a problem points clearly to one of them.
There are two things to check. Very old clients can stop working when a major release removes old protocol versions, as 4.0 did, so I read the release notes for the oldest supported client version. And a client feature that needs a new broker feature, such as the new consumer group protocol, needs the brokers upgraded and the feature enabled first, and only then the clients.
- “How long should it take?”
Plan on hours, not minutes, and treat the time as a function of data per broker. The slow part of each step is not the restart; it is the follower catching up on what it missed, then the cluster settling.
rolling upgrade timeruns offline# illustrative (assumed values per broker) shutdown + start + log load 10 min catch-up to zero URP 15 min watch dashboards 10 min = 35 min x 6 brokers = 3.5 hours plus controllers and the final metadata stepSo I plan half a day with margin. I do it in business hours with the team present. A script can automate the loop, but its gate must be "under-replicated partitions equal zero", never a fixed timer. A script that ignores health is how a rolling upgrade becomes an outage.
Brokers with more data take longer, so I time the first broker and use that to forecast the rest. If it took 50 minutes, I tell the business to expect the whole upgrade to finish in about five to six hours, with a pause point after each broker where we can safely stop.
- “What about moving from an older ZooKeeper cluster?”
It is a separate migration, and it must happen before the upgrade, not as part of it. Kafka 4.0 removed ZooKeeper entirely, so a 4.x broker cannot start against one. A cluster still on ZooKeeper must first move to KRaft while on a late 3.x release that supports the migration, and only then upgrade to 4.x.
- Prepare: move to a supported 3.x release (the exact minimum is in the migration guide) and make sure topics, ACLs and configs are healthy.
- Start KRaft controllers: a new quorum starts in migration mode and copies the metadata out of ZooKeeper.
- Roll the brokers to register with the controllers, then finalise the migration and shut ZooKeeper down.
Rollback is possible only until the final step, and the exact order is in the official guide, so I follow it line by line. It is a planned project with a staging rehearsal, not a rolling restart.
Q137. “How do you secure Kafka: TLS, SASL, ACLs?”
Reveal answer
Strong answer Three layers. Encryption: TLS on client-broker and broker-broker links so data cannot be read or altered on the network. Authentication: clients prove who they are with TLS client certificates or SASL (SCRAM passwords, OAUTHBEARER tokens, or Kerberos).
Authorization: ACLs say what each principal can do on each resource: read a topic, write a topic, join a group, create topics. Default deny: with an authorizer enabled and no matching ACL, access is refused.
Least privilege: each service gets its own principal, with rights only to its topics and group prefix. Admin rights go to a few people and automation.
Also rotate credentials, restrict network access, and audit authorization failures.
Picture it A client configuration and an ACL.
The setup: Service billing reads orders and writes invoices.
security.protocol=SASL_SSL
sasl.mechanism=SCRAM-SHA-512
sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule required username="billing" password="${BILLING_PASSWORD}";
ssl.truststore.location=/etc/kafka/truststore.jkskafka-acls.sh ... --add --allow-principal User:billing --operation Read --topic orders
kafka-acls.sh ... --add --allow-principal User:billing --operation Read --group billing-
kafka-acls.sh ... --add --allow-principal User:billing --operation Write --topic invoicesMake the invisible visible: What a missing ACL looks like.
# illustrative output
org.apache.kafka.common.errors.TopicAuthorizationException: Not authorized to access topics: [payments] ✓ default denyWhy: Encryption protects the wire, authentication names the caller, authorization limits the caller.
Land it TLS for the wire, SASL or client certificates for identity, ACLs with default deny and one principal per service.
- “SCRAM, OAUTHBEARER or mTLS?”
I choose by what the organisation can operate and rotate, not by which is strongest on paper. All three are sound when carried over TLS.
Option Identity lives in Good when Watch for SCRAM the cluster (salted password hashes) no identity provider, small or medium setups password rotation by hand OAUTHBEARER your identity provider (short-lived tokens) many apps, central revocation wanted token refresh in clients mTLS your certificate authority certificate issuance is already automated expiry and revocation Never use SASL PLAIN without TLS, because the password then crosses the network readable. Even with TLS, PLAIN means the broker sees the raw password, so I prefer SCRAM.
My default for a team without an identity provider is SCRAM; with one, OAUTHBEARER.
- “Do ACLs apply to Connect and Streams?”
Yes. They are ordinary Kafka clients, so ACLs apply to them like any other. The surprise is how many topics they touch quietly.
A Streams app with application id
orders-appneeds read on its input topics and write on its output topics. It also needs create, read and write on its internal topics, whose names start with the application id (changelog and repartition topics), and the consumer group permission for the group of that same name. With exactly-once on, it also needs rights on its transactional ids. One prefixed ACL onorders-app-covers the internals.A Connect worker needs rights on its three internal topics (config, offsets and status, whose names you choose) and its group. The connectors' own clients then need rights on the data topics they read or write.
A missing ACL usually shows as the app failing to start with an authorisation error in the log, so I test in staging with the real ACLs, and I grant by prefix.
- “How do I rotate credentials without downtime?”
I rotate by overlap, so there is never a moment where clients are locked out. The pattern is add the new, move everyone, remove the old.
- Add: create the new credential beside the old one. SCRAM allows several users, so I can create a second user with the same ACLs. For certificates, issue a new one while the old stays valid until its expiry.
- Roll: change the client's secret in the secret manager and restart instances gradually. Watch the brokers' authentication-failure metrics during the roll.
- Remove: when no client uses the old credential, which the broker's authentication logs prove, delete it and its ACLs.
Secrets live in a secret manager and are injected at start, never baked into images or committed to git. Broker TLS certificates rotate in a similar way, and recent versions can reload them through a dynamic config update without a restart; check the docs for yours. I schedule rotation and rehearse it, because an expired certificate at night is the common failure.
- “What is a common mistake?”
The most common is one shared admin-level principal used by every application, because it is the quickest way to make something work. When that credential leaks, through a log line, a repository or one compromised service, the attacker can read, write or delete anything, and the audit log cannot say which service did it.
Second is the broad wildcard:
ALLOW ALL ON TOPIC *"just for now", which never gets removed. Third is a long super-user list, or a listener left without authentication in a "private" network, where any internal host or misconfigured pod can still connect.The fix is dull and effective. One principal per service. ACLs generated from reviewed config in git, not typed by hand. Super users limited to a few automation identities. And a regular report listing every principal with wildcard or admin rights. I review ACL changes like firewall rules, since that is what they are.
Q138. “What is KRaft, and why did Kafka drop ZooKeeper?”
Reveal answer
Strong answer KRaft is Kafka's own metadata system: a small group of controller nodes forms a quorum using the Raft consensus algorithm and keeps cluster metadata (topics, partitions, leaders, configs) in an internal log. Since Kafka 4.0, ZooKeeper is gone and KRaft is the only mode.
Why: running two systems doubled operations, ZooKeeper held metadata separately from Kafka, and controller failover had to reload large state, so large clusters had slow recoveries and a limit on partitions. With KRaft, metadata is a log that followers already hold, so a new active controller takes over quickly.
A quorum needs a majority alive: three controllers tolerate one failure, five tolerate two. Controllers can be dedicated nodes or combined with brokers in small clusters.
Brokers fetch metadata updates from the controllers like any follower.
Picture it Quorum arithmetic.
The setup: Controller quorum sizes.
| Controllers | Majority | Failures tolerated |
|---|---|---|
| 1 | 1 | 0 (dev only) |
| 3 | 2 | 1 |
| 5 | 3 | 2 |
Make the invisible visible: Roles in a node's config.
process.roles=controller # dedicated controller (or "broker,controller" for small clusters)
node.id=1
controller.quorum.voters=1@c1:9093,2@c2:9093,3@c3:9093
controller.listener.names=CONTROLLERWhy: Metadata becomes ordinary replicated data inside Kafka, so there is one system to run and recover.
Land it KRaft puts metadata in a Raft-replicated log on controller nodes, so there is one system to operate and failover is fast.
- “Why 3 or 5 controllers, not 4?”
Because Raft needs a majority of controllers alive, and a majority of four is three. So a four-node quorum tolerates one failure, exactly like a three-node one, while costing a node more and slightly slowing writes. The extra node adds cost with no extra safety.
quorum sizesruns offline# illustrative controllers majority failures tolerated 3 2 1 4 3 1 5 3 2 6 4 2Odd numbers give the most tolerance per node. Three suits most clusters. But during a rolling upgrade one controller is down on purpose, so a second failure at that moment would lose the quorum. For a critical cluster spread over several zones, I pick five, which survives one planned and one unplanned loss.
More than five is rare, because every metadata write waits for a majority. Without a quorum, no metadata changes, such as new topics or leader elections, can be made until it returns.
- “Dedicated or combined mode?”
Combined mode runs the broker and controller roles in one process on the same node. It is fine for development, tests and small clusters, because it needs fewer machines and is simple.
The trouble is shared fate and shared resources. A broker under heavy load, or in a long garbage-collection pause, slows the controller on the same node, and delayed metadata decisions then ripple through the whole cluster. A broker restart also takes a controller vote away, which matters when you have only three nodes.
Dedicated controllers are separate small nodes that run only the controller role. They hold no partition data, so three modest machines are enough. Metadata work is isolated from data traffic, controllers and brokers can be upgraded separately, and a broker problem never takes a quorum vote with it.
For production at any serious scale I use three dedicated controllers. I choose combined mode only when the cluster is small and the cost of extra nodes is a real concern.
- “What does the active controller do?”
It is the one node that makes decisions about cluster metadata. It decides which broker leads each partition, runs leader elections when a broker fails, creates and deletes topics, adds partitions, applies config changes, and assigns replicas. Each decision is written as a record to the metadata log, a special internal log that the other controllers copy.
Brokers do not ask for metadata on every request. They fetch the metadata log from the controllers, like a follower, and apply the changes to their own cache. So when a leader changes, brokers learn it from the log.
The other controllers are followers holding the same log. If the active one fails, they elect a new one by Raft. Because they already hold the log, the new one takes over quickly, typically in seconds, without the big state reload that made ZooKeeper-era failover slow.
The active controller count must be exactly one. Zero means no metadata changes can be made, so I alert on it.
- “Does this affect clients?”
Not in how they work. Clients connect to brokers using bootstrap servers, with the same protocol as before, and learn the cluster layout from the brokers. Producers and consumers have not talked to ZooKeeper in modern versions, so their code and config do not change.
What changes is the tooling and the scripts around Kafka. Admin commands use
--bootstrap-serverto talk to brokers, and old flags that pointed at ZooKeeper, such as--zookeeper, no longer exist. Broker config loses its ZooKeeper settings and gains node settings such asprocess.rolesand the controller quorum settings.Monitoring changes too. ZooKeeper dashboards go away, and I add controller metrics such as the active controller count and metadata log lag.
So the migration work is in operations: runbooks, deployment charts, health checks and old scripts, not in application code.
Q139. “What is tiered storage, and when would you turn it on?”
Reveal answer
Strong answer Tiered storage keeps recent data on the brokers' local disks and moves older, closed segments to cheap remote storage such as object storage. Consumers still read the whole topic through Kafka; old reads are served from the remote tier. It is generally available since Kafka 3.9.
Two retention settings control it: how long data stays locally (local.retention.ms) and how long in total (retention.ms). A topic might keep 6 hours locally and 90 days overall.
Turn it on when you need long retention but disk cost or recovery time on brokers is the problem. Less data per broker also means faster rebalancing and broker replacement.
The catch: reading old data is slower and uses network to the object store, and topics with compaction are not supported in the way you might hope, so check restrictions for your version.
Picture it Local versus remote.
The setup: Topic with 20 MB/s ingress, RF 3, wanted for 30 days.
illustrative:
no tiering : 20 MB/s x 86,400 x 30 x 3 = 155 TB on broker disks
tiering : local 6 h: 20 x 21,600 x 3 = 1.3 TB on brokers; remote 30 d one copy: 52 TB in object storage (object store holds its own redundancy)Make the invisible visible: Topic config.
kafka-configs.sh --bootstrap-server b1:9092 --alter --entity-type topics --entity-name orders \
--add-config remote.storage.enable=true,local.retention.ms=21600000,retention.ms=2592000000Why: Brokers hold the hot tail; the object store holds the long history at a lower price per terabyte.
Land it Tiered storage keeps a short hot window on local disks and the long tail in object storage, for cheap long retention and lighter brokers.
- “What happens when a consumer reads old data?”
The broker fetches the needed segment from remote storage, caches parts of it, and serves it to the consumer, so the consumer code does not change. The difference is latency: a local read takes milliseconds, while a remote fetch involves a request to the object store, often tens to hundreds of milliseconds for the first bytes.
How it works: each partition keeps an index of which segments live remotely. When a fetch asks for an offset older than the local window, the broker finds the remote segment, reads the needed range from object storage, and returns it. Some versions add a local cache for remote reads; check the settings for yours.
Batch jobs, replays and rebuilds of a read model are happy with this, as they care about throughput. Latency-sensitive consumers stay within the local window. I watch two things: the rate of remote fetches, which shows who is reading old data, and the object-store request and transfer cost, since a big replay is billed per request and per byte.
- “Does it replace backups?”
No. Tiered storage extends retention. It does not make a second, independent copy of your data, and it protects against a different problem.
Think about what it does not cover. The remote segments belong to the topic, so deleting the topic deletes its remote data too. A bad producer that writes wrong records writes them to the remote tier as well. A mistake that sets retention too short removes data from both tiers when it expires. And there is no point-in-time copy to restore.
What it does give is durability in the object store, which the provider usually replicates within a region, and that helps when a broker disk is lost. For a region or account loss, you need the object store's cross-region settings or cluster mirroring to a second cluster.
So disaster recovery is still two clusters with asynchronous replication. I describe tiered storage as "cheap long retention", never as "backup".
- “How does it help broker recovery?”
A replacement broker only needs to copy the local window, not the whole history, so it joins the cluster much sooner. The long tail already sits in object storage and is shared by all replicas.
replacement broker copy timeruns offline# illustrative (assumed: 90 days retained, 1 day local, 9 TB per broker, 100 MB/s copy) without tiering 9,000 GB / 0.1 GB/s = 90,000 s = 25 h with tiering 100 GB / 0.1 GB/s = 1,000 s = 17 minThe same effect speeds up everything that moves data: adding brokers, rebalancing partitions, and recovering after a disk loss. During the copy the cluster has reduced redundancy, so shorter is safer.
It also makes scale-out cheaper, because brokers are sized for the hot window and the network, not for ninety days of disk. I would still check the actual numbers in a pilot, since remote reads for the catch-up path can differ by version.
- “When would you not use it?”
I would skip it when there is little to offload, or when the topic needs features that tiering does not fully support in my version.
- Short retention: a topic that keeps 24 hours gains nothing, because there is no long tail to move. Tiering adds remote requests and an object store to operate.
- Compacted topics: as the answer says, tiering and compaction do not combine as you might hope. The docs list restrictions for each version, so I check before turning it on.
- Latency-critical old reads: if a service must read old records in a few milliseconds, remote fetches will disappoint.
The rule is that it is another moving part, with its own failure modes, such as an object store outage and per-request cost. I turn it on when the disk bill or the recovery time is a measured problem, run a pilot on one or two large topics, and compare cost and latency before rolling it out wider.
Q140. “What do you watch for when running Kafka on Kubernetes with Strimzi?”
Reveal answer
Strong answer Kafka is a stateful system, so it needs stable identity and storage. Strimzi's operator creates a StatefulSet-style set of broker pods, each with its own persistent volume, with stable network names, and manages upgrades, certificates and topics through custom resources.
Key points: use fast persistent volumes (not network storage with unpredictable latency), spread brokers across zones with rack awareness and anti-affinity, set PodDisruptionBudgets so node drains evict one broker at a time, and give pods requests equal to limits so they are not throttled or evicted.
External access needs care: clients outside the cluster need per-broker addresses (load balancers or node ports), since each client connects to the leader's broker directly.
Operate the operator's rolling updates: they restart brokers one at a time and wait for health, as a manual upgrade would.
Picture it A Strimzi cluster fragment.
The setup: Three brokers across three zones.
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata: { name: prod }
spec:
kafka:
replicas: 3
rack: { topologyKey: topology.kubernetes.io/zone }
storage: { type: persistent-claim, size: 2Ti, class: fast-ssd }
resources: { requests: { cpu: "4", memory: 16Gi }, limits: { cpu: "4", memory: 16Gi } }
config: { default.replication.factor: 3, min.insync.replicas: 2 }Make the invisible visible: What can go wrong.
❌ node drain evicts 2 brokers at once -> partitions below min.insync.replicas -> writes fail
fix: PodDisruptionBudget maxUnavailable: 1
❌ CPU limit lower than request -> throttled brokers -> latency spikes
❌ network-attached volume with 20 ms stalls -> ISR shrink
❌ clients outside cluster get internal pod names -> cannot connect (advertised listeners)Why: Kubernetes will happily move things; Kafka needs to be told what it must not move at the same time.
Land it Persistent fast storage, zone spread, disruption budgets, guaranteed resources, and per-broker external access, with the operator handling rolling changes.
- “Why not just use a Deployment?”
A Deployment treats pods as interchangeable. They get random names, any pod can be replaced by a new one with a new identity, and storage, if any, is shared or throw-away. A Kafka broker is not interchangeable: it has a broker id, and it owns specific partition replicas on its own disk.
What a broker needs is a stable id and network name, so clients and other brokers find broker 2 as broker 2 after a restart, and its own persistent volume that follows it, so a restart rejoins with its data and copies only what it missed. A StatefulSet gives both: ordered names like
kafka-0and one volume per pod. Strimzi manages its own pod sets built on the same idea; check the current docs for the exact resource.With a Deployment, or with data in an
emptyDir, a restart brings up an empty broker with a new identity, forcing a full copy, or losing data if several restart at once. So I never use emptyDir for broker data.- “How do I think about the cost of Kafka on Kubernetes versus a managed service?”
The honest comparison counts engineering time, not only the infrastructure bill. Self-managed Kafka on Kubernetes has a lower per-unit cost, especially at large volume, and gives control over versions, settings and network layout. A managed service charges a premium but removes most routine work.
List what you take on: upgrades with rehearsals, capacity planning, partition rebalancing, certificate rotation, security patching, night-time incidents, and the skill to debug a broker. Example, with stated assumptions: a managed cluster costs $12,000 a month and the self-run one costs $7,000 in infrastructure, a saving of $5,000. If an engineer's loaded cost is $15,000 a month and a third of their time goes to Kafka, that is $5,000, so the saving is gone.
The balance moves toward self-managed with large scale, special needs such as data residency, custom networking or particular versions, or a team that already runs Kubernetes and Kafka well. It moves toward managed with a small team. I count the on-call load honestly, including the nights.
- “How does rack awareness help?”
It spreads each partition's replicas across zones, so one zone failing does not take all the copies. Each broker is given a rack label, here its availability zone, using
broker.rack. When Kafka creates a topic or reassigns partitions, it places the replicas of each partition in different racks where it can.With replication factor 3 across three zones, each partition has one replica per zone. A whole zone can fail and every partition still has two replicas, enough for acks=all with min.insync.replicas=2. Without rack awareness, all three replicas could land in one zone, and a zone outage would mean offline partitions.
It also enables follower fetching. A consumer sets
client.rackto its zone, the brokers use a rack-aware replica selector (replica.selector.class), and the consumer reads from a replica in its own zone instead of the leader in another, which cuts cross-zone traffic cost.In Strimzi, I set the rack's topology key to the zone label, such as
topology.kubernetes.io/zone, and combine it with pod anti-affinity.- “What about the operator's topic management?”
The topic operator lets you manage topics as Kubernetes resources. You write a
KafkaTopicobject with the name, partitions, replicas and configs, commit it to git, and apply it. The operator reconciles: it creates or changes the real topic in Kafka to match.kafkatopic.yamlruns offline# illustrative; apiVersion depends on your Strimzi version apiVersion: kafka.strimzi.io/v1beta2 kind: KafkaTopic metadata: name: orders.order.created.v1 labels: strimzi.io/cluster: main spec: partitions: 12 replicas: 3 config: retention.ms: 604800000This fits provisioning by pull request. The review we already want, owners, partition limits and retention maximums, happens in the pull request, with automated policy checks on the YAML. Git history is the audit trail, and a rollback is a revert.
Two cautions. Deleting a resource can delete the topic and its data, so I protect important topics. And a partition increase through it has the key-mapping effect discussed earlier, so I review those values.
Q141. “Kafka, RabbitMQ or SQS: how do you choose, and where do share groups fit?”
Reveal answer
Strong answer Kafka is a durable, replayable log built for high throughput, many independent readers and ordering per key. RabbitMQ is a broker for routing messages to queues with per-message acknowledgement and flexible routing. SQS is a managed queue with almost no operation.
Choose Kafka when many consumers need the same stream, replay matters, or volume is large. Choose a queue when each message is a task to be done by one worker, with retries and delays, and replay does not matter.
Share groups (KIP-932, production-ready in Kafka 4.2) bring queue behaviour to Kafka: several consumers can read the same partition, each record is acknowledged individually, and failed records can be released for redelivery.
That narrows the gap, but does not remove it: queue features such as routing and delayed delivery are still stronger in a dedicated broker.
Picture it The table.
The setup: Four jobs: audit stream, image-resize tasks, order events to 6 services, delayed email.
| Option | Pick it when | Cost or catch |
|---|---|---|
| Kafka (consumer groups) | Several readers of one stream, replay, ordering per key, high volume | Parallelism capped by partitions; no per-record ack |
| Kafka share groups | Task-queue behaviour on data already in Kafka | Newer feature; no per-key ordering guarantee across consumers |
| RabbitMQ | Rich routing, per-message ack, priorities, delays | Not a replayable log; scaling is different |
| Amazon SQS | Managed simple queue, no operations | Limited ordering and replay; vendor-specific |
Make the invisible visible: The four jobs mapped.
audit stream (keep 1 year, replay) -> Kafka
image-resize tasks (one worker each) -> queue, or Kafka share group if data already in Kafka
order events to 6 services -> Kafka consumer groups
delayed email in 24 h -> queue with delay (RabbitMQ/SQS), not KafkaWhy: A log answers “what happened”, a queue answers “who does this task”; share groups let one platform answer both.
Land it A log for streams and replay, a queue for tasks and delays; share groups let Kafka act as a queue when the data is already there.
- “Why does a partition limit consumers in a normal group?”
Because the group protocol hands each partition to exactly one member at a time, and that is what keeps order. If two consumers read one partition at once, they could take records 10 and 11 in parallel and finish them in the wrong order.
The consequence is a ceiling: a topic with 12 partitions can use at most 12 active consumers in a group, and a thirteenth sits idle. If processing takes 100 ms per record, one partition gives at most 10 records per second, and the only way to scale is more partitions, which has costs.
A share group drops the one-owner rule. Members share a partition: the broker hands records to whichever member asks and tracks each record's state. A member acknowledges each record with accept, release or reject, and unacknowledged records are redelivered after a lock timeout. So 3 partitions can feed 30 workers.
The cost is that ordering across members is gone. I use share groups for independent tasks, not for ordered state changes.
- “Can RabbitMQ replay?”
Classic and quorum queues do not replay. Once a message is acknowledged it is removed, and there is no way to read it again. That is the central difference from a log.
RabbitMQ added streams, a log-like structure. Messages stay for a retention period, many consumers read independently, and a consumer can start from an offset or a timestamp. That covers replay, and it is a real option when you already run RabbitMQ at modest volume.
Kafka remains the more natural fit when replay is central: heavy volume, very long retention, many consumer groups, stream processing with Kafka Streams or Flink, and a large ecosystem of connectors and schema tooling. Replay is its main design purpose, not an add-on.
Example: to rebuild a search index from 90 days of events, a new Kafka group reads from offset zero and that is the standard pattern. A RabbitMQ stream can do it too, but the surrounding tooling is less established for that job. Feature sets move, so I check the current version before deciding.
- “What would make you leave Kafka for a queue?”
I would leave when the workload is purely tasks, so Kafka's strengths go unused while its costs are paid. Typical signs: each message is a job for one worker, there are delays or priorities ("send in 10 minutes", "urgent first"), volume is modest, and nobody needs replay or several readers.
The costs in that case are real. You size partitions for parallelism you do not need. You build retry topics to imitate delays. A failed record can block a partition unless you handle it. And you run, upgrade and secure a cluster for what a managed queue does with a few settings and a per-request price.
Example: 200 background jobs a minute, such as resizing images and sending receipts, is about 3 per second. A managed queue with visibility timeouts, delayed delivery and a dead-letter queue costs a few dollars a month and nobody to patch. Kafka here would be an expensive to-do list.
If the organisation already runs Kafka well and volume is growing, share groups may be enough. Otherwise I choose the queue.
- “How do you migrate?”
I migrate in small reversible steps, so at every point I can stop or go back.
- Dual publish: the producer sends to both the old system and Kafka, through an outbox so they stay consistent. Consumers still read from the old one.
- Shadow consume: a copy of one consumer reads from Kafka and processes without side effects. Its output is compared with the live one's, and every difference is a bug.
- Cut over one consumer at a time: stop the old reader after it drains, start the Kafka reader from just before that point, and let idempotent handlers absorb the overlap.
- Retire: stop publishing to the old system once its queues have been idle and empty for a while.
At each step I check ordering, with keys chosen to match the order the queue gave, and idempotency. See the migration design question (Q148) for the full plan.
Q142 · Scenario. “Your architect proposes Kafka as the primary database, with event sourcing for everything. How do you respond?”
Reveal answer
Strong answer I would not say no, I would say where it fits. Kafka is excellent as the durable log of events, but a log is not a query engine: finding the current state of one entity means replaying or maintaining a separate view.
Event sourcing makes sense for domains where history matters (accounts, orders with audit). Even then, the common pattern is: events in a log, read models in a database or key-value store, built by consumers, and rebuilt by replay when needed.
Problems to raise: ad-hoc queries, schema evolution of years of events, privacy erasure, retention (infinite retention costs), and the team's skill. Transactions across entities are also harder.
My proposal: use Kafka as the event backbone, keep a database for current state and queries, and adopt event sourcing only for the aggregates that need it.
Picture it Where each job belongs.
The setup: Read model rebuilt from events.
commands -> service -> event log (Kafka, source of truth for history)
|-> consumer builds "orders_current" table in Postgres (queries, reports)
|-> consumer builds search index
lose the table? replay the log from offset 0 and rebuild ✓
"find all orders over $500 in Berlin last week" on the log alone ✗ needs a read modelMake the invisible visible: The honest trade.
| Need | Kafka alone | With a read model |
|---|---|---|
| Replay history | Yes | Yes |
| Lookup one entity fast | Needs a store such as Streams state or a table | Yes |
| Ad-hoc queries | No | Yes |
| Erase personal data | Hard (immutable) | Easier in the read model; log still needs crypto-shredding |
| Cross-entity transaction | No | Database transaction |
Why: A log is a great memory and a poor index. Use each for what it is good at.
Land it Kafka is a good log of events but a poor query engine, so I keep read models in a database and apply event sourcing where history really matters.
- “Is it ever reasonable to treat Kafka as the system of record?”
Yes, in a deliberate design for the right data. Where the data is a stream of events and the log is the truth, Kafka can be the system of record. Examples are clickstreams, sensor readings, audit trails, and financial event logs where the sequence matters.
Three things make it work. Retention is long or infinite, using tiered storage so disk cost stays reasonable. Compacted topics hold the latest state per key, so state can be rebuilt by reading one record per key. And lookups go through a state store, such as a Kafka Streams store or an external read model, because the log has no query engine.
Some companies run this at scale with a strong platform team, because they accepted the costs: schema evolution over years, privacy erasure, and rebuild times.
My test is: what would we do if the cluster were lost? If the answer is "restore from the mirrored cluster by a tested procedure", it can be the record. If it is "we have no other copy", it is not ready. It must be chosen on purpose, never by default.
- “What is the biggest risk of event sourcing?”
The biggest risk is the meaning of events changing over the years. An event is a fact recorded long ago, and you must still understand it. If "OrderPlaced" version 1 had no tax field and version 5 has three, every consumer that replays history must handle all five shapes.
That makes schema evolution permanent work. The usual tool is an upcaster: a function that converts an old event into the current shape when it is read, so each schema change adds one step to a chain. Registry compatibility checks prevent new breaking changes, but they cannot repair a past mistake, such as an event that carried the wrong data.
Replay time is the second cost. Rebuilding one order from its events is quick; rebuilding a whole table from three years of events is slow. The remedy is snapshots: store an aggregate's state every 100 events, and replay only from the latest snapshot.
So before adopting it, I plan versioned schemas, upcasters, snapshots and a privacy strategy up front, since all four are painful to add later.
- “How do you rebuild a read model?”
The log makes this safe, because the old model keeps serving while the new one is built beside it.
- Create the new table: a new table or index with the new shape, empty.
- Start a new consumer group: it reads the topic from the earliest offset and writes each event into the new table. Its handlers are idempotent, so a restart in the middle is safe.
- Wait until caught up: when the new group's lag is near zero, it is as fresh as the old one. Compare counts or checksums on a sample.
- Switch: point reads at the new table, keep the old one for a while for rollback, then drop it.
Time depends on history. If replay runs at 20,000 events per second and the topic holds 2 billion events, that is 100,000 seconds, nearly 28 hours. So I plan the rebuild, and snapshots or compaction shorten it. The old group's lag is unaffected, because the two groups are independent.
- “How do you keep the discussion constructive?”
I turn the argument into requirements, because opinions about "Kafka as a database" are hard to settle and requirements are not. I ask the architect for the three most important questions the system must answer, for example "what is the current balance of account X", "list all orders of customer Y this month", and "show everything that changed on order Z".
Then I show, query by query, where each would live in the proposed design. The balance and list queries need a read model. The "everything that changed" query is where the event log shines. That shows which part the log serves well and which parts need a database, without telling anyone they are wrong.
I also ask about facts that matter later: how long events must be kept, who can request erasure, how many teams read the data, and the recovery time.
Finally I offer a small pilot on one aggregate, with success measures agreed first, such as rebuild time and query latency. Evidence from a small trial ends most debates.
These last questions combine everything: tune throughput, read client errors, control cost, migrate, set standards and take ownership.
Q143 · Scenario. “Producers top out at 20 MB/s although the network and disks are nowhere near their limits. Where do you look?”
Reveal answer
Strong answer When hardware is idle, the limit is in how the client sends. I look at batching first: with tiny batches the producer makes many small requests, each with a round trip, and throughput is bounded by requests per second, not bytes.
Check batch.size (default 16 KB), linger.ms (default 5 ms since 4.0), compression, and how many threads call send. A producer that blocks on each send's future is limited to one record per round trip.
Then the partitions: records to one partition are in order and sent one batch at a time per connection. A single hot key or a topic with few partitions caps throughput. Also max.in.flight.requests.per.connection (default 5).
Finally the broker side, request queue and handler idle, but if those are idle, the fault is on the client.
Picture it Why small batches cap throughput.
The setup: Round trip 2 ms, one in-flight request per connection, records of 1 KB.
batch of 1 record : 500 requests/s x 1 KB = 0.5 MB/s (blocking on every send)
batch of 16 KB : 500 requests/s x 16 KB = 8 MB/s
batch of 128 KB : 500 requests/s x 128 KB = 64 MB/s (linger.ms=10, batch.size=131072)
with compression 3:1 the same bytes on the wire cost a thirdMake the invisible visible: Producer metrics that tell you.
# illustrative output
batch-size-avg 1,800 bytes <- far below batch.size 16,384: batches not filling
records-per-request-avg 1.7
request-rate 11,000/s <- lots of tiny requests
fix: linger.ms=10, batch.size=131072, compression.type=lz4, send asynchronouslyWhy: A producer's throughput is batch size times batches per second, so fill the batches.
Land it With idle hardware, the cause is small batches or blocking sends, so I check batch size, linger, compression and whether callers wait on each future.
- “Does higher linger.ms hurt latency?”
It can, but only when traffic is low.
linger.msis the longest the producer waits for a batch to fill before sending it. If records arrive slowly, a record can wait up to that time, so a 10 ms linger adds up to 10 ms to each send at low rates.At high rates it does not hurt, because the batch fills to
batch.size(16 KB by default) before the linger expires, and is sent at once. Example: at 20,000 records per second of 1 KB each, that is 20 MB/s, so a 16 KB batch fills in 0.8 ms. The linger never comes into play.In exchange, batching gives fewer, bigger requests, better compression and less broker work, so throughput rises. The default is 5 ms since Kafka 4.0, changed for exactly that reason.
I choose it per topic. For a user-facing path with a strict latency budget, a small linger of 1 to 5 ms. For a high-volume telemetry stream, 20 to 100 ms. Then I measure end-to-end latency with the new setting, not assume it.
- “Which compression should I pick?”
I choose by CPU cost against ratio, and I measure on real data.
Codec Speed Ratio Use when lz4 very fast decent throughput first, low CPU snappy fast decent similar to lz4 zstd moderate best network or storage is the cost, CPU is spare gzip slow good rarely; mostly legacy Compression works on a whole batch, so larger batches compress better, which is another reason for a little linger. JSON and text often shrink several times over; already-compressed data such as images or encrypted payloads barely shrinks.
The producer compresses, and with the topic's
compression.typeleft atproducerthe broker stores the batch as it is. The saving then carries through disk, replication and consumer fetches. Forcing a different codec on the topic makes the broker recompress, which costs broker CPU, so I avoid it.- “What if one partition is the limit?”
Then I check the key distribution first. Records for one partition are written in order, so one partition can only go as fast as its one leader can accept. If a few keys carry most of the traffic, one partition runs hot while the others idle.
Example: a topic with 3 partitions funnels everything into three leaders. If one customer sends 60 percent of the traffic and records are keyed by customer id, one partition carries 60 percent, and the topic is capped by that partition's rate however many producers you add.
To confirm, I look at per-partition bytes in, from broker metrics or by comparing log sizes. A big imbalance means skew. An even spread with all partitions busy means you need more partitions.
The fixes: increase partitions if the key space allows, remembering the key-mapping effect, or fix the key. For a hot key where per-key order is not needed, adding a small salt spreads it over several partitions. A more even key is better still. Then I measure again.
- “How do I test throughput properly?”
I use the tool that ships with Kafka, with realistic settings, and change one thing at a time. Without a baseline, tuning is guessing.
producer perf testruns offline# illustrative kafka-producer-perf-test.sh --topic perf-test --num-records 5000000 --record-size 2048 --throughput -1 --producer-props bootstrap.servers=b1:9092 acks=all linger.ms=5 batch.size=65536 compression.type=lz4It reports records per second, MB per second and latency percentiles. I run a baseline with the current settings, then change only
batch.size, then onlylinger.ms, and record every result in a table.Use the real record size, and if possible a payload file of realistic data, because random bytes do not compress and give wrong numbers. Run each setting for several minutes and repeat it, to see how much results vary.
Test on a production-like cluster, with the same broker count, replication factor and network, since a small test cluster gives numbers that do not carry over.
Q144 · Scenario. “Consumers log CommitFailedException or 'unknown member id' after being slow. What does it mean?”
Reveal answer
Strong answer The group coordinator removed this member (because it did not poll in time or lost its session) and started a rebalance. When the slow consumer finally tries to commit, its member id and generation are stale, so the commit is rejected.
The records it processed will be processed again by the new owner of the partition, which is the at-least-once behaviour showing up. Nothing is lost, but there are duplicates.
Fix the cause: processing too slow per poll (shrink max.poll.records, speed up work), long GC pauses, or a session timeout too short for the environment.
And make handlers idempotent so these events are harmless.
Picture it The sequence.
The setup: Member A takes 6 minutes on one poll; max.poll.interval.ms is 5 minutes.
t=0 A polls 500 records, starts work
t=5:00 coordinator: A has not polled -> removes A, rebalance, partitions go to B
t=6:00 A finishes, tries commit(generation 7) -> group is at generation 8
CommitFailedException: member not part of the group / unknown member id ✗
B reprocesses the same 500 records (duplicates)Make the invisible visible: Settings that matter.
max.poll.records=100
max.poll.interval.ms=300000
session.timeout.ms=45000
heartbeat.interval.ms=15000 # about one third of session.timeout.msWhy: A commit is only valid for the generation you hold; once removed you are a stranger to the group.
Land it The coordinator already removed the slow member, so its commit is stale and the batch will be reprocessed elsewhere; fix the slowness and keep handlers idempotent.
- “Should I catch the exception and retry the commit?”
No. Retrying will not help, because the problem is not temporary. The commit was rejected because this member's id and generation are no longer valid in the group: the coordinator removed it and moved on. Sending the same commit again with the same stale generation fails in the same way.
What the consumer should do is let the exception reach the poll loop, or catch it, log it, count it, and continue to the next
poll(). On that poll the client rejoins the group, takes part in the rebalance and receives a new assignment, then starts from the committed offset of whichever partitions it gets. The records it handled before the failed commit will be processed again, by it or by another member.So the handling is: do not retry, keep handlers idempotent, and fix the cause of the slowness. With Spring Kafka the listener container deals with it inside its loop, so application code rarely catches it. I add a counter and an alert on its rate, because a steady stream of these signals a sizing problem.
- “How is it different from a heartbeat failure?”
Both end with the member being removed, but they come from different failures, and the fix differs.
- Heartbeat or session failure: a background thread sends heartbeats to the coordinator. If the process crashes, freezes or loses the network, heartbeats stop and, after
session.timeout.ms(45 seconds by default), the member is removed. - Poll timeout: the application thread is alive and heartbeats continue, but it did not call
poll()withinmax.poll.interval.ms(5 minutes by default), because handling a batch took too long. The client then leaves the group by itself.
The log message tells which one. A poll-interval message names
max.poll.interval.msand suggests reducingmax.poll.recordsor speeding up the work. A session timeout points at the process or the network: GC pauses, CPU starvation, or a node problem.Under the new protocol (KIP-848) the broker handles liveness differently, but the poll-interval rule remains.
- Heartbeat or session failure: a background thread sends heartbeats to the coordinator. If the process crashes, freezes or loses the network, heartbeats stop and, after
- “Could a long GC pause cause it?”
Yes. A stop-the-world pause freezes every thread in the JVM, including the heartbeat thread. If the pause lasts longer than the session timeout, no heartbeat reaches the coordinator, and the member is removed even though nothing is wrong with the code.
timeline of a long pauseruns offline# illustrative (session.timeout.ms = 45 s) t=0 s last heartbeat sent t=1 s full GC starts, all threads frozen t=45 s coordinator removes the member t=61 s GC ends (60 s pause); consumer tries to commit -> rejected, stale member id and generationWith a 60-second pause against a 45-second session, removal is certain. I check the GC logs at the same timestamps as the exception. Remedies: tune the heap and collector, reduce allocation, and give the container enough CPU and memory, since a container at its memory limit can thrash. Raising the session timeout is only a stopgap, because it also delays detecting real failures.
- “What does the new protocol change?”
With
group.protocol=consumer(KIP-848, GA in Kafka 4.0), the broker computes the assignment, not a leader client, and members move through changes incrementally. When one member is removed, only its partitions are reassigned. The others keep working through it, instead of every member stopping for a group-wide rebalance.So a slow consumer being kicked out disturbs fewer partitions. The stop-the-world effect of the old rebalance is mostly gone, and large groups are more stable.
What does not change: a member still has to poll in time and commit with a valid generation. A consumer removed for being slow still loses its partitions, and its pending commit fails in the same way. Duplicates are still possible, so idempotent handlers remain required.
So the pain is smaller and the cause is the same: fix the slow processing. To adopt it, I set the property on the consumers and test in staging first, because some settings, such as the assignment strategy, are handled differently; the docs list the differences.
Q145 · Design. “Design backpressure for a consumer that writes to a database which can only take 500 writes per second.”
Reveal answer
Strong answer Make the database's limit the pace of the whole chain. Consume in batches, write with a bulk insert, and limit the rate with a token bucket at 500 writes per second, pausing partitions when the in-memory queue fills.
Bulk inserts help most: 500 single-row writes per second might become 5,000 rows per second in batches of 100 if the limit is in transactions and round trips, not rows. Measure what the real limit is.
The backlog waits in Kafka, which is built for it. Size retention to hold the longest expected backlog, and alert on time-to-drain.
If sustained input exceeds capacity, no design saves you: scale the database or reduce what you write.
Picture it The arithmetic and the loop.
The setup: Input 800 records per second for 1 hour, DB limit 500 per second.
deficit 800 - 500 = 300 records/s
after 1 h 300 x 3,600 = 1,080,000 records of lag
drain at 0 input: 1,080,000 / 500 = 2,160 s = 36 min
with batches of 100 (limit measured at 5,000 rows/s): keeps up, lag stays near 0Make the invisible visible: The consumer shape.
@KafkaListener(topics = "events", batch = "true")
void on(List<ConsumerRecord<String, Event>> recs) {
limiter.acquire(recs.size()); // token bucket: 500 rows/s
jdbc.batchUpdate("INSERT INTO t(id, v) VALUES (?, ?) ON CONFLICT DO NOTHING",
recs, 100, (ps, r) -> { ps.setString(1, r.key()); ps.setString(2, r.value().json()); });
}Why: The limiter converts the database's capacity into consumer speed; Kafka stores the difference.
Land it I batch the writes, rate-limit to the database's real capacity, let the backlog sit in Kafka, and alert on time to drain.
- “Why not scale out the consumers?”
More consumers send more writes to the same database and make things worse. Say the database takes 500 writes per second and one consumer already sends 500. A second consumer makes 1,000 per second of requested work, but the database does not get faster. Requests queue inside it, latency rises, timeouts begin, and retries add even more load.
The bottleneck decides what to scale, and the consumers are not the bottleneck; the database is. So I either scale the database (a bigger instance, sharding) or reduce the write volume (batching, skipping unchanged rows, writing less often).
Consumer parallelism has a place: when each record needs slow work before the write, such as a remote call. Then more consumers help, but a shared limiter in front of the database keeps writes at 500 per second regardless of how many consumers there are.
The rule: concurrency beyond the limit does not add throughput, it adds queueing.
- “How do I find the database's real limit?”
I measure it, because a vendor figure rarely matches my schema. I load-test the database with the production schema, indexes and data size, writing in the same shape as the consumer will. Suppose the 500 limit is transactions per second, so batching changes rows per second a lot.
batch size sweepruns offline# illustrative (assumed results) batch size rows/s p99 latency 1 480 40 ms 10 2,100 55 ms 100 6,500 120 ms 500 7,200 650 msThe pattern is that batching raises throughput a lot, until latency grows with almost no gain. I pick the knee, here a batch of 100, then apply a safety fraction. A limiter at 70 percent of 6,500 is about 4,500 rows per second, leaving room for other users of the database and for failover.
I also watch CPU, replication lag and lock waits during the test, and re-measure whenever the schema changes, since an added index can halve write capacity.
- “What if a poll takes too long with the limiter?”
The risk is that working through one poll batch at the limiter's rate takes longer than
max.poll.interval.ms(5 minutes by default), so the consumer is removed from the group and its commit fails. The arithmetic is simple: time per poll is records per poll divided by the limiter rate.poll timeruns offline# illustrative max.poll.records 500 / 500 per s = 1 s fine max.poll.records 50,000 / 500 per s = 100 s within 300 s, but little margin 50,000 at a degraded 100 per s = 500 s over 300 s: member removedSo I set
max.poll.recordsso a batch finishes in a small fraction of the poll interval even when the database is slow, for example 1 to 5 seconds at the normal rate.The other tool is pause and resume. When the in-memory queue is full, I call
pause()on the assigned partitions and keep callingpoll(), which returns no records but keeps the member alive, thenresume()when the queue drains.- “What does the business see?”
They see data arrive in the database a little later than it happened, by the amount of the lag. At normal load that is seconds, and nobody notices. During a spike or a recovery it can be minutes or hours, and what they see is stale.
That is a product decision, not only a technical one, so I make it visible and agree on it. I expose a freshness figure, such as "data as of 10:42:15", taken from the event time of the latest record written, so users and downstream systems can see how old the data is. I agree a target such as "99 percent of events visible within 30 seconds", and alert when it is missed.
Example: input of 800 per second against a limit of 500 builds a backlog of 300 records each second, so after ten minutes it is 180,000 records. If input then falls to 100 per second, the spare 400 per second drains it in 450 seconds, 7.5 minutes.
If the data feeds payments or alerts, where stale is harmful, I raise the capacity. If it feeds a daily report, minutes of delay are fine.
Q146. “A compacted topic still contains many duplicates of the same key. Is that a bug?”
Reveal answer
Strong answer No. Compaction is a background process, not a constraint. It keeps at least the latest value per key but does not remove older ones immediately. The active segment is never compacted, and cleaning starts only when a log's dirty ratio passes min.cleanable.dirty.ratio (default 0.5).
So a reader of the topic may see several values for a key. The correct reading is: the last value wins. Consumers building a table just overwrite.
Tombstones (null values) delete keys, kept for delete.retention.ms (default 24 hours) so consumers see them. Then they are removed.
If you need quicker cleanup, lower the segment size or time (segment.ms), and min.compaction.lag.ms controls the opposite: how long a record stays uncompacted.
Picture it Before and after a cleaning run.
The setup: Topic customers.state, key = customerId.
# illustrative output
before: c1=A c2=X c1=B c1=C c2=Y | active segment: c1=D
after : c2=Y c1=C | active segment: c1=D (c1=D is still in the active segment)
reader sees on a full read: c2=Y c1=C c1=D -> last wins -> c1=DMake the invisible visible: Settings that control it.
cleanup.policy=compact
min.cleanable.dirty.ratio=0.3 # clean sooner
segment.ms=3600000 # roll the active segment hourly so it becomes cleanable
delete.retention.ms=86400000 # keep tombstones for a dayWhy: Compaction promises the latest value is kept, never that older values are gone yet.
Land it Duplicates in a compacted topic are normal: compaction is lazy and skips the active segment, and readers rely on last value wins.
- “What is the point of compaction then?”
It bounds the size of a state topic and makes restores fast. A topic that records every change to a customer's address would grow forever if kept by time. With compaction, after cleaning it holds about one record per key, the latest, so the topic is as large as the number of customers, not the number of changes.
Example: 1 million customers, each changed 200 times over a year. Without compaction that is 200 million records. After compaction it is close to 1 million, so a consumer rebuilding a table reads 200 times fewer records.
That is why Kafka Streams changelog topics and Kafka Connect's offset and config topics are compacted. After a restart, a task restores its state by reading the topic, and compaction keeps that quick.
It is not a promise that duplicates are gone at any moment. It is a promise that the latest value for each key is kept, within a log of bounded size.
- “How do I delete a key?”
You produce a record with that key and a null value, called a tombstone. It is a normal record that says "this key no longer has a value".
- Write the tombstone:
send(key, null). Readers see it as a delete and remove the key from their table. - Cleaning: when the cleaner next runs over that part of the log, older values for the key are removed.
- Tombstone expiry: the tombstone itself stays for
delete.retention.ms(24 hours by default), so consumers that were slightly behind still see it, and then it is removed.
After that, a consumer that joins fresh never learns the key existed. The trap: a consumer that was offline for longer than the tombstone retention can miss the delete and keep a stale row. So I make the retention longer than the longest period a consumer may be down, or rebuild such consumers from scratch after a long outage.
- Write the tombstone:
- “Can I combine compaction and time retention?”
Yes. Setting
cleanup.policy=compact,deletedoes both: compaction keeps the latest value per key, and the delete policy also removes segments older thanretention.ms. So no record, even the latest for its key, lives past the retention time.That suits state that should expire. Example: a "device last seen" topic with 30 days of retention. Active devices keep a current value because they keep writing, and a device that has been silent for 30 days disappears from the topic completely, so the topic cannot grow without limit.
compact and deleteruns offline# illustrative (30 days = 2,592,000,000 ms) kafka-configs.sh --bootstrap-server b1:9092 --alter --entity-type topics --entity-name device.last-seen.v1 --add-config 'cleanup.policy=[compact,delete],retention.ms=2592000000'I check what the consumers expect first. A rebuilt table will lack the expired keys, which is the point, but a consumer that assumed the latest value per key is kept forever would be surprised.
- “What if the key is null?”
A compacted topic needs a key on every record, because compaction decides what to keep by the key. A record without a key has no "latest value for its key" to compare. In practice the broker rejects such a record on a compacted topic, so the produce fails with an error and nothing is stored silently.
The consequence is for design: decide the key before enabling compaction. The key must identify the thing whose latest state you want, for example the customer id, not the event id. If the key is a unique event id, compaction removes nothing, because every key is different, and the topic grows like an ordinary one.
The key also picks the partition, through the murmur2 hash, so all updates for one key go to the same partition and compact together. A key that mixes entity types, such as "order:42" and "customer:42", works if that is intended, but a delete must use the exact same string.
A producer that sends null keys will fail early in testing, which is good.
Q147 · Scenario. “Finance reports the Kafka cloud bill doubled, mostly network. What is the usual culprit and what do you do?”
Reveal answer
Strong answer Cross-availability-zone traffic. With replicas in three zones, every produced byte is copied to two other zones, and consumers reading from a leader in a different zone pay for that transfer as well. Cloud providers charge for traffic between zones.
Fixes by size of effect: let consumers read from a replica in their own zone (follower fetching, client.rack with a rack-aware replica selector, KIP-392); compress at the producer; reduce the replication factor on low-value topics; and stop unneeded copies, such as dev topics replicated to production size.
I first measure which topics and which clients generate the transfer, using broker byte metrics per topic and the cloud's cost breakdown.
Replication across zones is the price of surviving a zone outage, so I keep it for important topics.
Picture it Where the bytes go.
The setup: Illustrative: 100 MB/s ingress, RF 3 over 3 zones, consumers in all 3 zones.
producer to leader in another zone (2/3 of the time) : 67 MB/s cross-zone
replication leader -> 2 followers in other zones : 200 MB/s cross-zone
consumers reading leader in another zone (2/3 of reads): 67 MB/s per consumer group
with follower fetching: consumer cross-zone drops to about 0; compression 3:1 cuts all three by two thirdsMake the invisible visible: Configuration.
# broker
broker.rack=zone-a
replica.selector.class=org.apache.kafka.common.replica.RackAwareReplicaSelector
# consumer
client.rack=zone-a
# producer
compression.type=zstdWhy: The network bill follows copies and distance, so cut copies, shrink bytes, and keep reads local.
Land it Cross-zone replication and reads are the usual network cost, so I enable follower fetching, compress, and trim replication where it is not needed.
- “Can I avoid cross-zone replication entirely?”
Only by giving up zone fault tolerance. If all three replicas of a partition live in one zone, there is no cross-zone replication traffic and no charge for it. But if that zone fails, the topic is unavailable until it returns, and a partition lost on disk may be lost for good.
That is a business risk decision. For some topics it is right: dev and test topics, derived data that can be rebuilt, or logs where an outage costs little. For others, such as payment events, it is not.
cross-zone replication costruns offline# illustrative (assumed: 20 MB/s ingress, RF 3, $0.02 per GB cross-zone) copies leaving the leader's zone 2 x 20 = 40 MB/s per day 40 x 86,400 = 3,456,000 MB = about 3,456 GB cost 3,456 x $0.02 = about $69 a day = about $2,000 a monthSo I make it a per-topic choice with a recorded sign-off. If the topic is not worth that sum for zone safety, it can move to a single zone, knowing the risk.
- “Does compression always pay?”
Almost always for text-like data, and rarely for data that is already compressed. JSON, logs and CSV shrink several times over with lz4 or zstd, and the saving multiplies, because the producer compresses once and the compressed batch is what gets sent, replicated, stored and fetched.
Example: 100 MB/s of JSON that compresses 4 to 1 becomes 25 MB/s. With replication factor 3, the two cross-zone copies fall from 200 MB/s to 50 MB/s, saving 150 MB/s, and disk use falls by the same factor.
The costs are CPU at the producer, and a little at the consumer to decompress. For binary data that is already compressed, such as images or encrypted payloads, the ratio is close to 1 and the CPU is wasted.
So I verify on real data: take a sample of real batches, compress them with the candidates, and compare ratio and CPU. I set the codec at the producer and leave the topic's
compression.typeatproducer, so the broker does not recompress.- “What about tiered storage?”
It reduces the disk line of the bill, not the cross-zone traffic line, and it adds costs of its own, so it does not fix a network bill.
Data written to the local tier still replicates across zones exactly as before. Tiered storage then moves old, closed segments to the object store, so the brokers' local disks hold less. The disk and broker count may fall, which helps the storage cost.
What it adds: object-store storage, which is cheaper per terabyte, request charges for each upload and download, and transfer charges if the object store is in another region or the reads cross zones. A big replay that reads 50 TB from remote storage is billed for those requests and bytes.
So when the bill doubled mostly in network, I fix the zones first, with follower fetching and compression, and consider tiering separately for storage cost. I count its added request and transfer costs in the estimate and test it on one topic first.
- “How do I keep costs visible?”
I give each team its own number, because teams reduce what they can see. The data comes from broker metrics: bytes in and bytes out per topic or principal, mapped to a team by naming prefix, and bytes retained per topic from log sizes.
- Collect: export the metrics to the monitoring system with a team label.
- Price: turn bytes into money using three unit prices (ingest with replication, egress, storage) taken from the cluster's cost.
- Report: send a monthly report per team, with its top five topics by cost and the change from last month.
- Alert: watch the cloud bill's daily trend and alert on a set percentage rise, so a runaway job is caught in days, not at month end.
The first report usually produces quick wins: a test topic with 30 days of retention at 12 partitions, a client without compression, a consumer group reading from another zone. Showing the number does most of the work.
Q148 · Design. “Design a zero-downtime migration from RabbitMQ to Kafka.”
Reveal answer
Strong answer The shape is expand, migrate, contract. First expand: have producers publish to both RabbitMQ and Kafka (or bridge messages from RabbitMQ into Kafka with a connector), while consumers still read from RabbitMQ. Nothing changes for consumers.
Then migrate: move consumers one service at a time to read from Kafka, running them in shadow mode first (processing without side effects, comparing results). Handlers become idempotent first, since cutover causes some duplicates.
Ordering: choose Kafka keys to preserve the ordering the queue gave, and cut each consumer over at a clean point. Finally contract: stop publishing to RabbitMQ and remove it.
Keep a rollback at each step: since both paths run, going back is a config switch.
Picture it The three phases.
The setup: Orders flow from the web service to 5 consumers.
Phase 1 expand : web -> RabbitMQ AND Kafka (dual publish); consumers: RabbitMQ only
Phase 2 migrate : consumer 1..5 each: shadow on Kafka -> compare -> switch -> RabbitMQ off for it
Phase 3 contract : web -> Kafka only; delete exchanges and queues
Rollback at any point in phase 2: flip the consumer back to its RabbitMQ queueMake the invisible visible: Risks and checks.
| Phase | Risk | Check |
|---|---|---|
| Expand | Dual publish diverges when one fails | Reconcile counts; use an outbox so both come from one source |
| Migrate | Duplicates at cutover | Idempotent handlers; cut at a known offset or timestamp |
| Migrate | Ordering differs | Key by entity id; compare per-entity sequences in shadow |
| Contract | Forgotten consumer | Check queue consumer counts are zero for a week before deleting |
Why: Both systems run side by side until the numbers match, so each step is reversible.
Land it Dual publish, shadow consumers, one-by-one cutover with idempotent handlers, then remove the old path once its queues have been idle.
- “How do I avoid dual-publish divergence?”
The risk is the dual write. If the service sends to RabbitMQ and to Kafka in two separate calls, a crash between them leaves one system with the event and the other without it. The two paths then disagree, and you cannot tell which is right.
The fix is the outbox. The service writes the business change and an outbox row in one database transaction. A relay, a poller or Debezium, reads the outbox and publishes to both targets. The row stays until both publishes succeed, so a failure to reach one target is retried on its own and nothing is lost.
Duplicates are possible on retry, so consumers must be idempotent, which the cutover needs anyway.
To catch drift, I reconcile daily: count messages by type per hour on both sides and compare, or compare a checksum of event ids. A mismatch points to a relay bug or a consumer that lost messages. Reconciliation is what lets me trust the Kafka side before the cutover.
- “How do I cut over a consumer without losing or doubling messages?”
The aim is a small, deliberate overlap, never a gap. Stopping one reader and starting another cannot be perfectly atomic, so I accept some duplicates and rely on idempotency to absorb them.
- Drain the old: stop the RabbitMQ consumer after it empties its queue, and record the timestamp of the last message it processed.
- Start Kafka slightly earlier: find the offsets for a time a few minutes before that point (the client can look up offsets by timestamp) and start the Kafka consumer there. Messages in the overlap are handled twice, and the dedup on event id absorbs them.
- Verify: compare counts for the cutover window, and watch error rates and lag.
- Keep rollback: keep the old consumer deployable while dual publish still feeds the queue, so going back is a config switch.
A small overlap is safer than a gap, because a duplicate is handled and a missing message is not.
- “What changes in the programming model?”
The shift is from per-message to per-position. In RabbitMQ the broker tracks each message: the consumer acknowledges it, a failure requeues it, and the next message goes to whichever worker is free. In Kafka the consumer tracks a position, an offset, in each partition it owns, and commits that, so order and parallelism are tied to partitions and keys.
Several things you had for free must be rebuilt: retry with delay (retry topics or a scheduler), priorities (separate topics per priority), dead-lettering (a DLT with a recoverer), and per-message redelivery counts. Competing consumers on one queue become members of a group, limited by the partition count. The keys you choose now define ordering.
These are what teams miss, so I list the features each queue uses and plan a replacement for each before migrating the first one. Share groups can cover queue-like tasks, with per-record acknowledgement, if your version supports them.
The team also needs new habits: idempotent handlers, offsets, lag monitoring and rebalances.
- “When should we not migrate?”
When the workload is a good fit for RabbitMQ, I would not migrate. The typical case is tasks with delays and priorities at modest scale, where each message is a job for one worker and nobody needs replay or fan-out to many readers. RabbitMQ's routing, per-message acknowledgement and delayed delivery are native there, and it is lighter to run than a Kafka cluster.
A migration costs real effort: dual publishing, shadow runs, idempotent handlers, new monitoring, retraining, and a period of running both systems. It should buy something concrete: replay, higher scale, many independent consumers, stream processing, or a shared event platform.
My test is to write the benefit down first, in numbers, such as "rebuild the search index from history in a day", "handle ten times today's volume", or "five more teams consume the same events". If I cannot write it, I do not start.
A common middle path is to keep RabbitMQ for task queues and use Kafka for the event stream.
Q149 · Design. “Design the standards for an event platform shared by two hundred microservices.”
Reveal answer
Strong answer Standards make the shared platform predictable. Naming and ownership: domain.entity.event.vN, each topic with an owner team and a documented contract. Schemas in a registry with FULL_TRANSITIVE compatibility and CI checks.
Event envelope: every record carries a header set: event id, event type, schema version, occurred-at, trace context (for distributed tracing), and the producer's service name. That makes dedup, debugging and tracing uniform.
Delivery rules: producers use idempotence and acks=all, publish through an outbox when tied to a database write; consumers are idempotent, use dead-letter topics and bounded retries. Libraries wrap these defaults so teams get them for free.
Operations: quotas per team, lag and error dashboards generated per consumer group, ACLs by prefix, and a deprecation process.
Picture it The envelope and the paved road.
The setup: A record from any service looks the same at the edges.
# illustrative record headers
event-id 3f9a... (dedup key)
event-type order.placed
schema-version 4
occurred-at 2026-11-19T10:02:11Z
traceparent 00-4bf92f3577b34da6-...-01 (continues the trace across the async hop)
producer order-serviceMake the invisible visible: What the starter library enforces.
| Concern | Default in the shared library | Teams may change it? |
|---|---|---|
| Producer reliability | Idempotent, acks=all, delivery timeout 2 min | Only with platform review |
| Serialization | Avro + registry, auto-register off | No |
| Consumer errors | Bounded retries then dead-letter topic with headers | Retry counts yes |
| Metrics | Lag, errors, processing time per handler | No |
| Tracing | Propagate traceparent header | No |
Why: With two hundred services, defaults beat documents: the safe path must be the lazy path.
Land it Naming, schemas with checks, a common event envelope, and a shared library that bakes in safe producer and consumer defaults.
- “Why a common envelope when each event has its own schema?”
Because the tools that serve all services need the same fields in every event, whatever its payload. Tracing, deduplication, auditing, replay and debugging tools cannot know two hundred different schemas. A common set of headers lets them work on any topic.
The envelope carries the event id (for dedup), the event type and schema version (so a consumer knows which shape to parse), the occurred-at time (separate from the publish time), the trace context (so a request can be followed across services), and the producer's service name (so you know whom to ask).
Example: an on-call engineer finds a bad record. With the envelope, one tool can show its producer, its trace, and each consumer's handling of that event id, on any topic. Without it, every topic needs a custom investigation.
I prefer record headers for this metadata, so the payload schema stays specific to the event and does not carry cross-cutting fields.
- “How do you stop the platform becoming a bottleneck?”
By making the platform team own the paved road, not each change. With 200 services, a ticket queue for topics and schemas means waiting days, and teams start to route around the platform.
- Self-service through git: a team opens a pull request that adds a topic or schema file. Automated checks run: naming, partition and retention limits, compatibility, owner present.
- Owners review: a human reviewer from the owning domain checks meaning, not syntax.
- Pipeline applies: merging applies the change through the operator or an API, with no platform engineer involved.
The platform team's work is building and improving that pipeline, the shared library and the dashboards. I measure lead time from request to a working topic, with a target such as under an hour, and the share of changes needing manual help. If those numbers rise, the platform is becoming the bottleneck, and I fix the pipeline.
- “How do you handle a team that ignores standards?”
I make the right path the easiest and the wrong one visible. Telling people off does not scale to 200 services; tooling does.
First, make compliance free. The shared library has the safe defaults built in, and templates produce a compliant service. A team that ignores a standard is often a team for which the standard was harder than the shortcut.
Second, make non-compliance visible: a dashboard, updated daily, that lists topics and clients breaking the rules (no owner, no schema, auto-created, no idempotence), with team names. Visibility alone moves most teams.
Third, add gates for the serious cases. A topic with no owner is not created. A producer without a registered schema is refused. Quotas can be tighter for non-compliant principals. A persistent case goes to the team's management, with the dashboard data, as a risk with a date.
Policy that lives only in a document gets ignored. Policy in tooling gets followed.
- “How do you retire topics and events?”
With a process that treats a topic like an API with a lifecycle. Without one, the cluster fills with ghost topics that nobody dares delete.
- Announce: mark the topic deprecated in the catalogue, with a date and the replacement.
- Find consumers: list every consumer group reading it, from group metadata and ACLs, and show the remaining ones on a dashboard.
- Dual publish: producers write to the old and the new topic while consumers move.
- Stop writing: when no consumer remains, stop the old writes and let the topic sit for a quiet period, say 30 days.
- Delete: remove the topic, its schemas and its ACLs, and record it.
Teams will not move without the dashboard and a date, since nothing forces them. Ghost topics cost partitions, disk and attention, and make audits harder.
Q150 · Design. “You take over a Kafka platform tomorrow. What do you put in the runbook and the first-month plan?”
Reveal answer
Strong answer Week one is observation: list clusters, topics, groups, versions, owners, and what pages today. I check the five health basics: offline and under-replicated partitions, controller count, disk, lag, and request latency, and confirm they have alerts that someone responds to.
The runbook gets one page per incident type: lag growing, broker down, disk full, rebalance storm, poison pill, schema break, with the first three commands, a decision tree, and who to call. Each page has been executed once in staging.
Weeks two to four: close the largest risks. Typical findings: replication factor 1 topics, min.insync.replicas=1, unclean election on, no ACLs, no tested backup or DR, auto-create on, stale versions.
I report numbers to the owners: topics at risk, estimated recovery time, cost per team, and a ranked list with effort.
Picture it The first-month list.
The setup: Inherited cluster, six brokers, 300 topics.
# quick audit commands
kafka-topics.sh --bootstrap-server b1:9092 --describe | grep -E "ReplicationFactor: 1" # unsafe topics
kafka-configs.sh --bootstrap-server b1:9092 --describe --all --entity-type brokers --entity-default | \
grep -E "unclean.leader.election|min.insync|auto.create"
kafka-consumer-groups.sh --bootstrap-server b1:9092 --all-groups --describe | sort -k6 -n | tail # biggest lagMake the invisible visible: The runbook page shape.
RUNBOOK: consumer lag growing
1. Is it every partition or one? kafka-consumer-groups.sh --describe --group X
2. Rebalances or restarts? group log, pod restarts, rebalance count
3. Rate: produce vs consume compute drain time
4. Action: rollback / scale (cap = partitions) / skip poison / pause downstream
5. Escalate: owner team Slack #x, platform on-call after 30 min
Last rehearsed: 2026-11-xx in stagingWhy: A runbook is a rehearsed decision tree, not a document: if nobody has run it, it is a guess.
Land it Observe first, write rehearsed runbooks per incident type, then close the biggest risks and report them with numbers.
- “What are the first risks you look for?”
I look for the settings and gaps that can lose data or cause an outage on a bad day. A short script over topic and broker config finds most of them.
first risk scanruns offline# illustrative kafka-topics.sh --bootstrap-server b1:9092 --describe --under-replicated-partitions kafka-topics.sh --bootstrap-server b1:9092 --describe | grep "ReplicationFactor: 1" kafka-configs.sh --bootstrap-server b1:9092 --describe --all --entity-type topics | grep min.insync.replicasThe list I build from it: topics with replication factor 1 or min.insync.replicas of 1, where one disk loss loses data. Unclean leader election enabled, which can silently lose acknowledged records. No authorization, so anyone can read or delete. Disks above 70 percent. No consumer lag alerts. And no tested recovery. Each is cheap to find and expensive to discover during an incident.
I also check the quiet basics: who owns each topic, which versions are running, and when anyone last restored anything. The result is a plain list the owners can read in five minutes, sorted by how badly each item could hurt.
- “How do you decide what to fix first?”
I rank by likelihood times damage, weigh it against effort, and agree the order with the owners.
- Cheap config fixes now: turn off unclean leader election, disable auto topic creation, set min.insync.replicas to 2 where the replication factor is 3. These take minutes, but raising min.insync.replicas can make producers fail while brokers are down, so I check with owners first.
- Data-loss risks and single points of failure first: topics with replication factor 1, no tested restore, no alert on offline partitions. The damage is high, so they earn the effort.
- Scheduled projects: ACL rollout, DR setup, version upgrades, planned with dates.
I show the ranked list, with effort and risk, to the owners, since they know which topics matter. Quick wins first build the trust I need for the big changes.
- “How do you test the runbook?”
A runbook is tested when someone who did not write it can follow it under pressure. So I run a game day in staging.
- Break something: kill a broker, fill a disk, inject a poison record, or stall a consumer, one at a time, without telling the responder which.
- Follow the page: a person who did not write it follows the page, while an observer notes each hesitation or wrong turn.
- Time it: record the time to detect, to diagnose and to recover.
- Fix the page: change confusing steps, missing commands and unclear decisions straight away.
I repeat after each major change, such as an upgrade or a new alert, and at least twice a year. Each page records the date of its last rehearsal, and a page not rehearsed for a year is treated as untested.
- “What do you tell leadership after a month?”
A short, honest report in numbers, with dates, and no surprises later. I keep it to one page and use the same format each month, so progress is visible.
It covers four things. The state: risks found and closed, as counts such as "14 found, 9 closed, 5 scheduled", with the worst remaining ones named. The recovery picture: estimated and, where tested, measured recovery times for a broker loss and a site loss, against the targets. The cost: total and per team, with the trend. And what is coming: upgrades and migrations, with dates and what could go wrong.
Then what I need, stated plainly: people, budget or decisions. For example, "a second platform engineer for on-call, because one person is a single point of failure", or "agreement to enforce quotas from next month".
If there is bad news, I include it early, with the plan. Leaders forgive known problems with plans; they do not forgive surprises.
12 · RecapWhat You Can Do Now
- You can explain Kafka as a partitioned, replicated log and say why ordering exists only inside one partition, so the key is the first design decision
- You can configure a producer so an acknowledged write survives a broker loss: idempotence, acks=all, min.insync.replicas, and a future you actually read
- You can size partitions from bytes per second and consumer speed, and explain why you cannot easily change the number later
- You can run a consumer group safely: commit after processing, keep polls inside max.poll.interval.ms, and choose between classic, cooperative, static and KIP-848 rebalancing
- You can say precisely where exactly-once stops, and close the gap with an idempotent consumer, an outbox, or a Kafka transaction as the case requires
- You can build a Spring Kafka service with dead-letter handling, retry topics, ErrorHandlingDeserializer and tests that use a real broker
- You can keep data changing safely with a schema registry, move database changes with Debezium, and explain state, windows and co-partitioning in Kafka Streams
- You can diagnose lag, a lost broker, a full disk or a rebalance storm from the first three symptoms, and design a platform with quotas, ACLs, DR and a runbook
Close the page and write down, from memory: the five places an acknowledged record can still go missing between a producer and a consumer, and the one setting or habit that closes each. Then reach back to the outbox in Chapter E7: why does an outbox plus an idempotent consumer give an exactly-once effect even though Kafka's own transactions cannot cover the database write?
13 · SummaryAll 20 Patterns on One Page
Every pattern in this chapter, each with the problem it solves and the solution in one line. Click a pattern name to jump to its full breakdown.
02 · The log
| Pattern | Problem | Solution |
|---|---|---|
| Key-based partitioning | Records for one entity land on different partitions and arrive out of order. | Use the entity id as the key so the same key always goes to the same partition, in order. |
| Compacted topic | A state topic grows forever and takes ages to rebuild from. | Keep only the latest value per key, with a null value as a delete marker. |
| acks=all + min.insync.replicas | A broker crash can lose records that were already acknowledged. | Acknowledge only after several in-sync replicas have the record, and refuse writes if too few are alive. |
03 · Producers
| Pattern | Problem | Solution |
|---|---|---|
| Idempotent producer | A retry after a lost acknowledgement writes the same record twice. | Give each producer an id and sequence numbers so the broker drops repeats. |
| Batch and compress | Sending one tiny record per request wastes the network and caps throughput. | Wait a few milliseconds to fill a batch and compress it before sending. |
04 · Consumers and groups
| Pattern | Problem | Solution |
|---|---|---|
| Commit after process | Committing the offset first loses records if the app crashes mid-work. | Commit the offset only after the work is done, accepting that a crash causes a repeat. |
| Incremental rebalancing | Every rebalance makes all consumers stop and drop their partitions. | Move only the partitions that must move while the rest keep working. |
| Static membership | A routine restart triggers a full rebalance and a pause. | Give each consumer a fixed identity so a quick restart keeps its partitions. |
| Queue semantics with share groups | Consumers per partition are capped and one slow record blocks the rest. | Let many consumers share a partition and acknowledge each record on its own. |
05 · Delivery guarantees and transactions
| Pattern | Problem | Solution |
|---|---|---|
| Idempotent consumer | Redelivery makes the same event take effect twice. | Record each event id in the same transaction as the effect so repeats are skipped. |
| Consume-transform-produce transaction | A crash between writing output and committing input duplicates or loses work. | Commit the output records and the input offsets in one Kafka transaction. |
| Non-blocking retry topics | Retrying one failing record in place blocks everything behind it. | Move the failed record to a delayed retry topic so the main stream keeps going. |
| Dead-letter topic | A record that can never succeed blocks the partition or is silently dropped. | Park it in a separate topic with the error details for inspection and replay. |
| Outbox via CDC | Writing to the database and to Kafka separately can lose or invent events. | Write the event in the database transaction and publish it from the change log. |
06 · Spring Kafka, schemas, Connect and Streams
| Pattern | Problem | Solution |
|---|---|---|
| Schema evolution with a registry | A change to a message shape breaks consumers without warning. | Register every schema and refuse changes that break the compatibility rule. |
| Event-carried state transfer | Services keep calling each other to fetch data they need. | Publish state changes as events and let each service keep its own local copy as a table. |
| Change data capture with Connect | Copying database changes by hand or by double-writing falls out of step. | Read the database's own change log with a connector and publish each change to a topic. |
07 · Running Kafka in production
| Pattern | Problem | Solution |
|---|---|---|
| Partition sizing | Too few partitions cap throughput and too many slow recovery. | Compute from bytes per second and the slowest consumer's rate, then add headroom. |
| Alert on consumer lag | Consumers fall behind or get stuck and nobody notices until users complain. | Alert on time to drain and on offsets that stop moving, not on a raw count. |
| Pause/resume backpressure | A slow downstream floods the consumer's memory or gets kicked out of the group. | Pause fetching when a queue is full and resume when it drains, while still polling. |