Design: distributed message queue

In one sentence

Store each topic as partitioned append-only logs, replicate every partition from a leader to in-sync followers, acknowledge once they have the write, and let consumer groups pull by offset and commit their own position.

Producers append to the partition leader; followers fetch from it, and the ack returns once the in-sync replicas have the batch. Consumers pull by offset and commit their position.

How it works

  • A partition is an append-only log of segment files; a message's id is its offset.
  • Sequential writes, the OS page cache, batching and zero-copy sendfile make plain disks fast.
  • A write is committed once every in-sync replica has it; consumers only see committed messages.
  • Replication factor 3, min.insync.replicas=2 and acks=all survive a broker loss without losing acknowledged data.
  • Consumers pull at their own pace: the broker tracks one offset per group and partition, not per-message acks.

Check yourself

Answer to mark it learned; your answers aren't scored.

A topic has replication factor 3 and min.insync.replicas=1; producers use acks=all. Both followers lag and leave the ISR. The leader acknowledges a batch, then loses its disk: no other broker ever had that batch. What do you change?

Go deeper

Do this round in 45 minutes System design round
Full explanation

Requirements

Functional: producers publish to a topic; every consumer group reads every message, in order per key; messages are retained for days and can be replayed. Non-functional: no acknowledged message is lost when a broker dies; throughput near disk and network limits; publish latency of a few ms.

Scale (assumed): 1M messages/s × 1 KB ≈ 1 GB/s ≈ 86 TB/day; 7 days × 3 replicas ≈ 1.8 PB.

Questions I'd ask:

  1. Task queue (one worker per message, deleted on ack) or log (retained, replayable)? Queues vs streams (Kafka) covers the difference; here I design the log.
  2. Ordering: global, or per key?
  3. May a producer trade durability for latency?

API and data model

produce(topic, key, value) → (partition, offset), fetch(topic, partition, offset, max_bytes), commit(group, partition, offset). A topic is split into partitions; hash(key) % partitions picks one, so order holds per key. A partition is an append-only log and a message's id is its offset.

Architecture

  1. Storage: a partition is a directory of segment files (1 GiB by default in Kafka) with a sparse offset index. Writes append to the last segment; retention deletes whole old segments.
  2. Replication: each partition has a leader and followers that fetch from it. The in-sync replicas (ISR) are the ones keeping up. A write is committed once every ISR member has it, and consumers only see committed messages (Replication).
  3. Consumers pull. A group coordinator gives each partition to one member of the group, and members commit their offsets to an internal topic.
  4. Metadata (brokers, partition leaders, ISR) lives in a small Raft quorum: KRaft in Kafka, which dropped ZooKeeper in 4.0 (March 2025) (Consensus (Raft)).

The hard parts

  1. Throughput from disks: sequential I/O, the OS page cache, batching and zero-copy.
  2. Durability vs availability when replicas fall behind: acks, min.insync.replicas and who may become leader.
  3. Duplicates: retries and rebalances redeliver, so exactly-once needs idempotent producers and transactions.
Code A partition log: append, sparse index, high watermark
pythonA partition log: append, sparse index, high watermark
import bisect, os, struct

class PartitionLog:
    """One replica of a partition: an append-only file plus a sparse offset index."""
    def __init__(self, path: str):
        self.f = open(path, "ab+")          # append-only: every write goes to the tail
        self.index = [(0, 0)]               # sparse (offset, byte position), sorted
        self.next_offset = self.unindexed = 0
        self.high_watermark = 0             # first offset NOT yet committed

    def append(self, value: bytes) -> int:
        pos = self.f.seek(0, os.SEEK_END)
        self.f.write(struct.pack(">QI", self.next_offset, len(value)) + value)
        self.unindexed += 12 + len(value)
        if self.unindexed >= 4096:          # one index entry per ~4 KB of log
            self.index.append((self.next_offset, pos))
            self.unindexed = 0
        self.next_offset += 1
        return self.next_offset - 1         # the message's id is its offset

    def on_replica_progress(self, isr_log_ends: list[int]) -> None:
        self.high_watermark = min(isr_log_ends)   # committed = on every in-sync replica

    def read(self, offset: int, max_msgs: int = 100) -> list[tuple[int, bytes]]:
        i = bisect.bisect_right(self.index, (offset, float("inf"))) - 1
        self.f.seek(self.index[i][1])       # jump near the offset, then scan forward
        out = []
        while len(out) < max_msgs and len(head := self.f.read(12)) == 12:
            off, size = struct.unpack(">QI", head)
            value = self.f.read(size)
            if off >= self.high_watermark:  # never serve uncommitted messages
                break
            if off >= offset:
                out.append((off, value))
        return out
Real example

Topic orders: 12 partitions, replication factor 3, min.insync.replicas=2, producers with acks=all. Broker B2, leader of partition 7, dies. B1 and B3 are in the ISR, so both hold every committed message; the controller makes B1 leader and producers retry against it. Sequence numbers let B1 drop a batch it already stored. Consumers continue from their committed offsets. If B3 then falls behind, the ISR shrinks to one and acks=all writes fail with NotEnoughReplicas: the partition stays readable but refuses writes rather than risk losing them.

Trade-offs +3 · −3

