Design a Distributed Message Queue

How a log-based message broker stores, replicates and delivers messages, and the questions interviewers ask about it.

Case study30 minLesson 5 of 7
On this page
  1. Clarify the problem
  2. Estimate the scale
  3. Define the API (optional)
  4. Model the data
  5. High-level design
  6. Deep dives
  7. Bottlenecks and failures
  8. What a strong answer sounds like
  9. Follow-up questions

A distributed message queue is a cluster of servers (brokers) that accepts messages from many producers, stores them durably, and lets many consumers read them later at their own pace. Kafka is the best-known example, and this lesson designs that kind of system: a log that several consumer groups read independently and can replay.

The question is hard because the broker must combine three things that pull against each other: very high throughput, an acknowledgement that really means the message will not be lost when a machine dies, and ordering that survives retries and failovers. The steps follow A Framework for Any Design, and how applications use a queue is covered in Message Queues and Streams.

Clarify the problem

The first five minutes
Interviewer

Design a distributed message queue.

You

Should it be a job queue, where each message goes to one worker and is deleted once handled, or a log that several consumer groups read and can replay?

Interviewer

A log.

You

Do consumers need ordering across all events, or only per key, for example per order ID? And what are the message rate and the retention?

Interviewer

Order per key is enough. Assume 100,000 messages a second on average and three times that at peak, about 1 KB each, kept for seven days. Each message is read by about three consumer groups.

You

Then my priorities are that an acknowledged message is never lost when a broker dies, that order holds per key, and that consumers can rewind to an older position.

Functional requirements. Producers publish messages to a topic, with an optional key. Consumers read in groups: every group receives every message, and the members of a group share the work. Consumers can save their position and rewind it.

Non-functional requirements. No acknowledged message is lost when one broker fails. Messages with the same key are read in the order they were written. Producing has a p99 latency under about 10 ms.

Out of scope. This design does not cover delayed messages or replication across regions.

Estimate the scale

The ingest rate is 100,000 messages a second × 1 KB = 100 MB/s on average and 300 MB/s at peak. With three consumer groups, the cluster sends out 300 MB/s on average and 900 MB/s at peak.

Estimate: Disk for seven days

How much disk does the cluster need to keep 7 days of messages with 3 copies of each?

You know
  • 100 MB/s of messages on average
  • Kept for 7 days
  • 3 copies of every message

Show the working
  1. 100 MB/s × 86,400 s ≈ 8.64 TB a day
  2. 8.64 TB × 7 ≈ 60 TB
  3. 60 TB × 3 copies ≈ 180 TB

Estimate 180 TB (anything from 60 TB to 600 TB is a good answer)

At 12 TB of usable disk per broker, 180 ÷ 12 = 15 brokers if completely full, so about 20 with headroom. The cluster size is therefore decided by disk capacity, not by throughput.

Your turn: Define the API

Write the calls for producing, consuming and saving a position. What does a producer hear when it contacts the wrong broker?

Compare with a model answer

Produce returns the offset of the batch. Fetch takes a partition and an offset, so the consumer owns its position, and commit saves that position for the group. When leadership moves, the broker returns an error that tells clients to refresh their metadata.

Define the API Optional

Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.

Broker protocol (binary over TCP)
Metadata(topics)
  -> per partition: leader broker, replicas, in-sync replicas
 
Produce(topic, partition, batch, acks = 0 | 1 | all,
        producer_id, sequence)
  OK base_offset=5000
  NOT_LEADER                 leadership moved; refresh metadata, retry
  NOT_ENOUGH_REPLICAS        fewer in-sync copies than required
  DUPLICATE_SEQUENCE         already written; returns the first offset
 
Fetch(topic, partition, offset, max_bytes, max_wait_ms)
  records from offset up to the high watermark
  OFFSET_OUT_OF_RANGE        that data was deleted by retention
 
JoinGroup(group, member) / Heartbeat(group, member, generation)
  -> assigned partitions, generation=12
 
CommitOffset(group, generation, partition, offset)
  OK
  ILLEGAL_GENERATION         you were removed from the group; rejoin

The API decision worth arguing is pull versus push. In this design consumers pull from their own offset at their own pace. A slow consumer then slows nobody else, and rewinding is just a fetch with an older offset. A fetch on an empty partition waits up to max_wait_ms before returning.

