Distributed Message Queue
An order event is accepted, then its consumer crashes. What exactly survives, and where does processing restart?
Problem statement
This design assumes independent readers need replay. For a task queue where one worker handles each delivery, such as a RabbitMQ work queue, start with acknowledgements and redelivery. Here we build a retained event log that lets independent applications process the same stream at different speeds. An order service publishes order events; billing and warehouse consumer groups each keep their own position. Reading a record does not delete it. , rather than an acknowledgement from one consumer, determines how long replay remains possible.
Functional requirements
- Create topics with a partition count, replication factor and policy.
- Publish keyed records and return their partition and offset after the configured acknowledgement condition.
- Let independent consumer groups pull bounded batches and save their own progress.
- Replay retained records after a restart or a deliberate offset reset.
Non-functional requirements
- Preserve append order within a partition, without promising global or wall-clock event ordering.
- Target 100,000 messages/s at 1 KB each; measure acknowledgement latency separately from end-to-end processing latency.
- Use three replicas across three availability zones, acks=all and min.insync.replicas=2 for the baseline.
- Allow at-least-once processing with duplicate-safe effects; bound client buffers, retries and .
The numbers behind the design
| Interview assumption | How it changes the design |
|---|---|
| 100k messages/s × 1 KB ≈ 100 MB/s ingress | With three copies, budget about 300 MB/s stored before overhead and batch compression. |
| 100 MB/s × 86,400 ≈ 8.64 TB/day logical | Three replicas and three days require about 77.8 TB before overhead; disk-full behavior must be defined. |
| 6M backlog; 120k/s service and 100k/s arrival | Net drain is 20k/s, so recovery needs 300 seconds. More consumers help only while useful partitions remain. |
Entities
| Entity / logical owner | Minimal authoritative fields and boundary |
|---|---|
| Topic(name, partitions, replicationFactor, ) | Logical stream configuration. More partitions add parallelism but change key placement unless explicitly managed. |
| Record(topic, partition, offset, key, producerId, sequence, payload) | An offset identifies a position within one partition. Ordering is the leader's append order. |
| Segment(baseOffset, logFile, sparseOffsetIndex) | Append to the active segment. An index lookup finds a nearby byte position, followed by a short scan. removes eligible closed segments. |
| PartitionMetadata(topic, partition, leader, leaderEpoch, ) | The controller stores ownership metadata. includes the leader and sufficiently caught-up replicas. |
| ConsumerOffset(group, topic, partition, nextOffset) | Stored in replicated __consumer_offsets. The value is where processing should resume, not the last fetched record. |
API design
| Operation / input | Response and retry contract |
|---|---|
CREATE_TOPIC {name, partitions, replicationFactor, retention} | Administrative operation. The controller establishes partition placement and leadership. |
METADATA {topic} | Ask a bootstrap broker for partition leaders; cache and refresh this mapping in the client. |
PRODUCE {topic, partition, producerId, sequence, records, acks} | Send a batch directly to the partition leader. Return assigned offsets or an error; a timeout leaves acceptance uncertain. |
FETCH {topic, partition, nextOffset, maxBytes, maxWaitMs} | Pull a bounded batch. Long polling waits briefly for data without a busy polling loop. |
COMMIT {group, topic, partition, nextOffset, ownershipEpoch} | Send progress to the group coordinator after the contiguous prefix of business work completes. These are conceptual interfaces, not REST routes or exact wire schemas. |
High-level design
How to draw this design
- Client routingProducers choose partitions using cached broker metadata.
- Replicated dataEach partition has one leader and follower logs on other brokers.
- Group progressConsumers fetch data and separately commit through their group coordinator.
- Cluster controlMetadata controllers track replica placement and partition leaders.
Discover a leader, append and replicate, fetch a batch, apply effects, then commit the next offset.
- State ownership
- Broker disks own data and internal offset logs. The controller owns cluster metadata, not business records or consumer processing results.
- Scale
- Spread partition leaders across brokers. Consumer parallelism within one group is limited by assigned partitions.
- Correctness
- Ordering is per partition. Producer acceptance, replication visibility and consumer business completion are separate boundaries.
- Failure and recovery
- Elect eligible leaders, reject stale ownership, replay from checkpoints and protect effects against duplicates.
Distributed Message Queue: data, progress and control
An orders stream with independent groups. The drawing expands P0; broker roles are specific to this partition and group.
- Edge
- Messaging
- Compute
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the 8 flow steps
One data partition is expanded to show replicas and the separate group coordinator. Other partitions repeat this pattern with different leaders. The broker hosting the coordinator also hosts ordinary partition replicas.
End-to-end flow
Create the orders topic with six partitions, three replicas and a window. The metadata controllers record placement and leader epochs.
The producer discovers metadata through any bootstrap broker, chooses a partition from orderId and sends a batch directly to its leader. There is no separate central routing hop.
The leader appends the batch. Followers fetch it; the configured and acknowledgement policy determine when the producer receives success.
The billing and warehouse groups join their respective coordinators. Each receives partition assignments independently.
An assigned consumer long-polls its partition leader for replicated records, processes the batch and makes its effects durable.
It commits the next offset to its group coordinator. The replicated internal offsets topic retains that for recovery.
After a consumer failure, a new owner resumes at the and may repeat work. After a broker failure, clients refresh leader metadata. Both paths preserve retry identities.
High-level design component walkthrough
Order event producers
Batch records and route by orderId directly to a partition leader.
Why, tradeoff and connected operations
The client discovers metadata from a bootstrap broker and caches partition ownership. No central routing service is needed.
Tradeoff: A timeout can hide an accepted batch; retries need stable producer identity.
Connected operations: Publish keyed batch; Acknowledge accepted batch
Broker A: P0 leader
Append ordered batches and serve replicated records.
Why, tradeoff and connected operations
Append-only segments and sparse indexes support independent retained reads. With acks=all, success waits for the current and its configured minimum.
Tradeoff: Hot partitions and replication lag limit throughput.
Connected operations: Publish keyed batch; Replica data after fetch; Replica data after fetch; Acknowledge accepted batch; Fetch replicated records; Placement and leader epochs
Broker C: P0 follower
Fetch and retain the leader log in another availability zone.
Why, tradeoff and connected operations
A sufficiently caught-up replica can be elected after leader failure. includes the current leader as well as eligible followers.
Tradeoff: Copies consume disk and bandwidth; lag can remove a replica from .
Connected operations: Replica data after fetch
Broker B: replica + coordinator
Replicate P0 and coordinate the billing group as separate responsibilities.
Why, tradeoff and connected operations
This broker leads the internal offsets partition mapped to billing. The coordinator handles group membership and checkpoints, not leadership of every data partition.
Tradeoff: Coordinator failover requires rediscovery; rebalances can interrupt work.
Connected operations: Replica data after fetch; Join group / commit next offset; Replicate
Billing consumer group
Pull assigned partitions, apply duplicate-safe effects, then commit next offsets.
Why, tradeoff and connected operations
One active owner per partition provides ordered progress within this conventional group. Other groups read independently.
Tradeoff: A crash before commit replays completed work.
Connected operations: Fetch replicated records; Join group / commit next offset
Replicated group checkpoints
Store group, topic, partition and nextOffset in __consumer_offsets.
Why, tradeoff and connected operations
The compacted internal topic uses broker replication. Its coordinator is the leader of the relevant offsets partition.
Tradeoff: Checkpointing is separate from the business transaction.
Connected operations: Replicate
Metadata controllers
Maintain topic placement, metadata and leader epochs.
Why, tradeoff and connected operations
A controller provides consistent metadata and elects eligible partition leaders. Consumer assignment belongs to group coordination.
Tradeoff: Loss of impairs elections and metadata changes.
Connected operations: Placement and leader epochs
Engineering control room
Deep dives — decisions, failures and recovery
Open a deep dive to follow the steps, try an example and see how recovery works.
Additional failure cases and alternatives
Tradeoffs and alternatives
| Decision | Tradeoff / alternative and recovery implication |
|---|---|
| Store a partition as a sequence of segments | is finite. A slow consumer can lose its replay window, and a hot key still concentrates work on one partition. |
| Get throughput from batching and the operating system | Larger batches and longer linger add latency. Page cache pressure, TLS and record transformations can change the effective data path. |
| Define exactly what a producer acknowledgement promises | Waiting for replication adds latency. Losing enough eligible replicas must stop successful writes instead of quietly weakening the durability promise. |
| Separate group coordination from message storage | A group cannot use more active partition owners than its partition count. Rebalances can interrupt work, and a hot ordered partition remains a bottleneck. |
| Make replay safe for business effects | consumes state. External APIs need their own contract or ; a local processed flag is insufficient. |
| Recover backlog without exhausting | Extra replicas, and recovery capacity cost money. More consumers do not repair insufficient partition parallelism or a saturated downstream database. |
Production scars & failure modes
One malformed record repeatedly crashes a consumer partition.
Look for: Track the stuck offset, partition lag and repeat failure fingerprint.
Recovery and invariant: Quarantine with its original partition/offset and audited error context; decide explicitly whether skipping breaks ordering or downstream invariants before advancing.
| Component / failure | Impact | Recovery mechanism | Alternative / tradeoff |
|---|---|---|---|
| Leader broker crashes | Writes pause and eligible replicas elect a replacement. | Promote only a sufficiently replicated member and enforce the new at replicas. | Promoting a stale replica may restore availability by losing acknowledged records; that is a different contract. |
| Consumer dies after business commit | The offset may not reflect completed work. | Reassign its partition and replay; durable suppresses duplicate logical effects. | Without sink support duplicates are possible and must be reconciled. |
| Poison message | One partition can repeatedly fail without progress. | Use bounded retries, record failure and move to a durable if product semantics allow skipping. | Skipping relaxes complete in-order business processing; preserve an audit/replay path. |
| overtakes slow consumer | Required offsets no longer exist in the broker. | Alert on oldest required offset, expand or restore from archive/source . | and admission control are safer than claiming unlimited buffering. |
90-second interview summary
I would build a retained, partitioned log. Producers obtain broker metadata, choose a partition using the business ordering key, and send batches directly to its leader. Each partition uses append-only segments and sparse indexes. Batching, compression and the operating-system page cache provide throughput without adding a database to the message path.
The baseline uses three replicas across zones, acknowledgements from the current in-sync set and a minimum of two in-sync replicas. That set includes the leader. If the minimum cannot be met, writes fail rather than silently weaken durability. Metadata controllers track partition leadership and elect an eligible replacement when a leader fails.
Independent consumer groups pull the same log at their own pace. Their group coordinators track membership and replicated offsets. A names the next record to read and advances only after a contiguous prefix of work completes. A crash after a business commit but before an offset commit causes replay, so I make the sink duplicate-safe.
I would monitor lag age, replica health and disk headroom, reserve spare processing capacity and cap retries. bounds recovery, one hot ordered key limits parallelism, and asynchronous regional replication accepts a loss window. The tradeoff is efficient replay and independent consumers in exchange for partition, and duplicate-handling complexity.
Redraw the system from memory
Draw the data log first, then add consumer checkpoints and cluster metadata as separate responsibilities.
Does a consumer acknowledgement delete the record?
Reveal answer
No. A retained log uses policy; each group has its own .
After processing offset 840, what should the group commit?
Reveal answer
841, provided every earlier required record is complete.
Does acks=all with minimum two always wait for two replicas?
Reveal answer
No. Two is the floor; successful writes wait for the current .
Can a committed invoice be applied twice after restart?
Reveal answer
Yes without sink : the invoice may commit before the offset does.
Rehearsal checklist
- Separate producer acceptance from consumer completion.
- Explain leader and coordinator roles per partition/group.
- Include the leader in .
- Commit the next offset and show one crash window.
- Calculate net backlog drain and name the limit.
60-minute interview outline
60-minute interview walkthrough
| Time | Focus | What to cover |
|---|---|---|
| 0–5 min | Introductions | Introduce yourself briefly and confirm the interview format. |
| 5–15 min | Scope and scale | Clarify retained-log semantics, per-key ordering, throughput, and the failures producer acknowledgement must survive. |
| 15–30 min | High-level design | Draw producer routing, a replicated partition, consumer groups and the separate metadata . Trace acceptance, fetch and offset commit. |
| 30–45 min | Deep dives | Explain segments and batching, acks=all with minimum , group ownership and the next-offset rule. Work through the duplicate-effect crash window. |
| 45–55 min | Failure and recovery | Exercise leader loss, consumer loss, a hot partition and expiry. Finish with backlog drain and regional recovery tradeoffs. |
| 55–60 min | Wrap-up | Summarize the design and its main tradeoff. Leave time for questions. |