Menu

Apache Kafka course · Lesson 13 of 13

Top 50 Apache Kafka Interview Questions and Answers

Top 50 Apache Kafka interview questions with answers: partitions, consumer groups, exactly-once, KRaft, compaction, Connect, Streams, Flink and operations.

  • Intermediate
  • 140 min read
  • Updated Oct 2026
On this page
  1. Question list
  2. Beginner Kafka interview questions (freshers)
  3. Intermediate Kafka interview questions
  4. Advanced Kafka interview questions (experienced)

These 50 Kafka interview questions cover topics and partitions, producers and consumers, consumer groups, delivery guarantees and transactions, KRaft, log compaction, Kafka Connect, Kafka Streams and Flink, schemas, security, monitoring and multi-region operations. They are grouped from beginner (freshers) to advanced (experienced). Each question has one clear answer in plain words, with an example where it helps and the mistakes interviewers watch for.

Question list

Show all 50 questions
  1. Walk through the life of one record from producer to consumer
  2. Create and configure a topic from the CLI
  3. What makes a good message key?
  4. Can you change a topic’s partition count, and what breaks when you do?
  5. Synchronous vs asynchronous sends, flush() and delivery callbacks
  6. The consumer poll loop: what poll() does and why max.poll.interval.ms matters
  7. auto.offset.reset: earliest, latest, none and by_duration
  8. How is consumer lag measured, and what does the output mean?
  9. What happens when a broker fails, and how does leadership recover?
  10. Kafka Connect architecture: workers, connectors, tasks and internal topics
  11. Avro vs Protobuf vs JSON Schema for Kafka events
  12. KStream vs KTable vs GlobalKTable in Kafka Streams
  13. What to monitor on a Kafka cluster, and the key broker metrics
  14. Securing Kafka: TLS, SASL mechanisms, ACLs and quotas
  15. How should you name and organise Kafka topics?
  16. Running KRaft: controllers, quorum sizing and metadata versions
  17. How the producer picks a partition, and why Python and Java can disagree
  18. Producer batching, linger.ms and compression: tuning for throughput
  19. Producer retries, timeouts and error handling
  20. max.in.flight.requests.per.connection, idempotence and ordering
  21. Offset commit strategies: auto, sync, async and “store then commit”
  22. Replaying data: seek, offsets-for-times and kafka-consumer-groups --reset-offsets
  23. Consumer fetch tuning: fetch.min.bytes, fetch.max.wait.ms and partition fetch sizes
  24. Processing faster than one thread per partition: worker pools and ordering
  25. Partition assignment strategies: range, round-robin, sticky and cooperative-sticky
  26. How replication works: leaders, followers, the ISR and the high watermark
  27. How Kafka stores a partition on disk: segments, indexes and deletion
  28. Record timestamps: CreateTime vs LogAppendTime, and how they affect retention and replay
  29. Converters vs SMTs vs serializers in Kafka Connect
  30. Error handling in Kafka Connect: errors.tolerance and dead letter queues
  31. Debezium snapshots, incremental snapshots and replication-slot risks
  32. Debezium change events: the envelope, tombstones and flattening with ExtractNewRecordState
  33. Schema Registry under the hood: wire format, schema IDs and subject naming strategies
  34. Windowing in Kafka Streams: tumbling, hopping, sliding, session windows and grace
  35. State stores, changelog topics and restoring state in Kafka Streams
  36. Log compaction in practice: settings, tombstones and how long deletes take
  37. How do you send large messages through Kafka?
  38. How do you handle poison messages and retries in a consumer application?
  39. The KIP-848 consumer group protocol: what changes with group.protocol=consumer?
  40. Share groups (Queues for Kafka): how do they differ from consumer groups?
  41. Unclean leader election and Eligible Leader Replicas (ELR)
  42. Rack awareness and fetching from the closest replica
  43. Exactly-once from Kafka into an external database
  44. Write a transactional consume-transform-produce loop
  45. Tiered storage: how it works and what it changes operationally
  46. Exactly-once source connectors and what “exactly-once” means for sinks
  47. Joins in Kafka Streams: stream-table, stream-stream and co-partitioning
  48. Capacity planning: brokers, disks, network and partition-count limits
  49. Multi-region Kafka: MirrorMaker 2, offset translation and cluster-linking concepts
  50. Kafka Streams vs Apache Flink: event time, watermarks and exactly-once sinks

Beginner Kafka interview questions (freshers)

1. Walk through the life of one record from producer to consumer

Beginner · Very Common · Architecture

The producer turns the record into bytes, picks a partition and adds the record to a batch in memory. A background thread sends that batch to the broker that leads the partition. The leader appends it to its log, the follower brokers copy it, and the leader confirms once enough copies exist. A consumer in a group then fetches it from the leader, up to the high watermark, processes it and later commits its offset.

Interviewers use this question to see whether you can connect the pieces covered in Kafka core concepts: broker, topic, partition, offset, replication into one flow.

  1. Metadata. On start-up the client contacts any bootstrap.servers broker. It learns which broker leads each partition and caches that map, refreshing it when leadership moves.
  2. Serialise and partition. Key and value become bytes (Avro, JSON, Protobuf). The partitioner hashes the key, or uses a sticky choice when there’s no key (see How the producer picks a partition, and why Python and Java can disagree).
  3. Accumulate. The record joins a per-partition batch in the producer’s buffer. The batch is sent when it reaches batch.size or linger.ms expires (see Producer batching, linger.ms and compression: tuning for throughput).
  4. Produce request. The sender thread groups batches by leader broker and sends one request per broker. With idempotence on (the default), each batch carries a producer ID and sequence number.
  5. Append and replicate. The leader writes the batch to the active segment of the partition log (page cache, not a forced fsync). Followers fetch it just as consumers do.
  6. Acknowledge. With acks=all, the leader replies once every in-sync replica has the batch and the ISR is at least min.insync.replicas. The high watermark (HW) advances to the last offset that all ISR members hold.
  7. Consume. A group consumer’s poll() sends fetch requests. The broker returns data only up to the HW, so consumers never read records that could vanish after a leader failover. read_committed consumers stop at the last stable offset instead (see Kafka idempotent producers and transactions).
  8. Commit. The consumer commits “next offset to read” to __consumer_offsets. The record stays on disk until retention removes it, whether or not anyone read it.

Example

# Runtime: Python 3.11, confluent-kafka 2.16, Apache Kafka 4.3 broker on localhost:19092
import json
from confluent_kafka import Producer, Consumer

p = Producer({"bootstrap.servers": "localhost:19092", "acks": "all", "linger.ms": 5})

def on_delivery(err, msg):
    if err:
        print("FAILED", err)
    else:
        print(f"acked key={msg.key().decode()} partition={msg.partition()} offset={msg.offset()}")

for i, acct in enumerate(["acc-1", "acc-2", "acc-1"]):
    p.produce("payments", key=acct, value=json.dumps({"seq": i, "amount": 10 * i}),
              on_delivery=on_delivery)
p.flush(10)   # produce() is async; flush waits for every acknowledgement

c = Consumer({"bootstrap.servers": "localhost:19092", "group.id": "lifecycle-demo",
              "auto.offset.reset": "earliest"})
c.subscribe(["payments"])
seen = 0
while seen < 3:
    m = c.poll(5.0)
    if m is None or m.error():
        continue
    seen += 1
    print(f"read  key={m.key().decode()} partition={m.partition()} offset={m.offset()} value={m.value().decode()}")
c.close()   # commits final offsets (auto-commit) and leaves the group

Output against a 3-partition payments topic:

Both acc-1 records share a partition and keep their order. Across partitions the consumer saw them in a different order from the one they were sent in.

Learn more: Kafka Producers: acks, Batching, Compression, Idempotence and Ordering

2. Create and configure a topic from the CLI

Beginner · Very Common · Topics & Partitions

Use kafka-topics.sh --create with a name, the number of partitions and the replication factor, plus any --config settings. Change settings later with kafka-configs.sh --alter. Topic settings, such as retention.ms, override the broker defaults, such as log.retention.hours. In production, turn off automatic topic creation and manage topics as code, so every change is reviewed and repeatable.

Creating a topic means making three kinds of decisions:

Decision Flag or config Can change later?
Partitions --partitions Increase only (see Can you change a topic’s partition count, and what breaks when you do?)
Replication factor --replication-factor Yes, but only with a reassignment plan
Retention, cleanup, size limits --config retention.ms=…, cleanup.policy, max.message.bytes Yes, dynamically
Durability min.insync.replicas Yes, dynamically

Config precedence. Topic override, then the broker’s dynamic default (cluster-wide), then server.properties, then the built-in default. kafka-configs.sh --describe shows the “synonyms” chain, so you can see where each effective value comes from.

Names differ between layers. The topic setting max.message.bytes corresponds to the broker setting message.max.bytes, and retention.ms corresponds to log.retention.ms. Candidates mix these up often.

Auto-creation. auto.create.topics.enable is still true by default, with num.partitions=1 and default.replication.factor=1. A typo in a producer’s topic name then silently creates a one-partition, unreplicated topic. Turn it off and create topics through Terraform, a GitOps job or an operator such as Strimzi.

Naming. Pick a convention such as <domain>.<entity>.<event>.v<major> (see How should you name and organise Kafka topics?). Avoid mixing . and _, because metric names treat them as the same character.

Example

# Runtime: Apache Kafka 4.3.1 CLI against a local broker
B=localhost:19092
bin/kafka-topics.sh --bootstrap-server $B --create --topic orders \
  --partitions 6 --replication-factor 1 \
  --config retention.ms=259200000 --config cleanup.policy=delete
bin/kafka-topics.sh --bootstrap-server $B --describe --topic orders

bin/kafka-configs.sh --bootstrap-server $B --alter --entity-type topics --entity-name orders \
  --add-config retention.ms=604800000,max.message.bytes=2097152
bin/kafka-configs.sh --bootstrap-server $B --describe --entity-type topics --entity-name orders

Output (abridged):

(Replication factor 1 is only for this single-node lab. Use 3 in production.)

Common mistakes:

  • Leaving auto-creation on in production.
  • Setting broker-level properties on a topic, or the reverse.
  • Creating production topics with replication factor 1.
  • Using --alter --config on kafka-topics.sh; topic configs are changed with kafka-configs.sh.

3. What makes a good message key?

Beginner · Very Common · Topics & Partitions

The key should be the thing whose events must stay in order, or whose latest state you want to keep, such as order_id or account_id. All events with the same key go to the same partition, so they stay in order. A good key is stable and has many different values that spread evenly. Use no key (null) only when order does not matter and you just want data spread evenly.

A key does three jobs at once:

  1. Routing and ordering. Same key, same partition, so events for that key stay in order (see What ordering guarantees does Kafka provide?).
  2. Compaction identity. On compacted topics the key decides what counts as “the same row” (see Kafka retention vs log compaction).
  3. Join co-partitioning. Kafka Streams and Flink joins expect both sides keyed and partitioned the same way.

A good key is:

  • Aligned with the ordering need. For order lifecycle events, order_id. For a ledger balance, account_id (all of an account’s postings in sequence).
  • High-cardinality and roughly uniform. country puts most traffic on a handful of partitions. Skewed keys create hot partitions (see A hot partition in a Kafka topic).
  • Stable. Use an immutable ID, not a mutable attribute.
  • Small. Keys are stored with every record and hashed on every send.

Trade-offs to discuss

Key choice Ordering scope Skew risk
null None Lowest
user_id Per user Bots and heavy users
tenant_id Per tenant High when one tenant is very large
tenant_id:user_id Per user within a tenant Low

Composite keys keep ordering for the smallest unit that needs it. If one tenant is 40% of traffic, tenant_id alone is a bad key, while tenant_id:order_id spreads load and still keeps each order in sequence.

Keys vs headers. Put routing and identity in the key. Put metadata such as trace IDs, schema hints and source system in headers, so the key stays meaningful for compaction.

Example

# Runtime: Python 3.11, confluent-kafka 2.16
from confluent_kafka import Producer

p = Producer({"bootstrap.servers": "localhost:19092", "partitioner": "murmur2_random"})
event = {"tenant": "t-9", "order_id": "o-1001", "status": "PAID"}

# Order-level ordering, spread across partitions even for a huge tenant
key = f'{event["tenant"]}:{event["order_id"]}'
p.produce("orders", key=key, value=str(event),
          headers=[("trace_id", b"9f2c"), ("source", b"checkout")])
p.flush()

Common mistakes:

  • Using a timestamp or random UUID as the key on a compacted topic, which disables compaction in practice.
  • Choosing low-cardinality keys such as status or country.
  • Re-keying a live topic without planning a cut-over for consumers that depend on per-key order.

Learn more: Kafka Topics, Partitions and Consumer Groups

4. Can you change a topic’s partition count, and what breaks when you do?

Beginner · Very Common · Topics & Partitions

You can only increase the number of partitions; Kafka refuses to decrease it. Adding partitions changes hash(key) % N, so most keys start going to a different partition. Order per key breaks at the moment of the change, and compacted topics or keyed state can end up with a key’s old and new values in two places. Existing data is never moved. So pick enough partitions up front.

What happens on increase

  • New, empty partitions are created and assigned to brokers. Existing records stay where they are.
  • Producers notice on their next metadata refresh (metadata.max.age.ms, 5 minutes by default) and start routing keys by the new modulo.
  • Consumer groups rebalance to pick up the new partitions. With auto.offset.reset=latest, records written to a new partition before the group gets its first assignment can be skipped. The consumer config docs warn about exactly this.

What breaks

Concern Effect
Per-key order Old events for key K are in partition 0 and new ones in partition 3, and consumers may process them in either order
Compacted topics Two “latest” values for K in different partitions; readers can see a stale one
Kafka Streams state Stores are partitioned by input partition, so keys are now in the wrong task. Treat it as an application reset
Join co-partitioning Both sides of a join must have equal partition counts

Why no decrease? Records in a removed partition would have nowhere to go without rewriting offsets, and offsets are the contract consumers rely on.

Safer patterns

  1. Over-provision at creation (see the partition-count page).
  2. If you must grow a keyed topic: create orders.v2 with more partitions, dual-write or replicate into it, and let consumers drain v1 before switching.
  3. For unkeyed topics (logs, clicks), adding partitions in place is usually fine.

Example

# Runtime: Apache Kafka 4.3.1 CLI
bin/kafka-topics.sh --bootstrap-server localhost:19092 --alter --topic payments --partitions 2
# Error while executing topic command : The topic payments currently has 3 partition(s); 2 would not be an increase.
bin/kafka-topics.sh --bootstrap-server localhost:19092 --alter --topic payments --partitions 6

Three of the four keys moved partition, so their old and new events now live in different logs.

Common mistakes:

  • Saying “just add partitions” for lag on a keyed or compacted topic without mentioning remapping.
  • Believing Kafka moves existing data into the new partitions.
  • Forgetting that Kafka Streams apps reading the topic need a reset.

In depth: How do you choose the number of partitions for a Kafka topic?

5. Synchronous vs asynchronous sends, flush() and delivery callbacks

Beginner · Common · Producers

send() (or produce()) is always asynchronous: it puts the record in a local buffer and returns straight away. “Synchronous” sending just means waiting for that record’s confirmation, for example send().get() in Java or flush() after each record in Python. That is safe but slow. The usual pattern is asynchronous sends with a delivery callback, poll(0) in the loop, and one flush() when shutting down.

Pattern Throughput Error visibility When
Fire-and-forget (no callback) Highest None, so errors are silent Never in production
Sync (get() / flush() per record) Low: one round trip per record Immediate Rare control messages, tests
Async with callback High Per record, slightly delayed Default
Async, flush() per batch of input High At batch boundaries Batch jobs, such as a file to Kafka

Python specifics (confluent-kafka)

  • produce() raises BufferError when the local queue is full (queue.buffering.max.messages / queue.buffering.max.kbytes). Call poll() and try again.
  • Delivery callbacks run only inside poll() or flush(), so call poll(0) regularly.
  • flush(timeout) returns how many messages are still queued. A non-zero return means data was never confirmed.
  • Callbacks run on your thread, so keep them short.

Java specifics

  • Callbacks run on the producer’s I/O thread, so don’t block in them.
  • close() waits for in-flight records. Call it on shutdown (try-with-resources or a shutdown hook).

Shutdown. Kubernetes sends SIGTERM and waits terminationGracePeriodSeconds. Catch the signal, stop taking input, flush(), then exit. Otherwise records still in the buffer are lost.

Example

# Runtime: Python 3.11, confluent-kafka 2.16, Apache Kafka 4.3 (local single broker)
import time
from confluent_kafka import Producer

conf = {"bootstrap.servers": "localhost:19092", "enable.idempotence": True}  # librdkafka default is False
N = 2000
failures = []

def on_delivery(err, msg):
    if err:
        failures.append((msg.key(), err))

# 1) "Synchronous": wait for each ack before sending the next record
p = Producer(conf)
t = time.time()
for i in range(N):
    p.produce("orders", key=str(i), value=b"{}", on_delivery=on_delivery)
    p.flush()                       # blocks until this record is acked
print(f"sync : {N / (time.time() - t):8.0f} msg/s")

# 2) Asynchronous: keep sending, serve callbacks with poll(0), flush once at the end
p = Producer(conf)
t = time.time()
for i in range(N):
    while True:
        try:
            p.produce("orders", key=str(i), value=b"{}", on_delivery=on_delivery)
            break
        except BufferError:         # local queue full: let callbacks drain it
            p.poll(0.1)
    p.poll(0)                       # run delivery callbacks that are ready
remaining = p.flush(30)
print(f"async: {N / (time.time() - t):8.0f} msg/s, unflushed={remaining}, failures={len(failures)}")

Even on a local broker with sub-millisecond round trips, waiting per record cost most of the throughput. Over a real network, with milliseconds per round trip, the gap gets much wider.

Common mistakes:

  • Thinking produce() returning means the record is stored.
  • Never calling poll() in Python, so callbacks never fire and the queue fills.
  • Calling flush() after every record in a high-volume path.

Learn more: Kafka Producers: acks, Batching, Compression, Idempotence and Ordering

6. The consumer poll loop: what poll() does and why max.poll.interval.ms matters

Beginner · Very Common · Consumers

A Kafka consumer is a loop around poll(). Each call returns records the client has already prefetched, keeps the consumer in its group and runs rebalance callbacks. Heartbeats are sent in the background, but if your code does not call poll() again within max.poll.interval.ms (5 minutes by default), the consumer is thrown out of the group. Its partitions go to other consumers, and its next commit fails. So keep the processing between polls short.

Two liveness checks

Check Setting (Java default) Detects
Heartbeat session.timeout.ms (45 s), heartbeat.interval.ms (3 s) Dead process, network partition
Poll interval max.poll.interval.ms (5 min) A live process stuck in processing

What poll() does

  • Returns up to max.poll.records (500) records in Java. librdkafka’s consume(num_messages=…) and poll() read from a local prefetch queue.
  • Sends fetch requests in the background (see Consumer fetch tuning: fetch.min.bytes, fetch.max.wait.ms and partition fetch sizes for fetch tuning).
  • Handles group joins and syncs, and calls on_assign / on_revoke listeners.
  • With auto-commit, commits offsets returned by the previous poll.

A sound loop

  1. subscribe() with rebalance callbacks.
  2. poll(), process the batch, then mark or commit offsets (see Offset commit strategies: auto, sync, async and “store then commit”).
  3. Handle msg.error(). Some errors are informational, such as partition EOF.
  4. On shutdown, close(). It commits (when auto-commit is on) and leaves the group immediately, so others don’t wait for a session timeout.

If processing is slow

The Java KafkaConsumer is not thread-safe. Use one consumer per thread, and call wakeup() from another thread to break out of a long poll.

Example

# Runtime: Python 3.11, confluent-kafka 2.16, Apache Kafka 4.3
# Shows what happens when processing takes longer than max.poll.interval.ms.
import time
from confluent_kafka import Consumer

c = Consumer({
    "bootstrap.servers": "localhost:19092",
    "group.id": "slow-worker",
    "auto.offset.reset": "earliest",
    "enable.auto.commit": False,
    "session.timeout.ms": 6000,      # heartbeats keep flowing in the background
    "max.poll.interval.ms": 6000,    # but poll() must be called at least this often
})
c.subscribe(["clicks"])
first = True
deadline = time.time() + 20
while time.time() < deadline:
    msg = c.poll(1.0)
    if msg is None:
        continue
    if msg.error():
        print("poll() returned error:", msg.error().name(), "-", msg.error().str())
        continue
    if first:
        print(f"got offset {msg.offset()} from partition {msg.partition()}; simulating 9 s of work")
        time.sleep(9)                # longer than max.poll.interval.ms
        first = False
        try:
            c.commit(message=msg, asynchronous=False)
        except Exception as e:
            print("commit failed:", e)
c.close()

The record was processed but its offset couldn’t be committed, so another member would process it again.

Common mistakes:

  • Raising session.timeout.ms to fix slow processing. Session timeout covers heartbeats, not processing time.
  • Sharing one Java KafkaConsumer across threads.
  • Forgetting close(), so every restart costs a full session timeout before partitions move.