Your turn: Model the data

How does a broker store a partition so that appends and reads from any offset are fast, and deleting old data is cheap? What must the cluster agree on?

Compare with a model answer

A partition is a directory of segment files named by their first offset, each with a sparse index. Appends go to the newest segment, and retention deletes whole old segments. The cluster must agree on each partition's replicas, its leader and its set of in-sync replicas.

Model the data

One partition on disk, and the cluster metadata
orders-7/                             partition 7 of topic "orders"
  00000000000004000000.log            closed segment, about 1 GB
  00000000000004000000.index          offset -> byte position, every 4 KB
  00000000000005000000.log            active segment: appends go here
  00000000000005000000.index
 
record batch (as sent, as stored, as served)
  base_offset, producer_id, sequence, crc
  records: offset_delta, timestamp, key, value, headers
 
cluster metadata                      held by the controller
  topic -> partitions
  partition -> replicas [1, 2, 3], leader 1, leader_epoch 4,
               in_sync [1, 2, 3]
 
consumer offsets                      an internal topic, compacted
  (group, topic, partition) -> next offset to read

There is no database: the brokers' own files are the store, accessed only by appending and by reading forward from an offset. Consumer positions are stored as messages in a compacted internal topic. The metadata that must never be wrong, such as who leads each partition, is held by a controller that is replicated with consensus.

Your turn: High-level design

Sketch one partition with three replicas. Who does the producer talk to, how do the other copies get the data, and who chooses the leader?

Compare with a model answer

Producers and consumers talk to the leader of the partition, and the followers fetch from the leader in the same way consumers do. A controller quorum records the leaders and the in-sync replicas and replaces a leader that dies.

High-level design

Each topic is split into partitions. Each partition has one leader and two followers on different brokers, and leaders are spread evenly across brokers.

