DS·67
Kafka in Depth
Apache Kafka 4.x from the storage layer up: brokers, topics, partitions and segments, replicas, leaders and the ISR, high watermark and acks, KRaft metadata quorum, producers (batching, partitioners, serializers, idempotence, transactions), consumers and consumer groups (offsets, the KIP-848 rebalance protocol, cooperative and static membership), share groups (queues for Kafka), exactly-once semantics, log compaction, retention and tiered storage, Schema Registry, Kafka Streams and Connect, and operations, with clients in Java, Go, Python and Rust.
Start here: partitions, offsets and consumer groups
Three words carry the whole design
A topic (orders) is split into partitions, and each partition is an append-only log in which every record gets the next offset: 0, 1, 2… The producer chooses the partition by hashing the record's key:
for i, k := range []string{"A", "B", "C", "A", "B", "C", "A", "B", "C"} {
r := &kgo.Record{Topic: "orders", Key: []byte("order-" + k), Value: []byte(fmt.Sprintf("event %d", i+1))}
p.ProduceSync(ctx, r) // r.Partition and r.Offset are filled in by the broker's reply
}
1) 9 events for orders A, B, C (key = order id) into 3 partitions:
partition 0: B@0 C@1 B@2 C@3 B@4 C@5
partition 1:
partition 2: A@0 A@1 A@2
Every event for order A went to partition 2, so a consumer of partition 2 sees A's events in the order they were written: Kafka orders records within a partition, not across a topic. Notice too that B and C collided on partition 0 while partition 1 got nothing: hashing three keys onto three partitions is rarely even. With thousands of keys it evens out; with a few huge keys (one giant customer) you get a hot partition.
Consumer groups share partitions
Consumers that share a group.id divide the partitions among themselves; each partition is read by exactly one member of the group:
2) one consumer group reading the 3-partition topic:
1 consumers in the group: consumer 1 → [0 1 2]
2 consumers in the group: consumer 1 → [1], consumer 2 → [0 2]
3 consumers in the group: consumer 1 → [2], consumer 2 → [1], consumer 3 → [0]
4 consumers in the group: consumer 1 → [], consumer 2 → [2], consumer 3 → [0], consumer 4 → [1]
So the partition count is the ceiling on parallelism for one group: the fourth consumer sat idle. Choose partitions for the consumers you'll need at peak, because adding partitions later moves keys (the lab measured 74% of keys moving). A different group (analytics, say) gets its own copy of everything: that's the log's pub/sub.
Offsets are the consumer's bookmark
3) partition 0, consumer group 'billing', committing after each read:
first run reads offsets [0 1] and commits
restarted, it resumes at the committed offset: [2 3]
a new group 'audit' starting from the earliest offset replays: [0 1 2 3]
lag for 'billing': p0 committed 4, end 9, lag 5 | p1 committed -1, end 5, lag 5 | p2 committed -1, end 7, lag 7
The broker doesn't delete records when they're read. Each group commits the offset of the next record it wants, stored in Kafka's internal __consumer_offsets topic; on restart it continues from there. A group with no commit uses auto.offset.reset (earliest or latest). Lag is the log end minus the committed offset: the work the group hasn't done yet, and the first metric to watch on any Kafka consumer.
Producers: batching and idempotence
Producers don't send records one by one: they collect them per partition into batches (linger.ms, batch.size) and send several batches in one request. Since Kafka 3.0 producers are idempotent by default (enable.idempotence=true, acks=all): each producer has an ID and numbers its batches, so if a response is lost and the producer retries, the broker recognises the duplicate. The lab cut a connection after the broker had written a batch: with idempotence off the retry wrote the five charges twice; with it on, once.
How deep to go in Kafka
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain topics, partitions, offsets, producers, consumers and consumer groups |
| L2 | Write producers and consumers with keys, acks, idempotence, manual commits and error handling |
| L3 | Explain replication, ISR, high watermark, rebalancing protocols, transactions, compaction and retention |
| L4 | Diagnose lag, rebalance storms, hot partitions, duplicates and under-replicated partitions |
| L5 | Design topics, keys, partition counts, schemas and retention for a platform; plan EOS pipelines |
| L6 | Operate Kafka at scale: KRaft, tiered storage, multi-cluster replication, quotas and upgrades |
Kafka as a distributed log
The idea
Kafka (created at LinkedIn in 2010–11, Apache top-level project) is a distributed, partitioned, replicated commit log. Producers append records; consumers read sequentially from positions they choose. The broker doesn't track per-message consumption, so it's simple and fast: appends are sequential disk writes, reads are sequential (often served from the OS page cache), and data moves to the network with zero-copy (sendfile).
The roadmap's key point: Kafka is both a message platform and a durable log. It can move messages between services, but because data is retained and replayable, it can also be the system of record for events, the backbone for CDC, stream processing and event sourcing.
Records
A record has:
- key (optional bytes): determines the partition and is the unit of compaction
- value (bytes): the payload
- headers (key/value pairs): metadata such as trace IDs and event type
- timestamp: set by the producer (CreateTime) or broker (LogAppendTime)
- offset: assigned by the broker; its position in the partition
Kafka sees only bytes. Serializers turn objects into bytes (and deserializers back), so the schema is a contract between producers and consumers (Schema Registry, below).
Topics, partitions and storage
Partitions
A topic is split into partitions. Each partition is an ordered, immutable sequence of records with increasing offsets. Partitions give:
- Parallelism: different partitions live on different brokers and are consumed by different consumers.
- Ordering: guaranteed within a partition only.
- Scale unit: throughput, storage and consumer parallelism scale with partition count.
Choosing partition count: enough for peak consumer parallelism and throughput (a partition handles roughly 10s of MB/s), with headroom. You can add partitions later but never remove them, and adding changes hash(key) % n, so keys move to new partitions and per-key ordering breaks across the change. Over-partitioning costs memory, file handles, longer leader elections and slower rebalances. KRaft clusters handle far more partitions than ZooKeeper-era ones (millions per cluster), but each still has overhead.
Segments and indexes
On disk, each partition replica is a directory of segment files (00000000000000368769.log, named by base offset), plus an offset index (offset → file position) and a time index (timestamp → offset). Only the active segment is written; closed segments are immutable, which makes retention cheap (delete whole files) and compaction possible (rewrite files in the background).
Records are written in batches (record batches, possibly compressed with lz4, zstd, snappy or gzip), and the batch, not the record, is the unit of storage, replication and fetching.
Replication, leaders and the ISR
Leaders and followers
Each partition has replication factor RF copies (typically 3). One replica is the leader: all produce requests go to it, and by default consumers fetch from it (or from the nearest follower with rack-aware fetching, KIP-392, to save cross-zone costs). Followers continuously fetch from the leader, like consumers.
In-sync replicas (ISR)
The ISR is the set of replicas that are caught up with the leader (fetched within replica.lag.time.max.ms, default 30 s). A follower that falls behind is removed from the ISR; when it catches up, it rejoins.
The high watermark (HW) is the highest offset replicated to all ISR members. Consumers can read only up to the HW, so they never see a record that could be lost on leader failover.
acks and min.insync.replicas
Durability is a contract between the producer's acks and the topic's min.insync.replicas:
Producer acks |
Leader responds when… | Risk |
|---|---|---|
0 |
Never (fire and forget) | Loss on any failure |
1 |
Leader wrote it locally | Loss if the leader dies before followers copy it |
all (-1, default since Kafka 3.0) |
All current ISR members have it | Safe if ISR is big enough |
acks=all alone isn't enough: if the ISR shrinks to just the leader, "all" means one. min.insync.replicas=2 (with RF=3) makes the leader reject writes (NotEnoughReplicas) when fewer than 2 replicas are in sync. The standard durable configuration is RF=3, min.insync.replicas=2, acks=all: it tolerates one broker failure with no data loss and continued writes.
Leader failover and unclean election
When a leader broker dies, the controller elects a new leader from the ISR, which by definition has every acknowledged record, so no acknowledged write is lost. If no ISR member is alive, you choose:
unclean.leader.election.enable=false(default): the partition stays unavailable until an ISR replica returns (consistency over availability).true: elect an out-of-sync replica, giving availability, but acknowledged records are lost and consumers may see offsets reused.
This is CAP in miniature (chapter 70). Kafka 4.x's eligible leader replicas (KIP-966) work tightens this further by tracking which replicas are safe to elect even below min ISR.
Leader epochs (a counter incremented on each leadership change) let followers truncate divergent log tails correctly after failover, which is the same idea as Raft terms (chapter 72).
KRaft: metadata without ZooKeeper
What changed
Kafka originally stored cluster metadata (brokers, topics, partition leaders, ISR, configs, ACLs) in ZooKeeper, with one broker acting as controller. KRaft (Kafka Raft, KIP-500) replaces ZooKeeper with a Raft-based metadata quorum inside Kafka itself:
- A small set of controller nodes (typically 3 or 5) run Raft over a single internal metadata log (
__cluster_metadata). - One controller is the active controller (the Raft leader); it handles admin requests, broker registration and leader elections, and appends decisions to the metadata log.
- Brokers replicate the metadata log too, so every broker has an up-to-date, ordered view of cluster state, and failover of the controller is near-instant (the standby already has the log).
Timeline: KRaft became production-ready in 3.3; Kafka 4.0 (March 2025) removed ZooKeeper support entirely, so every 4.x cluster is KRaft. Migration from ZooKeeper must happen on a 3.x bridge release (3.9 is the last) before upgrading to 4.x. Dynamic controller quorums (KIP-853) let you add and remove controllers without downtime.
Results: one system to operate and secure, faster controller failover, and support for far more partitions. Deployment modes: dedicated controllers (recommended for production) or combined (process acts as both broker and controller, fine for development).
Producers
The produce path
send() is asynchronous:
- Serialize the key and value.
- Partition: choose a partition (below).
- Accumulate into a per-partition batch in memory (
batch.size, default 16 KB;linger.ms, default 5 ms since Kafka 4.0, previously 0). - A background sender thread ships batches to partition leaders, compressed, with up to
max.in.flight.requests.per.connection(default 5) requests in flight. - On response, invoke the callback / complete the future. Retriable errors are retried up to
delivery.timeout.ms(default 2 minutes).
Throughput levers: bigger batch.size, linger.ms of 5–50 ms, compression.type=zstd or lz4. Latency levers: small linger. buffer.memory bounds memory; when full, send() blocks up to max.block.ms, which is natural backpressure.
Partitioners
- Key present:
murmur2(key) % numPartitions, so the same key always lands on the same partition (until partition count changes). That's how you get per-entity ordering. - No key: since Kafka 2.4 the sticky partitioner fills a batch for one partition before switching, which beats round-robin for batching; KIP-794 (3.3) improved it to avoid overloading slow brokers.
- Custom partitioners exist, but changing the partitioning scheme for a key breaks its ordering history.
Hot partitions: a skewed key (one huge customer) makes one partition a bottleneck. Mitigations: compound keys (customerId + bucket), which give up strict per-customer order, or isolate the giant into its own topic.
Idempotent producer
Retries can duplicate (the leader wrote the batch, the ack was lost, the producer retries) and, with several in-flight requests, reorder. The idempotent producer fixes both within a partition:
- The broker assigns the producer a producer ID (PID) and epoch.
- Each batch carries a sequence number per partition.
- The leader rejects duplicates (sequence already seen) and out-of-order sequences, so retries are safe and ordering holds even with 5 in-flight requests.
Enabled by default since Kafka 3.0 (enable.idempotence=true, with acks=all). Its scope: one producer session, per partition. A producer that restarts gets a new PID unless it uses a transactional.id, and an application that calls send() twice for the same business event produces two records: idempotence de-duplicates retries, not your logic.
Transactions
Kafka transactions let a producer write to multiple partitions and topics atomically, optionally including consumer offset commits, so either all writes become visible or none do.
Mechanics:
- The producer has a stable
transactional.id, which survives restarts. OninitTransactions(), the transaction coordinator bumps the epoch and fences any older ("zombie") instance with the same ID; its writes are rejected. - Records are written to partitions immediately but marked as part of an open transaction. On commit, the coordinator writes commit markers to every partition involved (two-phase commit inside Kafka, recorded in the
__transaction_statelog). - Consumers with
isolation.level=read_committedonly see records from committed transactions (they read up to the last stable offset); aborted records are skipped. The default isread_uncommitted.
Kafka 4.0 shipped Transactions V2 (KIP-890's server-side defense), which bumps the epoch on every transaction to close a class of "hanging transaction" and zombie bugs.
Consumers and consumer groups
Groups and partition assignment
Consumers with the same group.id form a consumer group. Each partition is assigned to exactly one consumer in the group, so:
- Within a group, the work is split (like competing consumers), with at most one consumer per partition. Consumers beyond the partition count sit idle.
- Different groups each receive all records independently (pub/sub).
Offsets
Consumers commit offsets to the internal __consumer_offsets topic (compacted, keyed by group + topic + partition). The committed offset is the next offset to read. Options:
enable.auto.commit=true(default) commits periodically inpoll(), which commits offsets of records returned by the previous poll. If you process synchronously inside the poll loop, that's at-least-once; if you hand records to other threads, auto-commit can commit before they finish (at-most-once for those).- Manual commit (
commitSync/commitAsync) after processing, for explicit at-least-once. - Transactional commit (
sendOffsetsToTransaction) for exactly-once read-process-write. auto.offset.reset(earliest/latest) decides where a group with no committed offset starts.
Consumer lag = log end offset − committed offset, per partition: the primary health metric.
Rebalancing
When group membership or subscriptions change (a consumer joins, leaves, crashes, or misses its deadline), partitions are reassigned: a rebalance.
Classic protocol (pre-KIP-848):
- Eager rebalancing: every consumer revokes all partitions, the group leader (a client) computes a new assignment, and everyone resumes: a stop-the-world pause for the whole group.
- Cooperative / incremental rebalancing (KIP-429,
CooperativeStickyAssignor): consumers keep partitions that don't move; only moved partitions are revoked, over two rounds. Much less disruption. - Liveness via
session.timeout.ms(heartbeats from a background thread) andmax.poll.interval.ms(default 5 min): if your processing betweenpoll()calls exceeds it, the consumer is kicked out, its partitions are reassigned, and its later commits fail. That's a classic source of duplicate processing and "rebalance storms".
The new consumer rebalance protocol (KIP-848), GA in Kafka 4.0, enabled with group.protocol=consumer:
- The group coordinator (broker) computes assignments (server-side assignors
uniformorrange), not a client leader. - Rebalancing is fully incremental: each consumer converges on its target assignment via heartbeats, with no global synchronisation barrier, so one slow consumer doesn't stall everyone.
- Much faster, more predictable rebalances, especially in large groups. The classic protocol remains the default for compatibility; new deployments should opt in.
Static membership (KIP-345, group.instance.id): a consumer with a stable instance ID (e.g. a StatefulSet pod name) that restarts within session.timeout.ms gets its partitions back without a rebalance. That's ideal for rolling deploys.
Rebalance hazards and processing
- When partitions are revoked, commit what you've processed (in
onPartitionsRevoked) or the next owner reprocesses it. - Never block the poll loop for longer than
max.poll.interval.ms; for slow work, lowermax.poll.records, or pause partitions and process asynchronously while still polling. - One consumer thread is not thread-safe; use one consumer per thread, or a framework that parallelises within a partition by key (Confluent's parallel-consumer library for Java does key-ordered parallelism beyond partition count).
Share groups: queues for Kafka
Consumer groups cap parallelism at partition count and acknowledge by offset (you can't skip one poison record without blocking the partition). Share groups (KIP-932) add queue semantics:
- Many consumers can read the same partition, and records are delivered to one of them with a time-limited acquisition lock (like SQS visibility timeout).
- Consumers acknowledge individual records as accept, release (redeliver) or reject, and a delivery count limits retries.
- No per-partition ordering guarantee: this is for work distribution, not ordered streams.
Share groups were early access in 4.0, preview in 4.1, and production-ready in Kafka 4.2 (February 2026). They let Kafka cover many workloads that previously needed a separate queue broker, while keeping retention and replay.
Exactly-once semantics (EOS)
What Kafka guarantees
Kafka's exactly-once semantics combine three pieces:
- Idempotent producer: no duplicates from producer retries.
- Transactions: atomic writes across partitions plus the consumer offset commit.
read_committedconsumers: never see aborted or uncommitted writes.
Together they give exactly-once for read-process-write within Kafka: consume from input topics, transform, write to output topics, and commit input offsets in the same transaction. If the app crashes mid-way, the transaction aborts and the input is reprocessed, but the aborted output is never visible, so the visible effect is exactly-once. Kafka Streams wraps all this in one setting: processing.guarantee=exactly_once_v2.
// Java: transactional read-process-write loop (what Kafka Streams does for you)
producer.initTransactions(); // fences zombies with the same transactional.id
while (running) {
ConsumerRecords<String, Order> records = consumer.poll(Duration.ofMillis(200));
if (records.isEmpty()) continue;
producer.beginTransaction();
try {
for (var r : records)
producer.send(new ProducerRecord<>("invoices", r.key(), toInvoice(r.value())));
producer.sendOffsetsToTransaction(nextOffsets(records), consumer.groupMetadata());
producer.commitTransaction(); // outputs + input offsets, atomically
} catch (ProducerFencedException e) {
producer.close(); throw e; // a newer instance took over
} catch (KafkaException e) {
producer.abortTransaction();
rewindToCommitted(consumer); // reprocess the batch
}
}
Where it stops
The boundary matters (chapter 68 expands): EOS covers Kafka-to-Kafka. Side effects outside Kafka (writing to Postgres, calling a payment API, sending an email) aren't part of the Kafka transaction. For those you need idempotent sinks (upserts keyed by event ID, chapter 74), the outbox pattern for the reverse direction (chapter 73), or connectors that support exactly-once (Kafka Connect source connectors with EOS, KIP-618; sinks that store offsets alongside data).
Retention, compaction and tiered storage
Delete retention
cleanup.policy=delete (default) removes whole closed segments older than retention.ms (default 7 days) or beyond retention.bytes per partition. Deletion is segment-granular, so data can live a little longer than configured.
Log compaction
cleanup.policy=compact keeps at least the latest record for each key:
- A background cleaner rewrites closed segments, dropping older records whose key has a newer value.
- A record with a null value is a tombstone: it deletes the key, and is itself removed after
delete.retention.ms. - Offsets are preserved (gaps appear); order per key is preserved.
A compacted topic is a table as a changelog: replay it from the beginning and you rebuild the latest state per key. Uses: __consumer_offsets, Kafka Streams state store changelogs, CDC topics of current rows, configuration and reference data. You can combine compact,delete to compact and also drop very old keys.
Tiered storage
Tiered storage (KIP-405, production-ready since Kafka 3.9) moves closed segments to remote object storage (S3, GCS, Azure Blob) while keeping recent data on local disk. Brokers become lighter (faster recovery and rebalancing of replicas), and long retention becomes cheap: months or years of history for replay. Managed and Kafka-compatible offerings (Confluent, Redpanda, WarpStream, AutoMQ, Aiven) push further toward object-storage-first designs that write straight to S3 and trade some latency for much lower cost and cross-zone traffic. Apache Kafka is discussing similar "diskless topics" proposals.
Schemas and Schema Registry
Why schemas
Kafka moves bytes, and topics outlive any one producer or consumer version. Without a contract, a producer adding or renaming a field silently breaks consumers, possibly months later during a replay. A schema registry stores versioned schemas per subject (usually per topic value/key) and enforces compatibility rules when producers register new versions.
How it works
- The producer serializer registers (or looks up) the schema and gets a schema ID.
- It writes the ID in the record (in the Confluent wire format: a magic byte plus a 4-byte ID before the payload; newer versions can put it in a header).
- The consumer deserializer fetches the schema by ID (cached) and decodes.
Formats: Avro (compact, schema-required, strong evolution rules, the traditional Kafka choice), Protobuf (field numbers, popular across gRPC estates), JSON Schema (readable, larger, weaker typing). Implementations: Confluent Schema Registry, Apicurio Registry (Red Hat, Apache-licensed), Karapace (Aiven, open source), AWS Glue Schema Registry.
Compatibility modes
| Mode | Rule | Safe upgrade order |
|---|---|---|
| BACKWARD (default) | New schema can read data written with the previous schema (e.g. add optional fields with defaults, remove fields) | Upgrade consumers first |
| FORWARD | Old schema can read data written with the new one (e.g. add fields, remove optional ones) | Upgrade producers first |
| FULL | Both | Any order |
*_TRANSITIVE |
Check against all previous versions, not just the latest | Needed when consumers may replay old data |
| NONE | No checks | Dangerous |
// Protobuf evolution rules: never reuse a field number, add new optional fields, reserve removed ones
syntax = "proto3";
message OrderPlaced {
string order_id = 1;
string customer_id = 2;
int64 total_cents = 3;
reserved 4; // was 'coupon', removed: number can never be reused
reserved "coupon";
optional string currency = 5; // new field: old consumers ignore it, new consumers default it
}
Kafka Streams, Connect and the ecosystem
- Kafka Connect: a framework and runtime for source connectors (databases via Debezium CDC, files, SaaS) and sink connectors (Elasticsearch, S3, data warehouses, JDBC), configured as JSON rather than code, with offsets tracked for you and single message transforms. Chapter 73 covers CDC.
- Kafka Streams (Java library): stateful stream processing inside your application, with no separate cluster. KStream (event stream) and KTable (changelog / latest value per key) abstractions, joins, windowed aggregations, local RocksDB state stores backed by compacted changelog topics, interactive queries, and EOS v2. Kafka 4.x adds the new Streams rebalance protocol (KIP-1071, broker-coordinated) and a built-in dead-letter queue for processing errors (KIP-1034).
- Apache Flink: a separate cluster for large-scale stateful stream processing (event time, watermarks, savepoints, SQL), commonly reading and writing Kafka.
- ksqlDB / Flink SQL: SQL over streams.
- Kafka-compatible implementations: Redpanda (C++, thread-per-core, Raft per partition, no JVM), WarpStream and AutoMQ (object-storage-based), Azure Event Hubs' Kafka endpoint, AWS MSK (managed Apache Kafka).
Clients across languages
The official client is Java. Most others wrap librdkafka (C), which is mature, fast and feature-rich:
| Language | Client |
|---|---|
| Java / Kotlin / Scala | kafka-clients (reference implementation, first to get new features such as KIP-848 and share groups); Spring for Apache Kafka; Kafka Streams |
| Go | confluent-kafka-go (librdkafka), franz-go (pure Go, very complete and fast), segmentio/kafka-go |
| Python | confluent-kafka-python (librdkafka), aiokafka (asyncio), FastStream |
| Rust | rdkafka (librdkafka bindings, async via Tokio) |
| C / C++ | librdkafka, cppkafka |
| .NET | Confluent.Kafka (librdkafka) |
| Elixir | brod (Erlang), broadway_kafka |
| Node | KafkaJS (unmaintained), @confluentinc/kafka-javascript (librdkafka) |
// Java: reliable producer + KIP-848 consumer with manual commits
Properties p = new Properties();
p.put("bootstrap.servers", "kafka:9092");
p.put("acks", "all"); // default since 3.0, stated for clarity
p.put("enable.idempotence", "true"); // default since 3.0
p.put("compression.type", "zstd");
p.put("linger.ms", "10");
try (var producer = new KafkaProducer<String, String>(p, new StringSerializer(), new StringSerializer())) {
producer.send(new ProducerRecord<>("orders", order.id(), json(order)), (md, ex) -> {
if (ex != null) log.error("send failed after retries", ex); // e.g. delivery.timeout.ms exceeded
});
}
Properties c = new Properties();
c.put("bootstrap.servers", "kafka:9092");
c.put("group.id", "billing");
c.put("group.protocol", "consumer"); // KIP-848 rebalance protocol (GA in 4.0)
c.put("group.instance.id", System.getenv("POD_NAME")); // static membership
c.put("enable.auto.commit", "false");
c.put("isolation.level", "read_committed");
try (var consumer = new KafkaConsumer<String, String>(c, new StringDeserializer(), new StringDeserializer())) {
consumer.subscribe(List.of("orders"));
while (running) {
var records = consumer.poll(Duration.ofMillis(500));
for (var r : records) billing.handle(r.key(), r.value()); // idempotent handler
consumer.commitSync(); // at-least-once
}
}
// Go: franz-go producer and consumer group
cl, _ := kgo.NewClient(
kgo.SeedBrokers("kafka:9092"),
kgo.ConsumerGroup("billing"),
kgo.ConsumeTopics("orders"),
kgo.DisableAutoCommit(),
kgo.RequiredAcks(kgo.AllISRAcks()),
kgo.ProducerBatchCompression(kgo.ZstdCompression()),
)
defer cl.Close()
cl.Produce(ctx, &kgo.Record{Topic: "orders", Key: []byte(o.ID), Value: body},
func(r *kgo.Record, err error) { if err != nil { log.Printf("produce: %v", err) } })
for {
fetches := cl.PollFetches(ctx)
fetches.EachRecord(func(r *kgo.Record) { handle(r.Key, r.Value) })
if err := cl.CommitUncommittedOffsets(ctx); err != nil { log.Printf("commit: %v", err) }
}
# Python: confluent-kafka (librdkafka) with Avro via Schema Registry
from confluent_kafka import Consumer
from confluent_kafka.schema_registry import SchemaRegistryClient
from confluent_kafka.schema_registry.avro import AvroDeserializer
from confluent_kafka.serialization import SerializationContext, MessageField
sr = SchemaRegistryClient({"url": "http://schema-registry:8081"})
deser = AvroDeserializer(sr)
c = Consumer({"bootstrap.servers": "kafka:9092", "group.id": "billing",
"enable.auto.commit": False, "auto.offset.reset": "earliest"})
c.subscribe(["orders"])
while True:
msg = c.poll(1.0)
if msg is None or msg.error():
continue
order = deser(msg.value(), SerializationContext(msg.topic(), MessageField.VALUE))
handle(order)
c.commit(message=msg, asynchronous=False)
// Rust: rdkafka StreamConsumer (async) with manual commit
let consumer: StreamConsumer = ClientConfig::new()
.set("bootstrap.servers", "kafka:9092")
.set("group.id", "billing")
.set("enable.auto.commit", "false")
.create()?;
consumer.subscribe(&["orders"])?;
loop {
let msg = consumer.recv().await?;
if let Some(payload) = msg.payload() {
handle(msg.key(), payload).await?;
}
consumer.commit_message(&msg, CommitMode::Async)?;
}
Operations essentials
- Sizing: RF=3,
min.insync.replicas=2, spread replicas across racks/zones (broker.rack), and leave disk and network headroom for replica catch-up after failures. - Key metrics:
- under-replicated partitions (should be 0)
- offline partitions
- ISR shrink/expand rate
- request latency (produce/fetch p99)
- consumer lag and lag growth
- active controller count (exactly 1)
- disk usage
- Topic hygiene: create topics explicitly (
auto.create.topics.enable=false), name them with a convention (<domain>.<entity>.<event>.v1), set retention per use case, and use ACLs or OAuth per principal. - Reassignment and balancing:
kafka-reassign-partitions, Cruise Control for automated rebalancing; throttle replication traffic during moves. - Upgrades: rolling, one broker at a time; watch under-replicated partitions return to 0 before moving on; mind
metadata.version/ feature levels in KRaft. - Kubernetes: Strimzi operator (CNCF) is the common way to run Kafka on Kubernetes; managed services (MSK, Confluent Cloud, Aiven) remove most toil.
Lab: Kafka client behaviour you can measure
The franz-go 1.18 client against kfake (an in-memory cluster that implements the Kafka protocol: produce, fetch, groups, offsets, idempotent producers). The point is client and protocol behaviour, which doesn't depend on the broker implementation; for throughput numbers, test a real Kafka or Redpanda cluster on your own hardware.
Experiment 1: what linger does to requests
20,000 records of 100 bytes produced asynchronously at about 100 records per millisecond (a steady trickle, like a busy web app), with the broker counting produce requests:
linger 0s : 262 produce requests, 76.3 records/request, 304ms
linger 5ms : 92 produce requests, 217.4 records/request, 277ms
linger 50ms : 7 produce requests, 2857.1 records/request, 264ms
Even with linger = 0 the client batched (76 records per request), because records that arrived while a request was in flight queued up behind it. A 5 ms linger cut the requests by 3×, and 50 ms by 37×. Every request costs the broker a network round, a log append and replication; fewer, bigger batches compress better and cost less CPU. The price is up to linger of extra latency per record. Since Kafka 4.0 the Java producer's default linger.ms is 5 (it was 0).
Experiment 2: the duplicate that idempotence prevents
A dialer wrapper let the producer send a batch of five charge records, waited 100 ms for the broker to append them, then cut the connection so the response never arrived. The client retried the batch:
idempotence off: sent 5 charges (+1 warm-up), connection lost after the broker wrote them, client retried: 11 records in the log
idempotence on : sent 5 charges (+1 warm-up), connection lost after the broker wrote them, client retried: 6 records in the log
Without idempotence the log held every charge twice. With it, the broker saw the same producer ID, epoch and sequence numbers and acknowledged the retry without appending. That's the ambiguous timeout of the Start Here chapter, solved by the protocol. It covers retries within one producer session: if the application crashes and resends from its own state, it needs a transactional ID or deduplication downstream (chapter 74).
Experiment 3: when to commit
100 email records; the consumer crashes while handling record 57 and is restarted:
commit after processing, every 20: 17 sent twice, 0 never sent
commit before processing: 0 sent twice, 1 never sent
Committing after processing is at-least-once: everything since the last commit (offset 40) was redone, so 17 emails went out twice. Committing first is at-most-once: the record being handled at the crash was lost. Committing more often shrinks the duplicate window but never closes it. The consumer itself has to be idempotent (an email-sent table keyed by message ID), or the side effect and the offset must be committed together (Kafka transactions for Kafka-to-Kafka pipelines, or storing offsets in the same database transaction as the result).
Experiment 4: eager versus cooperative rebalancing
12 partitions, three consumers; a fourth joins:
eager range: 6 partitions changed owner, 12 partition revocations (processing paused on them)
cooperative-sticky: 3 partitions changed owner, 3 partition revocations
In the eager protocol every member gives up every partition before the new assignment, so all 12 stopped, and the range assignor then shuffled 6 to new owners. The cooperative (incremental) protocol moved only the 3 partitions the newcomer needed, and the other 9 kept processing throughout. In autoscaling deployments, rolling restarts and Kubernetes pod churn, that's the difference between brief hiccups and a stop-the-world pause on every change. Kafka 4.0 made the new KIP-848 consumer protocol generally available, which moves assignment to the broker and is incremental by design (group.protocol=consumer).
Experiment 5: adding partitions moves keys
1,000 user keys produced to a 6-partition topic, then the topic was grown to 8 partitions and the same keys produced again:
1,000 user keys, topic grown from 6 to 8 partitions: 744 keys now land on a different partition (74%)
A key stays put only if hash % 6 == hash % 8, which holds for about a quarter of hashes. For three-quarters of users, the old events sit on one partition and new events on another, so a consumer can process them out of order during the switch, and per-key state held in a stream processor is suddenly on the wrong instance. Choose partition counts with headroom (for example, peak consumers × 2), and if you must grow, create a new topic and migrate deliberately.
Try it yourself
- Repeat experiment 1 with
kgo.ProducerBatchCompression(kgo.ZstdCompression())and measure bytes sent. - Make experiment 3's consumer idempotent with a
sentset and confirm 0 duplicates after the crash. - Add static membership (
kgo.InstanceID) and restart one consumer within the session timeout. How many partitions move? - Use
kfake.ControlKeyto make the broker answerNOT_LEADER_FOR_PARTITIONto the first produce request and watch the client refresh metadata and retry.
Revision sheet: Kafka in depth
Key ideas
- Model: distributed, partitioned, replicated commit log; records are key, value, headers and timestamp at an offset.
- Storage: partitions are segment files with offset and time indexes; sequential I/O, page cache and zero-copy make it fast.
- Replication: leader and followers per partition; the ISR;
acks=allwithmin.insync.replicas=2and RF 3 for durability; the high watermark limits what consumers see; unclean leader election trades data for availability. - KRaft: the metadata quorum replaces ZooKeeper (Kafka 4.0 removed ZooKeeper entirely).
- Producers: partitioner (murmur2 of key, sticky for null keys), batching (
linger.ms,batch.size), compression, idempotence (producer ID + epoch + sequence), retries anddelivery.timeout.ms, transactions. - Consumers: groups, assignment strategies, eager vs cooperative rebalancing, KIP-848 protocol, static membership, offset commits,
auto.offset.reset,max.poll.interval.ms, lag. - Share groups (KIP-932): queue semantics on topics, with per-record acknowledgement and several consumers per partition.
- EOS: idempotent producer + transactions +
read_committedconsumers for read-process-write within Kafka. - Retention: delete by time/size, compaction by key (latest value per key, tombstones), tiered storage for cheap long retention.
- Ecosystem: Schema Registry with compatibility modes, Kafka Connect (source/sink, Debezium CDC), Kafka Streams, Flink, MirrorMaker 2.
Numbers to remember
- RF 3,
min.insync.replicas=2,acks=allis the standard durable setting. - Lab: linger 5 ms cut produce requests 3×, 50 ms cut them 37×; idempotence turned 11 records into 6 after a lost response; committing every 20 records redid 17 after a crash; cooperative rebalancing revoked 3 partitions instead of 12; growing 6→8 partitions moved 74% of keys.
Pitfalls
- Too few partitions for future consumers, or growing a keyed topic in place.
- Hot keys and skewed partitions.
acks=1ormin.insync.replicas=1in production; unclean leader election enabled.- Auto-commit with asynchronous processing, losing records on crash.
- Slow processing exceeding
max.poll.interval.ms, causing rebalance storms. - No schema contract, so producers break consumers.
- Assuming exactly-once covers side effects outside Kafka.
Glossary
- ISR: in-sync replicas, the followers caught up with the leader.
- High watermark: highest offset replicated to all ISR; consumers read up to it.
- Consumer group: consumers sharing partitions with common committed offsets.
- Rebalance: reassignment of partitions when membership changes.
- Compaction: retention keeping only the latest record per key.
- Tombstone: a null-value record that deletes a key under compaction.