7. auto.offset.reset: earliest, latest, none and by_duration

Beginner · Very Common · Consumers

auto.offset.reset only matters when a group has no valid saved offset for a partition: a brand-new group, offsets that expired, or an offset whose data retention already deleted. latest, the default, starts at the end, so old data is skipped. earliest starts at the oldest record still kept. none throws an error. Since Kafka 4.0, the Java client also accepts by_duration:<ISO-8601>, which starts from records written that long ago.

Value Starts at Typical use
latest Log end Live dashboards and alerts, where history is irrelevant
earliest Log start Pipelines that must see everything, such as loading a lake or rebuilding state
by_duration:PT1H Records with timestamp ≥ now − 1 h A new consumer that only needs recent context
none Throws NoOffsetForPartitionException Critical consumers where silently skipping or replaying is unacceptable

When it fires

  1. A new group.id that has never committed.
  2. The group was empty longer than offsets.retention.minutes (7 days by default), so its offsets were deleted.
  3. The committed offset is now below the log start, because retention deleted the data (OFFSET_OUT_OF_RANGE).
  4. New partitions were added and the group has no offset for them. With latest, records written before the first assignment are skipped.

It does not fire when the group already has offsets. That’s the most common confusion. Changing the setting from latest to earliest on an existing group does nothing, as the second run below shows. To move an existing group, reset its offsets (see Replaying data: seek, offsets-for-times and kafka-consumer-groups --reset-offsets).

Client differences. librdkafka spells the values smallest/earliest/beginning and largest/latest/end, and uses error instead of none. Its default is also latest (largest). by_duration is a Java-client feature. Product behaviour changes; checked October 2026.

Example

# Runtime: Apache Kafka 4.3.1 CLI. Topic "clicks" holds 30 events, one every 6 minutes over the last 3 hours.
for r in latest earliest by_duration:PT1H; do
  n=$(bin/kafka-console-consumer.sh --bootstrap-server localhost:19092 --topic clicks \
        --group reset-demo-${r//[:]/-} --command-property auto.offset.reset=$r \
        --timeout-ms 5000 2>/dev/null | wc -l)
  echo "auto.offset.reset=$r -> $n records"
done
# Run the 'earliest' group again: it now has committed offsets, so the reset policy is ignored
bin/kafka-console-consumer.sh --bootstrap-server localhost:19092 --topic clicks \
  --group reset-demo-earliest --command-property auto.offset.reset=earliest --timeout-ms 5000 | wc -l

Common mistakes:

  • Expecting earliest to replay history for a group that has already committed.
  • Using latest for pipelines that must not miss data, especially when partitions might be added.
  • Not alerting when a consumer falls behind the retention boundary and silently jumps ahead.

Learn more: Kafka Consumers: Poll Loop, Offsets, Commits and Lag

8. How is consumer lag measured, and what does the output mean?

Beginner · Very Common · Consumers

Lag for one partition is the latest offset written minus the offset the group has committed: how many records are written but not yet processed. Total lag adds up all partitions. But a lag of 10,000 records can mean seconds or hours, so also track time lag: how old the oldest unprocessed record is. That tells you how out of date the downstream data really is.

How to diagnose growing lag is covered in Kafka consumer lag keeps growing and on this site’s lag page. This question is about reading the numbers correctly.

kafka-consumer-groups.sh --describe columns

Column Meaning
CURRENT-OFFSET Committed offset (next to read), not the consumer’s in-memory position
LOG-END-OFFSET Next offset to be written
LAG The difference
CONSUMER-ID, HOST The member that owns the partition; - means nobody does

--state shows the group state (Stable, PreparingRebalance, Empty) and assignor. --members --verbose shows which partitions each member holds.

Pitfalls

  • Commit cadence: lag is measured at commits, so a healthy consumer committing every 5 s shows a saw-tooth pattern.
  • Transactions: control markers take offsets, so read-committed consumers can show a small lag that never reaches zero.
  • Compacted topics: offsets have gaps, so offset lag overstates the number of records left.
  • Different traffic per partition: 10,000 records of lag is seconds on a busy partition and hours on a quiet one. Time lag normalises this.

Tools. The CLI, consumer metrics (records-lag-max), Burrow (status by sliding window), Kafka exporters for Prometheus, and the lag metrics managed services provide.

Example

# Runtime: Apache Kafka 4.3.1 CLI
bin/kafka-consumer-groups.sh --bootstrap-server localhost:19092 --describe --group ledger-writer
bin/kafka-consumer-groups.sh --bootstrap-server localhost:19092 --describe --group ledger-writer --state

Partition 1 has only 4 records of lag, but they are 26 minutes old. That’s the number a freshness SLA cares about.

Common mistakes:

  • Treating CURRENT-OFFSET as where the consumer actually is right now.
  • Alerting on a single global offset-lag threshold.
  • Expecting lag to reach exactly zero on transactional or compacted topics.

In depth: Consumer lag keeps growing. How do you diagnose and fix it?

9. What happens when a broker fails, and how does leadership recover?

Beginner · Very Common · Replication & Durability

The controller notices that the broker stopped sending heartbeats and removes it. For each partition that broker led, a new leader is picked from the in-sync replicas, and clients find the new leaders by refreshing metadata and retrying. Those partitions have one copy fewer until the broker comes back and catches up. Then leadership moves back to the preferred replica, automatically or with kafka-leader-election.sh.

Timeline of a hard crash

  1. Brokers heartbeat to the active controller. After broker.session.timeout.ms (9 s by default) with no heartbeat, the controller fences the broker.
  2. For each partition the broker led, the controller elects a new leader from the ISR (or the ELR, see Unclean leader election and Eligible Leader Replicas (ELR)) and writes the change to the metadata log.
  3. Brokers apply the change. Producers and consumers get NOT_LEADER_OR_FOLLOWER, refresh metadata and retry, which is invisible to the application with default retries.
  4. The failed broker is also removed from the ISR of partitions it followed. Those partitions are now under-replicated.
  5. When it restarts, the broker truncates any divergent tail (using leader epochs), catches up and rejoins the ISR.
  6. Preferred leader = first replica in the assignment list. With auto.leader.rebalance.enable=true (the default) the controller moves leadership back to preferred replicas on a timer, every leader.imbalance.check.interval.seconds (300 s). The old leader.imbalance.per.broker.percentage threshold isn’t in the 4.3 broker config list. You can force it at once with kafka-leader-election.sh --election-type PREFERRED.

Controlled shutdown (SIGTERM) is gentler: the broker asks the controller to move its leaderships away first, so clients see almost no errors. Always do rolling restarts this way, one broker at a time, waiting for zero under-replicated partitions between brokers.

What a client notices

  • acks=all with min.insync.replicas=2 and RF 3: one broker down, writes keep succeeding.
  • A latency spike for a few seconds while leadership moves.
  • Consumers keep reading from new leaders. Groups don’t rebalance unless consumer processes themselves failed.

Example

# Runtime: Apache Kafka 4.3.1 lab: 1 KRaft controller + 3 brokers on one host
source ../env.sh; C=localhost:29091,localhost:29092,localhost:29093
leaders(){ kafka-topics.sh --bootstrap-server $C --describe --topic orders4 2>/dev/null | awk '/Partition:/ {printf "p%s:L%s(isr %s) ", $4, $6, $10} END {print ""}'; }
kafka-topics.sh --bootstrap-server $C --create --topic orders4 --partitions 6 --replication-factor 3 --config min.insync.replicas=2 >/dev/null
sleep 2; echo "start           : $(leaders)"
bash ../cluster/stop.sh 1 -9 >/dev/null                       # hard crash, no controlled shutdown
sleep 12; echo "broker 1 killed : $(leaders)"
kafka-topics.sh --bootstrap-server $C --describe --under-replicated-partitions 2>/dev/null | grep -c Partition: | sed "s/^/under-replicated partitions (all topics): /"
bash ../cluster/start.sh 1 >/dev/null; sleep 10   # restart broker 1
# preferred.json: {"partitions":[{"topic":"orders4","partition":2},{"topic":"orders4","partition":4}]}
echo "broker 1 back   : $(leaders)"
kafka-leader-election.sh --bootstrap-server $C --election-type PREFERRED --path-to-json-file preferred.json
echo "after preferred : $(leaders)"

Killing broker 1 moved its two leaderships (p2, p4) to broker 2 and broker 3 within seconds, and every partition dropped to two in-sync replicas. After the restart, broker 1 rejoined every ISR but led nothing. Within the run the automatic rebalance (5-minute timer) hadn’t fired yet, so a preferred election moved p2 and p4 back.

Learn more: Kafka Replication: Leaders, ISR, min.insync.replicas and KRaft

10. Kafka Connect architecture: workers, connectors, tasks and internal topics

Beginner · Very Common · Kafka Connect

Kafka Connect moves data between Kafka and other systems using configuration, not code. Source connectors bring outside data into Kafka; sink connectors write Kafka data out. A cluster of workers runs the connectors, and each connector splits its work into tasks that run in parallel. In distributed mode, workers share their settings, progress and status through three internal topics, and you manage everything through a REST API.

Pieces

Concept What it is
Worker A JVM process running the Connect runtime. Workers with the same group.id form a cluster
Connector A configured instance of a plugin, such as a JDBC sink for one database
Task A unit of parallel work. A sink’s tasks act like consumers in a group; a source’s tasks split tables, files or shards
Converter Turns Connect’s internal data into bytes and back (see Converters vs SMTs vs serializers in Kafka Connect)
Transform (SMT) A light, per-record change applied between connector and converter
Plugin path Where connector JARs are loaded from, each in its own isolated classloader

Standalone vs distributed

  • Standalone: one process, with offsets in a local file. Good for development or a single edge agent.
  • Distributed: any number of workers. Connector configs live in config.storage.topic, source offsets in offset.storage.topic, and state in status.storage.topic. Tasks rebalance across workers when one fails (incremental cooperative rebalancing, with scheduled.rebalance.max.delay.ms of 5 minutes before a lost worker’s tasks are reassigned).

Offsets

  • Sink connectors use normal consumer group offsets (connect-<connector-name>).
  • Source connectors store their own “source offsets” (a file position, a WAL LSN, a row timestamp) in the offsets topic. Since Kafka 3.6 (KIP-875) you can read and reset them through the REST API (GET/PATCH/DELETE /connectors/{name}/offsets).

When not to use Connect. For complex business logic, use stream processing (Kafka Streams or Flink) and let Connect do only the I/O.

Example

bootstrap.servers=localhost:19092
group.id=connect-lab
listeners=http://localhost:18083
config.storage.topic=connect-lab-configs
offset.storage.topic=connect-lab-offsets
status.storage.topic=connect-lab-status
config.storage.replication.factor=1
offset.storage.replication.factor=1
status.storage.replication.factor=1
key.converter=org.apache.kafka.connect.storage.StringConverter
value.converter=org.apache.kafka.connect.json.JsonConverter
value.converter.schemas.enable=false
plugin.path=/opt/kafka/libs/connect-file-4.3.1.jar
exactly.once.source.support=enabled

The file connectors ship with Kafka but have not been on the default classpath since 3.2, which is why plugin.path points at connect-file-4.3.1.jar. (Lab paths are shortened here.)

Learn more: Kafka Connect and Debezium CDC

11. Avro vs Protobuf vs JSON Schema for Kafka events

Beginner · Common · Schema Registry

All three can be enforced with a Schema Registry. Avro is compact, needs the writer’s schema to decode, and has the most mature rules for schema changes across data tools (Connect, Spark, Flink, lakes). Protobuf is compact, uses field numbers to handle changes, and suits teams already using gRPC. JSON Schema keeps human-readable JSON, but messages are bigger and types are looser. Choose by your tools and how your schemas will change, not by raw speed.

Avro Protobuf JSON Schema
Encoding Binary, no field tags (schema needed) Binary with field numbers Text JSON
Size Smallest typically Small Largest
Evolution rule Add or remove fields with defaults; resolution by field name Never reuse field numbers; new fields optional by default (proto3) Depends on additionalProperties and open or closed content models
Nullability Explicit unions ["null", "string"] proto3 defaults and optional, which can hide “unset vs zero” type: ["string", "null"]
Code generation Optional (generic records work) Usually required Optional
Data platform support Strongest (Connect, Debezium, Spark from_avro, Flink) Good and growing Good, but types are weaker (numbers, dates)
Human-readable on the wire No No Yes

Guidance

  • Data platform / CDC / lake: Avro is the usual default, with logical types for decimals and timestamps.
  • Service-to-service events in a gRPC shop: Protobuf, so teams share one IDL.
  • Low-volume integrations, or teams new to schemas: JSON Schema. It’s better than schemaless JSON, but enforce additionalProperties: false (or the reverse) on purpose, because it changes what counts as compatible.

Pitfalls to mention

  • Avro decimal and timestamp logical types must be handled the same way by every reader.
  • In proto3 a missing field and a zero value look identical unless the field is marked optional.
  • Plain JSON without a schema makes “schema drift” the consumer’s problem (see Upstream added and renamed columns without notice (schema drift)).

Example

# Schema definitions, not executable: the same event in each format
# Avro (orders-value, registered as AVRO)
{"type": "record", "name": "OrderPlaced", "namespace": "shop.orders",
 "fields": [{"name": "order_id", "type": "string"},
            {"name": "amount", "type": {"type": "bytes", "logicalType": "decimal", "precision": 12, "scale": 2}},
            {"name": "coupon", "type": ["null", "string"], "default": null}]}

# Protobuf (registered as PROTOBUF)
syntax = "proto3";
package shop.orders;
message OrderPlaced {
  string order_id = 1;
  int64 amount_cents = 2;
  optional string coupon = 3;   // never reuse 3 after deleting it; mark it `reserved 3;`
}

# JSON Schema (registered as JSON)
{"$schema": "https://json-schema.org/draft/2020-12/schema", "title": "OrderPlaced", "type": "object",
 "properties": {"order_id": {"type": "string"}, "amount": {"type": "number"},
                "coupon": {"type": ["string", "null"]}},
 "required": ["order_id", "amount"], "additionalProperties": false}

For size: the Q504 demo encoded a two-field order in 14 bytes as framed Avro, against 44 bytes as JSON.

Common mistakes:

  • Choosing on benchmark speed alone.
  • Reusing a deleted Protobuf field number.
  • Adding an Avro field without a default and breaking backward compatibility.
  • Representing money as floating-point in any format.

Learn more: Kafka Schema Registry and Schema Evolution: Compatibility Modes

12. KStream vs KTable vs GlobalKTable in Kafka Streams

Beginner · Very Common · Kafka Streams

A KStream treats every record as a separate event, like an insert. A KTable treats each record as the newest value for its key, like an upsert, where a null value means delete; it is stored in a local state store. A GlobalKTable is a KTable copied in full to every instance, so you can join on any field without matching partitions. The same topic can be read either way; this is called stream-table duality.

KStream KTable GlobalKTable
Semantics Event log Changelog: latest per key Changelog, fully replicated
A new record for key K Another event Replaces K’s value Replaces K’s value
Null value A record with null value Deletes K (tombstone) Deletes K
Partitioned? Yes Yes, each instance holds its own partitions No, every instance holds all of it
Join requirements Co-partitioned with the other side Co-partitioned Any key extractor; no co-partitioning
Typical source Clicks, payments, sensor readings Customer profile, account balance (a compacted topic) Small reference data: currencies, product catalogue

Converting

  • stream.groupByKey().aggregate(…) or .count() gives a KTable. Aggregating a stream gives a table.
  • table.toStream() gives the change stream of the table.

Why aggregations over a KTable “retract”. When a table row changes, Streams subtracts the old value from the old group and adds the new one, so a count by tier stays correct as users change tiers. The demo shows this.

Choosing GlobalKTable. It’s small, read-mostly data that every instance needs. The cost is that every instance stores and restores the whole topic, and GlobalKTable joins aren’t time-synchronised: lookups use whatever is loaded.

Example

// Runtime: Java 21, Apache Kafka Streams 4.3.1 + kafka-streams-test-utils (TopologyTestDriver, no broker)
// Run: java -cp "kafka_2.13-4.3.1/libs/*" StreamVsTable.java
import java.util.Properties;
import org.apache.kafka.common.serialization.*;
import org.apache.kafka.streams.*;
import org.apache.kafka.streams.kstream.*;

public class StreamVsTable {
    public static void main(String[] args) {
        StreamsBuilder b = new StreamsBuilder();
        // Same input topic, read two ways
        KStream<String, String> events = b.stream("tier-changes", Consumed.with(Serdes.String(), Serdes.String()));
        events.groupByKey().count()                                          // every record is an event
              .toStream().to("change-counts", Produced.with(Serdes.String(), Serdes.Long()));
        KTable<String, String> current = b.table("tier-changes-compacted",
              Consumed.with(Serdes.String(), Serdes.String()), Materialized.as("current-tier"));
        current.groupBy((user, tier) -> KeyValue.pair(tier, user),         // re-key by tier: updates retract
                       Grouped.with(Serdes.String(), Serdes.String()))
               .count().toStream().to("users-per-tier", Produced.with(Serdes.String(), Serdes.Long()));

        Properties p = new Properties();
        p.put(StreamsConfig.APPLICATION_ID_CONFIG, "stream-vs-table");
        p.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "dummy:9092");
        p.put(StreamsConfig.STATESTORE_CACHE_MAX_BYTES_CONFIG, 0);        // show every update
        p.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
        p.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
        try (TopologyTestDriver d = new TopologyTestDriver(b.build(), p)) {
            var in1 = d.createInputTopic("tier-changes", new StringSerializer(), new StringSerializer());
            var in2 = d.createInputTopic("tier-changes-compacted", new StringSerializer(), new StringSerializer());
            String[][] changes = {{"asha", "silver"}, {"ben", "silver"}, {"asha", "gold"}, {"asha", "platinum"}};
            for (String[] c : changes) { in1.pipeInput(c[0], c[1]); in2.pipeInput(c[0], c[1]); }

            System.out.println("KStream count per user : " + d.createOutputTopic("change-counts",
                new StringDeserializer(), new LongDeserializer()).readKeyValuesToMap());
            System.out.println("KTable current tier    : asha=" + d.<String, String>getKeyValueStore("current-tier").get("asha")
                + ", ben=" + d.<String, String>getKeyValueStore("current-tier").get("ben"));
            System.out.println("KTable users per tier  : " + d.createOutputTopic("users-per-tier",
                new StringDeserializer(), new LongDeserializer()).readKeyValuesToList());
        }
    }
}

The stream counted three events for asha, while the table kept only her latest tier. When asha moved from silver to gold, the per-tier count emitted silver → 1 (retracting her) and gold → 1, and then gold → 0 when she moved on to platinum. Running a .java file directly needs only the Kafka libs/ directory on the classpath (java -cp "libs/*" StreamVsTable.java).

Common mistakes:

  • Reading an event topic as a KTable and losing all but the last event per key.
  • Using a GlobalKTable for a huge, fast-changing dataset.
  • Forgetting that KTable source topics should be compacted.

Learn more: Kafka Streams Basics: KStream, KTable, Windows, Joins and State

13. What to monitor on a Kafka cluster, and the key broker metrics

Beginner · Very Common · Operations & Monitoring

First, alert on signs that data is unavailable or at risk: offline partitions, partitions below min ISR, under-replicated partitions, and an active controller count that is not exactly one. Next, watch how busy the brokers are: request handler and network idle ratios, produce and fetch latency, disk usage, and how often the ISR shrinks. On the client side, track consumer lag (measured in time, see How is consumer lag measured, and what does the output mean?) and producer errors, because those are what users actually notice.

Metric (JMX name) Healthy Meaning when bad
kafka.controller:type=KafkaController,name=OfflinePartitionsCount 0 Partitions with no leader: unavailable
kafka.server:type=ReplicaManager,name=UnderMinIsrPartitionCount 0 acks=all producers are failing on these
kafka.server:type=ReplicaManager,name=UnderReplicatedPartitions 0 Reduced redundancy (broker down, slow disk, network)
kafka.controller:type=KafkaController,name=ActiveControllerCount 1 across controllers 0 means no metadata changes are possible
IsrShrinksPerSec / IsrExpandsPerSec Near 0 Flapping followers
KafkaRequestHandlerPool … RequestHandlerAvgIdlePercent > 0.3 Brokers are CPU-bound on requests
SocketServer … NetworkProcessorAvgIdlePercent > 0.3 Network threads saturated
RequestMetrics … TotalTimeMs (Produce, FetchConsumer) p99 Stable Latency regressions; break down by queue, local, remote time
BrokerTopicMetrics … MessagesInPerSec, BytesInPerSec, BytesOutPerSec Expected Traffic and capacity trends
Disk used per log dir, LogFlush, partition and leader count per broker Balanced Skew and capacity

How to collect. Kafka exposes JMX. Most teams run the Prometheus JMX exporter as a Java agent, or use the managed service’s metrics, and build alerts plus a per-broker dashboard. kafka-jmx.sh is handy for spot checks.

Alerting tiers

  • Page: offline > 0, under-min-ISR > 0 for more than a minute, no active controller, disk > 85%.
  • Ticket: URP > 0 for more than 10 minutes, idle ratios < 0.2, consumer time-lag SLO breaches, leader imbalance.