For one partition, producers and consumers talk to the leader, the followers pull from the leader, and the controller quorum records who leads and who is in sync.Producers to Broker 1 (leader) (produce); Consumer group to Broker 1 (leader) (fetch, commit); Broker 2 (follower) to Broker 1 (leader) (fetch); Broker 3 (follower) to Broker 1 (leader) (fetch); Controller quorum to Broker 1 (leader) (leader, ISR).ProducersConsumer groupBroker 1(leader)Broker 2(follower)Broker 3(follower)Controllerquorumproducefetch, commitfetchfetchleader, ISR
For one partition, producers and consumers talk to the leader, the followers pull from the leader, and the controller quorum records who leads and who is in sync.
Produce, replicate, consume, then the leader diesUse the arrows or ← → keys
  1. Produce, replicate, consume, then the leader dies, step 1Producers to Broker 1 (leader); Consumer group to Broker 1 (leader); Broker 2 (follower) to Broker 1 (leader); Broker 3 (follower) to Broker 1 (leader); Controller quorum to Broker 1 (leader).ProducersConsumer groupBroker 1(leader)Broker 2(follower)Broker 3(follower)Controllerquorum
    end of log
    5000
    high watermark
    5000

    1A producer hashes the key order-881 to partition 7, whose leader is broker 1, and sends a batch with acks=all, producer id 31 and sequence number 42.

  2. Produce, replicate, consume, then the leader dies, step 2Producers to Broker 1 (leader); Consumer group to Broker 1 (leader); Broker 2 (follower) to Broker 1 (leader); Broker 3 (follower) to Broker 1 (leader); Controller quorum to Broker 1 (leader).ProducersConsumer groupBroker 1(leader)offset 5000Broker 2(follower)Broker 3(follower)Controllerquorum
    end of log
    5001
    high watermark
    5000

    2Broker 1 appends the batch at offset 5,000. Only one machine has it, so the producer keeps waiting.

  3. Produce, replicate, consume, then the leader dies, step 3Producers to Broker 1 (leader); Consumer group to Broker 1 (leader); Broker 2 (follower) to Broker 1 (leader); Broker 3 (follower) to Broker 1 (leader); Controller quorum to Broker 1 (leader).ProducersConsumer groupBroker 1(leader)Broker 2(follower)has 5000Broker 3(follower)has 5000Controllerquorum
    end of log
    5001
    high watermark
    5000

    3Brokers 2 and 3 fetch from offset 5,000 and append the same bytes to their own logs.

  4. Produce, replicate, consume, then the leader dies, step 4Producers to Broker 1 (leader); Consumer group to Broker 1 (leader); Broker 2 (follower) to Broker 1 (leader); Broker 3 (follower) to Broker 1 (leader); Controller quorum to Broker 1 (leader).ProducersConsumer groupBroker 1(leader)Broker 2(follower)Broker 3(follower)Controllerquorum
    end of log
    5001
    high watermark
    5001

    4Their next fetches ask for 5,001, which tells the leader they hold 5,000, so the high watermark moves to 5,001 and the producer receives OK.

  5. Produce, replicate, consume, then the leader dies, step 5Producers to Broker 1 (leader); Consumer group to Broker 1 (leader); Broker 2 (follower) to Broker 1 (leader); Broker 3 (follower) to Broker 1 (leader); Controller quorum to Broker 1 (leader).ProducersConsumer groupcommitted 5001Broker 1(leader)Broker 2(follower)Broker 3(follower)Controllerquorum
    high watermark
    5001
    billing offset
    5001

    5A billing consumer reads the record from offset 5,000, which is below the high watermark, processes it, and then commits offset 5,001. Committing after processing gives at-least-once delivery.

  6. Produce, replicate, consume, then the leader dies, step 6Producers to Broker 1 (leader); Consumer group to Broker 1 (leader); Broker 2 (follower) to Broker 1 (leader); Broker 3 (follower) to Broker 1 (leader); Controller quorum to Broker 1 (leader).ProducersConsumer groupBroker 1(leader)downBroker 2(follower)has 5001Broker 3(follower)has 5001Controllerquorum
    high watermark
    5001
    billing offset
    5001

    6The producer sends sequence 43. Both followers copy it, but broker 1 dies before it sends the OK, so the producer cannot tell whether the batch was written.

  7. Produce, replicate, consume, then the leader dies, step 7Producers to Broker 1 (leader); Consumer group to Broker 1 (leader); Broker 2 (follower) to Broker 1 (leader); Broker 3 (follower) to Broker 1 (leader); Controller quorum to Broker 1 (leader).ProducersConsumer groupBroker 1(leader)downBroker 2(follower)leaderBroker 3(follower)Controllerquorumepoch 5
    leader
    broker 2
    leader epoch
    5

    7Broker 1 stops sending heartbeats. After a few seconds the controller makes broker 2, which is in sync, the new leader and raises the leader epoch from 4 to 5.

  8. Produce, replicate, consume, then the leader dies, step 8Producers to Broker 1 (leader); Consumer group to Broker 1 (leader); Broker 2 (follower) to Broker 1 (leader); Broker 3 (follower) to Broker 1 (leader); Controller quorum to Broker 1 (leader).ProducersConsumer groupBroker 1(leader)downBroker 2(follower)dup seq 43Broker 3(follower)Controllerquorum
    leader
    broker 2
    copies of seq 43
    1

    8The producer refreshes its metadata and retries sequence 43 at broker 2, which already holds it and returns the original offset 5,001 without writing a second copy.

  9. Produce, replicate, consume, then the leader dies, step 9Producers to Broker 1 (leader); Consumer group to Broker 1 (leader); Broker 2 (follower) to Broker 1 (leader); Broker 3 (follower) to Broker 1 (leader); Controller quorum to Broker 1 (leader).ProducersConsumer groupread 5001Broker 1(leader)downBroker 2(follower)Broker 3(follower)Controllerquorum
    leader
    broker 2
    billing offset
    5001

    9The consumer group moves to broker 2 and continues from offset 5,001. Nothing acknowledged was lost.

  10. Produce, replicate, consume, then the leader dies, step 10Producers to Broker 1 (leader); Consumer group to Broker 1 (leader); Broker 2 (follower) to Broker 1 (leader); Broker 3 (follower) to Broker 1 (leader); Controller quorum to Broker 1 (leader).ProducersConsumer groupBroker 1(leader)truncate, followBroker 2(follower)Broker 3(follower)Controllerquorum
    leader
    broker 2
    leader epoch
    5

    10When broker 1 restarts, it discards any records beyond what broker 2 held at the epoch change and then follows broker 2 until it is back in sync.

