Systemsfor Aravinda
0 / 78 core
Week 10 · Case studies

Design a distributed message queue

2 hours · core path

Read first: Queues and logs, Kafka, Replication

In one sitting

Build a log, not a buffer that deletes on ack. A partition is the order you actually promise, a consumer group remembers an offset, and retention bounds the disk. A poison record is copied aside after a few failures so the rest of that partition can move.

You are not building a function call with a waiting room. You are building an append-only log that several readers can replay, plus a way for one group of workers to split that log and remember how far they got. The ack does not delete the record. It moves an offset. If you need the record gone when someone says they handled it, you want a queue. This design is the log that a group consumes like a queue, and the difference is the whole interview.

The published vocabulary for this shape is Kafka: topics, partitions, consumer groups, a leader and in-sync replicas, lag as the signal. You are designing the system, not naming a vendor and sitting down. Use the words, and be precise about the promise.

Requirements

The user is another service. A producer appends facts. A consumer group does work. A second group may read the same facts for a different purpose.

It must:

  • Append a record to a topic and acknowledge it only when the record is durable on a majority of replicas.
  • Give each consumer group a split of the partitions, and let the group resume after a crash from the last offset it committed.
  • Keep records for a bounded time so a second group, or a rebuild, can replay.
  • Keep one bad record from wedging a partition forever.
  • Say, in one sentence, what order you guarantee.

Non-goals:

  • A global total order across the topic. If you need that, you have one partition, and you have given up throughput.
  • Exactly-once side effects in a database, an email system, or a card charge. Delivery guarantees stop at the edge of the log. Outside it, the handler is idempotent or you accept duplicates.
  • Per-message priority. A priority queue is a different structure. A log is ordered by append.
  • Infinite retention. Disk is finite. Say the bound.

Latency assumption: a producer ack at p99 is a few milliseconds inside one region, dominated by a disk flush and a replica round trip, not by the consumer. The consumer is off the producer’s clock. That is why you built a log.

Estimation

Assumptions:

  • 100,000 records per second average, 1 KB each.
  • Peak is 3 times average, inside the 2x to 5x band.
  • Replication factor 3. A commit needs a majority. For three replicas that is the leader and one follower. The third copy is so you can lose another machine and still have a majority later. All three store the bytes when they are healthy, so size disk for 3.
  • Retention is 7 days.
  • A consumer handles about 5 MB/s of these records. That throughput is an assumption about the handler, which might be doing real work, not a benchmark of the log itself. 5 MB/s at 1 KB is 5,000 records per second per consumer.

A day is 86,400 seconds.

average ingress = 100,000 * 1 KB = 100 MB/s
peak ingress    = 300 MB/s
disk, factor 3, peak = 900 MB/s written across the cluster

per day = 100 MB/s * 86,400 = 8.64 TB
shortcut, 100 MB/s * 1e5 = 10 TB, high because the shortcut day is long
7 days = 60.5 TB of unique bytes
with 3 replicas = about 181 TB

consumers at peak = 300,000 records/s / 5,000 = 60
partitions, round up for headroom = 128

A million records a day would be about 12 per second. You are at 100,000 per second average, and the disk bill is the replica factor times retention. 181 TB is the number you say out loud. Adding a day of retention adds about 26 TB at factor 3. That is the cost conversation, with no prices attached.

One hundred and twenty-eight partitions because the group can only parallelize one member per partition. Sixty busy consumers need at least sixty partitions. Extra partitions let you grow the group without a re-partition of the historical log, and they cost more files and a slower rebalance. If the handler is lighter than 5 MB/s, you need fewer members and could live with fewer partitions. The assumption is the handler, so say it.

High-level design

flowchart LR
  producer[Producer]
  leader[Partition leader]
  replicaA[Replica A]
  replicaB[Replica B]
  group[Consumer group]
  offsets[Committed offsets]
  dead[Dead letter log]
  producer --> leader
  leader --> replicaA
  leader --> replicaB
  leader --> group
  group --> offsets
  group --> dead

A topic is a name. It is split into partitions. Each partition is an ordered file with a leader. Producers append. Followers replicate. A consumer group has a membership and an assignment: each partition is read by one member at a time. The offset commit is a small durable record, keyed by group and partition. A second group has its own offsets and reads the same file. Nothing in the produce path consults a consumer.

The dead-letter log is another topic. It is how a poison record leaves the partition without pretending it was processed.

Deep dive

The order you actually promise

A partition is a total order. Record 100 sits after 99 and before 101 because the leader appended them that way. That is the promise.

A key hashes to a partition, so all records for that key share that order, as long as you do not change the partition count out from under the key. Two keys that land on different partitions have no order. “The topic is ordered” is the sentence that fails the interview.