Example

# Runtime: Apache Kafka 4.3.1 lab cluster; broker 3 started with JMX_PORT=9993
source ../env.sh
jmx(){ kafka-jmx.sh --jmx-url service:jmx:rmi:///jndi/rmi://localhost:9993/jmxrmi \
         --object-name "$1" ${2:+--attributes $2} --one-time true --report-format tsv 2>/dev/null | grep -v '^time'; }
echo "== healthy";   for m in UnderReplicatedPartitions UnderMinIsrPartitionCount PartitionCount LeaderCount; do
  echo "$m: $(jmx kafka.server:type=ReplicaManager,name=$m Value | cut -f2)"; done
bash ../cluster/stop.sh 2 >/dev/null; sleep 5
echo "== broker 2 stopped"; for m in UnderReplicatedPartitions UnderMinIsrPartitionCount IsrShrinksPerSec; do
  echo "$m: $(jmx kafka.server:type=ReplicaManager,name=$m | cut -f2 | head -1)"; done
echo "MessagesInPerSec (1-min rate): $(jmx kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec OneMinuteRate | cut -f2)"
echo "Produce p99 total time (ms): $(jmx 'kafka.network:type=RequestMetrics,name=TotalTimeMs,request=Produce' 99thPercentile | cut -f2)"
echo "RequestHandlerAvgIdlePercent: $(jmx kafka.server:type=KafkaRequestHandlerPool,name=RequestHandlerAvgIdlePercent OneMinuteRate | cut -f2)"
kafka-topics.sh --bootstrap-server localhost:29091 --describe --under-min-isr-partitions 2>/dev/null | head -3
bash ../cluster/start.sh 2 >/dev/null

Stopping one of three brokers made 20 of broker 3’s partitions under-replicated, but none fell below min.insync.replicas, so producers were unaffected. LeaderCount: 0 is a finding too: broker 3 had just restarted and hadn’t yet received leadership back (see What happens when a broker fails, and how does leadership recover?), so it carried replicas but no traffic. The lab was idle, which is why the rates read zero.

14. Securing Kafka: TLS, SASL mechanisms, ACLs and quotas

Beginner · Common · Security

Kafka security has three layers. Encryption: turn on TLS for every listener. Authentication: prove who each client is with mutual TLS or SASL (SCRAM, OAUTHBEARER/OIDC, Kerberos, or PLAIN, but only over TLS). Authorization: use ACLs to control who can use which topics, consumer groups, transactional IDs and cluster actions; in KRaft mode the StandardAuthorizer enforces them. Add quotas so one client cannot slow down all the others, and give each application its own identity with only the access it needs.

Listeners. Each listener has a security protocol: PLAINTEXT, SSL, SASL_PLAINTEXT or SASL_SSL. Production uses SSL or SASL_SSL everywhere, including inter-broker and controller listeners.

Authentication options

Mechanism Credential Notes
mTLS (SSL with ssl.client.auth=required) Client certificate Principal from the certificate DN (map it with ssl.principal.mapping.rules)
SASL/SCRAM-SHA-256/512 Username + password Credentials stored, salted, in cluster metadata; no external system
SASL/OAUTHBEARER OIDC token Integrates with an identity provider; short-lived tokens
SASL/GSSAPI Kerberos ticket Common in Hadoop-era enterprises
SASL/PLAIN Username + password Only over TLS; usually backed by a custom callback

ACLs

  • Resources: Topic, Group, Cluster, TransactionalId, DelegationToken. Pattern: LITERAL or PREFIXED.
  • A consumer needs Read on the topic and Read on its group. An idempotent or transactional producer needs Write, plus Write and Describe on its TransactionalId.
  • With an authorizer configured and no matching ACL, access is denied (allow.everyone.if.no.acl.found=false by default).
  • Manage ACLs as code, with prefixed patterns per team (team-a.), rather than by hand.

Quotas. Per user or client ID: producer_byte_rate, consumer_byte_rate, request_percentage, and controller mutation rate. Clients over quota are throttled, not failed.

Other: encrypt data at rest (disk encryption or a cloud KMS), keep secrets out of config files with config providers, and audit authorizer logs.

Example

# Runtime: Apache Kafka 4.3.1 single broker: StandardAuthorizer, super.users=User:ANONYMOUS (the lab's PLAINTEXT admin),
#          extra listener SASL_PLAINTEXT://localhost:19094 with SCRAM-SHA-512
source ../env.sh
kafka-topics.sh --bootstrap-server $B --create --topic payments.secure --partitions 1 >/dev/null 2>&1
# 1) Create SCRAM credentials (stored in KRaft metadata; the password is salted and hashed)
kafka-configs.sh --bootstrap-server $B --alter --entity-type users --entity-name analytics \
  --add-config 'SCRAM-SHA-512=[iterations=8192,password=analytics-secret]'
# 2) Least privilege: analytics may read payments.secure with its own group prefix, nothing else
kafka-acls.sh --bootstrap-server $B --add --allow-principal User:analytics \
  --operation Read --operation Describe --topic payments.secure
kafka-acls.sh --bootstrap-server $B --add --allow-principal User:analytics \
  --operation Read --group analytics- --resource-pattern-type prefixed
kafka-acls.sh --bootstrap-server $B --list --principal User:analytics

The broker config added a SASL_PLAINTEXT://localhost:19094 listener with sasl.enabled.mechanisms=SCRAM-SHA-512 and listener.name.sasl_plaintext.scram-sha-512.sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule required;. Each denial matched exactly one missing permission.

Common mistakes:

  • SASL/PLAIN or SCRAM without TLS, which sends credentials in clear text.
  • Granting a consumer topic Read but forgetting group Read.
  • Using allow.everyone.if.no.acl.found=true “temporarily”.
  • Shared credentials across applications, which makes auditing and revocation impossible.

15. How should you name and organise Kafka topics?

Beginner · Common · Topics & Governance

Pick one naming pattern and enforce it, for example <domain>.<entity>.<event>.v<major>, such as sales.order.created.v1. Kafka allows only letters, digits, ., _ and -, and up to 249 characters. Do not mix . and _, because Kafka treats them as the same in metric names and refuses names that collide. Leave environment names out when each environment has its own cluster. Give every topic an owner, and create topics through reviewed code, not automatic topic creation.

What a good name does

  • Shows who owns the data (the domain), what it describes, and what kind of event it is.
  • Lets you grant access by prefix: one ACL with a PREFIXED pattern on sales. covers every sales topic.
  • Carries a major version, so a breaking change becomes a new topic (.v2) that consumers move to on their own schedule. Small, compatible changes stay in the same topic, controlled by the Schema Registry (see Schema Registry under the hood: wire format, schema IDs and subject naming strategies).

Kafka’s own rules

  • Allowed characters: ASCII letters, digits, ., _ and -. Maximum length 249.
  • . and _ can collide: sales.order.created.v1 and sales_order_created_v1 would have the same metric name, so Kafka refuses the second one.
  • Names starting with __ are used by Kafka itself, such as __consumer_offsets. Kafka Streams creates internal topics that start with its application.id.

Organising topics

Decision Recommendation
Environment in the name Only if environments share a cluster; separate clusters are better
Team name in the name Use the business domain instead; teams change more often than domains
Creating topics Turn off auto.create.topics.enable; manage topics with Terraform, a GitOps tool or an internal portal
Metadata Record owner, schema, retention, sensitivity and on-call contact in a catalog or in the topic’s definition file
Dead letter and retry topics Use the main name plus a suffix, such as sales.order.created.v1.dlq

Example

# Runtime: Apache Kafka 4.3.1, 3 brokers on localhost
kafka-topics.sh --bootstrap-server localhost:19092 --create --topic sales.order.created.v1 --partitions 6 --replication-factor 3
kafka-topics.sh --bootstrap-server localhost:19092 --create --topic sales_order_created_v1 --partitions 6 --replication-factor 3
kafka-topics.sh --bootstrap-server localhost:19092 --create --topic sales/orders --partitions 1 --replication-factor 1

A small check that a CI job can run on every proposed topic name:

Common mistakes:

  • Leaving automatic topic creation on, so a typo in a producer creates a new topic with default settings.
  • Putting the team name or a person’s name in the topic name.
  • Making a breaking schema change in place instead of creating a .v2 topic.
  • Mixing . and _ across topics.

Intermediate Kafka interview questions

16. Running KRaft: controllers, quorum sizing and metadata versions

Intermediate · Common · Architecture (KRaft)

In KRaft mode, a few controller nodes form a Raft quorum that stores all cluster metadata in the __cluster_metadata log, and one of them is the active controller. ZooKeeper is no longer used. Run three controllers, or five for very large clusters, on their own machines in production. Upgrades have two steps: first roll out the new software, then raise metadata.version with kafka-features.sh.

Why ZooKeeper went away is a separate question (it has its own page on this site). This one is about running KRaft day to day.

Roles. process.roles can be broker, controller, or broker,controller (combined). Combined mode suits development and small clusters. Production clusters use dedicated controllers, so a broker under heavy load can’t starve the quorum.

Quorum sizing. Raft needs a majority. Three voters survive one failure and five survive two. An even number adds no extra tolerance. Spread voters across racks or availability zones.

Metadata log. Every change (topic created, ISR shrunk, ACL added) is a record in __cluster_metadata. Brokers replicate this log and apply it locally, so a failover means a new leader is elected among voters who already have the metadata. Nothing has to be reloaded, which is why failover is fast. Snapshots keep the log bounded.

Static vs dynamic quorum. Older setups listed voters in controller.quorum.voters. Newer ones use controller.quorum.bootstrap.servers and format with --standalone or --initial-controllers. Voters can then be added or removed at runtime (KIP-853).

Feature versions. metadata.version and feature flags such as group.version, transaction.version, share.version and streams.version turn on new protocols. Clusters freshly formatted with 4.3 enable them all, as the output below shows. An upgraded cluster must finalise them explicitly. Product behaviour changes; checked October 2026 against the Apache Kafka 4.3 docs.

Example

# Runtime: Apache Kafka 4.3.1, single combined-mode node (lab only)
bin/kafka-storage.sh format -t "$(bin/kafka-storage.sh random-uuid)" \
  -c server.properties --standalone
bin/kafka-server-start.sh server.properties &

bin/kafka-metadata-quorum.sh --bootstrap-server localhost:19092 describe --status
bin/kafka-features.sh --bootstrap-server localhost:19092 describe
# After a rolling upgrade of every node:
# bin/kafka-features.sh --bootstrap-server localhost:19092 upgrade --release-version 4.3

Abridged output:

Common mistakes:

  • Proposing two or four controllers.
  • Forgetting the kafka-features.sh upgrade step, then wondering why new protocols are unavailable after an upgrade.
  • Assuming a 3.x ZooKeeper cluster can jump straight to 4.x; it must migrate to KRaft first, ideally on 3.9, the bridge release.
  • Expecting metadata.version downgrades to always work; releases with metadata changes can’t be downgraded.

In depth: What is KRaft, and why did Kafka 4.0 remove ZooKeeper?

17. How the producer picks a partition, and why Python and Java can disagree

Intermediate · Common · Topics & Partitions

With a key, the Java client picks the partition with murmur2(key) % partitions. Without a key, it fills a batch for one partition before moving to the next (“sticky” partitioning), preferring faster brokers. Clients built on librdkafka, such as Python’s confluent-kafka, Go and .NET, use a different hash (CRC32) by default. So the same key can land in different partitions from Python and Java, unless you set partitioner=murmur2_random.

Java default (Kafka 3.3+)

  • Keyed record: toPositive(murmur2(keyBytes)) % numPartitions. Same key, same partition, as long as the partition count doesn’t change.
  • Null key: the built-in partitioner sticks to one partition until a batch fills, then switches. partitioner.adaptive.partitioning.enable=true (the default) sends fewer records to brokers that are responding slowly. The old DefaultPartitioner and UniformStickyPartitioner classes are deprecated.
  • partitioner.ignore.keys=true ignores keys and spreads records evenly. Use it only when per-key ordering doesn’t matter.

librdkafka default

  • partitioner=consistent_random hashes keys with CRC32, and spreads null keys randomly.
  • murmur2_random matches the Java client for keyed records.

Why it matters. Kafka Streams, ksqlDB, Connect and Java services all assume murmur2. Suppose a Python service writes customer_id-keyed records and a Java service writes the same keys to the same topic. Their records for one customer end up in different partitions, which breaks per-key ordering and joins. Co-partitioning for stream-table joins (see Joins in Kafka Streams: stream-table, stream-stream and co-partitioning) quietly fails too.

Custom partitioners are possible: implement Partitioner in Java, or specify the partition explicitly in produce(). They are hard to keep consistent across languages, so prefer choosing a good key (see What makes a good message key?).

Example

# Runtime: Python 3.11, confluent-kafka 2.16 (librdkafka 2.16), Apache Kafka 4.3, 6-partition topic "orders"
from confluent_kafka import Producer

def where(partitioner, keys):
    p = Producer({"bootstrap.servers": "localhost:19092", "partitioner": partitioner})
    out = {}
    def cb(err, msg):
        out[msg.key().decode()] = msg.partition()
    for k in keys:
        p.produce("orders", key=k, value=b"{}", on_delivery=cb)
    p.flush()
    return out

keys = ["cust-17", "cust-42", "cust-99"]
print("librdkafka default (consistent_random, CRC32):", where("consistent_random", keys))
print("Java-compatible   (murmur2_random)         :", where("murmur2_random", keys))

The same three keys written with the Java kafka-console-producer.sh (--reader-property parse.key=true) landed in partitions 1, 2 and 2, which matches murmur2_random.

Common mistakes:

  • Saying null-key records are always sent round-robin, one record per partition.
  • Assuming every client library uses the same hash.
  • Hashing on a value that changes for the same entity, such as an email address that can be edited.

Learn more: Kafka Producers: acks, Batching, Compression, Idempotence and Ordering

18. Producer batching, linger.ms and compression: tuning for throughput

Intermediate · Very Common · Producers

The producer groups records for each partition into batches. A batch is sent when it reaches batch.size or when linger.ms runs out, whichever happens first. Bigger batches mean fewer requests and much better compression, because compression is applied per batch. Kafka 4.0 changed the Java default linger.ms from 0 to 5. For high-volume topics, raise linger.ms and batch.size, and use lz4 or zstd compression.

The knobs (Java defaults, Kafka 4.3)

Setting Default Effect
batch.size 16384 bytes Upper bound per partition batch
linger.ms 5 Maximum wait to fill a batch
buffer.memory 32 MB Total memory for unsent records; when it’s full, send() blocks up to max.block.ms
compression.type none gzip, snappy, lz4, zstd
max.request.size 1 MB Largest request, and so the largest single record

librdkafka (Python, Go, .NET) uses the same names with different defaults: linger.ms=5, batch.size=1000000, batch.num.messages=10000.

Why lingering can lower latency. Under load, records queue behind in-flight requests anyway. Bigger batches mean fewer requests, less broker CPU and shorter queues, so tail latency often falls. That’s the reasoning behind the 4.0 default change, and the lab run below shows the same effect.

Compression. It happens in the producer, per batch. Brokers store the compressed batch as-is when the topic’s compression.type=producer (the default), and consumers decompress. So compression saves network, disk and replication traffic together. Small batches compress badly, which is why batching and compression are tuned together.

  • lz4: very fast and a good default.
  • zstd: best ratio for a little more CPU. Good for cross-region links and long retention.
  • snappy: older and similar to lz4.
  • gzip: high CPU, rarely the right choice today.

Setting a topic-level compression.type that differs from the producer’s codec forces the broker to recompress every batch, which costs broker CPU.

Example

