System design interview: design a distributed message queue
A distributed message queue lets producers hand off messages that consumers process later, so services stay decoupled and absorb bursts. In the interview you design the storage (usually a partitioned, replicated append-only log), how consumers track what they have processed, what ordering and delivery guarantees you offer, and what happens to messages when a broker or a consumer fails.
By Evin JohnPublished 7 min read
1. Clarify the requirements
"Message queue" covers two different products: a work queue where each message is handled once and then gone, and an event log that several independent readers consume at their own pace. Ask which one, or design the log and show how it serves both.
- Functional: producers publish messages to named topics; consumers subscribe, alone or as a group that shares the work; messages for the same key are delivered in order; consumers can replay from an earlier point; messages are kept for a configurable time.
- Non-functional: high throughput (assume 1 million messages a second); a published message survives a broker failure once acknowledged; end-to-end latency in the tens of milliseconds; horizontal growth by adding brokers.
- Out of scope unless asked: per-message routing rules and priorities, delayed delivery, global ordering across a whole topic, cross-region replication.
2. Estimate the scale
| Quantity | Assumption | Result |
|---|---|---|
| Incoming messages | 1 million a second at about 1 KB each | about 1 GB a second written |
| Retention | 7 days | 1 GB/s x 604,800 s is about 605 TB |
| Replication | 3 copies | about 1.8 PB of disk across the cluster |
| Readers | 3 consumer groups read everything | about 3 GB a second read, plus replication traffic |
| Partitions | about 10 MB a second per partition (assumed safe rate) | at least 100 partitions for the busiest topics combined; more for parallelism |
Throughput this high only works if writes and reads are sequential disk I/O and network copies, not random seeks or per-message database rows. That is the argument for an append-only log. The retention figure shows storage is the cost driver, so older segments may move to cheaper storage.
3. Define the API
produce(topic, key, value, headers) -> (partition, offset) once acknowledged
partition = hash(key) mod partitions, or round-robin when key is empty
subscribe(topic, group_id) -> partitions assigned to this consumer
poll(max_messages, max_wait_ms) -> batch of (partition, offset, key, value)
commit(partition, offset) -> progress saved for the group
seek(partition, offset_or_timestamp) -> replay from an earlier point4. Sketch the data model
| Thing | Shape | Notes |
|---|---|---|
| Partition log | Directory of segment files, each up to about 1 GB | Only the newest segment is written; older ones are immutable and easy to delete or offload |
| Record | offset, timestamp, key, value, headers, checksum | Records are written in compressed batches, not one by one |
| Offset index | Sparse map from offset to file position per segment | Find a starting point with a binary search, then read sequentially |
| Consumer offsets | (group, topic, partition) -> committed offset | Stored in an internal compacted topic or a metadata store |
| Cluster metadata | Topics, partitions, leader and replicas per partition, in-sync set | Kept by a controller backed by a consensus store |
5. The core decision: a log, not a mailbox
| Model | How consumption works | Good at | Weak at |
|---|---|---|---|
| Classic queue | Broker hands a message to one consumer, hides it for a timeout, deletes it on acknowledgement | Work distribution with per-message retries; uneven processing times | Replay, many independent readers, strict ordering |
| Partitioned log | Messages stay for the retention period; each consumer group tracks its own offset per partition | Throughput, replay, many readers of the same events, per-key order | Per-message retries and priorities; parallelism capped by partition count |
For a high-throughput platform the log is the stronger base. A broker never tracks individual deliveries, only offsets per group, so its work does not grow with the number of messages in flight. Work-queue behavior can be layered on top: a consumer that fails a message writes it to a retry topic, and after a few attempts to a dead-letter topic for inspection.
Ordering and consumer groups
The producer chooses a partition from the message key, so all events for one order or one user land in the same partition, in the order they were written. Within a consumer group, each partition is read by exactly one consumer at a time, so per-key order holds through processing too. The cost: a group cannot have more active consumers than partitions, so choose the partition count for future parallelism, not today's.
6. The architecture
- Producers
- Services publishing events (batched, compressed)
- Control plane
- Controller
- Consensus store
- Group coordinator
- Brokers
- Partition leaders
- Follower replicas on other brokers
- Segment files on local disk
- Consumers
- Consumer group A (billing)
- Consumer group B (search indexing)
- Retry and dead-letter topics
- Cold storage
- Object storage for old segments (optional)
- PublishThe producer batches messages per partition for a few milliseconds, compresses the batch and sends it to the leader. With
acks=all, it waits until every in-sync replica has the batch. - ReplicateFollowers continuously fetch from the leader. A follower that falls too far behind is dropped from the in-sync set, so a slow broker does not stall writes.
- ConsumeA consumer polls its partitions from the last committed offset, processes the batch and commits the new offset. Reads are mostly served from the operating system's page cache because consumers usually read recent data.
- ExpireA background task deletes whole segments older than the retention period, or keeps only the latest record per key for compacted topics.
7. Scale it and choose the guarantees
| Semantics | Consumer does | Risk |
|---|---|---|
| At most once | Commit the offset, then process | A crash after the commit loses the message |
| At least once | Process, then commit | A crash before the commit replays the message, so it is processed twice |
| Effectively once | Process idempotently (dedupe by message ID, or upsert by key) and commit, or write results and offsets in one transaction | Needs a unique ID per message and a consumer that tolerates repeats |
- Idempotent producers. A producer retry after a timeout can append a batch twice. Giving each producer an ID and numbering its batches lets the leader drop duplicates. Consumers still need their own deduplication for end-to-end effects.
- Add brokers and move partitions. New brokers receive partition replicas copied from existing ones, then take over leadership for some of them; throttle the copy so it does not starve live traffic.
- Batch everything. Producer batching, compression and consumer fetches of many records amortize per-request costs; that is where most of the throughput comes from.
- Tier old data. Keep recent segments on local disks and move older ones to object storage, so long retention does not require huge brokers.
- Rack awareness. Place a partition's replicas in different zones so one zone outage leaves a full in-sync copy.
8. What breaks, and what you do about it
| Failure | Effect | Mitigation |
|---|---|---|
| Leader broker dies | Its partitions stop accepting writes briefly | Controller elects a new leader from the in-sync set; producers refresh metadata and retry |
| All in-sync replicas lost | Choice between unavailability and data loss | By default refuse to elect an out-of-sync replica; allowing it trades acknowledged messages for availability |
| Consumer crashes mid-batch | Messages after the last commit are re-read | At-least-once by design; idempotent processing makes it harmless |
| Poison message | Consumer fails on it forever and the partition stalls | Bounded retries, then a dead-letter topic with the error attached |
| Consumer group falls behind | Lag grows; data may expire before it is read | Alert on lag, add consumers up to the partition count, extend retention for that topic |
| Rebalance storm | Consumers keep joining and leaving; processing pauses | Incremental reassignment and longer session timeouts for slow processing |
9. Trade-offs to discuss
- Durability versus latency. Waiting for all in-sync replicas is safest; acknowledging after the leader's write alone is faster and loses data if the leader dies before followers copy it.
- Partition count. More partitions allow more consumer parallelism but mean more files, more leader elections on failure and more metadata. It is hard to reduce later and changing it moves keys between partitions, which breaks per-key ordering during the change.
- Push or pull. Consumers pulling batches control their own pace and recover naturally from slowness; brokers pushing would need flow control per consumer.
- Log or queue. If the workload is mostly independent tasks with very different processing times and per-message retries, a classic queue may fit better than a log. Say which you would choose and why.
- Retention versus cost. Longer retention allows replays and new consumers to backfill, at the cost of disk; compaction keeps only the latest value per key for state-like topics.
10. How to talk through it in the interview
Fictional example
- Interviewer
- The billing team says they need exactly-once delivery. Can you give it to them?
- Candidate
- The broker can avoid writing duplicates from producer retries, but delivery to a consumer that might crash is at least once. What billing really needs is exactly-once effects. Each charge event carries a unique ID, and the billing service records processed IDs in the same database transaction as the charge, so a replayed event is skipped.
- Interviewer
- And ordering for one customer's events?
- Candidate
- Key by customer ID, so one customer's events share a partition and one consumer in the group handles them in order.
A 45-minute split that works: 5 minutes on queue versus log and the ordering question, 5 on the throughput and retention numbers, 5 on the API and on-disk format, 10 on the broker and replication architecture, 10 on consumer groups and delivery semantics, and 10 on failures and trade-offs. If time is short, drop tiered storage and rebalancing details first.
- Say "ordering per partition, partition chosen by key" in one breath.
- Explain delivery semantics as a question of when the consumer commits.
- Show how a dead-letter topic keeps one bad message from stalling a partition.
Queues appear inside many other designs too: the encoding tasks in design YouTube, the fan-out in a notification system and the scrapes in metrics and monitoring.
Practicing this design with Natively
Practice the delivery-semantics explanation until you can give it without hesitating. Set up a mock round on a call; Natively transcribes what both of you say and can suggest points when the interviewer asks a question, which makes it easy to spot later whether you ever mentioned dead-letter topics or the partition-count limit. Ask it to draw the broker and replica layout if you want a reference picture. The transcript and notes are there afterwards for a second, tighter attempt.
Questions people ask
How do you design a distributed message queue?
Store each topic as partitions, each an append-only log of segment files replicated to followers. Producers pick a partition from the message key; consumers in a group split the partitions and commit offsets. Then cover delivery semantics, retention and what happens when a broker or consumer fails.
How is message ordering guaranteed in a partitioned queue?
Only within a partition. Messages with the same key go to the same partition in write order, and each partition is read by one consumer in a group at a time, so per-key order holds. Ordering across the whole topic would need a single partition and gives up parallelism.
What is the difference between at-least-once and exactly-once delivery?
At-least-once means a consumer processes and then commits, so a crash can replay messages. Exactly-once effects come from idempotent processing, such as deduplicating by message ID in the same transaction as the work. The broker alone cannot make a crashing consumer's side effects happen once.
What is a dead-letter queue?
A separate topic or queue where messages go after failing a set number of retries. It stops one bad message from blocking a partition forever and keeps it, with the error, for someone to inspect and replay.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