The log order matches a single producer’s send order only when that producer has one outstanding append to the partition. If it pipelines several appends and retries an earlier one after a later one has already committed, the retry lands behind. The order you can defend is the order the leader appended. Say the pipelining caveat instead of waving at a configuration knob you do not intend to derive.

On the read side the promise is just as narrow. A consumer that pulls a batch, handles the records concurrently, and then commits the highest offset can commit past a failure. Process the partition in order. Commit the offset only through the last record that finished in that order. If 105 failed, do not commit 110.

You do not promise that the handler’s side effect happens once. Commit after the handler returns and a crash in between redelivers. That is at-least-once. Commit before the handler runs and a crash drops the record. That is at-most-once. Exactly-once is a property of a bounded protocol inside the log, the idempotent producer plus a transactional handoff between topics. It is not a property of the email you send at the end. The handler stays idempotent. This is the same line the delivery page draws, and the case is where people forget it.

A producer ack means a majority of replicas have the record. It does not mean a consumer has applied it. Replication is doing durability, not end-to-end completion. If you ack on the leader alone, a leader crash loses the tail and the producer believes it is safe. Synchronous replication to the majority stalls when a follower is slow. Take the stall. The third replica can catch up asynchronously after the majority commit. You still budget disk for three copies.

The leader carries an epoch, the same idea as a term in consensus. An old leader that still thinks it is in charge is fenced. Two leaders appending to one partition is a split brain, and no consumer-side trick repairs an order that forked. You do not re-derive the election in this interview. You say the partition has one leader, the epoch rejects the old one, and a producer that talked to the old leader retries on the new one with the same idempotency.

Producer retries need that idempotency. Give the producer a stable id and a sequence per partition. The leader ignores a sequence it has already accepted. A lost ack then does not append the record twice. Without it, at-least-once produce becomes a duplicate in the log, and every consumer sees the duplicate. The handler might still be idempotent. The log is cleaner if the duplicate never lands.

Groups, acks, retention, poison

A group assignment is a map from partition to member. When a member dies, a rebalance moves its partitions. The new member starts at the last committed offset. Records that were handled but not committed are handled again. That is a duplicate, and it is normal. Lag, the end of the log minus the committed offset, is the number you alert on. A per-message ack, in the sense of deleting the message, does not exist here. The queue versus the log is that distinction. Competing consumers are the group membership. The record stays for anyone else, and for replay, until retention.

Retention is 7 days or a size cap, whichever you hit first. After that the start offset moves forward and a slow consumer cannot read what is gone. A group that returns after 8 days finds its offset below the start. Do not silently jump forward. For this design the group stops and signals. An operator can reset the offset to the new start and accept the gap, or replay from a colder archive if you built one. A metrics topic might choose the silent skip. A topic that feeds a ledger must not. The queue does not know which one it is unless you configured the choice. Default to stop.

Compaction, keeping the latest record per key and dropping the rest, is a different retention mode. It fits a changelog of current state. It does not fit a stream of facts you needed every one of. Do not turn it on because the disk is full.

A poison record crashes the consumer every time: a negative length, a schema the code cannot read, a handler bug on one id. The member restarts, reads the same offset, and crashes. That partition’s lag grows without bound. The other partitions, on healthier members, drain. You have head-of-line blocking inside the partition because you promised order.

After 5 failed attempts, assumption, append the record to the dead-letter topic with the original partition, offset, and error, then commit past it. You broke the order on purpose. Downstream sees a gap. The dead letter is how a human sees the gap. Retrying forever preserves the promise and loses the partition. Name the trade when you do it. Do not commit past the record on the first failure. A blip in a dependency would then drop data that would have succeeded a moment later. Five attempts with backoff, then the side door.

The offset store is durable. It can be a small compacted log keyed by group and partition, or a row in a database. If the commit itself is lost, you redeliver a batch. That is at-least-once again, which you already accepted. If you batch offset commits to every 100 records for speed, a crash redoes up to 100. Say the number. Assumption: commit every successful record for topics that charge money or mutate accounts, and every few seconds for topics that can tolerate a short replay.

Partitioning by the key spreads producers. It does not split a hot key. If one tenant is half the traffic, that tenant’s partition is half the traffic, and partition 129 does not help. You either change the key, accepting that the tenant’s records are no longer ordered as one stream, or you isolate that tenant. Adding machines moves cold partitions. It does not move the hot one.