# Runtime: Apache Kafka 4.3.1, kafka-producer-perf-test.sh, single local broker, 6 partitions,
# payload.jsonl = 2,000 sample JSON click events (~150 bytes each)
for cfg in "linger.ms=0 compression.type=none" "linger.ms=5 compression.type=none" \
           "linger.ms=20 batch.size=131072 compression.type=lz4" \
           "linger.ms=20 batch.size=131072 compression.type=zstd"; do
  echo "== $cfg"
  bin/kafka-producer-perf-test.sh --bootstrap-server localhost:19092 --topic perf \
    --num-records 300000 --throughput -1 --payload-file payload.jsonl \
    --command-property ${cfg// / --command-property } 2>&1 | tail -1
done

Writing 100,000 of the same records to single-partition topics, one per codec, then checking kafka-log-dirs.sh --describe gave: none 15.62 MB, snappy 3.78 MB, lz4 3.81 MB, zstd 2.12 MB. These are lab numbers on one laptop-class node, so measure your own payloads.

Common mistakes:

  • Assuming linger.ms always adds that much latency to every record.
  • Compressing at the broker (a topic compression.type that differs from the producer’s) and burning broker CPU.
  • Raising batch.size without also raising buffer.memory when there are many partitions.

Learn more: Kafka Producers: acks, Batching, Compression, Idempotence and Ordering

19. Producer retries, timeouts and error handling

Intermediate · Common · Producers

Modern producers retry temporary errors, such as a leader change or NOT_ENOUGH_REPLICAS, almost forever. The real limit is delivery.timeout.ms (2 minutes in Java): the total time from send() to final success or failure. Errors that retrying cannot fix, such as a record that is too large or a permission failure, fail at once. Your code must handle both in the delivery callback, or a failed record is lost without anyone noticing.

Timeline of one record (Java defaults)

  • max.block.ms (60 s): how long send() itself may block waiting for metadata or buffer space.
  • linger.ms (5): time spent waiting in a batch.
  • request.timeout.ms (30 s): how long to wait for each broker response.
  • retry.backoff.ms (100) growing to retry.backoff.max.ms (1 s): exponential backoff between retries.
  • delivery.timeout.ms (120 s): an overall cap that must be at least linger.ms + request.timeout.ms.

In librdkafka the overall cap is message.timeout.ms (alias delivery.timeout.ms) and defaults to 300 s.

Error classes

Retriable (the client handles it) Non-retriable (your code must)
NOT_LEADER_OR_FOLLOWER, NOT_ENOUGH_REPLICAS, REQUEST_TIMED_OUT, network errors RECORD_TOO_LARGE / MSG_SIZE_TOO_LARGE, TOPIC_AUTHORIZATION_FAILED, serialisation errors, INVALID_RECORD

What your code should do

  • Always pass a callback (Java send(record, callback), Python on_delivery=). An ignored future means silent loss.
  • On final failure: log, raise a metric, and either stop the application (for critical data) or write the record to a local spool or fallback store so it can be replayed.
  • Don’t wrap send() in your own retry loop on top of client retries. It duplicates records and breaks the ordering guarantees that idempotence gives you (see max.in.flight.requests.per.connection, idempotence and ordering).
  • Keep retries at its default and tune delivery.timeout.ms instead, as the Kafka docs recommend.

Example

# Runtime: Python 3.11, confluent-kafka 2.16, Apache Kafka 4.3
# Setup: topic "small-msgs" created with --config max.message.bytes=1000
import time
from confluent_kafka import Producer

def send(bootstrap, topic, value):
    p = Producer({"bootstrap.servers": bootstrap, "acks": "all",
                  "delivery.timeout.ms": 5000,   # total budget for send + all retries
                  "retry.backoff.ms": 200})
    start = time.time()
    def on_delivery(err, msg):
        took = time.time() - start
        if err is None:
            print(f"{topic}: delivered after {took:.1f}s")
        else:
            print(f"{topic}: failed after {took:.1f}s -> {err.name()} (retriable={err.retriable()})")
    p.produce(topic, value=value, on_delivery=on_delivery)
    p.flush(15)

send("localhost:19092", "small-msgs", b"x" * 500)    # fits
send("localhost:19092", "small-msgs", b"x" * 5000)   # too big for the topic: retrying can't help
send("localhost:1", "orders", b"x")                  # no broker: retried until delivery.timeout.ms

The third record was retried internally for the whole 5-second budget, and only then reported as a final failure.

Common mistakes:

  • Setting retries=0 “to avoid duplicates”, when idempotence already removes them.
  • Ignoring the future or callback returned by send().
  • Setting delivery.timeout.ms below linger.ms + request.timeout.ms, which the Java client rejects.
  • Treating TimeoutException as proof the record was not written; it may have been.

Learn more: Kafka Producers: acks, Batching, Compression, Idempotence and Ordering

20. max.in.flight.requests.per.connection, idempotence and ordering

Intermediate · Common · Producers

max.in.flight.requests.per.connection is how many unconfirmed requests a producer may have open to one broker. Without idempotence, a value above 1 plus retries can reorder records: batch 2 succeeds while batch 1 is still being retried. With idempotence turned on, the broker uses sequence numbers to keep the order, for any value up to 5. Java turns idempotence on by default; librdkafka (used by Python) does not.

The reordering scenario (idempotence off)

  1. Batch A (offsets 1–100) and batch B (101–200) are both in flight.
  2. A fails with a transient error, while B succeeds and is appended.
  3. A is retried and appended after B, so the partition holds B before A.

The old fix was max.in.flight=1, which caps throughput at one round trip per batch.

With idempotence. Each batch carries a producer ID, an epoch and a per-partition sequence number. The broker remembers the last 5 batches per producer and partition. It rejects an out-of-order sequence so the client retries in order, and it discards duplicates. Hence the limit: max.in.flight ≤ 5.

Defaults differ by client

Client enable.idempotence default acks default max.in.flight default
Java (3.0+) true (unless conflicting configs) all 5
librdkafka 2.16 (confluent-kafka) false all (-1) 1000000

The silent-disable trap (Java). If you don’t set enable.idempotence but do set acks=1, retries=0 or max.in.flight=6, Java quietly turns idempotence off. If you set it explicitly to true alongside a conflicting value, the client throws a ConfigException. librdkafka refuses to start, as the output below shows.

Idempotence covers one producer session against each partition. For guarantees across restarts or across partitions, use transactions (see Kafka idempotent producers and transactions and Write a transactional consume-transform-produce loop).

Example

# Runtime: Python 3.11, confluent-kafka 2.16
from confluent_kafka import Producer

try:
    Producer({"bootstrap.servers": "localhost:19092",
              "enable.idempotence": True,
              "max.in.flight.requests.per.connection": 10})
except Exception as e:
    print(type(e).__name__, e)

# Safe, ordered, high-throughput settings for a Python producer:
p = Producer({"bootstrap.servers": "localhost:19092",
              "enable.idempotence": True,   # implies acks=all, retries, max.in.flight<=5
              "linger.ms": 20,
              "compression.type": "lz4"})

Common mistakes:

  • Recommending max.in.flight=1 as the only way to keep order.
  • Assuming Python and Java producers share defaults.
  • Setting acks=1 for speed and losing idempotence without noticing.

In depth: How does Kafka guarantee message ordering, and where can ordering break?

21. Offset commit strategies: auto, sync, async and “store then commit”

Intermediate · Very Common · Consumers

Auto-commit saves, every 5 seconds, the offsets of whatever poll() last returned, which can mark records as done before you have processed them. For at-least-once, commit only after processing. Use synchronous commits at batch boundaries and in the partition-revoked callback, and asynchronous commits in the busy path. In Python, a clean pattern is enable.auto.offset.store=false plus store_offsets() after each record, so the background auto-commit saves only what you marked.

Q68 introduced the before-vs-after rule. This question is about the mechanics.

Strategy How Latency cost Risk
Auto-commit (Java) enable.auto.commit=true, committed during poll() None With async hand-off, unprocessed records can be committed, so data is lost
Sync per batch commitSync() after processing a batch One round trip per batch Duplicates after a crash, up to one batch
Async + final sync commitAsync() in the loop, commitSync() on revoke and close Low A failed async commit isn’t retried (an older one could overwrite a newer one)
Store then auto-commit (librdkafka) enable.auto.offset.store=false, store_offsets(msg) after processing None Same duplicate window as async
External store Offsets saved with the results in the sink’s transaction Depends on the sink Most work, and gives exactly-once in effect (see Exactly-once from Kafka into an external database)

Details that come up

  • The committed value is the next offset to read: last processed + 1. store_offsets(message=msg) does the +1 for you.
  • Commit in on_revoke (classic eager protocol) or for revoked partitions only (cooperative). Otherwise the new owner reprocesses everything since the last commit.
  • Commits are per partition. A worker pool that finishes records out of order must commit only up to the lowest contiguous finished offset.
  • Committed offsets expire offsets.retention.minutes (7 days) after a group becomes empty. After that, auto.offset.reset decides where it starts (see auto.offset.reset: earliest, latest, none and by_duration).

Example

# Runtime: Python 3.11, confluent-kafka 2.16, Apache Kafka 4.3
# At-least-once: process first, then mark the offset as done, then commit in batches.
import os
from confluent_kafka import Consumer, TopicPartition

c = Consumer({
    "bootstrap.servers": "localhost:19092",
    "group.id": "ledger-writer",
    "auto.offset.reset": "earliest",
    "enable.auto.commit": True,         # background commit every auto.commit.interval.ms...
    "enable.auto.offset.store": False,  # ...but only of offsets we explicitly stored
    "auto.commit.interval.ms": 1000,
})
c.subscribe(["ledger-events"])          # 1 partition, 20 records txn-0..txn-19
done = 0
while done < 8:
    msg = c.poll(2.0)
    if msg is None or msg.error():
        continue
    # process(msg) -> write to the database here
    c.store_offsets(message=msg)        # mark as processed (stores msg.offset() + 1)
    done += 1
    if done == 5:
        c.commit(asynchronous=False)    # explicit sync commit of what has been stored
        print("sync-committed through", msg.offset())
committed = c.committed([TopicPartition("ledger-events", 0)], timeout=5)[0].offset
print(f"processed {done}, last processed offset {msg.offset()}, committed offset {committed}")
os._exit(0)                             # simulated crash: no close(), no final commit

A restarted consumer in the same group printed resumes at offset 5 value txn-5. Offsets 5–7 were processed twice, which is at-least-once by design, so the sink must tolerate duplicates.

Common mistakes:

  • Using auto-commit with asynchronous processing.
  • Committing msg.offset() instead of msg.offset() + 1 with low-level APIs.
  • Calling commitSync() after every record in a high-throughput consumer.
  • Never committing in the revoke callback.

Learn more: Kafka Consumers: Poll Loop, Offsets, Commits and Lag

In depth: What is at-least-once delivery and what problems can it create?

22. Replaying data: seek, offsets-for-times and kafka-consumer-groups --reset-offsets

Intermediate · Common · Consumers

To replay data, move the group’s saved offsets. Stop the consumers, then run kafka-consumer-groups.sh --reset-offsets, first with --dry-run, then with --execute. You can move to a time (--to-datetime), by a number of records (--shift-by), to the start (--to-earliest) or to an exact offset (--to-offset). Inside an application, you can seek() a partition, or turn a timestamp into an offset with offsets_for_times().

CLI reset options

Option Moves to
--to-earliest / --to-latest Log start or end
--to-datetime 2026-10-17T12:00:00.000 First offset with timestamp ≥ that time (UTC unless an offset is given)
--by-duration PT30M Now minus the duration
--shift-by -100 Current offset ± N, per partition
--to-offset 1234 That offset
--from-file plan.csv Per-partition values from a file

Scope it with --topic t (all partitions), --topic t:0,2 (some partitions) or --all-topics.

Rules

In-application seeking

  • consumer.offsets_for_times([TopicPartition(t, p, ts_ms)]) returns offsets, then seek() or assign() to them.
  • Seek inside on_assign to start every new assignment at a computed point.
  • Use a separate group ID for a one-off replay, so the production group’s position isn’t touched.

Is replay safe? Only if downstream is idempotent: upserts keyed by business ID, or deduplication by event ID. Otherwise a replay double-counts.

Example

# Runtime: Apache Kafka 4.3.1 CLI; group "reset-demo-earliest" is stopped
G=reset-demo-earliest
bin/kafka-consumer-groups.sh --bootstrap-server localhost:19092 --group $G --topic clicks \
  --reset-offsets --to-datetime "$(date -u -d '-30 min' +%Y-%m-%dT%H:%M:%S.000)" --dry-run
bin/kafka-consumer-groups.sh --bootstrap-server localhost:19092 --group $G --topic clicks:0 \
  --reset-offsets --shift-by -2 --execute

Common mistakes:

  • Resetting offsets while consumers are running (the tool refuses).
  • Replaying into a non-idempotent sink.
  • Forgetting that --to-datetime is interpreted as UTC unless an offset is given.

Learn more: Kafka Consumers: Poll Loop, Offsets, Commits and Lag

23. Consumer fetch tuning: fetch.min.bytes, fetch.max.wait.ms and partition fetch sizes

Intermediate · Occasional · Consumers

A fetch request waits on the broker until it has fetch.min.bytes of data or until fetch.max.wait.ms passes. It returns at most max.partition.fetch.bytes per partition and fetch.max.bytes in total. For bulk sinks, raise fetch.min.bytes to get fewer, bigger fetches. For low-latency consumers, keep it at 1, because on a quiet topic a high value just turns into waiting.

Setting (Java default) Effect Raise when Lower when
fetch.min.bytes (1) Broker holds the response until this much data is ready Bulk sinks; you want to cut broker request load Latency-sensitive consumers
fetch.max.wait.ms (500) Maximum the broker holds the request Paired with a big fetch.min.bytes You need a tight latency bound
max.partition.fetch.bytes (1 MiB) Per-partition cap per response Large records; few partitions Many partitions and limited memory
fetch.max.bytes (50 MiB) Per-response cap across partitions Very high throughput Memory pressure
max.poll.records (500) Records handed to the application per poll() Cheap per-record work Slow per-record work (see The consumer poll loop: what poll() does and why max.poll.interval.ms matters)

How they interact

  • The fetcher works ahead of the application. Java buffers completed fetches. librdkafka prefetches into a queue bounded by queued.max.messages.kbytes (64 MiB per client by default), which is a common cause of memory bloat when there are many partitions.
  • One record bigger than max.partition.fetch.bytes is still returned, so the consumer can’t get stuck. But memory must allow for it.
  • Cross-AZ costs: fetching from a follower in the same zone (client.rack, see Rack awareness and fetching from the closest replica) changes where bytes come from, not how many.

Rule of thumb profiles

  • Lake sink (S3/Iceberg writer): fetch.min.bytes=1 MB, fetch.max.wait.ms=500, larger max.poll.records.
  • Alerting or fraud: defaults or a lower fetch.max.wait.ms.

Example

# Runtime: Python 3.11, confluent-kafka 2.16, Apache Kafka 4.3
# A low-traffic topic (one record every 100 ms): how fetch.min.bytes changes end-to-end latency.
import statistics, threading, time
from confluent_kafka import Consumer, Producer

def measure(fetch_conf, n=30):
    c = Consumer({"bootstrap.servers": "localhost:19092", "group.id": f"lat-{time.time()}",
                  "auto.offset.reset": "latest", **fetch_conf})
    c.subscribe(["trickle"])
    while not c.assignment():
        c.poll(0.2)
    time.sleep(1)
    def produce():
        p = Producer({"bootstrap.servers": "localhost:19092", "linger.ms": 0})
        for _ in range(n):
            p.produce("trickle", value=str(time.time()).encode()); p.poll(0); time.sleep(0.1)
        p.flush()
    threading.Thread(target=produce).start()
    lat = []
    while len(lat) < n:
        m = c.poll(2)
        if m and not m.error():
            lat.append((time.time() - float(m.value())) * 1000)
    c.close()
    return f"median {statistics.median(lat):6.1f} ms, max {max(lat):6.1f} ms"

print("fetch.min.bytes=1 (default)            :", measure({}))
print("fetch.min.bytes=1MB, fetch.wait.max=500 :", measure({"fetch.min.bytes": 1048576, "fetch.wait.max.ms": 500}))

On a quiet topic the 1 MB threshold is never reached, so every fetch waits for the timeout. On a busy topic the same settings would cost almost nothing and save many requests. (librdkafka names the wait setting fetch.wait.max.ms; Java calls it fetch.max.wait.ms.)

Common mistakes:

  • Applying one consumer profile to every workload.
  • Confusing fetch.max.bytes with max.poll.records: one limits network responses, the other what poll() hands you.
  • Ignoring prefetch memory when one process consumes thousands of partitions.

24. Processing faster than one thread per partition: worker pools and ordering

Intermediate · Common · Consumers

The number of partitions caps how many consumers in a group can work in parallel. But inside one consumer, you can still hand records to a pool of worker threads. To keep the order per key, always send the same key to the same worker. Commit, per partition, only the lowest offset below which every record is finished. Use pause() and resume() to slow intake when workers fall behind, instead of letting queues grow without limit.

Options, from simple to complex

Approach Ordering Notes
More partitions + more consumers Per key Simplest, but changes key placement (see Can you change a topic’s partition count, and what breaks when you do?)
One consumer per thread, N threads in a process Per partition Same as scaling out; each thread has its own consumer
Consumer + worker pool routed by key Per key Higher parallelism than partitions; needs offset tracking
Consumer + unordered pool None Highest throughput; only for independent records
Share groups (see Share groups (Queues for Kafka): how do they differ from consumer groups?) None The broker does per-record dispatch and acknowledgement
Libraries such as Confluent Parallel Consumer (Java) Per key, per partition or none Handle offset tracking and retries for you

The offset problem. Workers finish out of order. If offsets 10–12 are done but 9 isn’t, committing 13 would lose 9 after a crash. Track finished offsets per partition and commit the contiguous high mark. This is what advance() does below.

Backpressure. When the work queues are full, call pause() on the assigned partitions but keep calling poll(), so the member stays in the group (see The consumer poll loop: what poll() does and why max.poll.interval.ms matters). resume() when the backlog drains.

Rebalances. On revoke, either wait for in-flight work on those partitions and commit, or drop it and accept reprocessing. Records still queued for a revoked partition must not be committed later by the old owner.

Example

# Runtime: Python 3.11, confluent-kafka 2.16, Apache Kafka 4.3
# One consumer, 8 worker threads. Per-key order is kept by routing each key to a fixed worker;
# offsets are committed only up to the lowest offset that is finished with no gaps before it.
import queue, threading, time, zlib
from collections import defaultdict
from confluent_kafka import Consumer, TopicPartition

N_WORKERS, MAX_QUEUED = 8, 200
queues = [queue.Queue() for _ in range(N_WORKERS)]
done = defaultdict(set)          # partition -> finished offsets not yet committed
lock = threading.Lock()
last_by_key = {}

def worker(q):
    while True:
        m = q.get()
        if m is None:
            return
        key, val = m.key().decode(), int(m.value())
        assert last_by_key.get(key, -1) < val, "per-key order violated"
        last_by_key[key] = val
        time.sleep(0.005)                        # pretend to call an API
        with lock:
            done[m.partition()].add(m.offset())

threads = [threading.Thread(target=worker, args=(q,)) for q in queues]
for t in threads: t.start()

c = Consumer({"bootstrap.servers": "localhost:19092", "group.id": "parallel-demo-2",
              "auto.offset.reset": "earliest", "enable.auto.commit": False})
c.subscribe(["events6"])
next_commit = {}                 # partition -> next offset we expect to commit from
paused, handled, idle = False, 0, 0

def advance():
    """Move each partition's commit point over contiguous finished offsets."""
    moved = []
    with lock:
        for p, nxt in next_commit.items():
            while nxt in done[p]:
                done[p].discard(nxt); nxt += 1
            if nxt != next_commit[p]:
                next_commit[p] = nxt
                moved.append(TopicPartition("events6", p, nxt))
    return moved

while idle < 6:
    m = c.poll(0.5)
    if m is not None and not m.error():
        idle = 0
        next_commit.setdefault(m.partition(), m.offset())
        queues[zlib.crc32(m.key()) % N_WORKERS].put(m)   # same key -> same worker
        handled += 1
    else:
        idle += 1
    backlog = sum(q.qsize() for q in queues)
    if backlog > MAX_QUEUED and not paused:
        c.pause(c.assignment()); paused = True           # keep polling, stop fetching
    elif backlog < MAX_QUEUED // 2 and paused:
        c.resume(c.assignment()); paused = False
    to_commit = advance()
    if to_commit:
        c.commit(offsets=to_commit, asynchronous=True)

for q in queues: q.put(None)
for t in threads: t.join()
advance()
c.commit(offsets=[TopicPartition("events6", p, o) for p, o in next_commit.items()], asynchronous=False)
print(f"handled {handled} records with {N_WORKERS} workers; committed:",
      {p: o for p, o in sorted(next_commit.items())})
c.close()

The committed offsets equal each partition’s log-end offset (kafka-get-offsets.sh printed events6:0:84 … events6:5:84), and the per-key order assertion never fired.

Common mistakes:

  • Committing the highest finished offset instead of the contiguous one.
  • Sharing one Java KafkaConsumer between threads.
  • Unbounded in-memory queues, which turn a slow sink into an out-of-memory crash.
  • Forgetting that a rebalance can hand a partition to someone else while its records sit in your queue.

25. Partition assignment strategies: range, round-robin, sticky and cooperative-sticky

Intermediate · Common · Consumer Groups

In the classic protocol, the group leader’s assignor decides who gets which partitions. Range gives each consumer a block of partitions per topic; it keeps the same partition numbers together across topics but can be uneven. Round-robin spreads everything evenly. Sticky is balanced and moves as few partitions as possible. Cooperative-sticky does the same but rebalances step by step, so consumers keep the partitions that are not moving while the group changes.

Assignor Balance Movement on change Rebalance style Notes
RangeAssignor Can be skewed with many topics High Eager Same partition numbers across co-partitioned topics go to one member
RoundRobinAssignor Even High Eager Breaks cross-topic co-location
StickyAssignor Even Minimal Eager Still stops everything during the rebalance
CooperativeStickyAssignor Even Minimal Incremental Two-phase: revoke only what moves, then assign it

Eager vs incremental. With eager assignors every member revokes everything, then receives a new assignment. With cooperative, only partitions that change owner are revoked, in a first round, and assigned in a follow-up round. Consumers keep processing the rest.

Defaults. Java’s default partition.assignment.strategy is [RangeAssignor, CooperativeStickyAssignor]. That lets a rolling upgrade move a group to cooperative by removing Range in a second roll. librdkafka defaults to range,roundrobin, so Python groups are eager unless you opt in. All members must support a common strategy.

Migrating to cooperative (classic protocol). Roll once with both [cooperative-sticky, range] listed, then roll again with only cooperative-sticky. Switching all at once with mixed members fails to agree on a protocol.

Where this is heading. With the KIP-848 protocol the broker computes assignments (uniform or range) and every rebalance is incremental (see The KIP-848 consumer group protocol: what changes with group.protocol=consumer?). Client-side assignors then don’t apply.

Example

# Runtime: Python 3.11, confluent-kafka 2.16, Apache Kafka 4.3 (classic group protocol)
# Two consumers, two topics with 3 partitions each: compare assignment strategies.
import time
from confluent_kafka import Consumer
from confluent_kafka.admin import AdminClient, NewTopic

admin = AdminClient({"bootstrap.servers": "localhost:19092"})
for f in admin.create_topics([NewTopic(t, 3) for t in ("ta", "tb")]).values():
    try: f.result()
    except Exception: pass               # already exists

def run(strategy):
    group = f"assign-{strategy}-{int(time.time())}"
    cs = [Consumer({"bootstrap.servers": "localhost:19092", "group.id": group,
                    "partition.assignment.strategy": strategy}) for _ in range(2)]
    for c in cs:
        c.subscribe(["ta", "tb"])
    end = time.time() + 12
    while time.time() < end:
        for c in cs:
            c.poll(0.2)
    for i, c in enumerate(cs):
        parts = sorted(f"{tp.topic}-{tp.partition}" for tp in c.assignment())
        print(f"{strategy:18} consumer{i}: {len(parts)} -> {parts}")
    for c in cs:
        c.close()

for s in ("range", "roundrobin", "cooperative-sticky"):
    run(s)

Range gave one member twice the work. The other two strategies balanced it 3/3.

Common mistakes:

  • Assuming Python and Java consumers share the same default assignor.
  • Switching every member to cooperative in a single deploy.
  • Using round-robin where a downstream process needs orders-3 and payments-3 on the same member.

In depth: What causes consumer group rebalances, and how do you reduce their impact?

26. How replication works: leaders, followers, the ISR and the high watermark

Intermediate · Very Common · Replication & Durability

Each partition has one leader that takes all writes. Followers copy from it by fetching, just like consumers do. Followers that keep up within replica.lag.time.max.ms (30 seconds) are the in-sync replicas (ISR). The high watermark is the highest offset that every ISR member has, and consumers only see records below it. Since Kafka 4.0, the high watermark also stops moving while the ISR is smaller than min.insync.replicas, whatever acks the producer used.

How acks, replication factor and min.insync.replicas combine into a durability choice is covered on this site’s durability page. This question is about the mechanism underneath.

Follower fetching. Followers send Fetch requests to the leader with their log-end offset. The leader learns how far each follower has got from these requests, and it returns its current high watermark (HW) in the response, so followers learn the HW too.

ISR membership. A follower drops out of the ISR if it hasn’t caught up to the leader’s log end within replica.lag.time.max.ms. A cleanly stopped broker is removed straight away. The leader asks the KRaft controller to shrink or expand the ISR, and the change is recorded in the metadata log.

The high watermark

  • HW = the minimum log-end offset across ISR members.
  • Consumers fetch only up to the HW, so they never see a record that could disappear in a leader failover.
  • “Strict min ISR” (KIP-966, Kafka 4.0+): if ISR size < min.insync.replicas, the HW stops. Even acks=1 writes are stored on the leader but stay invisible until enough replicas catch up. The run below shows this.

acks=all + min.insync.replicas=2 with replication factor 3

  • 3 in sync: writes succeed.
  • 2 in sync: writes still succeed (you can lose one broker).
  • 1 in sync: acks=all producers get NOT_ENOUGH_REPLICAS, retry, and finally time out. The partition is effectively read-only for them.

Leader epochs. Each leader change bumps an epoch. Followers use epoch boundaries to truncate divergent records after a failover, which replaced the older HW-based truncation and its edge cases.

Example

# Runtime: Apache Kafka 4.3.1 lab: 1 KRaft controller + 3 brokers (racks az-1..az-3) on one host; Python 3.11 + confluent-kafka 2.16
# send.py <acks> <value> produces one record to "ledger" with delivery.timeout.ms=8000 and prints the outcome
C=localhost:29091
kafka-topics.sh --bootstrap-server $C --create --topic ledger --replica-assignment 1:2:3 --config min.insync.replicas=2
python send.py all "deposit 100"
./stop.sh 3; python send.py all "deposit 50"
./stop.sh 2; python send.py all "withdraw 30"; python send.py 1 "withdraw 20"
kafka-get-offsets.sh --bootstrap-server $C --topic ledger      # shows the high watermark
./start.sh 2 3                                                  # bring the followers back

With one replica in sync, the acks=all write was refused (retried until the 8-second budget ran out). The acks=1 write was accepted, but stayed invisible (HW 2) until the followers rejoined and the HW moved to 3. Broker 2 also appeared in the ELR (see Unclean leader election and Eligible Leader Replicas (ELR)).

Learn more: Kafka Replication: Leaders, ISR, min.insync.replicas and KRaft

In depth: How do acks, replication factor and min.insync.replicas decide Kafka durability?

27. How Kafka stores a partition on disk: segments, indexes and deletion

Intermediate · Common · Storage & Retention

A partition is a folder of segment files. Each segment has a .log file of record batches, an .index file (offset to file position) and a .timeindex file (timestamp to offset), all named after the segment’s first offset. New records are only written to the newest, active segment. Retention and compaction work on whole closed segments, so Kafka deletes data one segment at a time, never one record at a time.

Files in <log.dirs>/<topic>-<partition>/

File Purpose
00000000000000006666.log Record batches starting at offset 6666
.index Sparse map offset → byte position, one entry per index.interval.bytes (4 KiB)
.timeindex Sparse map timestamp → offset, used by offsets_for_times and time-based resets
.snapshot Producer-state snapshot, used for idempotence and transactions after restart
leader-epoch-checkpoint Epoch → start offset, used for truncation after failover
partition.metadata Topic ID

Rolling. The active segment closes (“rolls”) when it reaches segment.bytes (1 GiB) or segment.ms (7 days) old, or when its index fills up. The output below shows the index pre-allocated at 10 MB for the active segment and trimmed when the segment rolls.

Why segments matter in interviews

  • Retention lags. A segment is deleted only when it’s closed and wholly past retention.ms (judged by its largest timestamp), or when deleting it would still leave the partition at or above retention.bytes. On a low-traffic topic with 1 GiB segments, a “7-day” topic can keep months of data, because the active segment never rolls by size. Lower segment.ms for those topics.
  • Retention is checked periodically, every log.retention.check.interval.ms (5 minutes), and files are removed after file.delete.delay.ms.
  • Compaction never touches the active segment (see Kafka retention vs log compaction).
  • Reads are cheap: a fetch binary-searches the sparse index, then streams bytes straight from the page cache to the socket (zero-copy).
  • Many partitions mean many open files and mapped indexes per broker, which is one reason partition counts have practical limits (see the partition-count page).

Example

# Runtime: Apache Kafka 4.3.1, single broker; topic created with --config segment.bytes=1048576
bin/kafka-producer-perf-test.sh --bootstrap-server localhost:19092 --topic segdemo \
  --num-records 20000 --throughput -1 --payload-file payload.jsonl --command-property linger.ms=10
ls -l data/segdemo-0/ | awk '{print $5, $9}'
bin/kafka-dump-log.sh --files data/segdemo-0/00000000000000000000.log | head -4
bin/kafka-dump-log.sh --files data/segdemo-0/00000000000000000000.index | head -4

Common mistakes:

  • Believing retention deletes individual records the moment they expire.
  • Forgetting that the active segment is never deleted or compacted.
  • Setting tiny segment.bytes cluster-wide, which creates huge numbers of files.

Learn more: Kafka Log Storage: Segments, Retention, Compaction and Topic Configuration

In depth: How do you choose retention and size disk for a Kafka topic?

28. Record timestamps: CreateTime vs LogAppendTime, and how they affect retention and replay

Intermediate · Occasional · Storage & Retention

Every record has a timestamp. With message.timestamp.type=CreateTime, the default, it is whatever the producer set. With LogAppendTime, the broker replaces it with its own clock. Time-based retention, offsets_for_times, --to-datetime resets and stream windows all use this value. So a producer with a wrong clock, or replaying old historical data, can make records expire too early or be rejected by the broker.

CreateTime LogAppendTime
Who sets it Producer (default: send time; can be the event time) Broker at append
Meaning Event time, if the producer sets it carefully Ingestion time
Validation Rejected if more than message.timestamp.after.max.ms (1 h) in the future or more than message.timestamp.before.max.ms (unlimited by default) in the past None; validation settings are ignored
Good for Stream processing on event time Retention and replay by arrival time, audit

How timestamps reach retention. A segment is eligible for time-based deletion when its largest timestamp is older than retention.ms. So:

  • Backfilling year-old events with CreateTime makes their segments eligible almost as soon as they roll. They may vanish within minutes.
  • One record with a far-future timestamp would keep its segment alive. That’s one reason Kafka 4.0 changed the default message.timestamp.after.max.ms from unlimited to 1 hour (KIP-1030). The before/after settings themselves arrived in 3.6 (KIP-937).

Batch-level rejection. Timestamp validation happens per batch. If one record in a batch is out of range, the whole batch fails with INVALID_TIMESTAMP, including valid records that happened to share it. The first run of the demo below batched both test records together, and both were rejected.

Stream processing. Kafka Streams and Flink extract event time from the record timestamp by default (see Windowing in Kafka Streams: tumbling, hopping, sliding, session windows and grace and Event time vs processing time vs ingestion time). If producers use LogAppendTime, windows reflect arrival time, not when things happened. Pick deliberately, and carry the business event time in the payload as well.

Example

# Runtime: Apache Kafka 4.3.1 CLI
bin/kafka-topics.sh --bootstrap-server localhost:19092 --create --topic ts-create --partitions 1
bin/kafka-topics.sh --bootstrap-server localhost:19092 --create --topic ts-append --partitions 1 \
  --config message.timestamp.type=LogAppendTime

(Run at 2026-10-17 18:59 UTC.) The CreateTime topic kept the producer’s timestamp and rejected the future one. The LogAppendTime topic accepted both and replaced their timestamps with the append time.

Common mistakes:

  • Assuming retention is measured from when the broker received the record.
  • Backfilling historical events into a short-retention CreateTime topic.
  • Not knowing that a single bad timestamp fails its whole batch.

Learn more: Kafka Log Storage: Segments, Retention, Compaction and Topic Configuration

29. Converters vs SMTs vs serializers in Kafka Connect

Intermediate · Common · Kafka Connect

Connectors work with Connect’s own record format (a schema plus a struct). Converters turn that format into bytes on the way into Kafka, and back on the way out: JSON, Avro, Protobuf, String or ByteArray. Single Message Transforms (SMTs) change one record at a time: rename a field, mask a value, change the topic or add a field. Both are set in configuration. The converter must match how the topic was really written, or the sink cannot read it.

Order on a source connector: connector → SMTs → converter → producer → Kafka. On a sink it’s the reverse: Kafka → consumer → converter → SMTs → connector.

Common converters

Converter Notes
JsonConverter schemas.enable=true embeds a schema in every message (bulky); false gives plain JSON with no types
AvroConverter / ProtobufConverter / JsonSchemaConverter Need a Schema Registry; compact and typed (see Schema Registry under the hood: wire format, schema IDs and subject naming strategies)
StringConverter / ByteArrayConverter Pass-through; good for keys or opaque payloads

Set them per worker (key.converter, value.converter) and override per connector. Key and value converters can differ: a String key with an Avro value is common.

Useful built-in SMTs (Apache Kafka): InsertField, ReplaceField (include, exclude, rename), MaskField, Cast, ExtractField, HoistField, ValueToKey, TimestampRouter, RegexRouter, Filter with predicates, HeaderFrom, InsertHeader, DropHeaders, TimestampConverter, Flatten. Debezium adds ExtractNewRecordState and the outbox router (see Debezium change events: the envelope, tombstones and flattening with ExtractNewRecordState).

When not to use SMTs. SMTs are stateless and per record. Joins, aggregations, lookups and anything needing state belong in Kafka Streams or Flink. Long SMT chains are hard to test and to version.

Predicates let an SMT apply conditionally, for example only to tombstones or to topics matching a pattern.

Example

Source connector: wrap each log line, add a field, then route to a daily topic.

{
  "connector.class": "org.apache.kafka.connect.file.FileStreamSourceConnector",
  "tasks.max": "1",
  "file": "/var/log/web/access.log",
  "topic": "web-access",
  "value.converter": "org.apache.kafka.connect.json.JsonConverter",
  "value.converter.schemas.enable": "false",
  "transforms": "wrap,addSource,route",
  "transforms.wrap.type": "org.apache.kafka.connect.transforms.HoistField$Value",
  "transforms.wrap.field": "line",
  "transforms.addSource.type": "org.apache.kafka.connect.transforms.InsertField$Value",
  "transforms.addSource.static.field": "source_host",
  "transforms.addSource.static.value": "web-01",
  "transforms.route.type": "org.apache.kafka.connect.transforms.TimestampRouter",
  "transforms.route.topic.format": "${topic}-${timestamp}",
  "transforms.route.timestamp.format": "yyyyMMdd"
}

TimestampRouter renamed web-access to web-access-20261017. HoistField turned the raw string into a struct, so InsertField had a struct to add source_host to. The two would fail the other way round.

Common mistakes:

  • Mixing up converters (Connect) with serializers (plain producers and consumers).
  • Leaving schemas.enable=true on, then wondering why every JSON message has a schema envelope.
  • Building business logic as a chain of ten SMTs.
  • Ordering SMTs wrongly (they run in the listed order).

Learn more: Kafka Connect and Debezium CDC

30. Error handling in Kafka Connect: errors.tolerance and dead letter queues

Intermediate · Common · Kafka Connect

By default (errors.tolerance=none), one bad record fails the task, and the pipeline stops until someone fixes it. With errors.tolerance=all, records that fail in conversion or transforms are skipped. For sink connectors, you can send those records to a dead letter queue topic, with headers that describe the error. Note that Connect’s DLQ only covers converter and SMT failures; errors inside the connector’s own write (such as a database constraint) are handled by the connector or fail the task.

Handling poison messages in general is on this site’s poison-messages page and in Q39. This question covers Connect’s built-in features.

Settings (per connector)

Setting Default Meaning
errors.tolerance none all skips bad records instead of failing
errors.retry.timeout 0 How long to retry retriable failures; -1 retries forever
errors.retry.delay.max.ms 60000 Backoff cap between retries
errors.log.enable, errors.log.include.messages false Log failures, optionally with the record content
errors.deadletterqueue.topic.name (none) Sink only: where failed records go
errors.deadletterqueue.context.headers.enable false Adds __connect.errors.* headers: topic, partition, offset, stage, exception
errors.deadletterqueue.topic.replication.factor 3 Lower it for small labs

What the DLQ catches. Failures in the key/value/header converter and in transforms. Since KIP-610, a sink connector may also report records with the ErrantRecordReporter, so a JDBC sink can route a row that hits a constraint violation. Whether it does depends on the connector.

Sources have no DLQ. A source connector produces records; if conversion fails, errors.tolerance=all skips and logs them.

Operating a DLQ

  • Alert on DLQ growth. A DLQ nobody reads is silent data loss.
  • Keep the original bytes (Connect writes the raw record) so a fixed pipeline can replay it.
  • Replay with a small consumer or a second connector after fixing the cause.

Example

{
  "connector.class": "org.apache.kafka.connect.file.FileStreamSinkConnector",
  "tasks.max": "1",
  "topics": "customers",
  "file": "/data/out/customers.out",
  "value.converter": "org.apache.kafka.connect.json.JsonConverter",
  "value.converter.schemas.enable": "false",
  "transforms": "mask,drop",
  "transforms.mask.type": "org.apache.kafka.connect.transforms.MaskField$Value",
  "transforms.mask.fields": "email",
  "transforms.drop.type": "org.apache.kafka.connect.transforms.ReplaceField$Value",
  "transforms.drop.exclude": "internal_note",
  "errors.tolerance": "all",
  "errors.retry.timeout": "0",
  "errors.log.enable": "true",
  "errors.deadletterqueue.topic.name": "dlq.customers-sink",
  "errors.deadletterqueue.topic.replication.factor": "1",
  "errors.deadletterqueue.context.headers.enable": "true"
}

(Header output reformatted one per line.) The task stayed RUNNING, the good records were written with email masked and internal_note dropped, and the poison record landed in the DLQ with its source offset.

Common mistakes:

  • Setting errors.tolerance=all without a DLQ or logging, which silently drops data.
  • Expecting a DLQ on a source connector.
  • Assuming every sink-side failure (like a database outage) goes to the DLQ; retriable errors are retried, and connector-level errors may fail the task.

Learn more: Kafka Connect and Debezium CDC

In depth: How do you handle poison messages and dead-letter topics in Kafka?

31. Debezium snapshots, incremental snapshots and replication-slot risks

Intermediate · Common · CDC with Debezium

When Debezium starts for the first time, it usually takes a snapshot: it reads the existing rows as op=r events, then switches to streaming changes from the transaction log. Incremental snapshots, started with a signal, re-read tables in chunks while streaming carries on, so you can backfill or add a table without stopping. The main risk is on the database side: an idle or slow Postgres replication slot keeps WAL on the database until the disk fills up.

The end-to-end CDC design is covered in Design a log-based CDC pipeline with Debezium and Kafka and on the Debezium page. This question is about running it.

snapshot.mode (Postgres connector, Debezium 3.x)

Mode Behaviour
initial (default) Snapshot if no offsets exist, then stream
initial_only Snapshot, then stop
no_data Skip existing rows; stream from now (formerly never)
when_needed Snapshot again if stored offsets are no longer available in the log
always Snapshot on every start
configuration_based / custom Fine-grained or pluggable control

Incremental snapshots (a watermark-based design)

  • Configure a signalling table (signal.data.collection) or a Kafka signal topic.
  • Insert an execute-snapshot signal. Debezium reads the table in primary-key chunks (incremental.snapshot.chunk.size, 1024) and interleaves them with live changes, so a row being updated isn’t overwritten by a stale snapshot read.
  • Events carry op=r with source.snapshot="incremental".
  • Use them to add a table to table.include.list, to repair a downstream sink, or to backfill after a long outage.

Replication slot hazards (Postgres)

  • The slot keeps WAL until Debezium confirms it. A stopped connector means WAL grows without limit.
  • Even an active slot can lag when the captured tables are quiet but the database is busy. Set heartbeat.interval.ms (default 0, off), and possibly a heartbeat.action.query, so offsets advance.
  • Guard rails: monitor pg_replication_slots lag, set Postgres max_slot_wal_keep_size, and drop slots of retired connectors.
  • On failover to a replica, the slot must exist there (Postgres 17+ failover slots, or recreate it and re-snapshot).

Example

{
  "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
  "database.hostname": "localhost",
  "database.port": "5498",
  "database.user": "postgres",
  "database.password": "postgres",
  "database.dbname": "shop",
  "topic.prefix": "shop",
  "plugin.name": "pgoutput",
  "slot.name": "shop_cdc",
  "publication.autocreate.mode": "filtered",
  "table.include.list": "public.customers",
  "snapshot.mode": "initial",
  "signal.data.collection": "public.debezium_signal",
  "key.converter": "org.apache.kafka.connect.json.JsonConverter",
  "key.converter.schemas.enable": "false",
  "value.converter": "org.apache.kafka.connect.json.JsonConverter",
  "value.converter.schemas.enable": "false",
  "tasks.max": "1"
}

Events on shop.public.customers, summarised (initial snapshot, live changes, then the incremental snapshot):

The slot showed 273 kB of lag although active, because nothing in the captured table had changed recently. That is what heartbeats are for.

Learn more: Kafka Connect and Debezium CDC

In depth: How would you stream database changes into Kafka with Debezium?

32. Debezium change events: the envelope, tombstones and flattening with ExtractNewRecordState

Intermediate · Common · CDC with Debezium

Each Debezium event has before, after, op (c for create, u update, d delete, r read), source details (log position, transaction ID, time, table) and ts_ms, and its key is the row’s primary key. A delete is sent as a d event followed by a tombstone (a null value), so compacted topics can drop the key. Most sinks just want the row itself, which the ExtractNewRecordState SMT gives you, optionally adding __op and a __deleted flag.

Envelope fields

Field Meaning
before Row before the change (nulls unless REPLICA IDENTITY FULL or the key-only default)
after Row after the change (null for deletes)
op c create, u update, d delete, r snapshot read, t truncate, m message
source Connector, database, schema, table, lsn, txId, snapshot, source timestamp
ts_ms / ts_us When Debezium processed the event

Keys and ordering. The record key is the primary key, so all changes to one row go to one partition in order (see What ordering guarantees does Kafka provide?). Downstream “latest wins” logic should compare source.lsn (or a similar position), not arrival order (see Design a log-based CDC pipeline with Debezium and Kafka).

Deletes

  • d event: the consumer learns what was deleted.
  • Tombstone: lets log compaction remove the key (see Kafka retention vs log compaction). Controlled by tombstones.on.delete (default true).

Flattening with ExtractNewRecordState

  • Emits only after, which is what JDBC, Elasticsearch or lake sinks expect.
  • add.fields=op,source.ts_ms copies metadata in as __op and __source_ts_ms.
  • delete.tombstone.handling.mode: tombstone (keep tombstones), drop, rewrite (a delete becomes the last known row with __deleted=true), rewrite-with-tombstone, or delete-to-tombstone (the delete becomes just a tombstone).

Outbox pattern. For domain events (not raw table changes), services write to an outbox table in the same transaction as their state change, and Debezium’s EventRouter SMT routes each row to a topic. This avoids dual writes and keeps internal table schemas private.

Example

{
  "topic.prefix": "shopflat",
  "slot.name": "shop_flat",
  "publication.name": "shop_flat_pub",
  "transforms": "unwrap",
  "transforms.unwrap.type": "io.debezium.transforms.ExtractNewRecordState",
  "transforms.unwrap.add.fields": "op,source.ts_ms",
  "transforms.unwrap.delete.tombstone.handling.mode": "rewrite"
}

(Added to the connector config shown in Q502.) After UPDATE customers SET tier='gold' WHERE id=3; DELETE FROM customers WHERE id=1;:

Compare the raw envelope in Q502, where the delete was a d event (after=null) followed by a null tombstone for key {"id":2}.

Learn more: Kafka Connect and Debezium CDC

33. Schema Registry under the hood: wire format, schema IDs and subject naming strategies

Intermediate · Common · Schema Registry

A registry-aware serializer registers, or looks up, the schema under a subject and gets a global schema ID. It then writes a magic byte 0, the 4-byte schema ID, and the encoded data (Protobuf adds message indexes). The consumer reads the ID, fetches and caches the schema, and decodes. The subject naming strategy decides what a subject is: one per topic (the default), one per record type, or one per topic and record type. That decides where the compatibility rules apply.

Compatibility modes and safe evolution are covered in What is a schema registry, and what are compatibility modes? and on this site’s schema-evolution page. This question is about the mechanics.

Flow

  1. The producer’s serializer derives the subject, for example orders-value.
  2. With auto.register.schemas=true it registers the schema if it’s new. The registry checks compatibility against earlier versions of that subject and returns the ID.
  3. Each record carries only the 5-byte header plus the body, not the schema.
  4. The consumer’s deserializer fetches the schema by ID once, caches it, and decodes. With Avro it can also resolve to a reader schema (specific.avro.reader or a generated class).

Subject naming strategies

Strategy Subject Use when
TopicNameStrategy (default) <topic>-key, <topic>-value One event type per topic
RecordNameStrategy <fully.qualified.RecordName> Same type in many topics, evolving together
TopicRecordNameStrategy <topic>-<RecordName> Several event types in one topic (to keep per-entity ordering)

Production settings

  • Set auto.register.schemas=false in production producers and register schemas from CI. Use use.latest.version=true or explicit IDs, so a stray build can’t register a schema nobody reviewed.
  • Use schema references (Avro, Protobuf, JSON Schema) for shared types such as Money, instead of copying them into every schema.
  • Registries can enforce rules at registration time: data contracts with metadata and validation rules in Confluent’s registry, and similar features elsewhere.

Some managed services (AWS Glue Schema Registry, Azure Schema Registry) use their own header formats. Clients must use the matching serializer.

Example

# Runtime: Python 3.11, fastavro 1.12 (no registry needed: this builds and parses the wire format by hand)
# Confluent Schema Registry framing: [magic byte 0][4-byte big-endian schema ID][Avro binary body]
import io, struct
from fastavro import parse_schema, schemaless_writer, schemaless_reader

order_v1 = parse_schema({
    "type": "record", "name": "OrderPlaced", "namespace": "shop.orders",
    "fields": [{"name": "order_id", "type": "string"},
               {"name": "amount_cents", "type": "long"}]})

def encode(schema_id, schema, record):
    buf = io.BytesIO()
    buf.write(struct.pack(">bI", 0, schema_id))   # what the serializer prepends
    schemaless_writer(buf, schema, record)
    return buf.getvalue()

def decode(payload, registry):
    magic, schema_id = struct.unpack(">bI", payload[:5])
    assert magic == 0, "not Schema Registry framed"
    return schema_id, schemaless_reader(io.BytesIO(payload[5:]), registry[schema_id])

msg = encode(42, order_v1, {"order_id": "o-1001", "amount_cents": 2599})
print("bytes:", msg.hex(" "))
print("size :", len(msg), "bytes vs JSON", len('{"order_id": "o-1001", "amount_cents": 2599}'))
print("decoded:", decode(msg, {42: order_v1}))

# A v2 reader schema with a new optional field can still read v1 bytes (backward compatible)
order_v2 = parse_schema({**order_v1, "fields": order_v1["fields"] + [
    {"name": "coupon", "type": ["null", "string"], "default": None}]})
body = io.BytesIO(msg[5:])
print("read with v2:", schemaless_reader(body, order_v1, order_v2))

Byte 0 is the magic byte and bytes 1–4 are schema ID 42 (00 00 00 2a). The rest is Avro: a zig-zag length prefix for the string, then the zig-zag varint for 2599. With the real client, confluent_kafka.schema_registry.avro.AvroSerializer writes exactly this framing after talking to the registry. This demo builds it by hand, so it runs without a registry server.

Learn more: Kafka Schema Registry and Schema Evolution: Compatibility Modes

In depth: How do you evolve Kafka message schemas safely with a Schema Registry?

34. Windowing in Kafka Streams: tumbling, hopping, sliding, session windows and grace

Intermediate · Common · Kafka Streams

Windowed aggregations group records by event time. Tumbling windows are fixed and do not overlap. Hopping windows are fixed and overlap. Sliding windows are defined by the time between records. Session windows group activity separated by a quiet gap. A grace period keeps a window open for late records after it ends; records later than that are dropped. By default, Streams sends an updated result for every record; suppress(untilWindowCloses) sends one final result per window.

Window API Example question
Tumbling TimeWindows.ofSizeAndGrace(5 min, 2 min) Orders per 5 minutes
Hopping TimeWindows…advanceBy(1 min) 5-minute moving count updated every minute
Sliding SlidingWindows.ofTimeDifferenceAndGrace(…) Any 10 minutes containing 3 failed logins
Session SessionWindows.ofInactivityGapAndGrace(30 min, …) User sessions (see Sessionise events with a 30-minute inactivity gap for the SQL version)

Stream time. Streams tracks the highest timestamp seen per partition. A window closes when stream time passes window end + grace, not when wall-clock time does. A quiet partition never advances stream time, so its last windows don’t close until new data arrives. That’s a classic surprise in tests and at low volume.

Grace. Kafka 3.0 deprecated the old implicit 24-hour grace. You now choose with ofSizeAndGrace or ofSizeWithNoGrace. Larger grace means more late data accepted, but more state and later final results.

Emission

  • Default: an update downstream for every input (reduced by the record cache).
  • suppress(Suppressed.untilWindowCloses(…)): one result per window, which suits alerts and sinks that can’t take updates. The buffer must fit in memory, or set a bound with a policy.
  • Kafka 3.3+ also has emitStrategy(EmitStrategy.onWindowClose()) on windowed aggregations.

Late records past grace are dropped and counted in the dropped-records-total metric. Alert on it.

Example

// Runtime: Java 21, Apache Kafka Streams 4.3.1 + kafka-streams-test-utils (TopologyTestDriver, no broker)
import java.time.*;
import java.util.Properties;
import org.apache.kafka.common.serialization.*;
import org.apache.kafka.streams.*;
import org.apache.kafka.streams.kstream.*;

public class Windows {
    public static void main(String[] args) {
        var s = Serdes.String();
        StreamsBuilder b = new StreamsBuilder();
        b.stream("clicks", Consumed.with(s, s))                                    // key = page
         .groupByKey()
         .windowedBy(TimeWindows.ofSizeAndGrace(Duration.ofMinutes(5), Duration.ofMinutes(2)))
         .count()
         .suppress(Suppressed.untilWindowCloses(Suppressed.BufferConfig.unbounded()))  // one final result per window
         .toStream((w, n) -> w.key() + "@" + w.window().startTime().toString().substring(11, 16))
         .to("clicks-per-5min", Produced.with(s, Serdes.Long()));

        Properties p = new Properties();
        p.put(StreamsConfig.APPLICATION_ID_CONFIG, "windows-demo");
        p.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "dummy:9092");
        try (TopologyTestDriver d = new TopologyTestDriver(b.build(), p)) {
            var in = d.createInputTopic("clicks", new StringSerializer(), new StringSerializer());
            var out = d.createOutputTopic("clicks-per-5min", new StringDeserializer(), new LongDeserializer());
            Instant t = Instant.parse("2026-10-17T09:00:00Z");
            String[][] events = {          // {event-time offset in seconds, label}
                {"30", "on time"}, {"200", "on time"}, {"290", "on time"},
                {"330", "next window"},
                {"280", "late but within grace (stream time 09:05:30)"},
                {"430", "advances stream time to 09:07:10 -> 09:00 window closes"},
                {"100", "too late: 09:00 window already closed"},
                {"900", "advances stream time, closes 09:05 window"}};
            for (String[] e : events) {
                in.pipeInput("/home", e[1], t.plusSeconds(Long.parseLong(e[0])));
                System.out.printf("event at %s (%s) -> emitted %s%n",
                    t.plusSeconds(Long.parseLong(e[0])).toString().substring(11, 19), e[1], out.readKeyValuesToList());
            }
            System.out.println("dropped late records: " + d.metrics().entrySet().stream()
                .filter(m -> m.getKey().name().equals("dropped-records-total"))
                .mapToDouble(m -> (Double) m.getValue().metricValue()).sum());
        }
    }
}

