"Design a message queue" is not "use a queue". The message queues lesson already covers why you would add one: decoupling, delivery guarantees, ordering and dead letter queues. This question asks you to build the broker, the machine that makes those promises hold when disks fail and consumers crash.
Interviewers use it to separate people who have used Kafka or SQS from people who know why they work. Three questions decide the outcome. Why is an append-only log fast enough to carry a million messages a second? What does a producer's "ack" actually promise, and when is it a lie? And how do many consumers share the work without breaking the order of related messages?
We will design a partitioned, replicated log, the structure behind most high-throughput brokers, and note where a classic per-message queue would differ.
Clarify the requirements
Functional requirements:
- Producers publish messages to a named topic.
- Consumers read messages from a topic. Several independent applications can each read every message (separate consumer groups), and within one application, several consumers share the work.
- Messages with the same key are delivered in the order they were published.
- Messages are retained for a configurable time (7 days by default), so a consumer can fall behind, crash and resume, or replay.
- Topics can be created with a chosen number of partitions.
Out of scope, said aloud: message routing by content, per-message priority, delayed delivery, schema management, cross-region replication.
Non-functional requirements:
- High throughput: hundreds of thousands of messages per second, sustained, on commodity hardware.
- Durable: an acknowledged message survives the loss of a broker.
- Available: producing and consuming continue when one broker or one zone fails.
- Ordered per key, not globally. Global order would cap throughput at one machine.
- Low latency: a few milliseconds from publish to a ready consumer.
Estimate the scale
Assume an average of 300,000 messages per second at 1 KB each, a 3× peak, 7 days of retention, a replication factor of 3 and three independent consumer groups.
Ingress: 300,000 × 1 KB = 300 MB/s on average, about 900 MB/s at peak.
Retained data: 300 MB/s × 86,400 × 7 days ≈ 181 TB, and with 3 replicas about 544 TB on disk.
Broker count: at about 10 TB of usable disk per broker, 544 ÷ 10 ≈ 54, so plan for about 60 brokers.
Disk write rate: replication triples the write volume: 300 MB/s × 3 = 900 MB/s across 60 brokers, about 15 MB/s each, easy for sequential writes.
Egress: three consumer groups each read everything: 3 × 300 MB/s = 900 MB/s on average.
Partitions: a consumer instance processing 5,000 messages a second serves one partition's share. To keep up at the 900,000 peak, you need 900,000 ÷ 5,000 = 180 consumers in a group, and a partition is read by at most one consumer in a group, so at least 180 partitions. Round up to 256 partitions for headroom. At 300,000 average, that is about 1,170 messages a second (1.2 MB/s) per partition.
"The disks are sized by retention, not by throughput: 544 TB over about 60 brokers. The partition count is set by the consumer parallelism you need at peak, because partitions are the unit of both ordering and parallelism, and they are hard to change later. Pick it from the 180-consumer number, not from a default."
The capacity estimator reproduces 300,000 writes per second and 181 TB, with the 7 days of retention entered as 0.0192 years.
API and data model
produce(topic, key, value, acks) -> { partition, offset }
fetch(topic, partition, offset, maxBytes) -> [{ offset, key, value, ts }]
commit(group, topic, partition, offset)
join(group, topic) -> assigned partitionstopic name, partitions[ ], replication factor, retention
partition leader, replicas[ ], in-sync set (ISR)
segment append-only file, ~1 GB each, named by its first offset
offset the position of a message in its partition, assigned by the leader
group offsets (group, topic, partition) -> committed offsetMessages are not deleted when read. A consumer only moves its own offset. That one idea gives replay, independent groups and cheap consumers, and it is the biggest difference from a classic queue, where the broker tracks and deletes each message.
High-level design
The slice to simulate is the produce and consume path: producers write to a replicated, partitioned log, and a consumer group reads each partition in order.
- Producers send messages to a broker front end, which appends them to a topic's partitions.
- The broker cluster replicates every partition to three brokers and acknowledges after the in-sync replicas have it.
- A consumer group reads each partition in order, and each partition is read by one consumer.
Describe this diagram
Components
- producers (Client)
- producer api (Service)
- broker cluster (Kafka)
- consumer group (Service)
Connections
- producers sends to producer api
- producer api sends to broker cluster
- broker cluster sends to consumer group
Run it, then try setting acks to 1, changing the partition count or reducing the consumers, and watch produce latency and consumer lag move.
The produce path: the producer hashes the key to pick a partition, batches messages for a few milliseconds (batching is where much of the throughput comes from) and sends the batch to that partition's leader. The leader appends it to the active segment, and followers copy it. Once every in-sync replica has it, the leader acknowledges.
The consume path: a consumer asks the leader for messages starting at an offset, processes them and commits the new offset. After a crash, a replacement resumes from the last committed offset, so a few messages may be processed twice. This is at-least-once delivery.
The interesting problem: why a log, and how it stays fast
The storage design decides throughput. There are three ways to build the broker.
Approach A: a database table, delete on ack
Insert each message as a row. Consumers SELECT ... FOR UPDATE SKIP LOCKED, process and delete.
Good: familiar and transactional, and fine up to a few thousand messages a second.
Bad: every message is a random write plus a delete, with index maintenance and lock contention on the head of the queue. It cannot reach 300,000 messages a second, and retention for replay is impossible once rows are deleted.
Approach B: per-message state in a broker
The broker keeps each message in memory and on disk, tracks which are delivered and acknowledged, redelivers on timeout and removes on ack. Classic brokers work this way.
Good: per-message acknowledgement, priorities, flexible routing and fast delivery for modest volumes. It suits work queues where each task is handled once.
Bad: tracking and deleting individual messages makes disk access random, and per-message bookkeeping caps throughput. Replay is not possible, and a slow consumer builds up unacknowledged state in memory.
Approach C: a partitioned, append-only log
Each partition is a file you only append to and only read forward. Messages get consecutive offsets. Consumers keep their own position.
Good: sequential disk I/O is far faster than random I/O. The operating system's page cache serves recent reads from memory, so a consumer that keeps up never touches the disk. The broker can send file bytes straight to the network without copying them through the application (zero-copy), and batching amortizes every cost. Deleting means dropping whole old segment files. Replay, many groups and cheap consumers fall out for free.
Bad: no per-message ack, no priorities, and a message cannot be removed from the middle. Ordering holds only within a partition. A consumer that fails mid-batch redelivers the whole batch.
The recommended answer is C for a high-throughput, replayable broker, and B when you need per-task acknowledgment and routing at modest volume. Say which requirement points to which. The throughput numbers above need the log.
The second decision: what an acknowledgement promises
A producer's acks setting decides when the broker says "done", and it is a direct durability-versus-latency choice.
acks=0: do not wait. Fastest, and messages vanish silently if the leader fails. Only for metrics you can lose.acks=1: the leader has written it. A leader crash before followers copy it loses the message, even though the producer was told it succeeded.acks=all: every replica in the in-sync set (ISR) has it. With replication factor 3 andmin.insync.replicas=2, an acknowledged message exists on at least two brokers, so one broker loss cannot lose it.
The ISR is the group of replicas that are caught up with the leader. A replica that falls behind is removed from it, so one slow follower does not stall every write. If the ISR shrinks below min.insync.replicas, the broker rejects writes, rather than acknowledging data it cannot keep safe. That is a deliberate choice for consistency: producers see errors and retry instead of silently losing data.
When a leader dies, the controller elects a new one from the ISR, so the new leader has every acknowledged message. Electing a replica outside the ISR (an unclean election) restores availability sooner but can lose acknowledged messages. State your default: durability first, with unclean election off.
Duplicates come from retries: a producer times out, retries, and the first attempt had succeeded. An idempotent producer attaches a producer id and sequence number to each batch so the broker drops repeats. Together with committing consumer offsets atomically with outputs, this builds the effect of exactly-once processing, within one system.
Bottlenecks and failures
A hot partition. Hashing by key sends all messages for one key to one partition. A customer producing 100 times the average makes that partition's broker and consumer the bottleneck while others idle. Choose keys with enough cardinality, or split large keys across a suffix when per-key order is not essential.
Consumer lag. If consumers fall behind, lag grows, and when lag exceeds retention, messages are deleted unread. Alert on lag in time ("the consumer is 12 minutes behind"), not in message counts, and keep retention well above the longest realistic stall.
Rebalance storms. When a consumer joins or leaves, partitions are reassigned and processing pauses. A consumer that crashes and restarts repeatedly can cause this repeatedly. Use sticky assignment so most partitions stay put, and tune session timeouts so a slow garbage-collection pause does not look like death.
A poison message. One message that always fails blocks its partition if the consumer retries forever. Retry a few times, then move it to a dead letter topic and continue, as the message queues lesson describes.
Controller and metadata. Leader elections and the topic map need a coordinator, a small quorum such as Raft (distributed coordination). If the quorum is lost, existing leaders keep serving reads and writes for a while, but elections and new topics stall.
A full disk. Retention by time can be outpaced by a burst. Also cap by size, alert at 70% and spread partitions evenly so one broker is not the first to fill. If a broker's disk fills, it stops accepting writes.
Trade-offs to name aloud
- Log over per-message queue: very high throughput and replay, in exchange for no per-message ack or priority.
acks=allwith ISR: durability at the cost of the slowest in-sync replica's latency.- Partition count: more partitions allow more parallelism and cost more files, metadata and rebalance time.
- Per-key ordering only: scalability, in exchange for no global order.
- At-least-once by default: consumers must tolerate duplicates, or the system must deduplicate.
What interviewers listen for
- A working answer: topics, partitions, producers appending, consumers tracking offsets and replication for durability.
- A strong answer: explains why an append-only log is fast, sizes partitions from consumer parallelism and defines acks and the in-sync set.
- A standout answer: also covers leader election from the ISR and the unclean-election trade-off, idempotent producers for retries, the one-way door of partition counts and lag measured in time.
Check your understanding
Common mistakes
Calling the broker a black box. "Kafka handles it" ends the interview. Explain the log, the partitions and the replication.
Claiming global ordering. Total order across partitions is not available at this throughput. Say "per key" and show how keys map to partitions.
Treating acks=1 as safe. The producer is told the write succeeded, and a leader crash before replication loses it. Know exactly what each setting promises.
Picking the partition count at random. It sets the maximum consumer parallelism and the key-to-partition mapping. Compute it from the peak consumer count.
Forgetting duplicates. Retries and consumer restarts create them under at-least-once delivery. Name idempotent producers or idempotent consumers.
Ignoring slow consumers. Lag beyond retention is silent data loss. Monitor it, and say what you do when a consumer cannot keep up.
Practice
Consumer lag on one topic has grown to 40 minutes and is still rising, while producers are healthy. How do you diagnose and fix it?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Compare the produce rate with what the consumers can process, and check whether the lag is on all partitions or a few.
Show a strong answer
Check how widespread it is. If lag is high on all 256 partitions, consumers are too slow overall. If it is high on a few, you have a hot key or a stuck consumer.
All partitions behind. Compare produce rate with total consume rate. If production is 300,000 per second and 180 consumers each handle 1,500, they manage only 270,000, a gap of 30,000 per second. Add consumers, up to the partition count, or make processing faster (batching its writes, removing a slow synchronous call).
A few partitions behind. Find the key that dominates them. A hot key needs a different key or sub-keys. A consumer stuck on a poison message needs a retry limit and a dead letter topic.
Protect against loss. Check the lag in time against the 7-day retention. At 40 minutes there is room, but extend retention temporarily if the backlog threatens to outlast it.
The pattern worth keeping: determine whether the problem is capacity (all partitions) or skew (a few), because the fixes are different.
Product asks for 'deliver this message in 10 minutes' on top of your log. Messages in a partition are read in order, so how do you add delay?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
You cannot make a consumer skip ahead, but you can control where a message is published.
Show a strong answer
A log has no delay feature, because consumers read strictly in order. A message with a later delivery time would block the ones behind it.
Use delay topics. Publish delayed messages to topics by delay bucket (for example delay-1m, delay-10m), each with messages naturally in due-time order, because every message in a bucket has the same delay. A forwarder consumes delay-10m, waits until the head message is due, and then republishes it to the real topic.
Or store the schedule elsewhere. For arbitrary delays, keep them in a scheduled-jobs store indexed by due time, and publish to the log when due. That is the job scheduler problem, covered in the job scheduler question.
The pattern worth keeping: when a structure forbids an operation, add a layer that preserves its invariant, such as in-order buckets, rather than weakening the structure.
Key takeaways
- A log is fast because it is sequential: append-only partitions, page cache, zero-copy and batching.
- Partitions give both ordering and parallelism. Order holds only within one, and the count is hard to change.
acks=allwith an in-sync set and a minimum makes an acknowledgement mean something.- Elect new leaders from the in-sync set so acknowledged messages survive failover.
- Consumers track offsets, which gives replay, independent groups and at-least-once delivery.
- Watch lag in time, and design for skew: hot keys and slow consumers are the common failures.
Further reading
- J. Kreps, N. Narkhede and J. Rao, "Kafka: a Distributed Messaging System for Log Processing", NetDB workshop (2011): the original design of the partitioned log.
- Apache Kafka documentation, "Design": the log, replication, the in-sync set and delivery semantics.
- Amazon Web Services, Amazon SQS Developer Guide: standard and FIFO queues, visibility timeout, the per-message alternative.
- D. Ongaro and J. Ousterhout, "In Search of an Understandable Consensus Algorithm" (Raft), USENIX ATC (2014).