Backpressure: when disk is past a watermark or the leader cannot append inside the deadline, reject the produce. A log with retention still fills if today’s ingress outruns the retention deletes. An unbounded buffer in front of a slow disk is a memory leak. Producers retry with jitter if the error is the overload kind, and they do not retry a validation error. The poison record should fail at the producer when you can tell, so it never enters the log. You cannot tell all of them. The dead letter is for the rest.

Tradeoffs

Choice What you gain What you spend
Ack is an offset, record stays until retention Replay, and many independent groups Disk, and a consumer bug can reprocess a week of data
Delete the record on ack, classic queue Smaller disk, simpler mental model A second consumer cannot read it, and a lost ack is a lost record if you deleted early
Majority commit before producer ack A leader crash does not eat acknowledged records A slow replica stalls produces
Leader-only ack A fast produce The tail is a lie after failover
In-order handling, commit only through the last success The partition order reaches the handler One slow record blocks that partition
Dead-letter after five failures The partition moves again A deliberate gap, and a human has to look at the side log
More partitions A larger consumer group More files, longer rebalances, and no help for a hot key
One in-flight produce per partition Send order matches append order Less batching, lower throughput per producer

Failure modes

  • Old leader still accepts writes after a new leader is elected. Symptom: two tails, consumers disagree, idempotent handlers cannot merge a forked order. The epoch fences the old process. Producers retry on the current leader with the same sequence.
  • Consumer crashes after the side effect and before the offset commit. Symptom: the next owner does the work again. If the work was “send an email,” the user gets two. The handler needs its own key. The log will not save you.
  • Consumer commits the offset, then crashes before the side effect. Symptom: the record is gone from this group’s point of view and the work never happened. You chose at-most-once. Do not do that for anything you cannot lose.
  • Poison record, no dead letter. Symptom: one partition’s lag climbs, alerts fire, the other partitions look fine, and a restart loop burns CPU. Five failures, then the side log.
  • Retention moves the start offset past a stopped group. Symptom: the group resumes and either skips a week or reads garbage. Stop and signal. An operator resets the offset on purpose.
  • Rebalance during a deploy. Symptom: a burst of duplicates and a pause while partitions move. Clients that are not idempotent page you on every deploy. That is a handler bug, revealed by a normal rebalance.
  • Retry storm from consumers replaying a day of log onto a database after a bad deploy. Symptom: the database falls over, lag looks like it is healing, and you are multiplying writes. Cap the replay rate. The log can be read slowly.
  • Disk fills because retention deletes cannot keep up with a peak. Symptom: produces fail, or the leader stalls and every producer times out and retries, which fills it faster. Reject early. Do not buffer without a bound.
  • Hot key. Symptom: one partition at high CPU, the rest idle, and someone proposes doubling the partition count. The key still hashes to one of them. Change the key or live with the skew.

In the interview

First five minutes: log, not a deleting queue; partition is the order; group offset is the ack; majority before you ack the producer; retention is 7 days and about 180 TB at these assumptions; poison records get a side door. Write the ingress number, 100 MB/s average, times 3.

Skip the election protocol. Say there is a leader and an epoch. If they want Raft, that is a different interview, and you can do it, but not by abandoning the queue.

The question that follows is “what order do you promise?” or the poison message. Answer with the partition, the single in-flight producer caveat, and the commit-through-the-last-success rule. Then the five failures and the deliberate gap. If they ask about exactly-once, draw the box around the log and leave the handler outside it.

Check yourself

A producer is acknowledged, then the leader dies. What has to be true so the record is still there, and what does the ack not mean?

A majority already stored it, so a new leader taken from that majority still has the record. The ack does not mean a consumer ran the handler. Durability of the log and completion of the work are different events.

Your consumer handles records 100 through 110 concurrently, fails on 105, and commits offset 110. What did you break?

The partition order. You told the log that 105 was done. Later records’ side effects landed, the failed one did not, and a restart will not go back. Commit only through the last in-order success. Concurrent handling inside the partition is how this bug sneaks in.

One record crashes the consumer on every delivery. What happens if you retry forever, and what do you do instead?

That partition stalls. The member restart-loops on the same offset while other partitions drain. After a small number of attempts, copy the record to a dead-letter log and commit past it. You chose a gap over a wedged partition, and you made the gap visible.

A consumer group has been off for eight days. Retention is seven. What should the group do when it comes back?

Its offset is below the start of the log. Jumping forward without a signal drops a week of records and looks like a healthy consumer. Stop and surface the gap. An operator can reset the offset if this topic is allowed to lose the window. The log should not decide that silently.

Based on: Kafka, Jay Kreps, Neha Narkhede, and Jun Rao; Designing Data-Intensive Applications, Kleppmann and Riccomini; Alex Xu, ByteByteGo volumes.