The 09:00 window counted four records, including the late 09:04:40 one that arrived within grace. It was emitted only once stream time passed 09:07 (end plus 2 minutes of grace). The 09:01:40 record came after that and was dropped.

Common mistakes:

  • Expecting windows to close on wall-clock time.
  • Using suppress with an unbounded buffer on high-cardinality keys.
  • Not handling dropped late records, which fails silently.
  • Mixing up hopping windows (fixed grid) and sliding windows (record-driven).

Learn more: Kafka Streams Basics: KStream, KTable, Windows, Joins and State

35. State stores, changelog topics and restoring state in Kafka Streams

Intermediate · Common · Kafka Streams

Operations that need memory of past records, such as aggregations, joins and windows, keep that memory in local state stores (RocksDB by default). Every change to a store is also written to a compacted changelog topic named <application.id>-<store>-changelog. If an instance dies or loses its disk, the instance that takes over the task rebuilds the store by replaying that changelog. Standby replicas keep ready copies on other instances, so recovery is much faster. You can also read a store directly from your app with interactive queries.

What gets created (shown by Topology.describe() and the topic list below)

  • One store per stateful operator, partitioned like its input: task N owns partition N of the store.
  • A changelog topic per store, with cleanup.policy=compact, plus compact,delete for windowed stores so expired windows age out.
  • Repartition topics (<app>-<name>-repartition) whenever you re-key before a stateful step.

