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

An order event is accepted, then its consumer crashes. What exactly survives, and where does processing restart?

Design◐ Medium27 min study estimate

Before you begin: 1 prerequisite

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 assumptionHow it changes the design
100k messages/s × 1 KB ≈ 100 MB/s ingressWith 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 arrivalNet drain is 20k/s, so recovery needs 300 seconds. More consumers help only while useful partitions remain.

Entities

Entity / logical ownerMinimal 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 / inputResponse 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

  1. Client routingProducers choose partitions using cached broker metadata.
  2. Replicated dataEach partition has one leader and follower logs on other brokers.
  3. Group progressConsumers fetch data and separately commit through their group coordinator.
  4. 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.

Distributed Message Queue: data, progress and control
G prod->leader 1. Publish keyed batch leader->follower 2. Replica data after fetch leader->coordinator 3. Replica data after fetch leader->prod 4. Acknowledge accepted batch grp->leader 5. Fetch replicated records grp->coordinator 6. Join group / commit next offset coordinator->offset 7. Replicate checkpoint ctrl->leader 8. Placement and leader epochs prod Order event producers Client-side partition routing leader → Broker A: P0 leader orders / P0 · append log follower → Broker C: P0 follower orders / P0 · replica coordinator → Broker B: replica + coordinator P0 follower · billing coordinator grp Billing consumer group Fetch · process · checkpoint offset → Replicated group checkpoints __consumer_offsets · RF3 ctrl Metadata controllers Control plane · no payloads
  • 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

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

  1. Create the orders topic with six partitions, three replicas and a window. The metadata controllers record placement and leader epochs.

  2. 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.

  3. The leader appends the batch. Followers fetch it; the configured and acknowledgement policy determine when the producer receives success.

  4. The billing and warehouse groups join their respective coordinators. Each receives partition assignments independently.

  5. An assigned consumer long-polls its partition leader for replicated records, processes the batch and makes its effects durable.

  6. It commits the next offset to its group coordinator. The replicated internal offsets topic retains that for recovery.

  7. 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

Client / user

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

Queue / event stream

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

Queue / event stream

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

Queue / event stream

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

Backend service

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

Queue / event stream

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

Coordination / ownership

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.

Deep dive 1

Store a partition as a sequence of segments

Keep broker-owned append-only files with sparse indexes, rather than adding a separate database to the message path.

Read the explanation and worked example
How it works

The leader assigns offsets and appends batches to an active segment. When its size or age threshold is reached, roll a new segment. A sparse index maps selected offsets to file positions; fetch seeks near the requested offset and scans to the batch. Delete eligible closed segments under time or size . is a different policy that retains the latest value per key, not an unlimited event history.

Walk through an example

The warehouse group resumes at offset 840. The broker chooses the segment containing that offset, seeks through its index and reads forward. Billing may already be at 1,200; its progress does not remove warehouse records.

Failure and recovery

If has deleted offset 840, report an out-of-range position. Restore from an archive or source under an explicit recovery policy. Silently jumping to the newest offset can skip business events.

Why this helps

Sequential writes and batch reads suit a retained log. Each consumer group can revisit the same records without duplicating the underlying stream.

What you give up

is finite. A slow consumer can lose its replay window, and a hot key still concentrates work on one partition.

Apache Kafka design and guarantees ↗

Deep dive 2

Get throughput from batching and the operating system

Batch and compress records, use the page cache, and avoid unnecessary copies on eligible fetch paths.

Read the explanation and worked example
How it works

The producer accumulates bounded batches per partition. The broker appends through the operating system page cache, which is flushed to disk later under the storage policy. On supported plaintext fetch paths, file-to-socket transfer can avoid copying payloads through the application heap. This is a conditional optimization, not a claim that every Kafka operation bypasses Java or that disk is always faster than memory.

Walk through an example

At 20,000 records/s for one partition, a 5 ms batching window can gather roughly 100 records before size limits intervene. That reduces request overhead but spends part of the latency budget before the broker receives anything. Measure batch size, queue time and acknowledgement latency together.

Failure and recovery

A slow disk eventually exhausts cache headroom. Bound pending bytes and throttle producers rather than buffering indefinitely. Replication to page caches can survive an isolated broker failure, but simultaneous loss of volatile copies is outside that guarantee unless the persistence policy covers it.

Why this helps

One batch amortizes request, checksum and network costs over many records. Recent reads often hit memory even though the log is file-backed.

What you give up

Larger batches and longer linger add latency. Page cache pressure, TLS and record transformations can change the effective data path.

Apache Kafka design and guarantees ↗

Deep dive 3

Define exactly what a producer acknowledgement promises

For the baseline, use replication factor three, acks=all and a minimum of two in-sync replicas.

Read the explanation and worked example
How it works

For each partition, clients write to its leader and followers fetch that log. With acks=all, successful acknowledgement waits for replication to the current ; min.insync.replicas=2 is an admission floor, not an instruction to wait for exactly two of three members. includes the leader. Consumers read below the high , an exclusive boundary for replicated records. Transactional read_committed consumers have an additional last-stable-offset boundary.

Walk through an example

Order event 840 reaches Broker A, the leader for P0. B and C fetch it, so the high can advance beyond 840. If C falls out of , A and B can still accept writes under the minimum of two. If only A remains, new writes cannot succeed with this configuration.

Failure and recovery

