Design a Distributed Message Queue: Commit Logs, Replication, ISR & Delivery Semantics
Designing Kafka From First Principles
Distributed Message Queue Internals
1. Storage Engine: Append-Only Partitioned Commit Logs
- Topics & Partitions: Each topic splits into $P$ partitions distributed across brokers. Every message inside a partition gets a monotonically increasing
offset. - Segment Files: Instead of one giant 10 TB file, each partition splits into rolling Segment Files (e.g., 1 GB chunks) accompanied by
.indexand.timeindexsparse lookup files sooffset -> byte_positionfinds any event in $O(\log N)$! - Sequential Disk + OS Page Cache: Sequential disk writes match RAM speeds on modern kernels, and Linux
sendfile()zero-copy transfers bytes straight from OS page cache to the network NIC without copying into JVM/user space.
2. Consumer Groups & Rebalancing
- Multiple Consumer Groups reading the same topic act as independent Pub/Sub subscribers (Billing + Analytics both read
ordersindependently). - Instances within ONE Consumer Group act as competing workers: each partition is assigned to at most one consumer instance inside that group, guaranteeing strict message ordering per partition!
- Offset Checkpointing: Store committed offsets cleanly in an internal compacted topic (
__consumer_offsets) rather than hitting ZooKeeper on every ack.
3. High Availability: Leader-Follower & In-Sync Replicas (ISR)
- ISR (In-Sync Replicas): The dynamic subset of followers actively caught up within
replica.lag.time.max.ms. - Producer Durability Settings (
acks):
acks Setting | Behavior | Trade-Off |
|---|---|---|
acks=0 | Fire-and-forget | Lowest latency, loses messages on crash |
acks=1 | Leader writes locally & acks | Fast; loses recent writes if leader dies before replication |
acks=all (-1) | Leader waits for all min.insync.replicas to persist | Zero data loss for critical financial/order streams |
4. Delivery Semantics & Batching Optimizations
- At-Most-Once: Commit offset before processing (risks loss, zero duplicates).
- At-Least-Once: Commit offset after processing (requires idempotent consumers to ignore duplicates).
- Exactly-Once: Combine idempotent producer sequence numbers + transactional coordinator across read-process-write atomic offsets.
- Throughput Boosters: Batch multiple small events client-side (
linger.ms+batch.size) compressed with LZ4/Snappy before shipping over TCP!