Restoration

  1. A task is assigned to an instance.
  2. If the local RocksDB checkpoint is current, it resumes almost at once.
  3. Otherwise it replays the changelog from the checkpointed offset, or from the start. For large stores that can take minutes to hours, and the task doesn’t process during that time.

Reducing downtime

  • num.standby.replicas=1 or more: another instance keeps a shadow copy by consuming the changelog.
  • Warm-up replicas (KIP-441): the assignor moves a task only once a new owner has caught up to within acceptable.recovery.lag (10,000 records). max.warmup.replicas (2) limits how many are in flight.
  • Keep state.dir on a persistent volume (a StatefulSet on Kubernetes), so restarts don’t replay from scratch.
  • Static membership, or the new Streams rebalance protocol (KIP-1071, group.protocol=streams, production-ready since 4.2), reduces needless task movement.

Exactly-once. With processing.guarantee=exactly_once_v2, changelog writes, output records and input offsets commit in one transaction (see Write a transactional consume-transform-produce loop). Commit interval drops to 100 ms by default.

Interactive queries. KafkaStreams.store(…) reads the local store. For keys held on other instances, use queryMetadataForKey to find the right host and call it over your own RPC layer.

Example

// Runtime: Java 21, Apache Kafka Streams 4.3.1 against a real broker (localhost:19092)
import java.time.Duration;
import java.util.Properties;
import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.*;
import org.apache.kafka.streams.*;
import org.apache.kafka.streams.kstream.*;
import org.apache.kafka.streams.state.*;

public class StateStores {
    public static void main(String[] args) throws Exception {
        var s = Serdes.String();
        StreamsBuilder b = new StreamsBuilder();
        b.stream("page-views", Consumed.with(s, s))                      // key = user, value = country
         .selectKey((user, country) -> country)                          // re-key -> repartition topic
         .groupByKey(Grouped.with("by-country", s, s))
         .count(Materialized.<String, Long, KeyValueStore<org.apache.kafka.common.utils.Bytes, byte[]>>as("views-by-country")
                .withKeySerde(s).withValueSerde(Serdes.Long()));

        Properties p = new Properties();
        p.put(StreamsConfig.APPLICATION_ID_CONFIG, "country-views");
        p.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:19092");
        p.put(StreamsConfig.STATE_DIR_CONFIG, "/tmp/claude-0/-home-user/2fbb010b-4216-53a7-9bcb-97b9a1ca7ff7/scratchpad/kbank/streams-state");
        p.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, StreamsConfig.EXACTLY_ONCE_V2);
        p.put(StreamsConfig.NUM_STANDBY_REPLICAS_CONFIG, 1);
        p.put(StreamsConfig.REPLICATION_FACTOR_CONFIG, 1);               // single-broker lab only

        Topology t = b.build();
        System.out.println(t.describe());
        try (KafkaStreams app = new KafkaStreams(t, p)) {
            app.start();
            try (var prod = new KafkaProducer<String, String>(Properties.class.cast(new Properties() {{
                    put("bootstrap.servers", "localhost:19092");
                    put("key.serializer", StringSerializer.class.getName());
                    put("value.serializer", StringSerializer.class.getName()); }}))) {
                String[][] views = {{"u1", "IN"}, {"u2", "US"}, {"u3", "IN"}, {"u4", "DE"}, {"u5", "IN"}};
                for (String[] v : views) prod.send(new ProducerRecord<>("page-views", v[0], v[1]));
            }
            ReadOnlyKeyValueStore<String, Long> store = null;
            for (int i = 0; i < 60; i++) {                                   // wait for RUNNING + data
                Thread.sleep(500);
                if (app.state() != KafkaStreams.State.RUNNING) continue;
                store = app.store(StoreQueryParameters.fromNameAndType("views-by-country", QueryableStoreTypes.keyValueStore()));
                Long in = store.get("IN");
                if (in != null && in == 3 && store.get("US") != null && store.get("DE") != null) break;
            }
            System.out.println("interactive query: IN=" + store.get("IN") + " US=" + store.get("US") + " DE=" + store.get("DE"));
        }
    }
}

Run against the single lab broker, then again after deleting the local state.dir (the second run produced the same five page views again):

The local RocksDB files were gone, yet the counts continued from the first run’s totals (IN 3 → 6). The store had been rebuilt from its changelog before the new records were counted.

Learn more: Kafka Streams Basics: KStream, KTable, Windows, Joins and State

36. Log compaction in practice: settings, tombstones and how long deletes take

Intermediate · Very Common · Storage

With cleanup.policy=compact, Kafka keeps at least the latest record for each key and removes older ones in the background. To delete a key, you send a tombstone: a record with that key and a null value. The tombstone itself is removed later, after delete.retention.ms. Compaction never touches the active segment, so how quickly old values disappear depends on segment.ms, min.cleanable.dirty.ratio and min.compaction.lag.ms. Offsets never change; compaction only leaves gaps.

Compaction turns a topic into “the latest value per key”, which is what changelogs, CDC topics and lookup tables need (see Kafka retention vs log compaction for when to use it).

How the cleaner works. A partition is split into the active segment (being written) and closed segments. The log cleaner threads pick the partition with the highest share of “dirty” (not yet cleaned) data, build a map of the latest offset per key, and rewrite closed segments without the older records.

Settings that decide timing

Setting What it controls
segment.ms / segment.bytes When the active segment closes. Until then, its records cannot be compacted.
min.cleanable.dirty.ratio (default 0.5) How much dirty data a partition needs before the cleaner picks it.
min.compaction.lag.ms Minimum age before a record may be compacted, so consumers can still see recent updates.
max.compaction.lag.ms Maximum time a record can stay uncompacted, which forces cleaning on quiet topics.
delete.retention.ms (default 1 day) How long a tombstone stays after cleaning, so slow consumers still see the delete.

compact,delete. Both policies together keep the latest value per key, but also delete anything older than retention.ms. Use this when you want a table that also forgets keys that have not changed for a long time.

What stays the same. Offsets are never renumbered, record order is kept, and a consumer reading from the start always ends with the correct latest value for every key it sees.

Example

# Runtime: Apache Kafka 4.3.1, 3 brokers on localhost. Tiny segment and ratio settings so compaction runs within seconds.
kafka-topics.sh --bootstrap-server localhost:19092 --create --topic customer-profile \
  --partitions 1 --replication-factor 3 \
  --config cleanup.policy=compact --config segment.ms=2000 \
  --config min.cleanable.dirty.ratio=0.01 --config delete.retention.ms=1000

# five updates, then a tombstone for c2 (the console producer turns the NULL marker into a null value)
printf 'c1:{"tier":"bronze"}\nc2:{"tier":"silver"}\nc1:{"tier":"silver"}\nc3:{"tier":"gold"}\nc1:{"tier":"gold"}\n' |
  kafka-console-producer.sh --bootstrap-server localhost:19092 --topic customer-profile \
    --reader-property parse.key=true --reader-property key.separator=:
printf 'c2:NULL\n' | kafka-console-producer.sh --bootstrap-server localhost:19092 --topic customer-profile \
    --reader-property parse.key=true --reader-property key.separator=: --reader-property null.marker=NULL

kafka-console-consumer.sh --bootstrap-server localhost:19092 --topic customer-profile --from-beginning \
  --formatter-property print.key=true --formatter-property print.offset=true --timeout-ms 5000

First read, a few seconds after the writes. The older values of c1 (offsets 0 and 2) are already gone, and the tombstone for c2 is still there:

After three more records for new keys (c4, c5, c6) and about a minute of cleaning, the tombstone and the old c2 value have both been removed:

kafka-get-offsets.sh still reports customer-profile:0:9: the end offset did not move, and the removed offsets are simply gaps.

Learn more: Kafka Log Storage: Segments, Retention, Compaction and Topic Configuration

In depth: What is Kafka log compaction, and when would you use it?

37. How do you send large messages through Kafka?

Intermediate · Common · Producers

By default Kafka accepts records up to about 1 MB. To send bigger ones, raise the limit in every place that checks it: the producer’s max.request.size, the topic’s max.message.bytes (or the broker’s message.max.bytes), and check the consumer’s fetch sizes. For payloads of many megabytes, the better design is usually the claim-check pattern: store the file in object storage such as S3 and send only a small message that points to it. Compression also helps when the data repeats a lot.

Where the size is checked

Layer Setting Default
Producer max.request.size 1,048,576 bytes
Broker / topic message.max.bytes / max.message.bytes 1,048,588 bytes
Producer buffer buffer.memory 32 MB, must hold the record
Consumer max.partition.fetch.bytes, fetch.max.bytes 1 MB and 50 MB

The consumer limits are soft: if the first batch is bigger than the limit, the broker still returns it, so the consumer keeps making progress. Follower brokers work the same way with replica.fetch.max.bytes. The producer and topic limits are hard: the record is rejected.

Why large records hurt. Each big record ties up broker memory, network threads and page cache, slows down replication for other partitions, and makes consumer polls slow and uneven. Batching also stops helping, because one record fills a batch.

Options, from best to worst for multi-megabyte data

  1. Claim check. Upload the payload to S3, ADLS or GCS, then send a small event with the object key, size and checksum. Consumers fetch the object when they need it. Kafka stays fast, and the payload can be any size.
  2. Compression. compression.type=zstd or lz4 on the producer. The size limit applies to the compressed batch, so text and JSON often fit after compression.
  3. Raise the limits for one topic only, with max.message.bytes on that topic, rather than for the whole cluster.
  4. Split the payload into chunks with the same key and a sequence number. This works, but the consumer has to reassemble the chunks and handle missing ones, so it is rarely worth the effort.

Example

# Runtime: Apache Kafka 4.3.1, 3 brokers on localhost. Send one 2 MB record three ways.
kafka-topics.sh --bootstrap-server localhost:19092 --create --topic docs-large --partitions 1 --replication-factor 3

# 1) all defaults
kafka-producer-perf-test.sh --topic docs-large --num-records 1 --record-size 2000000 --throughput -1 \
  --producer-props bootstrap.servers=localhost:19092
# 2) producer limit raised, topic still at its default
kafka-producer-perf-test.sh --topic docs-large --num-records 1 --record-size 2000000 --throughput -1 \
  --producer-props bootstrap.servers=localhost:19092 max.request.size=5242880
# 3) raise the topic limit too, then send again
kafka-configs.sh --bootstrap-server localhost:19092 --alter --entity-type topics --entity-name docs-large \
  --add-config max.message.bytes=5242880
kafka-producer-perf-test.sh --topic docs-large --num-records 1 --record-size 2000000 --throughput -1 \
  --producer-props bootstrap.servers=localhost:19092 max.request.size=5242880

The first error comes from the producer itself, before anything is sent. The second comes from the broker. Only when both limits allow the record does it succeed.

38. How do you handle poison messages and retries in a consumer application?

Intermediate · Very Common · Consumers

First decide whether an error is temporary (a timeout, a busy database) or permanent (broken JSON, a failed business rule). Retry temporary errors a few times with growing waits. Send permanent errors, and records that still fail after all retries, to a dead letter topic with headers that explain the error and point to the original record. Commit the offset only after the record is either processed or safely in the dead letter topic. That way one bad record never blocks the partition, and no record is lost.

Kafka has no built-in “reject this message” for plain consumers. If your code throws and never moves on, the same record is fetched again and again, and the whole partition stops. That record is called a poison message.

The usual pattern

  1. Classify the error. Parsing and validation errors are permanent. Network, timeout and lock errors are usually temporary.
  2. Retry temporary errors in place, with exponential backoff, but only for a short total time. A long wait inside the poll loop can exceed max.poll.interval.ms and trigger a rebalance (see The consumer poll loop: what poll() does and why max.poll.interval.ms matters).
  3. For longer delays, use retry topics, such as orders.retry.5m and orders.retry.1h. A separate consumer reads each one and waits until the record is old enough before trying again. Note that this gives up ordering for the retried keys.
  4. Send the rest to a dead letter topic. Keep the original key and value unchanged, and add headers: the error, the source topic, partition and offset, and the time.
  5. Commit after handling, with auto-commit off, so a crash in the middle means the record is processed again rather than lost.
  6. Monitor and replay. Alert when the dead letter topic grows. After fixing the bug or the data, replay those records into the main topic or process them directly.

When ordering matters. If later records for the same key depend on earlier ones (for example, account balances), skipping a record breaks correctness. Options: stop and alert for that partition, or park all later records for the same key until the failed one is fixed.

Kafka Connect has the same idea built in, with errors.tolerance and a dead letter topic setting (see Error handling in Kafka Connect: errors.tolerance and dead letter queues).

Example

# Runtime: Python 3.11, confluent-kafka 2.16, Apache Kafka 4.3.1 (3 brokers on localhost)
import json, time
from confluent_kafka import Producer, Consumer

BOOT = "localhost:19092"
p = Producer({"bootstrap.servers": BOOT, "acks": "all"})
for key, value in [("o1", '{"amount": 10}'), ("o2", '{"amount": '),      # o2 is broken JSON
                   ("o3", '{"amount": 30}'), ("o4", '{"amount": -5}')]:  # o4 breaks a business rule
    p.produce("orders", key=key, value=value)
p.flush(10)

class Transient(Exception): pass   # worth retrying: timeouts, 503s, deadlocks
class Permanent(Exception): pass   # retrying will never help: bad data

calls = {"o3": 0}
def handle(key, raw):
    try:
        order = json.loads(raw)
    except json.JSONDecodeError as e:
        raise Permanent(f"bad JSON: {e.msg}")
    if order["amount"] < 0:
        raise Permanent("amount must be >= 0")
    if key == "o3" and calls["o3"] < 2:          # fake a flaky database for o3
        calls["o3"] += 1
        raise Transient("db timeout")
    print(f"stored {key} amount={order['amount']}")

