Design a Distributed Message Queue
A message queue lets one service hand work or events to others without waiting for them, and survives crashes on both sides. This lesson designs a durable, partitioned log-based queue: topics split into partitions, an append-only log on disk, leader-follower replication, consumer groups that track their own offsets, and the trade-offs between at-most-once, at-least-once and effectively-once delivery.
What you will learn
- Model each partition as an append-only log; consumers read by offset.
- Partitions give parallelism; ordering is guaranteed only within a partition, chosen by key.
- Replicate each partition to followers; acknowledge writes once the in-sync replicas have them.
- Consumer groups share partitions; each group commits its own offsets.
- At-least-once plus idempotent consumers is the practical default.
- Retention by time or size makes replay possible and keeps disks bounded.
In this lesson
- The question
- Step 1: Clarify the requirements
- Step 2: Back-of-the-envelope estimates
- Step 3: The core idea, an append-only log
- Step 4: The client API
- Step 5: Topics and partitions
- Step 6: Producing messages
- Step 7: Storing the log on disk
- Step 8: Replication
- Step 9: Consumers, groups and offsets
- Step 10: Delivery guarantees
- Step 11: Retention, compaction and dead letters
- Step 12: One message, end to end
- Step 13: Control plane and failures
- Step 14: The follow-up questions
- Recap
The question
Welcome to lesson fifteen of the InterviewDryRun system design course. Today we design a distributed message queue. In almost every lesson so far, we have drawn a box labelled queue or event log between two services. Today we open that box and design it.
A message queue lets a producer, one service, hand messages to consumers, other services, without waiting for them, and without either side needing to be up at the same time. It absorbs bursts, decouples teams, and makes systems survive partial failures. At large companies, one queue cluster might carry millions of messages a second for hundreds of services, so it must be fast, durable and very reliable. Interviewers ask this to see whether you understand logs, replication and delivery guarantees, which come up everywhere else too.
Max asks
“Design a durable message queue with producers, consumers, partitions and at-least-once delivery.”
That is how Max, our AI interviewer, asks it. The question already names the key ideas: durable, partitions, and at-least-once delivery. So the interviewer expects a partitioned, replicated log design, and a clear explanation of delivery semantics. Do not spend long debating whether to use partitions. Spend time on how they work and what they guarantee.
The plan: requirements and numbers, then the core abstraction, the log. Then producers, storage on disk, replication, consumers and offsets, delivery guarantees, ordering, retention, the control plane, and scaling and failure. Then the follow-up questions.
Step 1: Clarify the requirements
- 01TopicsNamed streams: orders, clicks, emails-to-send
- 02ProduceAppend messages, optionally with a key
- 03ConsumeMany independent consumer groups per topic
- 04OrderingMessages with the same key stay in order
- 05Retention and replayKeep messages for days; re-read from any point
Start with questions, because message queue can mean two different things.
One kind of queue is a work queue: each message is a task, done by exactly one worker, then deleted. The other is a log, or stream: messages are kept for a while, and many independent groups of consumers can each read all of them, at their own pace. The question mentions partitions, which points to the log style. A log can also serve as a work queue, with one consumer group. So design the log, and say it covers both.
Ordering: ask whether global order matters, or order per key, for example all events for one order in sequence. Per key is the usual answer, and much cheaper. And retention: keep messages for some days, so consumers can replay after a bug, and new consumers can read history.
- 01DurableAn acknowledged message survives machine failures
- 02High throughputMillions of messages a second per cluster
- 03Low latencyMilliseconds from produce to consume
- 04AvailableKeep working through broker failures
- 05Scales outAdd machines to add capacity
The qualities. Durability: once we tell a producer a message is stored, it must survive a machine dying. That is the promise everything else depends on.
Throughput and latency: millions of messages a second across a cluster, and a few milliseconds from produce to consume in the normal case. Those two together push us towards sequential disk writes and batching, as we will see.
Availability, and horizontal scaling. Ask the interviewer to confirm one trade-off up front: when we must choose between losing an acknowledged message and briefly refusing writes, we refuse writes. Durability wins.
Step 2: Back-of-the-envelope estimates
Let us size a large cluster.
Say two million messages a second at peak, a kilobyte each. That is two gigabytes a second coming in. With three copies of everything, six gigabytes a second written to disks across the cluster.
If, on average, three consumer groups read each topic, that is another six gigabytes a second of reads. So the cluster's limits are disk throughput and network bandwidth, not CPU. A design that writes and reads sequentially, in large batches, is the only way to reach this efficiently.
Seven days of retention at two gigabytes a second is about a petabyte and a quarter with replication. Spread over fifty to a hundred brokers with large disks, that is fine. And it tells us something useful: old data is a large share of storage, so moving older segments to cheaper object storage is an option worth mentioning later.
One more number: messages per partition. A single partition is handled by one leader and read by one consumer per group, so it is limited to what one machine and one consumer can handle, perhaps tens of megabytes a second. Two gigabytes a second therefore needs at least a hundred partitions across the cluster, and in practice thousands, spread over many topics. That is why partitioning is not optional in this design.
Step 3: The core idea, an append-only log
topic: orders, partition 3
offset: 0 1 2 3 4 5 ...
[m0] [m1] [m2] [m3] [m4] [m5]
▲ ▲
consumer group 'billing' at 2 new writes appended here
consumer group 'email' at 5Here is the idea that makes everything else simple. Each partition of a topic is an append-only log. Producers only ever add messages to the end. Every message gets the next number, its offset. Messages are never changed after they are written.
Consumers do not remove messages. Each consumer group simply remembers how far it has read, its offset. Billing might be at offset two, email at offset five. Both read the same log independently. To replay, a consumer group moves its offset backwards. That is all.
Why is this so powerful? Because appending to the end of a file is the fastest thing a disk can do, even a spinning one, and reading sequentially is nearly as fast. There are no per-message locks, no deletions scattered through the data, and no per-message bookkeeping on the server about who has read what. The broker's job becomes: append to files, and serve ranges of files. That is why log-based queues reach throughputs that classic queues cannot.
Contrast this with a traditional queue, which tracks each message's state, delivered, acknowledged, deleted, per consumer. That works well for small volumes and complex routing, but the bookkeeping becomes the bottleneck at millions of messages a second. Mention both, and say the log is the right fit for this question's scale and its replay requirement.
Step 4: The client API
producer.send(topic = "orders", key = "order-8812",
value = {...}, headers = {...})
→ future: { partition: 3, offset: 1041 }
consumer = Consumer(group = "billing", topics = ["orders"])
loop:
batch = consumer.poll(timeout = 100 ms)
for msg in batch: handle(msg)
consumer.commit() // offsets of what we handledBefore the internals, the API that services actually use, because it makes the contract clear. A producer sends a message to a topic, with an optional key, a value and some headers. The call returns a future that completes with the partition and offset where the message landed, once it is acknowledged.
A consumer joins a group and subscribes to topics. It loops: poll for a batch of messages, handle them, and commit the offsets it has finished. That loop, poll, handle, commit, is where the delivery guarantees we will discuss later come from, so it is worth having it on the board.
Notice what the API does not have: no per-message acknowledgement and no delete. The consumer only says how far it has got. That simplicity is a direct consequence of the log design, and it is a big part of why it performs so well. The client libraries hide the complexity: finding partition leaders, batching, retries, and rebalancing.
Step 5: Topics and partitions
One log on one machine cannot carry two gigabytes a second. So each topic is split into partitions, each its own log, and partitions are spread across brokers, the servers of the cluster.
Which partition does a message go to? If it has a key, like an order id, hash the key to choose the partition. All messages with the same key land in the same partition, in order. Messages without a key can be spread round-robin, or batched to one partition at a time for efficiency.
Partitions are also the unit of parallelism for consumers. Within a consumer group, each partition is read by exactly one consumer at a time, and one consumer may read several partitions. So a topic with twelve partitions can be processed by up to twelve consumers in parallel in each group.
This gives us the ordering rule that you must state precisely: order is guaranteed within a partition, and therefore per key, but not across partitions. If someone needs a total order across a whole topic, the topic must have one partition, and its throughput is then limited to one machine. Choosing the key is therefore a design decision for every topic: it decides both ordering and how evenly load spreads.
How many partitions? Enough for the peak throughput and the maximum number of consumers you want, with room to grow, because increasing partitions later changes which partition each key maps to, which can break ordering for a moment. A common rule is to provision several times the current need.
Step 6: Producing messages
| Setting | Producer waits for | Risk |
|---|---|---|
| acks = 0 | nothing | messages lost silently |
| acks = 1 | leader wrote it | lost if leader dies before followers copy it |
| acks = all | all in-sync replicas | slower; safest |
Now the producer side. A producer library batches messages per partition for a few milliseconds, compresses each batch, and sends it to the partition's leader broker. Batching is the single biggest throughput lever: one network request and one disk write per batch instead of per message.
The producer chooses how long to wait. With no acknowledgement, it just sends and hopes. With leader acknowledgement, the leader has written it, but if the leader dies before followers copy it, it is lost. With all in-sync replicas acknowledging, the message is on several machines before the producer hears yes. For our durability requirement, the default is all, and we will define in-sync in a moment.
Producers retry on errors, which brings back an old friend: duplicates. If a batch was written but the acknowledgement was lost, the retry writes it twice. The fix is idempotent producers: each producer gets an id, numbers its batches per partition, and the leader discards a batch it has already written from that producer with that number. Retries then never create duplicates in the log. This is the same idempotency key pattern again, applied inside the queue.
Step 7: Storing the log on disk
- 01Segment filesThe log is split into files of about 1 GB
- 02Append onlyOnly the newest segment is written
- 03Sparse indexOffset to file position, every few KB
- 04Page cacheRecent data is read from memory
- 05Zero copySend file bytes straight to the network
On disk, each partition is a directory of segment files, each about a gigabyte. Only the newest segment receives writes. When it fills up, it is closed and a new one starts. Closed segments are never changed, which makes retention trivial: delete whole old files.
To find a message by offset quickly, each segment has a small sparse index mapping some offsets to positions in the file, say every few kilobytes. A read jumps to the nearest indexed position and scans forward. The index is tiny and stays in memory.
Two performance tricks are worth naming. First, rely on the operating system's page cache: recently written data is still in memory, so consumers that keep up read from memory, not disk. Second, zero copy: the broker asks the operating system to send bytes from the file straight to the network socket, without copying them through the application. Combined with batching and compression, a single broker can move hundreds of megabytes a second.
Should the broker force every write to disk before acknowledging? Surprisingly, often not. Durability comes from replication across machines rather than from forcing each write to the local disk: a message acknowledged by three replicas in different racks is safer than a message forced to one disk. Say this trade-off clearly; it is a classic follow-up.
Messages are stored exactly as the producer's compressed batch, and sent to consumers in the same form. The broker never decompresses or re-encodes them, which saves a lot of CPU and keeps the broker simple.
Step 8: Replication
Durability across machine failures comes from replication. Each partition has a leader replica, which takes all writes and usually all reads, and followers on other brokers, ideally in other racks or zones.
Followers continuously fetch new messages from the leader, just like a consumer would, and append them to their own copy of the log. The leader tracks which followers are caught up, within a small lag. That set is the in-sync replica set.
A message is committed when every in-sync replica has it. Only committed messages are shown to consumers, so a consumer never reads something that could later vanish. And with acknowledgements set to all, the producer hears yes only once the message is committed. Add a minimum, say at least two in-sync replicas, and if fewer are available, the partition refuses writes rather than accept a message that only one machine holds. That is the durability-over-availability choice we agreed earlier, made concrete.
If the leader dies, a controller, a small strongly consistent service that manages cluster metadata, picks a new leader from the in-sync replicas. Because every in-sync replica has every committed message, no committed message is lost. Electing a leader that was not in sync would be faster, but could lose data, so it is turned off by default. Each election increases an epoch number, so an old leader that comes back cannot keep accepting writes; followers and producers reject its stale epoch.
Step 9: Consumers, groups and offsets
- 01Pull, not pushConsumers fetch batches at their own pace
- 02One partition, one consumerWithin a group, at any moment
- 03RebalancePartitions reassigned when consumers join or leave
- 04Committed offsetsStored in an internal, replicated topic
Consumers pull. They ask the leader for messages from a given offset, and get a batch back. Pulling lets each consumer go at its own pace, batch naturally, and catch up after a pause, without the broker having to track or throttle anyone.
In a consumer group, a coordinator assigns partitions to consumers. When a consumer joins, leaves or stops sending heartbeats, partitions are rebalanced among the remaining ones. Mention that rebalances pause consumption briefly, and that incremental rebalancing, moving only the partitions that need to move, keeps that pause small.
Each group periodically commits its offset per partition: I have processed everything up to here. Commits are stored durably, conveniently in an internal topic of the queue itself, replicated like everything else. When a consumer restarts, or a partition moves to another consumer, reading resumes from the last committed offset.
Consumer lag, the difference between the newest offset and the committed offset, is the single most important health metric for a queue. Growing lag means consumers are falling behind. Alert on it per group and partition, and use it to scale consumers automatically, up to the number of partitions.
Step 10: Delivery guarantees
| Commit | Crash after commit, before processing | Crash after processing, before commit | Guarantee |
|---|---|---|---|
| Before processing | message skipped | fine | at most once |
| After processing | fine | message processed again | at least once |
| Atomically with the result | fine | fine | effectively once |
Now the guarantees, which the question asks about directly. The delivery guarantee a consumer gets depends on when it commits its offset relative to doing the work.
Commit first, then process: if the consumer crashes in between, the message is skipped forever. That is at most once. Fine for metrics where losing a few points does not matter.
Process first, then commit: if it crashes in between, the message is processed again after restart. That is at least once, which the question asks for. No message is ever lost, but duplicates happen, especially around rebalances and crashes.
Exactly once is the one everyone wants. In general, across arbitrary external systems, it is impossible to guarantee by the queue alone. What we can achieve is effectively once. If the output goes back into the queue, the queue can write the output and the offset commit in one transaction. If the output goes to a database, store the offset in the same database transaction as the result, or make processing idempotent, for example by keying writes on the message's unique id so a repeat has no effect.
So the practical answer is: at-least-once delivery from the queue, plus idempotent consumers. Say that sentence clearly. It is the honest answer interviewers want, and it shows you will not claim a magic exactly-once guarantee that does not exist.
Step 11: Retention, compaction and dead letters
- 01Time or size retentionDelete whole segments older than 7 days
- 02Compacted topicsKeep only the latest message per key
- 03Tiered storageOld segments move to object storage
- 04Dead letter topicMessages that keep failing go aside
Retention keeps disks from filling. Delete closed segments older than a time limit, say seven days, or beyond a size limit per partition. Because segments are whole files, deletion is instant and free.
Some topics are better kept forever but compacted: for each key, keep only the latest message. A topic of user profile changes, compacted, always holds the current profile of every user, which a new service can read from the beginning to build its own copy. Compaction runs in the background over closed segments.
Tiered storage moves older segments to cheap object storage while keeping them readable. Recent data stays on fast local disks, and replays from weeks ago come from object storage, more slowly. That cuts the petabyte of local disk we estimated down to a fraction.
And poison messages: a message that makes a consumer crash every time would block its partition forever, because the consumer cannot move past it. After a few failed attempts, the consumer writes it to a dead letter topic with the error, commits past it, and moves on. A person or a separate job deals with the dead letters later.
Step 12: One message, end to end
- 011. Producer batches itKey hashes to partition 3
- 022. Leader appendsOffset 1041 in the active segment
- 033. Followers fetchBoth in-sync replicas have it: committed
- 044. Producer acknowledgedWithin a few milliseconds
- 055. Consumers fetch and commitEach group on its own schedule
Let us trace one message through everything we have designed. The order service sends an order created event with the order id as its key. The client library hashes the key to partition three, adds the message to its current batch for that partition, and a few milliseconds later sends the batch to partition three's leader.
The leader checks the producer id and batch number to discard duplicates, appends the batch to its active segment, and assigns offsets, our message getting one thousand and forty-one. Both followers fetch it within a millisecond or two. Once they have it, it is committed, and the leader acknowledges the producer.
Billing's consumer, which owns partition three in its group, fetches it in its next poll, likely from the page cache, processes it, and commits its offset. The email group does the same, a moment later, entirely independently. If billing's consumer had crashed after processing but before committing, a new consumer would receive offset one thousand and forty-one again, and billing's idempotent handling would make the repeat harmless. Every guarantee we promised shows up in this one path.
Step 13: Control plane and failures
- 01Broker diesLeaders move to in-sync followers in seconds
- 02Slow followerDropped from in-sync set; rejoins when caught up
- 03Hot partitionBad key choice: one key gets most traffic
- 04Controller failsStandby controller from a consensus group
- 05Disk fullRetention, tiering, alerts well before
When a broker dies, the controller elects new leaders for its partitions from the in-sync followers. Producers and consumers get an error, refresh their metadata, and continue against the new leaders, within seconds. When the broker comes back, it catches up as a follower and rejoins the in-sync set.
A slow follower, on a struggling disk perhaps, is dropped from the in-sync set so it does not slow down every write, and rejoins once it has caught up.
A hot partition usually comes from a bad key: one customer or one null key getting most of the messages. The fix is at the producer: a better key, or adding a random suffix to spread a hot key, at the cost of ordering for that key.
The controller holds the cluster metadata, topics, partitions, leaders and epochs, so it runs as a small consensus group with standbys, and a new controller takes over in seconds if one fails. And disks: alert long before they fill, because a full disk stops writes for every partition on that broker.
Step 14: The follow-up questions
Max asks
“How do you deliver a message to a consumer after a delay of ten minutes?”
A log does not support per-message delays natively. Common answers: a set of delay topics, one per delay bucket like one minute, ten minutes and one hour, read by a service that waits until each message is due and then republishes it to the target topic; or a separate scheduler, which we will design in a later lesson. Because delay topics are ordered by time, the waiting service just reads from the front.
Max asks
“Why not just use a database table as the queue?”
At small scale, it works and is often a good choice, with a status column and conditional updates. At millions of messages a second, it becomes a hot spot: every message is an insert, an update and a delete, with index maintenance and lock contention. The log avoids all of that with sequential appends and offsets. And a database table does not naturally give us many independent consumer groups or replay.
Max asks
“A consumer is slow. Does it slow down the producers?”
No. That is a key benefit of the log design. Producers append regardless of how far behind any consumer is. The slow consumer's lag grows, and as long as it catches up before retention deletes the data, nothing is lost. If it falls behind by more than the retention period, it loses data, which is why lag alerts and retention settings must be planned together.
Max asks
“How would you replicate a topic to another region?”
Run a mirroring process that consumes the topic in the source region and produces into a topic in the target region, asynchronously. Offsets differ between the two clusters, so the mirror records a mapping, letting consumers fail over to the other region and resume near the right point. Replication is asynchronous, so a region loss can lose the last few seconds; if that is unacceptable, the producer must write to both regions, at the cost of latency.
Recap
- 010 to 5: requirementsLog not work queue; per-key order; durable
- 025 to 10: estimatesGB/s in and out; disk and network bound
- 0310 to 20: log and partitionsAppend-only, offsets, key to partition
- 0420 to 35: durability and consumersBatching, replicas, in-sync set, groups, offsets
- 0535 to 45: guarantees and opsAt least once + idempotent; retention; failures
On the clock: five minutes of requirements, clarifying log versus work queue and per-key ordering. Five minutes of numbers, showing the cluster is limited by disks and network.
Ten minutes on the log and partitions: append-only segments, offsets, keys choosing partitions, and order only within a partition.
Fifteen minutes on durability and consumption: batched idempotent producers, leaders and in-sync followers, commits, consumer groups and offsets. And ten minutes on delivery guarantees, retention and failures. If you can explain why at-least-once plus idempotent consumers is the honest answer, you will have nailed the part interviewers care about most.
Delivery guarantees are easy to mix up under pressure, especially when the interviewer asks where exactly a crash happens. Practicing out loud makes the reasoning automatic. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson sixteen.
Now say it out loud
Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.
Practice with MaxFree: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.