System Design Atlas
LOCAL GUEST MODERead and practice without an account.

Your saved topics and reading progress stay in this browser. Sign in to sync supported profile and progress data.

Distributed Message Queue

One malformed record repeatedly crashes a consumer partition.

◐ MediumSystem 041 min1 prerequisite
My progress
Topic tools

Layout updated

Explore the design, then rehearse the decisions without looking.

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 / inputResponse 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

  1. Accept recordsProducers and partition router
  2. Replicate logsLeader and follower brokers
  3. Consume and applyConsumer groups and idempotent handlers
  4. 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.
Distributed Message Queue
G prod->route 1. Resolve partition route->leader 2. Append record leader->follower 3. Replicate log ctrl->leader 4. Fence prior leader epoch leader->grp 5. Fetch committed records grp->sink 6. Process record grp->offset 7. Commit processed offsets offset->grp 8. Resume from committed offset prod Producers edge route Partition Router edge leader → Kafka Leader Brokers: Partition Logs messaging follower → Kafka Follower Brokers messaging ctrl Controller / Metadata compute grp Consumer Group compute offset → Kafka Internal Topic: Consumer Offsets messaging sink Idempotent Handlers compute
  • Edge
  • Messaging
  • Compute

━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault

Select a component or follow a numbered connection.

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

Client / user

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

Gateway / routing

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

Queue / event stream

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

Queue / event stream

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

Coordination / ownership

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

Backend service

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

Queue / event stream

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

Backend service

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.

Deep dive 1

Say exactly when a message is accepted

Reply to the producer only after the required log copies are durable.

Read the explanation and worked example
How it works

A producer acknowledgement is a promise about a particular log position. The leader appends the record, obtains the required replica acknowledgements, advances the committed position, and only then replies under the chosen durability policy. Specify which failures that replica placement survives.

Walk through an example

The leader dies after appending locally but before replication. An uncommitted record must not be reported as durably accepted merely because one disk contains it.

Failure and recovery

Elect only a permitted successor with the required committed history. A lost producer response can still cause a retry, so preserve producer identity or make downstream handling duplicate-safe.

Why this helps

Writing to a socket or memory does not mean the message will survive a broker crash.

What you give up

Waiting for more replicas takes longer and may reject writes when too few replicas are healthy. Choose that promise before sizing the brokers.

Deep dive 2

Keep order without skipping unfinished work

Assign one owner per partition and record only the completed sequence of work.

Read the explanation and worked example
How it works

Choose the partition key from the order the business needs, such as conversation or account. Give one consumer owner responsibility for each partition. Parallel work inside the partition is possible, but the stored progress position must advance only past a contiguous set of completed records.

Walk through an example

Record 42 finishes before 41. Committing progress at 42 and crashing would skip unfinished record 41 on restart.

Failure and recovery

Keep completion bookkeeping or process sequentially where order is strict. Rebalance with ownership epochs and drain or fence old workers; adding consumers beyond the partition count does not add useful ownership slots.

Why this helps

If item 102 finishes before 101, saving position 102 can cause a restart to skip the unfinished item.

What you give up

Sequential processing is simpler. Parallel processing needs to track gaps, and one hot ordered key still limits useful concurrency.

Deep dive 3

Make repeated delivery safe

Store the processed message ID and database change together, then acknowledge.

Read the explanation and worked example
How it works

Message delivery and the business transaction are separate events. In a local database, put the effect and a unique processed-message identity in the same transaction. Only after that commit should the worker acknowledge the delivery or advance its source position.

Walk through an example

The database commit succeeds, then the worker dies before acknowledging. The next worker sees the same message and finds the stored result instead of applying the effect again.

Failure and recovery

An external payment or email cannot join that local transaction. Reuse a provider-supported request identity and reconcile uncertain attempts; a local processed flag alone cannot guarantee an external exactly-once effect.

Why this helps

The worker can commit successfully and still lose its acknowledgement. The broker is then allowed to deliver the message again.

What you give up

A remote provider cannot join this database transaction. It needs its own retry identity or a way to check an uncertain result.

Deep dive 4

What happens if a region fails?

Recover the accepted log before a replacement region accepts more writes.

Read the explanation and worked example
How it works

Replicate accepted log history to the failure domain promised to producers. Three replicas in one region protect against some node or zone failures, not destruction of that region. Preserve producer identities and interpretable consumer positions across promotion.

Walk through an example

A remote log replica is behind when the whole producer region is lost.

Failure and recovery

Fence the old leader and promote only a history compatible with the declared durability promise. Reconcile uncertain producer retries and external effects before declaring processing complete.

Why this helps

A clear placement/acknowledgement contract prevents local replication from being advertised as regional durability.

What you give up

Remote synchronous acknowledgement adds cross-region latency; asynchronous replication accepts a possible loss window.

Tradeoffs and alternatives

DecisionTradeoff / alternative and recovery implication
Say exactly when a message is acceptedWaiting 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 workSequential processing is simpler. Parallel processing needs to track gaps, and one hot ordered key still limits useful concurrency.
Make repeated delivery safeA 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

Failure investigation

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 / failureImpactRecovery mechanismAlternative / tradeoff
Leader broker crashesWrites 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 commitThe 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 messageOne 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 consumerRequired 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

TimeFocusWhat to cover
0–5 minIntroductionsIntroduce yourself briefly and confirm the interview format.
5–15 minScope and scaleDefine ordering, , and replay requirements. Estimate throughput per partition and name the delivery contract.
15–30 minHigh-level designTrace one record from producer through leader and follower replication to a consumer and its committed offset.
30–45 minDeep divesExplain producer acknowledgement, consumer offset commits, and what happens when processing finishes before the offset is saved.
45–55 minFailure and recoveryWalk through a broker or consumer failure. Explain , replay, and how the consumer deduplicates a repeated effect.
55–60 minWrap-upSummarize the design and its main tradeoff. Leave time for questions.
On this page
  1. Problem statement
  2. Functional requirements
  3. Non-functional requirements
  4. Back-of-the-envelope estimates
  5. Entities
  6. API design
  7. High-level design
  8. High-level design component walkthrough
  9. Engineering control room
  10. Deep dives — decisions, failures and recovery
  11. Tradeoffs and alternatives
  12. Production scars & failure modes
  13. 90-second interview summary
  14. Explain it without looking
  15. Revision checklist
  16. 60-minute interview walkthrough

Save & sync your Atlas progress

Sync your profile and topic progress across browsers, then return to the same study desk.

Google sign-in will appear here after its Azure provider is configured.

Architecture diagram