def to_dlq(msg, err):
    p.produce("orders.dlq", key=msg.key(), value=msg.value(), headers={
        "error": str(err), "source.topic": msg.topic(),
        "source.partition": str(msg.partition()), "source.offset": str(msg.offset())})
    p.flush(10)          # make sure the DLQ copy is safe before committing the offset
    print(f"DLQ    {msg.key().decode()}: {err}")

c = Consumer({"bootstrap.servers": BOOT, "group.id": "orders-writer",
              "auto.offset.reset": "earliest", "enable.auto.commit": False})
c.subscribe(["orders"])
done = 0
while done < 4:
    msg = c.poll(5.0)
    if msg is None or msg.error():
        continue
    key = msg.key().decode()
    for attempt in range(1, 4):                  # up to 3 tries, with backoff
        try:
            handle(key, msg.value().decode())
            break
        except Transient as e:
            print(f"retry  {key}: {e} (attempt {attempt})")
            time.sleep(0.2 * 2 ** attempt)
        except Permanent as e:
            to_dlq(msg, e)
            break
    else:
        to_dlq(msg, "gave up after 3 attempts")
    c.commit(message=msg, asynchronous=False)    # commit only after the record is handled
    done += 1
c.close()

Reading orders.dlq with print.headers=true shows each failed record with its reason and original position:

In depth: How do you handle poison messages and dead-letter topics in Kafka?

Advanced Kafka interview questions (experienced)

39. The KIP-848 consumer group protocol: what changes with group.protocol=consumer?

Advanced · Common · Consumer Groups

KIP-848 moves partition assignment from a consumer acting as group leader to the broker’s group coordinator. Consumers send regular heartbeats with what they subscribe to, and the coordinator moves each consumer towards its target assignment, one at a time. There is no longer a group-wide stop-and-rejoin, so one slow consumer cannot stall everyone, and every change is incremental. It is generally available since Kafka 4.0, but clients still default to group.protocol=classic.

Q68 mentions KIP-848 in passing. The mechanics are worth knowing in detail.

Classic protocol

  • JoinGroup and SyncGroup rounds. One member, the leader, runs the assignor and hands out the result.
  • Every member must rejoin before anyone gets an assignment, so one slow member stalls the whole group.
  • Session timeout and heartbeat interval are client settings.

Consumer protocol (KIP-848)

  • A single ConsumerGroupHeartbeat API carries subscriptions, owned partitions and assignment updates.
  • The broker runs a server-side assignor: group.consumer.assignors=uniform,range (default uniform). Clients may pick one with group.remote.assignor.
  • Changes are reconciled per member: a partition is revoked from A, and only after A confirms is it assigned to C. No other member is touched.
  • Liveness is configured on the broker or per group: group.consumer.session.timeout.ms (45 s) and group.consumer.heartbeat.interval.ms (5 s). Clients that set session.timeout.ms get an error (shown below).
  • Regex subscriptions are evaluated on the broker.
  • Static membership still works through group.instance.id.

Migration. An empty classic group converts automatically when the first new-protocol member joins. A live group can be rolled member by member: the group converts when the first new-protocol member joins, and the coordinator interoperates with the remaining classic members. This works only if the classic assignor embeds no custom metadata. Rack-aware assignment isn’t fully supported yet. Clients: Java 4.0+, and librdkafka 2.12+ (GA). Check your client’s release notes for gaps such as rack-aware assignment or specific callbacks.

Kafka Streams has its own broker-side protocol (KIP-1071, group.protocol=streams), production-ready for its core feature set since 4.2. Product behaviour changes; checked October 2026.

Example

# Runtime: Python 3.11, confluent-kafka 2.16, Apache Kafka 4.3
# Two members own a 6-partition topic; a third joins. Which partitions move?
import sys, time
from confluent_kafka import Consumer

PROTOCOL = sys.argv[1]            # "classic-eager", "classic-cooperative" or "consumer"
closing = False
group = f"rb-{PROTOCOL}-{int(time.time())}"

def make(name):
    conf = {"bootstrap.servers": "localhost:19092", "group.id": group}
    if PROTOCOL == "consumer":
        conf["group.protocol"] = "consumer"            # KIP-848: broker computes assignments
    elif PROTOCOL == "classic-cooperative":
        conf["partition.assignment.strategy"] = "cooperative-sticky"
    else:
        conf["partition.assignment.strategy"] = "range"  # eager
    c = Consumer(conf)
    def log(verb):
        def cb(consumer, parts):
            if parts and not closing:     # skip empty incremental callbacks and shutdown noise
                print(f"  {name} {verb} {sorted(p.partition for p in parts)}")
        return cb
    c.subscribe(["events6"], on_assign=log("assigned"), on_revoke=log("revoked "))
    return c

def spin(cs, secs):
    end = time.time() + secs
    while time.time() < end:
        for c in cs:
            c.poll(0.1)

print(PROTOCOL)
members = [make("A"), make("B")]
spin(members, 15)
print(" -- C joins --")
members.append(make("C"))
spin(members, 15)
closing = True
for c in members:
    c.close()

Output (python rebalance.py classic-eager, then classic-cooperative, then consumer):

Eager stopped all six partitions to add one member. Both other protocols moved only two. Under KIP-848 each move was confirmed member by member. Inspecting a running new-protocol group:

Learn more: Kafka Consumer Groups and Rebalancing

40. Share groups (Queues for Kafka): how do they differ from consumer groups?

Advanced · Occasional · Share Groups

A share group (KIP-932, production-ready in Kafka 4.2) lets many consumers read the same partition together. Each record is taken by one consumer with a time-limited lock, then acknowledged on its own as ACCEPT, RELEASE (deliver it again) or REJECT. Kafka counts how many times each record was delivered. You get queue-like behaviour, but with no ordering and without the rule that you cannot have more consumers than partitions.

Consumer group Share group
Unit of assignment Whole partition to one member Records within a partition, to any member
Max useful members Number of partitions Not tied to partitions
Ordering Per partition None guaranteed
Progress tracking One committed offset per partition Per-record state: available, acquired, acknowledged, archived
Retries Application’s job RELEASE, or lock expiry, redelivers; delivery_count is tracked
Poison records DLQ pattern in app code (see Error handling in Kafka Connect: errors.tolerance and dead letter queues) REJECT, or exceeding the delivery limit, archives the record

How it works

  • The share-partition leader (on the partition leader broker) tracks in-flight records between the share-partition start offset (SPSO) and end offset (SPEO). State is persisted in __share_group_state.
  • group.share.record.lock.duration.ms (30 s) is how long a member holds a record before it becomes available again.
  • group.share.delivery.count.limit (5) caps attempts. After that the record is archived and never delivered again (4.3 adds a per-group share.delivery.count.limit).
  • Where a new group starts is set per group with share.auto.offset.reset (default latest) via kafka-configs.sh --entity-type groups, not in client config.
  • Acknowledgement is implicit (accept the previous batch on the next poll) or explicit.

When to use

  • Job or work queues where each item is independent: image processing, sending notifications, calling rate-limited APIs.
  • Spiky workloads that need more workers than partitions.

When not to

  • Per-key ordering, stateful stream processing, or Kafka transactions across read and write (not supported).

Example

# Runtime: Apache Kafka 4.3.1 CLI
bin/kafka-topics.sh --bootstrap-server localhost:19092 --create --topic jobs --partitions 1
seq 0 11 | sed 's/^/job-/' | bin/kafka-console-producer.sh --bootstrap-server localhost:19092 --topic jobs
bin/kafka-configs.sh --bootstrap-server localhost:19092 --alter --entity-type groups \
  --entity-name workers --add-config share.auto.offset.reset=earliest

Both members read the single partition. The released job went to the other member with delivery_count=2, and the rejected job was never redelivered. In a consumer group, w1 would have sat idle.

Learn more: Kafka Consumer Groups and Rebalancing

41. Unclean leader election and Eligible Leader Replicas (ELR)

Advanced · Common · Replication & Durability

Unclean leader election lets a replica that is not in sync become the leader when no in-sync replica is available. That brings the partition back online, but it loses any confirmed writes the new leader never received, so it is off by default (unclean.leader.election.enable=false). Kafka 4.x adds Eligible Leader Replicas (KIP-966, on by default for new clusters since 4.1): the controller remembers which out-of-sync replicas are still safe, so a clean election is possible in more failure cases.

The dilemma. All ISR members are down. You can wait for one of them (stay unavailable, lose nothing) or elect whatever replica comes back first (available now, possibly losing acknowledged data). Kafka defaults to waiting.

How ELR helps. With strict min ISR (see How replication works: leaders, followers, the ISR and the high watermark), the high watermark can’t advance while ISR < min.insync.replicas. So a replica that dropped out of the ISR during that period still has every committed record. The controller stores such replicas as the ELR. Election order is now:

  1. A live ISR member.
  2. An unfenced ELR member.
  3. The last known leader, if it comes back.
  4. Only if unclean election is enabled (or forced), any live replica.

Turning on unclean election. Set the topic or broker config, then either wait for the controller’s periodic unclean-election check (about 5 minutes) or force it now with kafka-leader-election.sh --election-type UNCLEAN. The 4.3 config docs point this out.

When people enable it

  • Metrics, logs and other data where availability matters more than a few lost records.
  • As a manual, last-resort step during an outage, after a decision to accept loss. Set it back afterwards.

Never leave it on for ledgers, orders, CDC or compacted state topics.

Example

# Runtime: Apache Kafka 4.3.1 lab: 1 KRaft controller + 3 brokers on one host; Python 3.11 + confluent-kafka 2.16
source ../env.sh; C=localhost:29091,localhost:29092,localhost:29093
desc(){ kafka-topics.sh --bootstrap-server $C --describe --topic $1 2>/dev/null | grep 'Partition:' | sed 's/^\s*//'; }
offs(){ echo "  end offset: $(kafka-get-offsets.sh --bootstrap-server $C --topic $1 2>/dev/null)"; }
down(){ bash ../cluster/stop.sh $1 >/dev/null; }
up(){ bash ../cluster/start.sh $@ >/dev/null; sleep 6; }
T=$1; MODE=$2                       # MODE = elr | unclean
kafka-topics.sh --bootstrap-server $C --create --topic $T --replica-assignment 1:2:3 --config min.insync.replicas=2 >/dev/null
python send.py all "r0" $T
down 3; python send.py all "r1 (written while broker 3 was down)" $T
down 2; down 1; echo "## brokers 3, 2, 1 stopped in that order"; desc $T
up 3; echo "## broker 3 back (it missed r1)"; desc $T
if [ "$MODE" = elr ]; then
  up 2; echo "## broker 2 back (it is in the ELR)"; desc $T; offs $T
else
  kafka-configs.sh --bootstrap-server $C --alter --entity-type topics --entity-name $T --add-config unclean.leader.election.enable=true >/dev/null
  echo "## unclean.leader.election.enable=true, then trigger the election now"
  kafka-leader-election.sh --bootstrap-server $C --election-type UNCLEAN --topic $T --partition 0 2>&1 | grep -v WARN
  sleep 3; desc $T; offs $T
  up 1 2; desc $T; offs $T
fi
up 1 2 2>/dev/null

Run 1, bash elr_exp.sh acct elr (wait for the ELR member):

Run 2, bash elr_exp.sh acct5 unclean (force an unclean election instead):

Broker 3 alone wasn’t eligible, so the partition stayed offline rather than lose data. Waiting for broker 2 (an ELR member) gave a clean leader with both records. Forcing an unclean election made broker 3 leader at once. When brokers 1 and 2 rejoined they truncated to its log: the acknowledged r1 was gone for good (end offset 1 instead of 2).

Learn more: Kafka Replication: Leaders, ISR, min.insync.replicas and KRaft

42. Rack awareness and fetching from the closest replica

Advanced · Occasional · Replication & Durability

Setting broker.rack to each broker’s availability zone makes Kafka spread every partition’s copies across zones, so losing one zone loses at most one copy. With replica.selector.class=RackAwareReplicaSelector on brokers and client.rack on consumers (KIP-392), consumers read from a copy in their own zone instead of always from the leader. That cuts traffic between zones, which is often a big part of a cloud Kafka bill.

Replica placement. With broker.rack set, topic creation and reassignment tools place replicas in different racks where possible. Three zones with RF 3 put one replica per zone. Combine with min.insync.replicas=2, and a whole zone can fail without losing acknowledged writes or acks=all availability.

Where the cross-zone bytes come from (RF 3, three zones, producer in one zone)

  • Producer → leader: about two-thirds of produce traffic crosses zones on average (the leader is in another zone two times in three).
  • Leader → two followers: always cross-zone, so 2× the produce volume.
  • Leader → consumers: about two-thirds cross-zone per consumer group, unless consumers fetch from a same-zone follower.

Replication is unavoidable for durability. Consumer traffic is the part you can remove, and with many consumer groups it’s often the biggest.

Follower fetching set-up

# broker
broker.rack=use1-az1
replica.selector.class=org.apache.kafka.common.replica.RackAwareReplicaSelector
# consumer
client.rack=use1-az1

The leader still serves the first fetch and redirects the consumer to a preferred read replica in its rack.

Trade-offs

  • Slightly higher end-to-end latency: followers only expose data up to the high watermark they’ve learned, which trails the leader a little.
  • If the follower falls out of the ISR, the consumer is sent back to the leader.
  • Producers can’t do this; writes always go to the leader. Some managed services offer zone-aware routing for producers in their own ways.

Example

A consumer in the leader’s zone fetched only from broker 1. A consumer in az-3 made its first fetch from the leader, was told to use the az-3 replica, and fetched from broker 3 after that.

Common mistakes:

  • Setting broker.rack but not replica.selector.class, then expecting consumers to fetch locally.
  • Hard-coding client.rack in images instead of reading the zone at start-up.
  • Assuming rack awareness also balances leaders across zones; leadership still follows the preferred replica.

43. Exactly-once from Kafka into an external database

Advanced · Common · Delivery Semantics & Transactions

Kafka transactions stop at Kafka’s edge, so a database sink cannot join them. You get an exactly-once result in one of two ways. Make the writes idempotent, with an upsert on a business key or event ID, so replaying a record does no harm. Or save the consumed offsets in the same database transaction as the results, and when the consumer starts, seek to the offsets stored in the database instead of Kafka’s.

What EOS means inside Kafka (idempotent producer, transactions, read_committed) is covered in Kafka idempotent producers and transactions and on this site’s exactly-once page. The real-world problem is the hop out of Kafka.

Why “commit after write” isn’t enough. Write row, then commit offset: a crash between the two replays the row (a duplicate). Commit offset, then write: a crash loses the row. No order of two separate systems is atomic.

Pattern 1: idempotent sink (most common)

  • MERGE/UPSERT keyed by a natural or event ID. Replaying the same event produces the same row.
  • Version or sequence guards: UPDATE … WHERE incoming_seq > current_seq. This also protects against out-of-order replays.
  • Deduplication table of processed event_ids with a TTL, for append-only facts.
  • Offsets stay in Kafka with ordinary at-least-once commits.

Pattern 2: transactional offsets in the sink

  • One database transaction holds the result rows and an (topic, partition, next_offset) row.
  • On assignment (on_assign) read the stored offsets and seek. Kafka’s committed offsets are only for monitoring.
  • Works with any transactional store: Postgres, MySQL, or Delta and Iceberg commits, which is how Spark and Flink sinks do it.

Pattern 3: two-phase commit

Aggregations (amount = amount + x) are not naturally idempotent. That makes Pattern 2 or a dedup key essential: the demo below counts events, which would double-count under plain at-least-once.

Example

# Runtime: Python 3.11 (sqlite3 stdlib), confluent-kafka 2.16, Apache Kafka 4.3
# Exactly-once *effect* into an external database: results and offsets commit in ONE db transaction,
# and on (re)assignment the consumer seeks to the offsets stored in the database, not Kafka's.
import sqlite3, sys
from confluent_kafka import Consumer, TopicPartition

db = sqlite3.connect("ledger.db")
db.execute("CREATE TABLE IF NOT EXISTS balances (account TEXT PRIMARY KEY, amount INT)")
db.execute("CREATE TABLE IF NOT EXISTS kafka_offsets (topic TEXT, part INT, next_offset INT, PRIMARY KEY (topic, part))")
db.commit()

def on_assign(consumer, partitions):
    for tp in partitions:
        row = db.execute("SELECT next_offset FROM kafka_offsets WHERE topic=? AND part=?",
                         (tp.topic, tp.partition)).fetchone()
        tp.offset = row[0] if row else 0          # resume from the DB, the source of truth
    consumer.assign(partitions)

crash_after = int(sys.argv[1]) if len(sys.argv) > 1 else 10**9
c = Consumer({"bootstrap.servers": "localhost:19092", "group.id": "balance-sink",
              "enable.auto.commit": False, "isolation.level": "read_committed",
              "session.timeout.ms": 6000})
c.subscribe(["ledger-events"], on_assign=on_assign)
n, idle = 0, 0
while idle < 5:
    m = c.poll(1.0)
    if m is None or m.error():
        idle += 1 if c.assignment() else 0   # only count idle polls once we own partitions
        continue
    idle = 0
    with db:                                      # one atomic transaction
        db.execute("INSERT INTO balances VALUES ('acc-1', 1) "
                   "ON CONFLICT(account) DO UPDATE SET amount = amount + 1")
        db.execute("INSERT OR REPLACE INTO kafka_offsets VALUES (?, ?, ?)",
                   (m.topic(), m.partition(), m.offset() + 1))
    n += 1
    if n == crash_after:
        print(f"crashing after {n} records"); import os; os._exit(1)
print("processed", n, "->", db.execute("SELECT amount FROM balances").fetchone()[0],
      "events counted; stored offset", db.execute("SELECT next_offset FROM kafka_offsets").fetchone()[0])
c.close()

Run once with 7 (crash after seven records), then twice with no argument, against the 20-record ledger-events topic:

The restart resumed at offset 7 from the database, not from Kafka’s committed offset (which this consumer never writes). The count is exactly 20 despite the crash and a third run.

Learn more: Kafka Delivery Semantics: At-Most-Once, At-Least-Once and Exactly-Once

In depth: What does exactly-once mean in Kafka, and how is it achieved?

44. Write a transactional consume-transform-produce loop

Advanced · Common · Delivery Semantics & Transactions

Call init_transactions() once, with a stable transactional.id. Then for each batch: begin_transaction(), produce the output records, add the consumer’s positions with send_offsets_to_transaction(), and commit_transaction(). If something fails, call abort_transaction() and rewind the consumer to the last committed position. Consumers downstream must use read_committed, or they will also see records from aborted transactions.

Q70 explains what transactions are. This question is about writing the loop correctly.

The pieces

Step Why
transactional.id Identity that survives restarts; init_transactions() bumps the epoch and fences zombies
isolation.level=read_committed on the input consumer Don’t process another app’s aborted data
enable.auto.commit=false Offsets are committed inside the transaction, not separately
send_offsets_to_transaction(positions, group_metadata) Ties input progress to output records atomically
commit_transaction() Writes commit markers to every output partition and __consumer_offsets

Error handling

  • Abortable errors (your own exception, a timeout in the transaction): abort_transaction(), then seek back to the first offset of the batch. Otherwise the consumer’s in-memory position has already moved past it.
  • Fatal errors (ProducerFenced, InvalidProducerEpoch): another instance owns the transactional.id. Close and exit; don’t retry.
  • transaction.timeout.ms (60 s by default) must cover a batch. The coordinator aborts transactions left open longer, and long transactions hold back the last stable offset for every read_committed reader.

transactional.id strategy. Since KIP-447 (Kafka 2.5+), fencing also uses the consumer group generation. One stable ID per application instance is enough; you no longer need one per input partition.

Kafka 4.0+ (KIP-890, transaction.version=2): the broker verifies that each write belongs to an ongoing transaction, and the epoch is bumped on every transaction. This closes “hanging transaction” gaps. Clients get it automatically once the feature is finalised (this lab cluster shows transaction.version at level 2).

Cost. Each commit adds round trips and a marker record per partition, so batch several hundred records or a few hundred milliseconds per transaction.

Example

# Runtime: Python 3.11, confluent-kafka 2.16, Apache Kafka 4.3 (transaction.version=2)
# Consume-transform-produce with Kafka transactions: output records and input offsets commit atomically.
from confluent_kafka import Consumer, Producer, TopicPartition

consumer = Consumer({"bootstrap.servers": "localhost:19092", "group.id": "enricher",
                     "auto.offset.reset": "earliest", "enable.auto.commit": False,
                     "isolation.level": "read_committed"})
producer = Producer({"bootstrap.servers": "localhost:19092",
                     "transactional.id": "enricher-tx-0",    # stable per instance/partition set
                     "transaction.timeout.ms": 60000})
producer.init_transactions()          # fences any older producer with the same transactional.id
consumer.subscribe(["tx-in"])

