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 Published 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

Back-of-envelope sizing for a shared event log (assumed figures)
QuantityAssumptionResult
Incoming messages1 million a second at about 1 KB eachabout 1 GB a second written
Retention7 days1 GB/s x 604,800 s is about 605 TB
Replication3 copiesabout 1.8 PB of disk across the cluster
Readers3 consumer groups read everythingabout 3 GB a second read, plus replication traffic
Partitionsabout 10 MB a second per partition (assumed safe rate)at least 100 partitions for the busiest topics combined; more for parallelism
Back-of-envelope sizing for a shared event log (assumed figures). Scroll sideways on a small screen.

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 point
Producers append; consumers pull batches from an offset and commit progress.

4. Sketch the data model

On disk and in the metadata store
ThingShapeNotes
Partition logDirectory of segment files, each up to about 1 GBOnly the newest segment is written; older ones are immutable and easy to delete or offload
Recordoffset, timestamp, key, value, headers, checksumRecords are written in compressed batches, not one by one
Offset indexSparse map from offset to file position per segmentFind a starting point with a binary search, then read sequentially
Consumer offsets(group, topic, partition) -> committed offsetStored in an internal compacted topic or a metadata store
Cluster metadataTopics, partitions, leader and replicas per partition, in-sync setKept by a controller backed by a consensus store
On disk and in the metadata store. Scroll sideways on a small screen.

5. The core decision: a log, not a mailbox

Two models for storing messages
ModelHow consumption worksGood atWeak at
Classic queueBroker hands a message to one consumer, hides it for a timeout, deletes it on acknowledgementWork distribution with per-message retries; uneven processing timesReplay, many independent readers, strict ordering
Partitioned logMessages stay for the retention period; each consumer group tracks its own offset per partitionThroughput, replay, many readers of the same events, per-key orderPer-message retries and priorities; parallelism capped by partition count
Two models for storing messages. Scroll sideways on a small screen.

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

  1. Producers
    • Services publishing events (batched, compressed)
  2. Control plane
    • Controller
    • Consensus store
    • Group coordinator
  3. Brokers
    • Partition leaders
    • Follower replicas on other brokers
    • Segment files on local disk
  4. Consumers
    • Consumer group A (billing)
    • Consumer group B (search indexing)
    • Retry and dead-letter topics
  5. Cold storage
    • Object storage for old segments (optional)
Brokers holding replicated partitions, with a controller and consumer groups. Producers fetch cluster metadata, then send batches for each partition directly to that partition's leader broker. The leader appends the batch to its log and followers on other brokers fetch and append the same records; once the in-sync replicas have them, the leader acknowledges. A controller backed by a consensus store tracks brokers, partition leaders and in-sync replica sets, and elects a new leader when a broker fails. Consumers in a group are assigned partitions by a group coordinator, fetch batches from the leaders and commit offsets. Old segments are deleted after the retention period or moved to object storage.
  1. 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.
  2. 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.
  3. 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.
  4. 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

Delivery semantics come from when the consumer commits
SemanticsConsumer doesRisk
At most onceCommit the offset, then processA crash after the commit loses the message
At least onceProcess, then commitA crash before the commit replays the message, so it is processed twice
Effectively onceProcess idempotently (dedupe by message ID, or upsert by key) and commit, or write results and offsets in one transactionNeeds a unique ID per message and a consumer that tolerates repeats
Delivery semantics come from when the consumer commits. Scroll sideways on a small screen.
  • 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 modes worth naming
FailureEffectMitigation
Leader broker diesIts partitions stop accepting writes brieflyController elects a new leader from the in-sync set; producers refresh metadata and retry
All in-sync replicas lostChoice between unavailability and data lossBy default refuse to elect an out-of-sync replica; allowing it trades acknowledged messages for availability
Consumer crashes mid-batchMessages after the last commit are re-readAt-least-once by design; idempotent processing makes it harmless
Poison messageConsumer fails on it forever and the partition stallsBounded retries, then a dead-letter topic with the error attached
Consumer group falls behindLag grows; data may expire before it is readAlert on lag, add consumers up to the partition count, extend retention for that topic
Rebalance stormConsumers keep joining and leaving; processing pausesIncremental reassignment and longer session timeouts for slow processing
Failure modes worth naming. Scroll sideways on a small screen.

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

The exactly-once follow-up
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.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP