2026-11-11·作者 Sijie Wang

Apache Kafka

Apache Kafka is a distributed commit log: partitions, replicas, ISR, consumer groups, and delivery semantics, explained from mechanism.

Apache Kafka is a distributed commit log: producers append records to an append-only log, consumers read by offset at their own pace. Every feature — partitions, replicas, consumer groups — exists to resolve three tensions: the log must be fast, must not lose data, and must let many readers work in parallel.

1. The core model: topic, partition, offset

What it is. A topic is a named log. A topic is split into partitions; each partition is one ordered, append-only log stored on one broker, and each record in a partition gets a sequential offset (0, 1, 2, …). A partition is the unit of parallelism AND the unit of ordering: records with the same key always land in the same partition (key hash mod partition count), so order is strict inside one partition and undefined across partitions. The offset is the consumer's bookmark: a consumer group stores how far it has read, per partition, in the internal __consumer_offsets topic (or in its own store).

Segment files. A partition's log is cut into segment files on disk: .log (the records), .index (offset to file position), .timeindex (timestamp to offset). Old segments are deleted by retention (time or size) or compacted (see §2).

Good example. Order events keyed by order ID: all events for one order land in one partition, in order — the consumer sees created, then paid, then shipped, in that exact order — and three consumers in the group read three partitions in parallel.

Bad example. Keying by user ID when one user produces 90% of traffic: that partition becomes hot, one consumer drowns while the others idle. Key skew is the classic partition mistake — the fix is a better key, or keyless round-robin when order does not matter.

2. Retention and compaction: two ways to forget

Why two mechanisms. A log cannot grow forever, but different uses need different forgetting. Retention deletes whole old segments after a time or size limit — right for event streams where old events lose value. Compaction keeps only the latest record per key and drops superseded ones — right for changelog and state topics (database CDC, config tables), where the topic IS the current state.

Mechanism. Compaction runs in the background: it scans segments, keeps the newest record for each key, and drops the rest; a key with a null value (a tombstone) deletes the key after a grace period. Compaction never touches the active segment.

Good example. CDC from a user table: the topic holds the latest row per user ID; a new consumer can rebuild the whole table by reading the compacted topic from offset 0.

Bad example. Compacting an order-events topic: "order created" would be dropped once "order shipped" arrives for the same key, and the history is gone. Events need retention, not compaction.

3. Why it is fast: sequential writes, page cache, zero-copy

Motivation. Random disk writes are slow; sequential writes are fast — a disk writes sequentially at near its full bandwidth. Kafka's whole design is built on one observation: if every write is an append to the end of a file, the disk never seeks.

Implementation. Three pieces:

  • Append-only. Producers only append; the broker never rewrites a record in place.
  • Page cache. The broker does not manage its own cache; it lets the operating system's page cache hold hot segments. Reads of recent data never touch disk, and writes go to cache first.
  • Zero-copy. When a consumer fetches, the broker sends file bytes to the socket with sendfile, without copying data into user space and back. No deserialization, no per-record work on the broker.

Batching and compression. Producers batch records and compress them (gzip, Snappy, LZ4, Zstd); the broker stores the batch as-is and the consumer decompresses. Throughput comes from batches, not from single records.

Bad example. acks=all plus fsync per record plus one record per request: every mechanism that makes Kafka fast is defeated at once, and throughput collapses to disk-sync speed. The fast path is: batch, compress, let the page cache do its job.

4. Replicas and not losing data: ISR, HW, LEO, acks

Motivation. One broker dies; the data must survive. So every partition has replicas on other brokers: one leader takes all reads and writes, followers pull new records from the leader and append them to their own logs.

The three numbers.

  • LEO (Log End Offset). The offset of the next record to be written on a replica — how far that replica has got.
  • HW (High Watermark). The largest offset replicated to all in-sync replicas. Records below the HW are committed: they survive a leader change. Records above it are not yet safe.
  • ISR (In-Sync Replicas). The set of replicas whose LEO is close enough to the leader's (within replica.lag.time.max.ms). A follower that falls behind drops out of the ISR.

Write path. Producer sends, leader appends (LEO moves), followers fetch and append, and once every ISR member has the record, the leader advances the HW; then the leader acks the producer (when acks=all). A consumer only ever reads up to the HW, so it never sees uncommitted data.

acks is a durability dial.

  • acks=0: fire and forget. Fastest, may lose data silently.
  • acks=1: leader appended, no replica wait. Loses data if the leader dies before followers copy.
  • acks=all (with min.insync.replicas): waits for every ISR member. Safe as long as at least min.insync.replicas are alive; if fewer are in sync, produce fails rather than risking loss.