batch_no, idle, failed_once = 0, 0, False
while idle < 5:
    msgs = consumer.consume(num_messages=3, timeout=1.0)
    msgs = [m for m in msgs if not m.error()]
    if not msgs:
        idle += 1 if consumer.assignment() else 0; continue
    idle, batch_no = 0, batch_no + 1
    producer.begin_transaction()
    try:
        for m in msgs:
            producer.produce("tx-out", key=m.value(), value=m.value().upper())
        if batch_no == 2 and not failed_once:
            failed_once = True
            producer.flush()          # records reach the broker, then we fail before commit
            raise RuntimeError("simulated failure mid-batch")
        producer.send_offsets_to_transaction(consumer.position(consumer.assignment()),
                                             consumer.consumer_group_metadata())
        producer.commit_transaction()
        print(f"batch {batch_no}: committed {[m.value().decode() for m in msgs]}")
    except RuntimeError as e:
        producer.abort_transaction()
        print(f"batch {batch_no}: aborted ({e}); rewinding")
        first = msgs[0]               # rewind to the first record of the failed batch
        consumer.seek(TopicPartition(first.topic(), first.partition(), first.offset()))
consumer.close()

Input: order-1 … order-9 on tx-in. Output, then both isolation levels reading tx-out:

The aborted batch reached the log (flushed before the failure), so a read_uncommitted reader saw ORDER-4..6 twice. A read_committed reader saw each exactly once. kafka-get-offsets.sh reported an end offset of 16: 12 data records plus 4 transaction markers, which is why offsets on transactional topics have gaps.

45. Tiered storage: how it works and what it changes operationally

Advanced · Common · Storage & Retention

Tiered storage (KIP-405, production-ready since Kafka 3.9) copies closed segments to remote storage such as S3, GCS or HDFS. It deletes them from local disk after a short local.retention.ms, while retention.ms still sets the total retention. Brokers then keep mainly the recent data on disk, so long retention becomes cheap, and recovering or rebalancing a broker moves far less data. Reads of old offsets are fetched from remote storage automatically.

Architecture

  • RemoteStorageManager (RSM): a plugin that copies segments and indexes to and from the remote store. Apache Kafka ships the interface and no production implementation, so you use a vendor or open-source plugin.
  • RemoteLogMetadataManager (RLMM): tracks which segments are remote. The default TopicBasedRemoteLogMetadataManager uses the internal __remote_log_metadata topic.
  • The leader’s remote log manager uploads closed segments (checked every remote.log.manager.task.interval.ms, 30 s). Followers don’t upload.

Two retention clocks

Setting Meaning
retention.ms / retention.bytes Total retention, local plus remote
local.retention.ms / local.retention.bytes How long segments stay on broker disk; -2 (default) means “same as total”

What gets better

  • Disk sizing depends on hot data only, so brokers become smaller and cheaper.
  • Adding or replacing a broker copies only the local tail. In 4.3, follower.fetch.last.tiered.offset.enable lets new followers skip data already in remote storage.
  • Long replays (Kappa-style reprocessing, see Lambda vs Kappa architecture) no longer need giant disks.

Limits and trade-offs

  • No compacted topics.
  • Historical reads have object-store latency, and backfill throughput depends on the RSM, its caches and the fetch thread pools.
  • The metadata topic is critical. 4.3 adds remote.log.metadata.topic.min.isr (2 by default).
  • Turning it off needs care: remote.log.copy.disable and remote.log.delete.on.disable control how a topic leaves tiered storage.
  • Data in the bucket is in Kafka’s segment format, not Parquet. It isn’t a lake table. For analytics, still land data into Iceberg or Delta.

Example

# Runtime: Apache Kafka 4.3 broker + a RemoteStorageManager plugin (Kafka ships none; plugin class shown is a placeholder)
# --- broker (server.properties) ---
remote.log.storage.system.enable=true
remote.log.storage.manager.class.name=com.example.tiered.S3RemoteStorageManager
remote.log.storage.manager.class.path=/opt/kafka/plugins/tiered/*
remote.log.metadata.manager.listener.name=PLAINTEXT

These commands were checked against the 4.3 topic and broker config reference. They weren’t run in the lab, because there is no RSM plugin there to upload to.

Common mistakes:

  • Expecting tiered storage to work on compacted changelog topics.
  • Treating the remote bucket as a queryable data lake.
  • Setting local.retention.ms so low that ordinary consumer lag pushes reads into remote storage.
  • Assuming Apache Kafka includes an S3 plugin out of the box.

46. Exactly-once source connectors and what “exactly-once” means for sinks

Advanced · Occasional · Kafka Connect

Since Kafka 3.3 (KIP-618), workers with exactly.once.source.support=enabled run each source task with a transactional producer. The records and the task’s source offsets are committed in the same Kafka transaction, so a crash cannot create duplicates or gaps in Kafka. Sinks do not use Kafka transactions: they are exactly-once only if the connector writes idempotently, or stores offsets in the target atomically (see Exactly-once from Kafka into an external database).

Without EOS (the default, exactly.once.source.support=disabled). A source task produces records and, separately, flushes source offsets every offset.flush.interval.ms (60 s). A crash between the two replays everything since the last flush, so you get duplicates.

With EOS

  • Turn it on cluster-wide in two rolls: preparing, then enabled. All workers must be 3.3 or newer and in distributed mode.
  • Each task gets a transactional ID like <group.id>-<connector>-<task>, as the lab output below shows. The leader also uses a transactional producer to write configs, which fences zombie workers.
  • transaction.boundary (per connector): poll (default, one transaction per poll batch), interval (time-based), or connector (the connector defines its own boundaries).
  • exactly.once.support=required makes connector creation fail if the plugin can’t support EOS. The default requested is best-effort.
  • Downstream consumers need isolation.level=read_committed (the default in librdkafka, but not in Java).
  • ACLs: the worker principal needs transactional ID and idempotent-write permissions.

What the connector must do. It must report precise source offsets and be able to resume from them. Debezium supports this for several databases; check each connector’s documentation.

Sinks

  • The Kafka side is just consumer offsets.
  • Exactly-once into the target needs idempotent upserts (JDBC insert.mode=upsert), deterministic object names (S3 sinks name files by partition and start offset), or atomic offset storage in the target.

Example

# Runtime: Apache Kafka 4.3.1 — worker started with exactly.once.source.support=enabled (see Q498's worker.properties)
bin/kafka-transactions.sh --bootstrap-server localhost:19092 list

connect-cluster-connect-lab is the worker leader’s config producer, and connect-lab-access-source-0 is task 0 of the access-source connector, which commits a transaction per poll. (enricher-tx-0 is the Python app from Q494.)

Common mistakes:

  • Thinking enabling EOS on the worker makes sink connectors exactly-once.
  • Enabling it in one step on a mixed-version cluster.
  • Forgetting read_committed downstream, so consumers still see aborted records.
  • Missing ACLs for transactional IDs, which shows up as tasks failing at start-up.

Learn more: Kafka Connect and Debezium CDC

47. Joins in Kafka Streams: stream-table, stream-stream and co-partitioning

Advanced · Common · Kafka Streams

A stream-table join adds the table’s current value for the key to each event, as it is at that moment. It has no window, and later table updates do not re-trigger it. A stream-stream join must have a window (JoinWindows), because both sides never end, and it keeps each side in window stores. Both sides of a join must be co-partitioned: same key, same number of partitions and same partitioner. Otherwise Streams repartitions the data, or the join fails.

Join Window Triggered by Result
KStream–KTable No Stream records only Event plus the table value at that time (leftJoin keeps unmatched events with null)
KStream–GlobalKTable No Stream records Lookup by any extracted key; no co-partitioning
KStream–KStream JoinWindows (time difference + grace) Either side One result per matching pair in the window (can be many)
KTable–KTable No Either side Continuously updated joined table
KTable–KTable foreign-key join No Either side Joins on a field in the left value (since 2.4)

Co-partitioning

  • Same partition count on both topics, and the same partitioner. A Python producer on CRC32 breaks it silently (see How the producer picks a partition, and why Python and Java can disagree).
  • If you change the key with selectKey or map before a join, Streams inserts a repartition topic automatically, at the cost of an extra network hop.
  • Streams checks partition counts at start-up and throws TopologyException on a mismatch.

Time semantics

  • Stream-stream joins match on record timestamps within the window. Late records are accepted within grace.
  • Stream-table joins use the table’s state as of processing. A table update that arrives slightly after an event isn’t seen. You can make table updates wait by setting a versioned store with a grace period, so the join looks up the version valid at the event’s timestamp (KIP-914, versioned stores).

Example

// Runtime: Java 21, Apache Kafka Streams 4.3.1 + kafka-streams-test-utils (TopologyTestDriver, no broker)
import java.time.*;
import java.util.Properties;
import org.apache.kafka.common.serialization.*;
import org.apache.kafka.streams.*;
import org.apache.kafka.streams.kstream.*;

public class Joins {
    public static void main(String[] args) {
        var s = Serdes.String();
        StreamsBuilder b = new StreamsBuilder();
        KStream<String, String> orders = b.stream("orders", Consumed.with(s, s));        // key = customer_id
        KTable<String, String> customers = b.table("customers", Consumed.with(s, s));     // key = customer_id
        KStream<String, String> payments = b.stream("payments", Consumed.with(s, s));     // key = customer_id

        // 1) stream-table join: enrich each order with the customer's tier AS OF the order's arrival
        orders.leftJoin(customers, (order, tier) -> order + " tier=" + tier, Joined.with(s, s, s))
              .to("orders-enriched", Produced.with(s, s));

        // 2) stream-stream join: an order and a payment for the same key within 10 minutes
        orders.join(payments, (order, pay) -> order + " paid " + pay,
                    JoinWindows.ofTimeDifferenceAndGrace(Duration.ofMinutes(10), Duration.ofMinutes(1)),
                    StreamJoined.with(s, s, s))
              .to("orders-paid", Produced.with(s, s));

        Properties p = new Properties();
        p.put(StreamsConfig.APPLICATION_ID_CONFIG, "joins-demo");
        p.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "dummy:9092");
        try (TopologyTestDriver d = new TopologyTestDriver(b.build(), p)) {
            var ser = new StringSerializer();
            var o = d.createInputTopic("orders", ser, ser);
            var c = d.createInputTopic("customers", ser, ser);
            var pay = d.createInputTopic("payments", ser, ser);
            Instant t0 = Instant.parse("2026-10-17T09:00:00Z");
            c.pipeInput("cust-1", "silver", t0);
            o.pipeInput("cust-1", "order-A", t0.plusSeconds(60));
            c.pipeInput("cust-1", "gold", t0.plusSeconds(120));          // tier changes after order-A
            o.pipeInput("cust-1", "order-B", t0.plusSeconds(180));
            o.pipeInput("cust-9", "order-C", t0.plusSeconds(200));       // unknown customer
            pay.pipeInput("cust-1", "pay-1", t0.plusSeconds(300));       // within 10 min of A and B
            pay.pipeInput("cust-9", "pay-9", t0.plusSeconds(200 + 1200)); // 20 min after order-C: no match

            var de = new StringDeserializer();
            System.out.println("stream-table : " + d.createOutputTopic("orders-enriched", de, de).readValuesToList());
            System.out.println("stream-stream: " + d.createOutputTopic("orders-paid", de, de).readValuesToList());
        }
    }
}

order-A kept the tier it had when it arrived (silver), even though the customer later became gold. The stream-stream join paired pay-1 with both orders in its 10-minute window, a reminder that windowed joins can fan out. pay-9 arrived 20 minutes after order-C, so it found no match.

Learn more: Kafka Streams Basics: KStream, KTable, Windows, Joins and State

48. Capacity planning: brokers, disks, network and partition-count limits

Advanced · Common · Operations & Sizing

Plan capacity from bytes per second, not from message counts. Peak write rate × replication factor gives the disk writes and incoming network traffic. Replication traffic plus every consumer group’s reads give the outgoing network traffic. Write rate × retention time × replication factor, plus spare room, gives the disk size. You need enough brokers to cover the largest of those needs (network, disk or partition count), plus one spare for maintenance. Partitions per broker have no hard limit, but too many slow down recovery and use more open files and metadata.

How many partitions a single topic needs is on this site’s partition-count page. This question is about sizing the cluster.

The core arithmetic (RF = 3, G consumer groups)

Resource Load at peak
Inbound network produce × RF (client writes plus follower fetches arriving)
Outbound network produce × (RF − 1) for replication + produce × G for consumers
Disk write produce × RF
Disk capacity average produce × retention × RF ÷ target fill (for example 60%)
Page cache Enough RAM to hold the tail that consumers read (minutes to hours), so reads don’t hit disk

Headroom matters more than averages. You need spare capacity for a broker failure (its load moves to the others), for consumers catching up after an outage (reads at many times the normal rate), and for partition reassignment traffic (throttle it with --throttle).

Partition limits. Kafka has no fixed maximum, and KRaft raised practical cluster-wide limits a lot. Per broker, every replica costs file handles, memory-mapped indexes, replica fetcher work and leader-election time after a failure. A few thousand replicas per broker is a common planning number; very small brokers should hold fewer. Measure: controlled shutdown time and leader-election time grow with replicas per broker.

Cost levers

Example

# Runtime: Python 3.11 (standard library only) — back-of-envelope Kafka capacity plan
import math

# ---- inputs (replace with your own measurements) ----
ingress_mb_s     = 120      # average produce rate across the cluster, MB/s (after compression)
peak_factor      = 2.0      # peak / average
rf               = 3        # replication factor
consumer_groups  = 4        # groups each reading the full stream (lag-free tail reads)
retention_days   = 3        # local retention
disk_headroom    = 0.6      # keep disks <= 60% full
broker_disk_tb   = 8        # usable disk per broker
broker_net_mb_s  = 1200     # ~10 Gbit/s NIC, usable MB/s per direction
net_headroom     = 0.5      # plan for <= 50% NIC use at peak (failover, catch-up, reassignment)
partitions_total = 600      # sum over topics, before replication
max_replicas_per_broker = 4000   # a conservative planning limit, not a hard Kafka limit

peak_in = ingress_mb_s * peak_factor
# Broker network: in = produce + replication from leaders; out = replication to followers + consumers
cluster_in  = peak_in * rf                          # every byte lands on rf brokers
cluster_out = peak_in * (rf - 1) + peak_in * consumer_groups
brokers_for_net = math.ceil(max(cluster_in, cluster_out) / (broker_net_mb_s * net_headroom))

stored_tb = ingress_mb_s * 86400 * retention_days * rf / 1e6
brokers_for_disk = math.ceil(stored_tb / (broker_disk_tb * disk_headroom))

replicas = partitions_total * rf
brokers_for_partitions = math.ceil(replicas / max_replicas_per_broker)

brokers = max(brokers_for_net, brokers_for_disk, brokers_for_partitions, rf)
print(f"peak produce          : {peak_in:,.0f} MB/s")
print(f"cluster network in/out: {cluster_in:,.0f} / {cluster_out:,.0f} MB/s at peak")
print(f"stored data           : {stored_tb:,.1f} TB ({retention_days} days x RF {rf})")
print(f"brokers needed  -> network {brokers_for_net}, disk {brokers_for_disk}, partitions {brokers_for_partitions}")
print(f"plan: {brokers} brokers (+1 for N+1 maintenance = {brokers + 1}); "
      f"{replicas / (brokers + 1):,.0f} replicas per broker")

# Same cluster with tiered storage keeping only 12 hours on broker disks (see Q497)
local_tb = ingress_mb_s * 86400 * 0.5 * rf / 1e6
print(f"with tiered storage (12 h local): {local_tb:,.1f} TB local -> "
      f"{math.ceil(local_tb / (broker_disk_tb * disk_headroom))} brokers for disk")

With these inputs, disk retention, not throughput, sets the broker count. Twelve hours of local data with tiered storage brings the disk requirement below the network one. Validate the per-broker figures with kafka-producer-perf-test.sh and kafka-consumer-perf-test.sh on your own hardware and payloads.

49. Multi-region Kafka: MirrorMaker 2, offset translation and cluster-linking concepts

Advanced · Common · Multi-Region & Replication

MirrorMaker 2 (MM2) is a set of Kafka Connect connectors that copy topics from one cluster to another, with a small delay. By default it renames the copies (east.payments on the target), copies topic settings and ACLs, and writes checkpoints that translate consumer group offsets, so consumers can switch to the other region and carry on. Because copying is not instant, a failover can lose the last few seconds of data and re-read some records. Cluster linking, found in some commercial platforms, copies the log itself, so offsets stay identical.

MM2 components

Connector Job
MirrorSourceConnector Copies records and topic configs and ACLs; writes offset-sync records
MirrorCheckpointConnector Translates group offsets into checkpoints on the target; with sync.group.offsets.enabled=true it writes them into the target’s __consumer_offsets
MirrorHeartbeatConnector Emits heartbeats to measure replication lag and detect topology

Topologies

  • Active–passive: one direction, for DR. Consumers fail over using translated offsets.
  • Active–active: both directions. The default DefaultReplicationPolicy adds a cluster prefix, which prevents infinite loops, and consumers read orders plus west.orders. IdentityReplicationPolicy keeps names but is only safe for one-way flows.
  • Hub-and-spoke / aggregation: many edge clusters feed a central analytics cluster.

Offsets differ between clusters. Offset 1,000 in the source isn’t offset 1,000 in the target (retention, compaction and restarts all shift them). MM2 records offset-sync pairs and translates conservatively: a failed-over consumer may re-read some records but shouldn’t skip any. Consumers must be idempotent.

What a DR plan has to say

  • RPO is replication lag (seconds, typically); RTO is how fast clients re-point.
  • Producers need a switch: DNS, a config flag, or client bootstrap lists per region.
  • Schema Registry, ACLs, quotas and topic configs must exist in both regions.
  • Fail-back: reverse the flow and catch up before switching back.

Cluster linking (concept). The destination broker fetches from the source like a follower, so offsets, record bytes and timestamps are preserved and no Connect cluster is needed. It’s available in some commercial platforms rather than Apache Kafka itself. Apache Kafka’s open-source path is MM2.

Example

# Runtime: Apache Kafka 4.3.1 MirrorMaker 2 (dedicated mode): replicate "east" (single broker) -> "west" (3-broker cluster)
clusters = east, west
east.bootstrap.servers = localhost:19092
west.bootstrap.servers = localhost:29091,localhost:29092,localhost:29093
east->west.enabled = true
east->west.topics = payments
east->west.groups = payments-reader
west->east.enabled = false
replication.factor = 3
sync.group.offsets.enabled = true
sync.group.offsets.interval.seconds = 5
emit.checkpoints.interval.seconds = 5
refresh.topics.interval.seconds = 10
refresh.groups.interval.seconds = 10
# single-broker source: internal topics on "east" can only have one replica
east.offset.storage.replication.factor = 1
east.config.storage.replication.factor = 1
east.status.storage.replication.factor = 1
checkpoints.topic.replication.factor = 3
heartbeats.topic.replication.factor = 3
offset-syncs.topic.replication.factor = 1
offset-syncs.topic.location = source

Common mistakes:

  • Assuming offsets are identical in the target cluster.
  • Using IdentityReplicationPolicy in active–active, which creates replication loops.
  • Forgetting Schema Registry, ACLs and quotas in the DR region.
  • Claiming zero data loss with asynchronous replication.

Advanced · Common · Stream Processing

Kafka Streams is a Java library that runs inside your own app and reads from and writes to Kafka only. Flink is a separate cluster that can read from and write to many systems. For event time, Kafka Streams tracks stream time (the highest timestamp seen) and closes windows after a grace period. Flink uses watermarks, which say “no events older than this are expected”. For exactly-once output, Kafka Streams uses Kafka transactions. Flink commits its sinks with a two-phase commit tied to its checkpoints.

Side-by-side

Kafka Streams Apache Flink
How it runs A library in your JVM app; scale by starting more instances A cluster of JobManager and TaskManagers, often on Kubernetes
Sources and sinks Kafka topics only Kafka, files, databases, CDC, lakehouse tables and more
State Local RocksDB stores, backed up to Kafka changelog topics (see State stores, changelog topics and restoring state in Kafka Streams) State backends, saved in periodic checkpoints to durable storage
Recovery Replay the changelog into a new store Restore the last checkpoint and rewind sources to it
Event time Stream time per task, plus a grace period per window (see Windowing in Kafka Streams: tumbling, hopping, sliding, session windows and grace) Watermarks generated at the source, plus allowed lateness
Late data Dropped after grace, counted in a metric Dropped, or sent to a side output for separate handling
Exactly-once processing.guarantee=exactly_once_v2 with Kafka transactions Checkpoints plus two-phase commit sinks
Languages Java and Scala Java, plus SQL and Python APIs

Watermarks vs stream time. A Flink watermark with bounded out-of-orderness of 10 seconds says “I have seen event time T, so assume nothing older than T − 10 s will still arrive”. A window closes when the watermark passes its end. If one source partition goes quiet, it holds the watermark back for the whole job, so Flink sources set withIdleness(...) to ignore idle partitions. Kafka Streams has a similar effect: a quiet partition does not advance stream time, so its windows stay open until new data arrives.

Learn more: Kafka Delivery Semantics: At-Most-Once, At-Least-Once and Exactly-Once

By , Data Engineer and Founder of DataDank · Last reviewed Oct 2026 · Product names and defaults as of October 2026; code snippets state their dialect or runtime

Progress is saved in this browser only. No account needed.

Search
Filter by type