+ You gain

  • Sequential appends and zero-copy reads: throughput is bounded by disk and network bandwidth, not by seeks.
  • Retention decouples consumers: a slow or new consumer replays from disk without affecting the others.
  • ISR replication survives f failures with f+1 replicas, fewer than a majority quorum needs.

− You pay

  • Ordering and parallelism are tied to partitions, and changing the partition count remaps keys.
  • Consumer groups have no per-message ack, delay or priority: one poison message blocks its partition.
  • A commit waits for the slowest in-sync replica until it is dropped from the ISR.

Use it when

High-volume event streams that several teams consume independently and replay: activity tracking, CDC, log and metrics pipelines, the input of stream processors.

Avoid it when

Task queues that need per-message acks, delays or priorities: use SQS or RabbitMQ. Kafka only added per-message acks with share groups (production-ready in 4.2, Feb 2026). For a few events a day, a database table is enough.

Numbers to know 5
  • Assumed load: 1M messages/s × 1 KB ≈ 1 GB/s ≈ 86 TB/day; 7 days × 3 replicas ≈ 1.8 PB.
  • Kafka defaults (4.4 docs, checked Nov 2026): 1 GiB segments, 7-day retention; acks=all and the idempotent producer are defaults since 3.0 (Sept 2021, KIP-679).
  • A follower leaves the ISR after 30 s behind the leader (replica.lag.time.max.ms).
  • Kafka design doc: linear writes ~600 MB/s vs ~100 kB/s random on a six-disk SATA array.
  • ISR survives f failures with f+1 replicas; a majority quorum needs 2f+1.
Common pitfalls 4
  • acks=all with min.insync.replicas=1: when the ISR shrinks to the leader, "all" is one copy and a crash loses acknowledged data.
  • Too few partitions: a consumer group can't run more active consumers than partitions, and adding partitions later breaks per-key order.
  • Turning on unclean leader election to restore availability: an out-of-sync replica becomes leader and committed messages disappear.
  • Sizing disks from the average rate: plan for peak × retention × replication factor, plus room to rebuild a replica.
Interview questions 3

Answer out loud first, then reveal.

A broker dies. What happens to its partitions, and can you lose data?Show answer

For each partition it led, the controller picks a new leader from the ISR. Every ISR member has all committed messages, so nothing acknowledged with acks=all is lost; producers retry, and sequence numbers drop duplicates. Data is at risk only if I allowed acks=1, or if min.insync.replicas=1 let the ISR shrink to the leader alone. I'd run replication factor 3, min ISR 2 and no unclean election.

Why does Kafka replicate with an ISR instead of a majority quorum like Raft?Show answer

Cost per partition. To survive f failures a majority quorum needs 2f+1 replicas; an ISR needs f+1, because a write commits only when every in-sync replica has it, so any of them can lead. For large data that is two copies instead of three to survive one failure. The price: a commit waits for the slowest in-sync replica until it is evicted. Metadata is small, so there Kafka does use a Raft quorum.

How would you offer exactly-once delivery on this log?Show answer

Two mechanisms. On the produce side, an idempotent producer: the broker gives each producer an id and drops batches whose sequence number it has already stored, so retries don't duplicate. For consume-process-produce, a transaction writes the output and the consumed offsets atomically, and readers use read_committed. That holds inside the log. Once I call an external system, I'm back to at-least-once plus an idempotency key.

Deep dive 3

Storage: segments, sequential I/O, retention

Appending to the end of a file is sequential I/O. Kafka's design doc measures linear writes at ~600 MB/s against ~100 kB/s for random writes on the same six-disk array. The broker keeps no cache of its own: it writes to the OS page cache and lets the kernel flush. Producers send batches, which stay compressed on disk and on the way to consumers. Reads go from page cache to socket with sendfile, without copying through user space, so consumers that keep up never touch the disk. A sparse index maps an offset to a file position: binary-search it, then scan a few KB. Retention drops whole segments by age (7 days by default) or size; compaction keeps only the latest value per key.

Replication: ISR, acks and leader election

Followers fetch from the leader like consumers. One that stops fetching or stays behind for replica.lag.time.max.ms (30 s by default) is removed from the ISR. The high watermark is the offset every ISR member has reached; only messages below it are committed and visible. Producers choose: acks=0 (no wait), acks=1 (leader only: lost if it dies before followers copy) or acks=all (every in-sync replica). acks=all only means something with min.insync.replicas ≥ 2: writes then fail when the ISR is too small, instead of being accepted on one copy. On leader failure the controller picks a new leader from the ISR. If none is left, unclean election (off by default) trades committed data for availability. ISR survives f failures with f+1 replicas; a majority quorum needs 2f+1 but never waits for its slowest member.

Consumers, offsets and exactly-once

Pull lets each consumer set its pace, batch, and rewind. A slow consumer builds lag (log end offset − committed offset), the metric to alert and autoscale on, without hurting anyone else. The broker tracks one number per group and partition, not per-message acks. A member that stops heartbeating triggers a rebalance, and work it had not committed is redelivered: at-least-once (Idempotency). Exactly-once inside the log takes two mechanisms. The idempotent producer (on by default since Kafka 3.0, 2021) gets a producer id and numbers its batches, so the broker drops a retried batch it already has. A transaction writes output messages and the consumed offsets atomically; consumers set isolation.level=read_committed to skip aborted data. Outside the log (a database, an email) you still need an idempotency key.