Distributed Message Queue
One malformed record repeatedly crashes a consumer partition.
Topic tools
Layout updated
Problem statement
Design a distributed message queue. Producers publish messages, and consumers process them at their own pace. Consumers can resume after a failure and replay messages that are still retained.
Functional requirements
- Publish messages and confirm accepted writes.
- Read messages in groups and resume after failure.
- Replay retained messages from a saved position.
Non-functional requirements
- Keep the promised order within each partition.
- Preserve accepted messages across the stated replica failures.
Back-of-the-envelope estimates
| Illustrative estimate |
|---|
| 100k messages/s × 1 KB ≈ 100 MB/s ingress |
| 100 MB/s × 86,400 ≈ 8.64 TB/day logical |
| 6M backlog; 120k/s service and 100k/s arrival |
Entities
| Entity / logical owner |
|---|
| Record(partition, offset, key, producerId, sequence, payload) |
| PartitionOwner(partition, leader, , eligibleReplicas) |
| ConsumerProgress(group, partition, offset, assignmentEpoch) |
API design
| Operation / input | Response and retry contract |
|---|---|
PUBLISH {topic, key, producerId, sequence, payload} | {partition, offset} after configured replicated durability. |
POLL {group, partition, offset, maxBytes} | Ordered bounded batch from the committed log. |
COMMIT {group, partition, assignmentEpoch, completedThrough} | Persist progress only after all earlier required effects completed durably. |
High-level design
How to draw this design
- Accept recordsProducers and partition router
- Replicate logsLeader and follower brokers
- Consume and applyConsumer groups and idempotent handlers
- Track progressMetadata controller and consumer offset topic
Route a record to its partition leader. Replicate it, then let consumers process and commit their offsets.
- State ownership
- Brokers own the partition log and the internal offsets topic.
- Scale
- Add partitions for throughput and balance consumers across them.
- Correctness
- Order is per partition. An offset commit records progress, while the handler protects its own side effects.
- Failure and recovery
- Fence the old leader after failover and replay from the last committed offset.
- 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
High-level design component walkthrough
Producers
Publish keyed messages; handle retry
Why, tradeoff and connected operations
An application or user-facing endpoint starts or receives this flow.
Tradeoff: Retries may create duplicates
Connected operations: Resolve partition
Partition Router
Hash key → ordered partition
Why, tradeoff and connected operations
Centralize admission and routing while keeping business-state ownership downstream.
Tradeoff: Hot key limits partition throughput
Connected operations: Resolve partition; Append record
Kafka Leader Brokers: Partition Logs
Append ordered records to the partition log hosted by its leader.
Why, tradeoff and connected operations
Kafka stores messages in ordered, append-only partition logs. Disk-backed supports durable consumption and replay. This is broker storage, not a or business database; a relational table is unnecessary for the message path.
Tradeoff: Leader failure interrupts writes
Connected operations: Append record; Replicate log; Fence prior leader ; Fetch committed records
Kafka Follower Brokers
Replicate across AZs; take over on failure
Why, tradeoff and connected operations
Follower logs replicate the same partitions across failure zones. An eligible follower can take over when the leader fails. These are copies of the broker log, not separate databases; durability depends on the acknowledgement and replication settings.
Tradeoff: Replication consumes bandwidth/storage
Connected operations: Replicate log
Controller / Metadata
Elect leader; assign + ownership
Why, tradeoff and connected operations
Make ownership/version changes explicit; downstream resources must reject stale owners.
Tradeoff: Controller outage stalls reassignment
Connected operations: Fence prior leader
Consumer Group
Assign partitions among consumers
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: Rebalance pauses consumption
Connected operations: Fetch committed records; Process record; Commit processed offsets; Resume from committed offset
Kafka Internal Topic: Consumer Offsets
Store committed group offsets in a broker-hosted compacted topic.
Why, tradeoff and connected operations
A compacted Kafka internal topic records each consumer group’s progress. The broker can recover offsets using its existing replicated-log machinery. This avoids adding a separate database just to store consumer checkpoints.
Tradeoff: loss causes replay/duplicates
Connected operations: Commit processed offsets; Resume from committed offset
Idempotent Handlers
Apply side effects safely on redelivery
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: Dedup state/atomicity complexity
Connected operations: Process record
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.
Tradeoffs and alternatives
| Decision | Tradeoff / alternative and recovery implication |
|---|---|
| Say exactly when a message is accepted | Waiting for more replicas takes longer and may reject writes when too few replicas are healthy. Choose that promise before sizing the brokers. |
| Keep order without skipping unfinished work | Sequential processing is simpler. Parallel processing needs to track gaps, and one hot ordered key still limits useful concurrency. |
| Make repeated delivery safe | A remote provider cannot join this database transaction. It needs its own retry identity or a way to check an uncertain result. |
| What happens if a region fails? | Remote synchronous acknowledgement adds cross-region latency; asynchronous replication accepts a possible loss window. |
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 design the queue around partitioned durable logs. Producers choose a partition key from the ordering the business needs, and the leader appends and replicates each record before acknowledging the promised durability level. The acknowledgement contract must name the failure domain; replicas in three zones are not automatically protection against losing a whole region.
Consumers track their own positions and one active owner handles each partition. Work can run concurrently, but committed progress advances only past a contiguous completed prefix. Otherwise, completing record 42 before 41 and crashing could permanently skip record 41.
Delivery may repeat. A database handler commits its effect and processed-message identity together, then acknowledges. External effects need provider-supported request identities or . Poison records require an audited quarantine policy so one bad input does not silently stop unrelated work forever.
I would monitor partition lag and oldest unprocessed records, reserve replay capacity and fence old owners during rebalancing or regional promotion. Remote asynchronous replication has a possible loss window; stronger remote commitment adds latency. The main tradeoff is ordered replay and independent consumers versus partition ownership, and duplicate-processing complexity. Adding consumers helps only while there are useful partitions to assign.
Explain it without looking
Explain say exactly when a message is accepted
Reveal answer
Reply to the producer only after the required log copies are durable.
Writing to a socket or memory does not mean the message will survive a broker crash.
Waiting for more replicas takes longer and may reject writes when too few replicas are healthy. Choose that promise before sizing the brokers.
Explain keep order without skipping unfinished work
Reveal answer
Assign one owner per partition and record only the completed sequence of work.
If item 102 finishes before 101, saving position 102 can cause a restart to skip the unfinished item.
Sequential processing is simpler. Parallel processing needs to track gaps, and one hot ordered key still limits useful concurrency.
Explain make repeated delivery safe
Reveal answer
Store the processed message ID and database change together, then acknowledge.
The worker can commit successfully and still lose its acknowledgement. The broker is then allowed to deliver the message again.
A remote provider cannot join this database transaction. It needs its own retry identity or a way to check an uncertain result.
Explain what happens if a region fails?
Reveal answer
Recover the accepted log before a replacement region accepts more writes.
A clear placement/acknowledgement contract prevents local replication from being advertised as regional durability.
Remote synchronous acknowledgement adds cross-region latency; asynchronous replication accepts a possible loss window.
Revision checklist
Revision checklist
- Reconstruct say exactly when a message is accepted: Reply to the producer only after the required log copies are durable.
- Reconstruct keep order without skipping unfinished work: Assign one owner per partition and record only the completed sequence of work.
- Reconstruct make repeated delivery safe: Store the processed message ID and database change together, then acknowledge.
- Reconstruct what happens if a region fails?: Recover the accepted log before a replacement region accepts more writes.
- Name the authoritative state, boundary, retry identity and failure-domain durability guarantee.
- Explain one alternative and exactly which guarantee you would relax.
- Redraw the request and recovery paths without looking; mark what required a hint.
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 | Define ordering, , and replay requirements. Estimate throughput per partition and name the delivery contract. |
| 15–30 min | High-level design | Trace one record from producer through leader and follower replication to a consumer and its committed offset. |
| 30–45 min | Deep dives | Explain producer acknowledgement, consumer offset commits, and what happens when processing finishes before the offset is saved. |
| 45–55 min | Failure and recovery | Walk through a broker or consumer failure. Explain , replay, and how the consumer deduplicates a repeated effect. |
| 55–60 min | Wrap-up | Summarize the design and its main tradeoff. Leave time for questions. |
On this page
- Problem statement
- Functional requirements
- Non-functional requirements
- Back-of-the-envelope estimates
- Entities
- API design
- High-level design
- High-level design component walkthrough
- Engineering control room
- Deep dives — decisions, failures and recovery
- Tradeoffs and alternatives
- Production scars & failure modes
- 90-second interview summary
- Explain it without looking
- Revision checklist
- 60-minute interview walkthrough