To design a message queue is to build a service that lets one part of a system hand work or events to another part without waiting for it, keeps those messages safe until they are handled, and lets many consumers share the load. A good answer explains how messages are split into partitions, what order is guaranteed, what happens when a consumer crashes half-way, how a slow consumer is detected, and how failing messages are kept from blocking healthy ones.
This lesson designs the queue behind FeeDesk, a college fee portal. Every payment becomes an event that has to produce a receipt, update a ledger and send an SMS, and those three jobs must not slow down the payment page. Six runnable programs in Java, with Python and C++ versions, test the decisions interviewers probe most: choosing the partition key, delivery guarantees, consumer lag, retries and poison messages, consumer group rebalances, and acknowledgements with a leader crash. All rates and timings are assumptions chosen to make comparisons clear, not benchmarks of a product.
Key takeaways
Keying by student kept every student's events in order and left the busiest of 8 partitions with 12.7% of the traffic. Keying by college put 48.0% on one partition, with an average wait of 57,077 ms. Round robin balanced perfectly (12.5%) but handled 2,373 of every 10,000 same-student pairs out of order.
Committing the offset before sending a receipt lost 92 receipts in 92 crashes. Sending first and committing after lost none and sent 92 duplicates. Committing every 100 messages sent 4,343 duplicates. Skipping already handled ids gave 0 lost and 0 duplicates.
During a deadline spike, one consumer reached a lag of 60,450 events and an oldest event of 40.3 s, and needed 123 s to catch up. A second consumer, added after 10 s over 5,000, held the lag to 21,450.
Retrying a failing message in place blocked healthy ones: 9,413 of 10,000 waited over 1 s. A retry queue with a 5 s delay delayed none and kept 106 poison messages in a dead-letter queue.
An eager rebalance paused 150 partition-seconds and a lag of 9,000. A cooperative rebalance paused 42 and peaked at 3,600.
With acks 1, 46 acknowledged messages were missing after a leader crash. With acks all there were 0, at 22.4 ms per send instead of 1.0 ms.
1. Clarifying Requirements
Functional requirements
Producers publish messages to a named topic.
Several independent groups of consumers each receive every message.
Within a group, each message goes to one consumer, so the work is shared.
Messages are kept for a retention period and can be read again from an earlier position.
Non-functional requirements
No acknowledged message is lost, even if a broker fails.
Messages about the same student are handled in order.
High throughput, and the ability to absorb a spike.
A failing message must not stop the others.
Say what you leave out: schema registry, message transformation, exactly-once across systems and multi-region replication.
2. Back-of-the-Envelope Estimation
Rate: 1,000 events per second on average and 3,000 at the peak on the last day to pay. Each event is about 1 KB.
Storage: 1 MB per second is 86 GB a day, 600 GB for 7 days of retention, and 1.8 TB with 3 replicas.
Reads: three consumer groups (receipts, ledger, SMS) each read every event, so 9 MB per second leaves the brokers at the peak.
The volume is modest. Order, failure and lag are the difficult parts.
3. Core APIs
POST /v1/topics/{topic}/messageswith{"key": "student-4411", "value": {...}, "acks": "all"}. The reply gives the partition and the offset.POST /v1/topics/{topic}/messages:batchsends many messages in one call.GET /v1/topics/{topic}/partitions/{p}/messages?offset=...&limit=...reads a batch from a position (a consumer library hides this).POST /v1/groups/{group}/joinand/heartbeatlet a consumer join a group and show that it is alive.POST /v1/groups/{group}/offsetscommits the position a consumer has reached.
4. High-Level Design
A topic is split into partitions. Each partition is an append-only log: new messages are added at the end and every message has an offset, its position in that log. Each partition has a leader and followers on other brokers. A consumer group divides the partitions among its consumers, and keeps for each partition the offset it has reached.
Topics, partitions, groups and offsets.
A producer chooses the partition from the message key, collects messages into batches and sends them to the leader of that partition. The leader appends the batch to its log, the followers copy it, and the producer is told it is done after as many copies as it asked for.
Key, batch, leader, followers, acknowledgement.
A consumer asks for the next batch from its partitions, does the work, and then commits the offset. After a crash it restarts from the last committed offset, so the work must be safe to repeat.
Do the work first, then remember the place.
Four layers, each with its own failure modes.
Because a log is read by position, a message is not removed when a consumer reads it. That is the difference from a classic work queue, where a message is deleted once one consumer acknowledges it. The log design makes replay, several independent groups and very high throughput easy. The work-queue design makes per-message acknowledgement, per-message delay and priorities easy.
5. Choosing the Partition Key
All messages with the same key go to the same partition, so they are handled in the order they were written. The key is therefore the unit of ordering and also the unit of balance. The first program sends 100,000 fee events (one a millisecond) to 8 partitions with one consumer each. Half of the events are a follow-up for the same student as the event before (payment, then receipt), and 40 in 100 students belong to one college. A consumer takes 3 to 11 ms per event, so the group has a little spare capacity.
Output
100000 fee events, 8 partitions, one consumer each, half of the events a follow-up for the same student, 40 in 100 students in one college.
partition key busiest average wait worst wait same-student pairs
partition handled out of order per 10,000
key = student 12.7% 72 ms 634 ms 0
key = college 48.0% 57077 ms 237202 ms 0
no key, round robin 12.5% 2 ms 35 ms 2373
Key = student: the busiest partition had 12.7% of the events (even is 12.5%), the average wait was 72 ms and no pair of events for the same student was handled out of order.
Key = college: one college had 40% of the students, so one partition had 48.0%. Its consumer was overloaded: the average wait was 57,077 ms and the worst 237,202 ms. Order was kept, but the system was unusable.
No key, round robin: the load was exactly even (12.5%, average wait 2 ms) and 2,373 of every 10,000 pairs of events for the same student were handled out of order, because two consumers had different backlogs.
The key decides order and balance at the same time.
Choose the smallest thing whose order matters (here the student) and check the share of the busiest partition. If one key is too hot, split it (for example by adding a number to the key) and accept the weaker order for that key. The number of partitions also limits the parallelism: a group cannot use more consumers than partitions, and adding partitions later changes which partition a key maps to.
6. Delivery Guarantees
A consumer does two things for each message: the work (send a receipt) and the commit (remember the offset). A crash can fall between them. The order of the two decides what is lost or repeated.
At most once: commit, then work. A crash between them loses the message.
At least once: work, then commit. A crash between them repeats the message.
Effectively once: at least once, plus a consumer that detects repeats (by message id) or an effect that is naturally repeatable.
The second program sends a receipt for each of 100,000 messages. The consumer crashes after 1 in 1,000 steps and restarts from the last committed offset.
Output
100000 messages, a crash after 1 in 1000 steps. Receipts sent twice are duplicates; messages never handled are lost.
consumer crashes lost duplicate receipts messages read
messages receipts sent (including repeats)
commit, then send 92 92 0 99908 100000
send, then commit 92 0 92 100092 100092
send, commit every 100 97 0 4343 104343 104343
as above, skip handled ids 97 0 0 100000 104343
Commit then send: 92 crashes, 92 receipts lost, 0 duplicates.
Send then commit: 0 lost, 92 duplicates.
Send, commit once per 100 messages: 97 crashes and 4,343 duplicates, because each crash replays up to 100 messages. Fewer commits are cheaper and cost duplicates.
The same, skipping ids already handled: 0 lost, 0 duplicates, and still 104,343 messages read.
Order of work and commit, and how often you commit.
The last row hides a difficulty: the id record and the receipt must be one atomic step. If the consumer sends the receipt and crashes before it records the id, the repeat is not detected. For a database effect, put the id and the change in one transaction. For an external call such as an email, send an idempotency key so that the other side ignores a second request. "Exactly once" in a real system means exactly this combination, inside one system, not magic across systems.
7. Consumer Lag and Back Pressure
Lag is the number of messages written but not yet handled (or the age of the oldest). It is the main health signal of a queue. A queue absorbs a spike by letting lag grow, and the question is how large it may get and what to do about it.
The third program has events at 1,000 per second, and 3,000 per second between seconds 40 and 80, the last day to pay, with 10% random variation each second. One consumer handles 1,500 per second. Part 2 shows how batch size changes the rate of a consumer whose call costs 20 ms plus 0.5 ms for each event.
Output
Part 1: 1,000 events a second, 3,000 a second between second 40 and 80, one consumer handles 1,500 a second. 300 s.
plan peak lag oldest event back to zero events refused
one consumer 60450 40.3 s 123 s 0
add a consumer after 10 s over 5000 21450 12.9 s 10 s 0
accept at most 1500 a second 0 0.0 s 0 s 60450
Part 2: a call costs 20 ms plus 0.5 ms for each event.
batch size events a second time for one call
1 48 20 ms
10 400 25 ms
100 1428 70 ms
1000 1923 520 ms
One consumer: a peak lag of 60,450 events, the oldest event 40.3 s old, and 123 s after the spike to reach zero again.
Add a second consumer after the lag has been over 5,000 for 10 s: the peak was 21,450, the oldest event 12.9 s, and zero lag 10 s after the spike.
Accept at most 1,500 a second: no lag, and 60,450 events refused. The producer has to hold them or retry, which suits some callers and not others.
Batch size: 1 event per call allowed 48 a second, 10 gave 400, 100 gave 1,428 and 1,000 gave 1,923 but one call took 520 ms.
Absorb, scale or refuse. Pick on purpose.
Alarm on lag and on its growth, not on CPU. A lag that is stable at a high level is a latency problem; a lag that keeps growing means the consumers are slower than the producers. Remember that the number of partitions caps how many consumers help.
8. Retries, Poison Messages and Dead-Letter Queues
Some messages fail for a short time (the mail server is busy). A few fail every time (a malformed record). A consumer that retries a failing message in place does not move on, so everything behind it waits. That is head-of-line blocking.
The fourth program has 10,000 receipts arriving one every 10 ms, and a consumer that takes 5 ms per receipt. 1 in 100 messages is poison and 5 in 100 fail once or twice and then work. It compares four plans: retry in place for ever; retry in place 3 times and drop; retry in place 3 times and send to a dead-letter queue; and a retry queue where a failed message returns after 5 s.
Output
10000 receipts, 1 in 100 poison, 5 in 100 fail once or twice and then work. A failed try in place waits 1 s.
plan healthy messages worst delay of worst delay of lost dead stuck
delayed over 1 s a healthy one a retried one letters behind a poison
retry in place for ever 85 5.9 s 5.9 s 0 0 9905
retry in place 3 times, then drop 9413 882.7 s 880.7 s 106 0 0
retry in place 3 times, then dead-letter 9413 882.7 s 880.7 s 0 106 0
retry queue with 5 s delay, then dead-letter 0 0.0 s 10.0 s 0 106 0
Retry for ever: the first poison message stopped the partition. 9,905 messages were stuck behind it.
3 tries, then drop: 106 messages lost, and 9,413 healthy messages were delayed over 1 s. The worst healthy message waited 882.7 s, because each failure held the line for 1 to 2 s.
3 tries, then dead-letter queue: nothing lost (106 in the dead-letter queue) with the same delay.
Retry queue, 5 s delay: no healthy message was delayed. A retried message came back after 5 s per failure (10.0 s at most) and the 106 poison messages ended in the dead-letter queue after 3 tries.
Move failures aside so that the line keeps moving.
Keep the failed message's key, the reason and the number of tries when it moves to the retry or dead-letter queue, alert when the dead-letter queue grows, and give people a way to fix and replay it. Use a delay that grows with each try, with a random part, so retries do not arrive together. A retry queue weakens the order for that key: a later message for the same student may now be handled before the earlier one. If order matters, park the rest of that key's messages until the failed one is resolved.
9. Consumer Groups and Rebalancing
When a consumer joins or leaves, the partitions are divided again. With an eager rebalance every consumer gives up all its partitions, waits for the new assignment and starts again, so the whole group stops. A cooperative (incremental) rebalance moves only the partitions that change owner, and the others keep working. Detection of a crashed consumer takes the session timeout, because the group has to wait to be sure it is gone.
The fifth program has 12 partitions at 100 events a second each and 4 consumers who can handle 800 a second each. A consumer crashes at second 60 (noticed at 70) and a new consumer joins at 120. An eager rebalance stops everything for 5 s. A cooperative one pauses only the 3 moving partitions for 2 s.
Output
12 partitions, 100 events a second each, 4 consumers (800 a second each). A consumer crashes at second 60 and a new one joins at 120. 180 s.
rebalance partition-seconds peak lag seconds with lag
with no processing over 1200 (1 s of traffic)
eager 150 9000 27
cooperative 42 3600 15
Eager: 150 partition-seconds with no processing (30 from the crash, then 60 for each rebalance), a peak lag of 9,000, and 27 s with the lag above 1,200 (one second of traffic).
Cooperative: 42 partition-seconds, a peak lag of 3,600 and 15 s above 1,200.
Only what has to move should stop.
The 30 partition-seconds before the first rebalance are the cost of the session timeout, the same in both. A shorter timeout finds a dead consumer faster and also declares a slow one dead, which causes needless rebalances. Static membership (a consumer keeps its identity across a quick restart) avoids a rebalance for a deploy.
10. Acknowledgements and Leader Failure
A producer can ask for no acknowledgement (acks 0), for the leader's (acks 1) or for the leader and all in-sync followers (acks all). More acknowledgement waits longer and loses less when the leader fails, because a new leader can only be a follower, and a follower may not have the last messages.
The sixth program sends one message a millisecond for 100 s. The leader has a message 1 ms later, and each of 2 followers copies it 1 to 30 ms after that (1 in 1,000 takes 500 ms longer). 1 message in 1,000 is dropped on the way to the leader. The leader crashes 3 times, and a randomly chosen follower takes over.
Output
100000 messages, 3 leader crashes, 2 followers, 1 in 1000 messages dropped on the way to the leader.
setting wait for ack lost without acknowledged but not acknowledged at
(average) anyone knowing missing after crash the crash (producer retries)
acks 0 0.0 ms 98 49 0
acks 1 1.0 ms 0 46 3
acks all 22.4 ms 0 0 69
acks 0: no wait. 98 messages were lost without anyone knowing (dropped on the way), and 49 more were missing from the new leader after a crash.
acks 1: 1.0 ms wait. Nothing was lost silently, but 46 acknowledged messages were missing from the new leader.
acks all: 22.4 ms average wait. No acknowledged message was missing. The cost was 69 messages in flight at the crashes, which the producer retried (and so may have sent twice, unless it uses an idempotent producer).
Safety is bought with waiting.
Real systems add a minimum number of in-sync replicas, so that acks all does not silently become acks 1 when followers are lagging, and they elect the new leader only from the in-sync set. The program uses fixed assumptions: a crash during a spike of copy delay would lose more.
11. Retention, Segments and Compaction
A log is stored as segments (files). Old segments are deleted when they pass the retention time or size, which is a cheap file delete, not a delete of single messages. A consumer that falls behind retention loses the data and must start from the earliest remaining offset or from a snapshot. Some topics keep only the latest message for each key (log compaction), which turns the log into a table of current values, such as the latest status of each student's fee.
12. Choosing the Design
Start from order and repeats.
| Concern | Choice | Watch for |
|---|---|---|
| Ordering | Key by the smallest unit whose order matters | A hot key |
| Delivery | At least once, commit after the work, idempotent effect | Duplicates after crashes |
| Spikes | Let lag absorb, scale consumers, cap by partitions | Age of the oldest message |
| Failing messages | Retry queue with delay, dead-letter queue | Order for the key |
| Group changes | Cooperative rebalance, static members | Timeout too short or too long |
| Durability | Replication, acks all, minimum in-sync replicas | Producer latency |
13. Trade-offs to Mention
More partitions allow more parallelism and make ordering weaker across keys, rebalances slower and recovery longer.
A log keeps messages for replay and costs disk; a work queue frees space when a message is handled and cannot replay.
Larger batches raise throughput and add latency.
acks allis safer and slower.A retry queue keeps the line moving and weakens order.
Exactly-once costs an extra record or transaction for every message.
14. Common Mistakes
Keying by something with a few huge values.
Committing the offset before the work is done.
Treating at-least-once as exactly-once and sending two receipts.
Retrying a poison message in place for ever.
No dead-letter queue, or one that nobody watches.
Alarming on broker CPU and not on consumer lag.
Adding consumers beyond the number of partitions.
Leaving
acks 1on for money events.
15. Interview Questions
How do you keep one student's events in order? Give them the same partition key, so they go to the same partition and one consumer.
What is the difference between at-least-once and exactly-once? At-least-once repeats messages after a crash; exactly-once needs the consumer to detect repeats or make the effect repeatable.
What is consumer lag and what do you do about it? Messages written but not handled; scale the consumers (up to the number of partitions), speed up the work, or refuse new work.
How do you stop one bad message from blocking a partition? Move it to a retry queue with a delay and then a dead-letter queue after a few tries.
What happens when a consumer dies? The group notices after the session timeout and gives its partitions to others; the new owner starts from the last committed offset.
What does
acks allprotect against? Losing an acknowledged message when the leader fails, because every in-sync replica already has it.
Summary
Partition by the smallest unit whose order matters, and check the busiest partition.
Do the work, then commit the offset, and make the work safe to repeat.
Watch the lag and its age; scale consumers within the number of partitions.
Use a retry queue with a delay and a dead-letter queue, not retries in place.
Prefer cooperative rebalances and sensible timeouts.
Use
acks allwith a minimum of in-sync replicas where loss is not acceptable.
Conclusion
A message queue looks like a pipe, and most of its design is about the moments when something goes wrong: a consumer that dies after the work and before the commit, a message that always fails, a spike that outruns the consumers, a leader that fails with followers behind. The design above handles each with a mechanism and a measured result. In an interview, say what must stay in order and what may be repeated, and then show how each choice protects that.
Previous topic: Design Object Storage like S3. Next topic: Design a Time-Series Database.
References and further reading
Kreps, Narkhede and Rao, Kafka: a Distributed Messaging System for Log Processing (2011), and the Apache Kafka documentation on producers, consumer groups, replication and the cooperative rebalance protocol.
Amazon SQS and RabbitMQ documentation for the work-queue model, visibility timeouts and dead-letter queues.
Kleppmann, Designing Data-Intensive Applications, chapter 11 (stream processing), on delivery guarantees and idempotence.
Design Key-Value Store, Design Distributed Cache and Design API Gateway on this site.