1 / 10

Deep dives

How the log is stored on disk

The broker has to write 100 MB/s of small messages. A random 1 KB write on a spinning disk costs a seek of about 10 ms, so it manages about 100 writes and 100 KB a second. Appending to the end of a file streams at about 200 MB/s, roughly 2,000 times faster. For this reason the broker only appends, and it never updates a record in place or keeps a per-message index.

Three techniques make the append-only design fast.

  • Batching: producers send messages in batches of about 16 KB, so the broker handles about 6,250 requests a second instead of 100,000.
  • The page cache: the broker writes into the operating system's file cache, so consumers that keep up read recent data from memory.
  • Zero copy: the stored bytes are the bytes sent to consumers, so the kernel sends a file range to the socket directly.

A partition is split into segments of about 1 GB. To serve a fetch for offset 4,712,345, the broker picks the segment from the file names, then uses a sparse index with one entry per 4 KB of data, about 250,000 entries or 2 MB, which fits in memory. A binary search finds the nearest entry in about 18 steps, and the broker scans forward less than 4 KB from there.

There are two ways to remove old data. With time-based retention, the broker deletes a closed segment once its newest record is older than seven days. This is a cheap file delete. With compaction, for topics where only the latest value for each key matters (such as the consumer offsets), a background job rewrites old segments and keeps the last record for each key.

Replication and what an acknowledgement means

Each partition is copied to three brokers so that one machine failing loses nothing. The leader tracks which followers are caught up, for example within the last 10 seconds; these and the leader are the in-sync replicas (ISR). The high watermark is the highest offset that every member of the ISR has stored, and consumers can only read below it. This means a consumer never reads a record that could vanish if the leader failed. The producer chooses how long to wait through the acks setting, and there are three options.

With acks=0 the producer does not wait, so a crash loses messages unnoticed. With acks=1 the producer waits for the leader alone, about 1 to 2 ms, so a message acknowledged just before the leader fails can be lost. With acks=all the leader acknowledges only after every ISR member has the batch, which costs the latency of the slowest in-sync follower.

What the producer waits for
OptionGood atBad atPick it when
acks=0It has the lowest latency because the producer does not wait.Any network error or broker crash loses messages silently.Use it for metrics or logs, where a small loss is fine.
acks=1It needs one round trip to the leader, about 1 to 2 ms.If the leader dies before the followers copy the batch, an acknowledged message is lost.Use it for high-volume events, where losing a few messages during a failover is acceptable.
acks=all, min ISR 2 Usual defaultAn acknowledged record is on at least 2 brokers, so one broker can die without any loss.It waits for the slowest in-sync follower, and writes are refused when only one replica is in sync.Use it for orders, payments and anything that must not be lost.

The choice is acks=all with a minimum ISR of 2, because acknowledged messages must not be lost. Without the minimum, the ISR could shrink to the leader alone, and acks=all would quietly behave like acks=1. With it, the broker returns NOT_ENOUGH_REPLICAS instead of accepting a write held by one machine.

An acknowledged record is in the log of at least two brokers, but possibly only in their page cache and not yet on disk. The safety comes from the copies failing independently, so the replicas belong in different racks or zones.

The controller is a quorum of three nodes that stores the cluster metadata in a consensus log. It detects dead brokers, chooses new leaders from the ISR and records every change of the ISR. Each new leader gets a higher leader epoch, and brokers reject requests that carry an older epoch. This fences a zombie leader, a broker that was replaced but does not know it yet.

If every member of the ISR dies, there are two options. The cluster can wait for one of them to come back, which loses nothing but keeps the topic unavailable. Or it can let an out-of-sync replica become leader, which restores availability but loses acknowledged records that replica never received. Waiting is safer.

Ordering and producing without duplicates

Order is guaranteed only within a partition, and the partition is chosen by hashing the key, so all messages with one key stay in order. Retries can break this: if batch 42 fails after batch 43 was already sent, batch 42 lands after 43. A retry after a lost acknowledgement can also write a batch twice.

The idempotent producer solves both problems. Every producer has an id and numbers its batches for each partition. The broker remembers the last few sequence numbers for each producer. If it sees a sequence number it already has, it returns the original offset without writing again. If it sees a gap, such as 43 arriving before 42, it rejects the batch, and the producer resends in order. See Idempotency and Retries.

Consumer groups, offsets and delivery guarantees

Within a group, each partition is read by exactly one member, so a topic has at most as many busy consumers as partitions. When a member joins, leaves or stops sending heartbeats, the group coordinator rebalances the assignment. Every assignment has a generation number, and the broker rejects commits that carry an old generation. A consumer that paused for a minute and was replaced therefore cannot overwrite its successor's position.

The time at which a consumer commits its offset decides the delivery guarantee. Committing after processing gives at-least-once delivery. If the consumer dies, it restarts from the last commit, and every message since that commit is processed again, so processing must be idempotent.

Exactly-once is possible inside the log. A consumer that reads from one topic and writes to another can commit its output messages and its input offsets in a single transaction, and readers configured to see only committed data never observe a half-finished result. The promise ends at the edge of the log: sending an email or writing to an external database is not covered, and those side effects still need idempotent handling.

Bottlenecks and failures

At 10 times the load, which is 1 GB/s of input and 1.8 PB of disk for a week, disk runs out first. 1.8 PB ÷ 12 TB is 150 brokers, or about 200 with headroom. Old segments can move to cheaper object storage.

When this failsWhat happensWhat you do
A leader brokerIts partitions refuse writes for a few seconds.The controller promotes an in-sync follower, and producers retry without creating duplicates.
A follower brokerIt leaves the ISR, and writes continue with two replicas in sync.Replace it, and it copies the log and rejoins. A second failure blocks writes but not reads.
A controller nodeNothing changes while two of the three nodes are alive.Replace it. If two fail, leader changes freeze.
A slow consumerIts lag grows, and producers are not affected.Alert on lag. After 7 days of lag, its fetch returns OFFSET_OUT_OF_RANGE.
A whole zoneOne replica of every partition is gone.With replicas spread over 3 zones, two in-sync copies remain and writes continue.

What a strong answer sounds like

LevelWhat the answer does
JuniorStores messages in a database table and deletes each one after it is read.
Mid-levelDesigns an append-only log with partitions and offsets, sizes the disks from retention, and adds replicas.
SeniorExplains why sequential writes are fast, defines the ISR, states exactly what acks=all guarantees and what breaks it, fences old leaders with epochs, and says what exactly-once does not cover.
What does acks=all promise?Strong answer
Interviewer

With acks=all, can an acknowledged message still be lost?

You

With a minimum ISR of 2, it is lost only if both brokers holding it fail before either flushes it to disk, which is why the replicas go in separate zones. Two settings lose it anyway: allowing an out-of-sync replica to become leader, and setting the minimum ISR to 1.

Interviewer

Why not call fsync on every message?

You

It limits each disk to its sync rate and adds milliseconds to every write, and copies on independent machines give more safety for less latency.

Follow-up questions

Why not use a database table as the queue?

Every consume becomes an update or a delete, and consumers compete for the same rows. A log only appends, and several groups can read and replay the same data.

How do you add partitions to a busy topic?

Adding partitions changes the result of hash(key) mod n, so new messages for a key go to a different partition from its older messages, and the order for that key breaks. Choose the partition count for next year's load at the start, or migrate to a new topic.

What happens to a consumer group that is far behind?

Producers are not affected, because each group reads at its own offset. The group reads older segments from disk instead of the page cache, which is slower. If its lag exceeds the retention period, the data it needs is deleted and it gets OFFSET_OUT_OF_RANGE, so it must restart from the earliest or latest available offset.

How do you choose the number of partitions?

The partition count caps the number of consumers in a group that can work in parallel, and it spreads load across brokers, so it should be at least the highest consumer parallelism you expect. Too many partitions add cost, because each has its own files and replication traffic. Since adding partitions later breaks per-key order, pick a count with room to grow.

What do you do about a hot key?

All messages with one key go to one partition, so a very busy key makes that partition and its leader much busier than the rest. If order for that key is not strictly required, add a random suffix to the key so its messages spread over several partitions, and merge the results on the consumer side. If order is required, the key has to stay on one partition.

Self-review: distributed message queue0 of 12

After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".

Before drawing

Numbers and interfaces

Design and depth

Failure