Bad example, the classic loss. acks=1, leader appends, crashes before any follower copies, and a follower with stale data becomes leader: the record is gone, and nobody is told. The fix is acks=all plus min.insync.replicas=2 (with replication factor 3): a write only succeeds when two brokers hold it, so one broker dying cannot lose it.

Unclean leader election. If all ISR members die, Kafka can elect an out-of-sync replica as leader (unclean.leader.election.enable=true) — the partition comes back, but everything after the new leader's LEO is lost. Default is off: the partition stays unavailable rather than silently losing data. Availability versus durability, chosen explicitly.

5. Producers and consumers: partitioning, idempotence, groups, delivery

Partitioner. The producer picks a partition per record: with a key, hash the key mod partition count (sticky partitioning keeps the batch on one partition for a while to improve batching); without a key, round-robin. Same key goes to the same partition, so order is preserved.

Idempotent producer. Retries can duplicate a record (produce, ack lost, retry, written twice). The idempotent producer gives each producer instance a PID (producer ID) and a sequence number per partition; the broker deduplicates by (PID, partition, sequence). Turned on with enable.idempotence=true; it only dedupes within one producer session.

Transactions. For read-process-write exactly-once, the producer uses a transactional.id and the transaction coordinator: it writes records and its offset commits as one atomic transaction, marked with a commit or abort marker in the log; consumers with isolation.level=read_committed skip aborted transactions.

Consumer groups and rebalancing. Consumers in one group split the partitions: each partition is read by exactly one consumer in the group, so the group's parallelism is capped by the partition count. When a consumer joins or leaves, the group rebalances — partitions are reassigned. Eager rebalancing stops all consumption while reassigning; cooperative rebalancing (KIP-429) moves partitions incrementally without a full stop.

Delivery semantics.

  • At-least-once: commit the offset after processing. A crash between processing and committing reprocesses the record — duplicates, no loss. This is the normal, honest default.
  • At-most-once: commit before processing. A crash loses the record.
  • Exactly-once: only inside Kafka transactions (read-process-write), and only when the downstream is Kafka or a transactional sink. A consumer alone cannot promise exactly-once to an arbitrary database — the offset commit and the database write are two systems, and no single transaction covers both (unless the sink participates, for example via the outbox pattern or a transactional sink).

Bad example. Six consumers in a group on a three-partition topic: three consumers idle forever — more consumers than partitions adds nothing. The fix is more partitions (at topic creation; adding partitions later breaks key-to-partition mapping for existing keys).

6. Controller and metadata: ZooKeeper to KRaft

Motivation. Somebody has to know which broker is leader for each partition, and somebody has to elect a new leader when one dies. Originally that somebody was ZooKeeper: brokers registered there, one broker was elected controller, and the controller pushed metadata to everyone. Two systems to run, two failure modes, and metadata changes went through ZooKeeper's write path — a bottleneck for large clusters.

KRaft (Kafka Raft, KIP-500). Since Kafka 2.8 (early access) and production-ready in 3.x, Kafka runs its own Raft quorum (the controller quorum) and stores cluster metadata in an internal __cluster_metadata topic. Brokers fetch metadata from the controller. No ZooKeeper, one system to run, faster metadata propagation, and clusters can scale to more partitions.

Mechanism. Controller quorum nodes elect a leader by Raft; the leader writes metadata records to the metadata log; all brokers replicate it. Partition leadership changes are metadata records too — the same log, the same consensus.

Good example. A new cluster in 2026: KRaft mode, no ZooKeeper anywhere. ZooKeeper mode is deprecated and removed in Kafka 4.0.

7. Using it well: rules and checks

When Kafka fits. Event streams between services, log aggregation, CDC, stream processing, replayable history (a new consumer reads from offset 0). When it does not fit: a strict priority queue, point lookups by key (that is a database), request-reply RPC (that is an RPC framework), or tiny low-throughput messaging where a simple queue is enough.

Rules that fall out of the mechanisms.

  • Partition count is the parallelism ceiling for one consumer group; size it for the peak, not the start.
  • Keys decide order and balance; a skewed key is a hot partition.
  • acks=all plus min.insync.replicas=2 plus replication factor 3 is the standard durability triple.
  • Monitor consumer lag (HW minus committed offset, per partition): lag that grows is the first sign of a slow consumer or a hot partition.
  • Rebalance storms come from short session timeouts and slow consumers; tune session.timeout.ms and max.poll.interval.ms before adding consumers.
  • Retention is disk: size it from bytes-per-day times retention days, not from hope.