Kafka implements its metadata controllers with KRaft, a that agrees on cluster metadata. After leader failure, the controller elects an eligible replica and changes the leader . Clients refresh metadata and retry with backoff; recovery is not instantaneous. Disable unclean election for this baseline. A producer timeout may occur after acceptance, so use producer idempotence to suppress supported retries and keep business handlers duplicate-safe.

Why this helps

The acceptance rule connects availability, replication lag and the failures an acknowledged record can survive.

What you give up

Waiting for replication adds latency. Losing enough eligible replicas must stop successful writes instead of quietly weakening the durability promise.

Apache Kafka design and guarantees ↗

Deep dive 4

Separate group coordination from message storage

Use one active consumer owner per partition within each conventional consumer group, and store the next offset to resume.

Read the explanation and worked example
How it works

A broker acts as group coordinator because it leads the relevant __consumer_offsets partition. It handles membership and the rebalance protocol; it is distinct from the cluster metadata controller. Consumers fetch from data-partition leaders and commit checkpoints to their coordinator. Assignments move when members join, leave or time out. Revoke or fence old ownership, and commit only a contiguous completed prefix. Assignment details differ between classic and newer consumer protocols.

Walk through an example

With six partitions and three consumers, an even assignment gives each two partitions. Adding a seventh consumer leaves at least one without a partition. If offsets 840 and 842 finish but 841 is unfinished, the next committed offset can be 841, not 843.

Failure and recovery

When a consumer dies, its replacement starts from the stored next offset. Work completed after that can repeat. Bound per-partition concurrency, stop revoked work and use sink-side or where an already-started external operation can outlive ownership.

Why this helps

Independent groups share the log but not checkpoints. Group membership changes must not let old and new owners both advance progress unchecked.

What you give up

A group cannot use more active partition owners than its partition count. Rebalances can interrupt work, and a hot ordered partition remains a bottleneck.

Apache Kafka design and guarantees ↗

Deep dive 5

Make replay safe for business effects

Commit the business effect and a stable processed-event identity atomically before advancing the consumer offset.

Read the explanation and worked example
How it works

For a database sink, enforce uniqueness on a stable event ID, or on topic, partition and offset when deduplicating deliveries of the same log record. In one transaction, record that identity and apply the business update. Commit the consumer offset afterward. Producer idempotence handles supported producer retries, not arbitrary duplicate business events. Kafka transactions can atomically couple Kafka output records with source offsets for Kafka-to-Kafka processing; an unrelated database is not automatically included.

Walk through an example

Billing records an invoice for event order-731-paid and commits. It crashes before saving nextOffset=841. The replacement receives offset 840 again, finds the event identity already recorded and avoids creating a second invoice before advancing its .

Failure and recovery

For an external payment, reuse the provider's key and reconcile a timeout before retrying an uncertain charge. For a poison event, use bounded retries and an audited quarantine path only if skipping is acceptable. A changes the ordering/completeness contract; it does not solve the error by itself.

Why this helps

A durable and an external side effect are different writes. There is always a crash window unless they participate in a stronger protocol.

What you give up

consumes state. External APIs need their own contract or ; a local processed flag is insufficient.

Apache Kafka design and guarantees ↗

Deep dive 6

Recover backlog without exhausting retention

Budget spare processing capacity and storage, with quotas and an explicit recovery window.

Read the explanation and worked example
How it works

Track per-partition lag, oldest unprocessed age, health, under-replicated partitions, disk headroom and producer throttling. Net backlog drain equals processing rate minus arrival rate. Bound producer retries and outstanding buffers. Tiered storage can move closed segments to object storage when supported, trading cheaper for slower historical reads. Cross-region asynchronous replication has a nonzero recovery-point window.

Walk through an example

A six-million-record backlog with 100,000 arrivals/s and 120,000 processed/s drains at 20,000/s: about five minutes, assuming that spare capacity is sustained. If processing reaches only 90,000/s, the backlog grows even though consumers are working.

Failure and recovery

Throttle noisy producers before disks fill and alert before overtakes a group. If the controller is unavailable, existing healthy leaders may continue serving, but elections and metadata changes are impaired. A region-wide outage needs an explicit promotion and offset-translation plan; three local-zone replicas are not a zero-loss regional backup.

Why this helps

Pull-based fetching protects consumer pace, but arrivals still consume broker disk while consumers are behind.

What you give up

Extra replicas, and recovery capacity cost money. More consumers do not repair insufficient partition parallelism or a saturated downstream database.

Apache Kafka design and guarantees ↗

Additional failure cases and alternatives

Tradeoffs and alternatives

DecisionTradeoff / 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 systemLarger 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 promisesWaiting for replication adds latency. Losing enough eligible replicas must stop successful writes instead of quietly weakening the durability promise.
Separate group coordination from message storageA 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

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

TimeFocusWhat to cover
0–5 minIntroductionsIntroduce yourself briefly and confirm the interview format.
5–15 minScope and scaleClarify retained-log semantics, per-key ordering, throughput, and the failures producer acknowledgement must survive.
15–30 minHigh-level designDraw producer routing, a replicated partition, consumer groups and the separate metadata . Trace acceptance, fetch and offset commit.
30–45 minDeep divesExplain segments and batching, acks=all with minimum , group ownership and the next-offset rule. Work through the duplicate-effect crash window.
45–55 minFailure and recoveryExercise leader loss, consumer loss, a hot partition and expiry. Finish with backlog drain and regional recovery tradeoffs.
55–60 minWrap-upSummarize the design and its main tradeoff. Leave time for questions.

Save & sync your Atlas progress

Keep your progress across devices.

Architecture diagram