Online checks. The numbers that matter: produce latency (p99), consumer lag per partition, ISR shrink rate (followers falling out), under-replicated partition count, and controller election frequency. A healthy cluster has zero under-replicated partitions and flat lag.

8. Scenario: five brokers, bad network

Setup. Five brokers B1–B5, one topic orders, 5 partitions, replication factor 3. Fifteen replicas in total: each broker holds 3 replicas and leads 1 partition.

Event 1: normal write path (acks=all).

Event 2: network jitter — a follower falls behind.

Event 3: consumer heartbeat timeout — rebalance storm.

Event 4: network partition — B3 isolated.

Reads are unaffected throughout: consumers keep reading committed data up to the old HW.

Event 5: controller isolated.

Event 6: node failures versus partition availability.

9. Consumer side: offsets, duplicate processing, and rebalancing

The offset is a bookmark, and when you move it decides your delivery semantics. A consumer group stores one committed offset per partition. Everything on the consumer side follows from one question: do you move the bookmark before or after processing?

Three ways to commit.

  • Auto commit (enable.auto.commit=true, every auto.commit.interval.ms, default 5s). A background thread commits whatever offset the consumer has reached, on a timer, regardless of whether those records were processed. Crash after the commit but before processing finishes: those records are skipped forever (data loss). Process slowly and the commit lags: a rebalance replays records you already processed (duplicates). The commit timing is decoupled from processing progress — that is the whole problem.
  • Manual synchronous commit (commitSync). You call it after processing a batch; it blocks until the broker acks. If it fails it retries — safe, because committing the same offset twice is harmless. The cost is a blocking round trip per batch.
  • Manual asynchronous commit (commitAsync). Non-blocking, with a callback; on failure it does not retry, because retries can arrive out of order and overwrite a newer commit with an older one. The standard pattern is commitAsync during steady processing plus a commitSync on shutdown or before a rebalance.

The honest default. Poll, process, commitSync (or commitAsync with a periodic commitSync). That is at-least-once: a crash between processing and committing replays the batch. Duplicates are the price; the fix belongs downstream.

Why rebalancing causes duplicate processing.

The records were processed but never committed, so the new owner replays them. This is not a bug — it is what at-least-once means.

Fixes, in order of strength.

  • Commit promptly after processing (shrink the window), and use a ConsumerRebalanceListener: in onPartitionsRevoked, commit the offsets of work already done before the partition is taken away — the last chance to close the window.
  • Make processing idempotent downstream: write with a business key (upsert by order ID, dedupe table). Reprocessing the same record then has no effect.
  • Transactions (read-process-write): the offset commit and the produced records go in one atomic transaction; consumers with read_committed skip aborted ones. This is the only way to get exactly-once, and only when the downstream is Kafka or a transactional sink.

Assignment strategies: who gets which partition.

  • Range (default). Partitions are dealt per topic in contiguous ranges; with uneven counts the split is lopsided (3 consumers, 2 topics of 3 partitions each: one consumer gets 4 partitions, another gets 2).
  • RoundRobin. Dealt round-robin across all topics: balanced, but scatters one topic's partitions across consumers.
  • Sticky (KIP-54). Keeps the previous assignment and moves only what must move — fewer partitions change hands per rebalance.
  • CooperativeSticky. The sticky assignor for cooperative rebalancing: partitions move incrementally, no full stop.

Static membership (KIP-345, group.instance.id). Motivation: every restart (deploy, upgrade) looks like a member leaving and a new one joining, which triggers a full rebalance and stops all consumption. Give the consumer a fixed instance ID; when it restarts and returns with the same ID within session.timeout.ms, the coordinator recognizes it as the same member and the partitions do not move — no rebalance.

Fencing. If the old instance is still alive somewhere (a zombie after a network partition), its requests carry a stale member epoch and are rejected (fenced). The epoch is what stops two instances with the same ID from both writing.

Offset reset (auto.offset.reset). When a group has no committed offset (brand new group, or offsets expired): earliest reads from the beginning, latest reads only new records, none throws. A new group with latest silently skips history — the classic onboarding mistake.

Good example. Process, commitSync, write downstream by business key (upsert), sticky assignor, static membership, session timeout sized for your network. Bad example. Auto commit on, slow processing, rebalance storm: duplicates on every rebalance, and records skipped whenever the commit runs ahead of processing.

关于这一条

sijie 的一条 wiki 条目。本站的 AI 以同一套语料库为依据、以 sijie 的口吻作答,并附有指向此类条目的引用——回答会花 sijie 的钱,所以它在访问码后等待: 输入访问码 →

Apache Kafka — Sijie Wang