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 Messaging (WhatsApp and Messenger)

A member is removed while a send and device reconnect race.

● HardSystem 1912 min3 prerequisites
My progress
Topic tools

Layout updated

Explore the design, then rehearse the decisions without looking.

Problem statement

Design a messaging service like WhatsApp. Users can send messages and media in direct and group chats, catch up after going offline, and see delivery and read status across devices.

Functional requirements

  • Send and receive messages in conversations.
  • Sync messages and receipts across devices.
  • Manage group membership and registered devices.

Non-functional requirements

  • Aim for accepted-send under 200 ms; online delivery under 500 ms.
  • Keep one message order per conversation, with retry-safe delivery.

Back-of-the-envelope estimates

Illustrative estimate
100M DAU × 50 sends/day = 5B messages/day ≈ 58k/s average; 5× peak ≈ 290k/s
10M concurrent sockets; benchmark target 50k/gateway
Heartbeat every 30 s across 10M sockets ≈ 333k heartbeats/s
500-member group × 2 devices/member = up to 1,000 deliveries/send
Backlog of 60M delivery tasks, arrival 300k/s, capacity 500k/s

Entities

Entity / logical owner
Conversation owner + replicated journal
History projection: ((conversationId, bucketId), sequence)
Membership and device registry
User inbox: (userId, /bucket), change cursor; receipts: (userId, deviceId, conversationId)
Presence + media

API design

Operation / inputResponse and retry contract
SEND {conversationId, clientMessageId, deviceId, ciphertext, keyEpoch}Stable client-generated ID survives retries. Owner returns {messageId, sequence, commitToken}. Dedup key = (senderUser, senderDevice, clientMessageId); payload hash detects reuse with different content.
SYNC {deviceId, inboxCursor}; HISTORY {conversationId, afterSeq, limit}Inbox identifies changed conversations. History uses bounded ranges and a projection . Cursor is scoped to authenticated user/device; access is checked on replay.
ACK {conversationId, receivedThrough, readThrough}Receipt store keyed by (user, device, conversation); conditional max updates prevent regressions. Cursor is a contiguous authorized prefix, not simply the maximum sequence observed.

High-level design

How to draw this design

  1. Accept a messageSender, edge gateway, and conversation owner
  2. Order it durablyReplicated conversation journal, membership, and device registry
  3. Deliver liveKafka delivery stream, workers, and recipient gateway
  4. Reconnect and catch upSync service, Cassandra histories, cursors, and receipts

Commit one ordered message, then deliver it live or replay it from the recipient's cursor.

State ownership
The conversation journal owns committed order. Cassandra holds derived sync views.
Scale
Partition by conversation and scale delivery separately.
Correctness
Deduplicate send retries with the same client message ID and enforce one sequencing authority.
Failure and recovery
On loss, stop new commits in that partition and resume from the committed prefix.
WhatsApp / Messenger Distributed Messaging
G sender->owner 1. Send message with stable ID membership->owner 2. Verify membership and versions owner->journal 3. Commit ordered command by quorum journal->relay 4. Relay committed events relay->delivery 5. Deliver projection work delivery->history 6. Project history and inbox delivery->presence 7. Look up live routes presence->delivery 8. Return active gateway hint delivery->gateway 9. Route to recipient gateway gateway->recipient 10. Push to active devices recipient->sync 11. Reconnect, sync or acknowledge sync->history 12. Read changes or update receipt sender Sender + Edge Gateway edge owner Conversation Owner / Sequencer compute journal Custom Raft Journal / RocksDB state · durable sync Sync / Receipt Service compute membership PostgreSQL / Membership / Device Registry state · durable relay → Kafka Delivery Stream messaging history Cassandra: History, Inbox and Receipts state · durable delivery Projection / Delivery Workers compute recipient Recipient Devices edge gateway Recipient Gateway edge presence Presence Redis + Push Wakeup state · memory
  • Edge
  • Compute
  • State
  • Messaging

━━ 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 12 flow steps

High-level design component walkthrough

Gateway / routing

Sender + Edge Gateway

TLS socket; authenticate; retry key

Why, tradeoff and connected operations

Centralize admission and routing while keeping business-state ownership downstream.

Tradeoff: Socket is not durable acceptance

Connected operations: Send message with stable ID

Coordination / ownership

Conversation Owner / Sequencer

Membership, dedup, sequence in order

Why, tradeoff and connected operations

Make ownership/version changes explicit; downstream resources must reject stale owners.

Tradeoff: One hot chat has serial work

Connected operations: Send message with stable ID; Verify membership and versions; Commit ordered command by

Distributed database

Custom Raft Journal / RocksDB

command; durability

Why, tradeoff and connected operations

RocksDB supplies local key-value persistence for the custom conversation journal. The separate protocol orders accepted commands and replicates them to a . An embedded store fits local ordered state; RocksDB itself does not provide distributed consensus or -style joins.

Tradeoff: WAN adds send latency

Connected operations: Commit ordered command by ; Relay committed events

Backend service

Sync / Receipt Service

Cursor replay; monotonic device

Why, tradeoff and connected operations

Isolate this operation so it can scale and fail independently from storage.

Tradeoff: Projection lag must be explicit

Connected operations: Reconnect, sync or acknowledge; Read changes or update receipt

Relational database

PostgreSQL / Membership / Device Registry

Roles and key-version boundaries

Why, tradeoff and connected operations

PostgreSQL stores conversation membership, roles and device registrations. Transactions keep related access and key-version changes consistent. fits this control data; the message journal and history have different ordering and volume needs.

Tradeoff: Stale authorization is unsafe

Connected operations: Verify membership and versions

Queue / event stream

Kafka Delivery Stream

Replay committed events only

Why, tradeoff and connected operations

Relay committed journal entries idempotently to projection consumers; journal and Kafka are not one distributed transaction. Isolate this operation so it can scale and fail independently from storage.

Tradeoff: At-least-once processing

Connected operations: Relay committed events; Deliver projection work

Distributed database

Cassandra: History, Inbox and Receipts

Store rebuildable tables keyed by conversation, user, or device as needed.

Why, tradeoff and connected operations

Cassandra keeps history, inbox and receipt tables keyed for conversation, user or device reads. Separate table shapes make paginated retrieval predictable at high volume. These are rebuildable views of the accepted journal, rather than the authoritative membership records.

Tradeoff: Projection; not ordering authority

Connected operations: Project history and inbox; Read changes or update receipt

Backend service

Projection / Delivery Workers

History first; live + offline routes

Why, tradeoff and connected operations

Isolate this operation so it can scale and fail independently from storage.

Tradeoff: Bound retries and group

Connected operations: Deliver projection work; Project history and inbox; Look up live routes; Return active gateway hint; Route to recipient gateway

Client / user

Recipient Devices

Persist then ; local dedup

Why, tradeoff and connected operations

An application or user-facing endpoint starts or receives this flow.

Tradeoff: Offline devices need later replay

Connected operations: Push to active devices; Reconnect, sync or acknowledge

Gateway / routing

Recipient Gateway

Push to active leased session

Why, tradeoff and connected operations

Centralize admission and routing while keeping business-state ownership downstream.

Tradeoff: Bound buffers; reconnect on failure

Connected operations: Route to recipient gateway; Push to active devices

Cache / in-memory index

Presence Redis + Push Wakeup

Return current gateway routing hints and trigger push wakeup when offline.

Why, tradeoff and connected operations

Redis keeps short-lived gateway locations and presence hints. Expiry removes abandoned sessions and helps route live delivery quickly. Presence is ephemeral; durable messages remain in the journal/history stores when a Redis entry disappears.

Tradeoff: Best effort; never message truth

Connected operations: Look up live routes; Return active gateway hint

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

Commit one conversation order

Record the message, sequence, membership check and delivery work at one owner.

Read the explanation and worked example
How it works

Route each conversation command to one fenced ordering authority. That authority validates current membership, allocates the next sequence, records the message and duplicate-request result, and commits delivery intent in its replicated journal before acknowledging. History and inbox stores are projections of that committed order.

Walk through an example

Two devices send at once while another command removes a member. A shared command order determines which membership version applies; independent database writes cannot reconstruct that decision safely afterward.

Failure and recovery

After owner failure, recover a committed prefix and a newer authority . A client retry with the same identity returns the existing sequence rather than creating another accepted message.

Why this helps

Allocating a sequence separately from storing the message can leave gaps or conflicting owners after a crash.

What you give up

Recover from the committed conversation log. Ordering is within a conversation, not a promise that every conversation shares one global clock.

Deep dive 2

Repair what a device missed

Save received messages and acknowledge only the complete received sequence.

Read the explanation and worked example
How it works

A device records received messages durably and advances its contiguous cursor only when every earlier sequence is present. Live sockets provide low latency but not complete delivery; reconnect uses durable history to request the missing range. A higher observed sequence alone is not a safe acknowledgement.

Walk through an example

The device receives sequence 104 before 103. Advancing its cursor to 104 would hide the gap from future synchronization and lose message 103 from the user's view.

Failure and recovery

Persist gap tracking, fetch missing history, and close the race between historical sync and resumed live delivery. Bound server buffers so slow devices repair through history instead of exhausting gateway memory.

Why this helps

Writing to a live socket does not prove the device durably stored the message.

What you give up

Reconnect must combine historical sync with buffered live updates and detect expired history. This uses more state but prevents gaps from being hidden.

Deep dive 3

Order membership changes with sends

Use the membership and device-key version effective when the send is accepted.

Read the explanation and worked example
How it works

Membership changes share the same command order as sends. Each accepted message carries the effective membership/key needed by the client encryption protocol. Device registration, removal and key changes must be authenticated and projected consistently into routing and synchronization decisions.

Walk through an example

A removed member reconnects using an old device token while a new message is accepted. An old presence record must not authorize access to that new conversation .

Failure and recovery

Reject unauthorized sync ranges, expire stale device routes and distribute key updates through the defined client protocol. Server ordering helps enforce membership, but does not itself implement end-to-end encryption or erase old plaintext already seen by a device.

Why this helps

An old cached membership entry can give a removed member access to new content.

What you give up

Use a reviewed encryption protocol. Removing a member can protect future sends, but cannot make them forget plaintext they already received.

Deep dive 4

What happens if a region fails?

Preserve the accepted message order when another region takes over.

Read the explanation and worked example
How it works

A home-region conversation survives its declared local failure domains. If permanent regional loss must preserve every acknowledged message, the journal's synchronous must also span the necessary regions. Gateways do not become independent sequencers during failover.

Walk through an example

A sender reconnects elsewhere after losing the acceptance response.

Failure and recovery

Retry the same client-message identity against the recovered committed journal. Fence old conversation owners, preserve membership order and rebuild inbox/history projections from that prefix.

Why this helps

Message acceptance, order and membership must retain one meaning across the region switch.

What you give up

A cross-region commit adds wide-area latency and partition rejection; asynchronous remote history permits a stated loss window.

Deep dive 5

Repair message history and inbox gaps

Use the committed conversation log to repair missing history and inbox entries.

Read the explanation and worked example
How it works

After journal commitment, relay entries with stable conversation/sequence/message identity. History and inbox workers persist their applied positions and tolerate duplicate updates. A successful history write does not prove the recipient inbox has been updated, so track and repair each projection independently.

Walk through an example

A worker writes history, crashes before the inbox update and replays the same journal entry after restart.

Failure and recovery

Reapply the missing inbox effect idempotently, compare projection cutoffs and repair gaps from the journal. Device sync must not equate a missing inbox hint with an unaccepted message.

Why this helps

Durable acceptance and complete user-visible delivery are separate progress boundaries.

What you give up

Additional projections speed reads and but create storage amplification, lag and repair responsibility.

Additional technical detail

End-to-end: Authenticated send → one fenced conversation owner → -committed command → SENT → replayable delivery pipeline → durable history and inbox projections → best-effort live socket → client . Reconnection repairs gaps from durable history, independently of presence.

1 · Scope, guarantees, and what to clarify

Design WhatsApp/Messenger-style 1:1 and bounded group chat: text/media, multiple devices, online delivery, offline replay, sent/delivered/read states, and membership changes. Ask about group size, , multi-device history policy, and end-to-end encryption. Calls, public broadcast channels, global search, and cryptographic protocol design are follow-ups. This is a proposed interview architecture, not a claim about either company’s implementation.

  • Ordering: all members observe the same server-defined sequence within one conversation; no total order across conversations and no reliance on client wall clocks.
  • Delivery: at-least-once transport plus durable server/client gives one visible message per logical send within the defined window. Do not claim exactly-once network delivery.
  • Durability: SENT means -committed acceptance, not a socket write. DELIVERED means a recipient device durably received it; READ means the recipient reported display/read. Define whether the UI aggregates “any device” or “all devices.”
  • Targets: accepted send under 200 ms in the normal home-region path, online delivery under 500 ms, 99.99% read availability, and no loss of -acknowledged messages within the chosen failure domain. Targets are assumptions; cross-region latency may force a higher send budget.

2 · Scale and capacity

Assumption / calculationDesign implication
100M DAU × 50 sends/day = 5B messages/day ≈ 58k/s average; 5× peak ≈ 290k/sAt 1 KB/message: 5 TB/day raw, 150 TB/30 days, ~450 TB at 3 replicas before indexes, metadata and journal overhead. Media is separate.
10M concurrent sockets; benchmark target 50k/gateway200 gateways at that tested limit; provision roughly 2× for headroom/ loss, then validate memory, TLS CPU and bandwidth. At 20 KB/socket, connection state alone is 200 GB.
Heartbeat every 30 s across 10M sockets ≈ 333k heartbeats/s heartbeats; refresh routing leases in batches and avoid one durable DB write per ping. Presence is soft state.
500-member group × 2 devices/member = up to 1,000 deliveries/sendStore one logical message plus per-device encrypted key envelopes as required; network/key remains O(member devices). Cap groups and isolate hot ones.
Backlog of 60M delivery tasks, arrival 300k/s, capacity 500k/sDrain time is 60M / 200k = 300 s. Include replay traffic in capacity, and bound per-gateway queues instead of buffering indefinitely.

3 · APIs, data model, and DB choices

/ ownerSchema and storage choice
SEND {conversationId, clientMessageId, deviceId, ciphertext, keyEpoch}Stable client-generated ID survives retries. Owner returns {messageId, sequence, commitToken}. Dedup key = (senderUser, senderDevice, clientMessageId); payload hash detects reuse with different content.
SYNC {deviceId, inboxCursor}; HISTORY {conversationId, afterSeq, limit}Inbox identifies changed conversations. History uses bounded ranges and a projection . Cursor is scoped to authenticated user/device; access is checked on replay.
ACK {conversationId, receivedThrough, readThrough}Receipt store keyed by (user, device, conversation); conditional max updates prevent regressions. Cursor is a contiguous authorized prefix, not simply the maximum sequence observed.
Conversation owner + replicated journalConsensus-backed group owns ordered command log, membership version, next sequence and dedup state. A command atomically records the accepted message and durable delivery intent. state plus replay enables recovery.
History projection: ((conversationId, bucketId), sequence)Cassandra/Bigtable-style wide-column store fits append/range-read access. Bound partitions by time/size; store ciphertext, sender, membership version, message ID and . This DB does not itself create a safe sequencer or /Kafka transaction.
Membership and device registry or distributed for users, group metadata, roles and registered device keys. Effective membership changes are ordered through the conversation authority, with committed versions projected back to the registry.
User inbox: (userId, /bucket), change cursor; receipts: (userId, deviceId, conversationId)Durable /wide-column projections; inbox change order is distinct from message sequence. Use a vector/per- cursor if the inbox is partitioned. max alone cannot account for gaps.
Presence + mediaRedis maps (userId, deviceId) to gateway/region/connectionEpoch. Object storage + carries encrypted attachments; only authenticated, short-lived object references and encryption metadata travel in the message.

4 · The atomic acceptance boundary

  • One owner: hash conversationId to a logical sequencing . A elects one leader with an ; followers reject stale terms. Gateways route to the owner, which validates membership/key and serializes sends with group changes.
  • One committed command: the state machine checks the dedup key, assigns the next conversation sequence, appends encrypted content/reference and a delivery intent, and records the dedup result atomically in its replicated log. A duplicate returns the original result. Commit before SENT.
  • Failover: the replacement owner recovers sequence, membership and dedup state from the same committed prefix. No separate Redis INCR followed by a DB write; no unprotected DB-write-then-Kafka-publish window.
  • Reliable relay: a replayable committed-log reader publishes events. Crashing before advancing its offset causes duplicate publication; crashing before publication leaves the offset behind. Idempotent downstream writes make both safe.
  • Alternative for a smaller system: co-locate conversation row, message, dedup record and in one transaction with a row lock/conditional next sequence. This is a simpler initial design. Use the log-first design when scaling append throughput; do not mix both as independent ordering authorities.

5 · Live delivery, offline recovery, and receipts

  • Projection order: workers materialize a message idempotently, then advertise the conversation change in recipient inboxes. Per-conversation visibleThrough advances only after all prior committed entries are represented. At scale, interval tracking and ordered completion prevent out-of-order worker completion from skipping data.
  • Live path: lookup destination sessions, route through the connection , and write to each gateway’s bounded buffer. Presence is a hint; a stale route is not delivery. Client deduplicates messageId, persists ciphertext locally, then ACKs. Sender’s other devices receive the same logical event.
  • Offline path: stop eager retries after a small budget; send a coalesced push wakeup without plaintext. On reconnect, subscribe to live updates, capture a sync , replay history through it, buffer/dedup concurrent live messages, then continue streaming. Page with bounded work to prevent reconnect storms.
  • Receipt semantics: a later may arrive before an earlier one. Advance receivedThrough only when the client has durably stored the entire eligible prefix; use gaps/range ACKs otherwise. readThrough cannot exceed receivedThrough. receipt writes and notifications.
  • Missing discovery: a lost/late inbox projection cannot strand a chat forever. Replay delivery intents, reconcile inbox watermarks against membership/conversation updates, and let an active conversation query history directly.
  • Projection lag: accepted messages can temporarily be absent from history. Use commitToken/sequence to wait, retry, or tail the committed journal for recent reads. Never present a lagging empty result as proof that no message exists.
  • : keep journal segments until durable projections/checkpoints are verified; archive or before trimming. If offline history has expired, return an explicit gap and fresh baseline. Do not silently advance past missing content.

6 · Group membership, multi-device, and encryption

  • Membership boundary: membership changes are commands in the same conversation order. If removal takes effect at sequence 151, the removed member cannot send/read messages after that boundary; earlier history access is an explicit product rule. Workers authorize using the effective version, not whichever cached member list is newest.
  • Group : store message content once per conversation. Split recipient/device delivery tasks into chunks with deterministic IDs, track completion and retry only missing chunks. Large broadcast channels need separate semantics; adding workers cannot remove the ordering bottleneck of one hot conversation.
  • Hot chat: move its ownership to a dedicated , batch log appends, rate-limit sends, and parallelize delivery after ordering. If one owner still cannot keep up, either cap throughput or explicitly relax total per-chat order; random message sharding breaks the original guarantee.
  • E2EE: clients encrypt/decrypt using a reviewed protocol and authenticated device keys; the server stores ciphertext and routes envelopes. Device additions/removals and group key epochs require rotation. A new device gets history only via the agreed encrypted backup or trusted-device transfer policy.
  • Limits: membership revocation stops future server access and new key distribution, not plaintext already received. Server-side search/content moderation is constrained by E2EE; use client search, metadata limits and user-initiated reports. Encryption does not hide all routing metadata.
  • Attachments: encrypt before direct upload, finalize the durable object, then send the message with a content key/reference encrypted for recipients. Garbage-collect abandoned uploads. Bound download sizes, use authenticated URLs and enforce .

7 · Failure and multi-region decision table

Failure / raceRecovery and guarantee
Acceptance lost; sender reconnects to another regionRetry same clientMessageId; route to conversation authority and recover the original sequence from durable dedup. Never make the gateway-local cache the only dedup state.
Journal commits, delivery stream is downMessage remains accepted; durable relay catches up. Bound backlog/storage and apply admission control before exhaustion. Delay delivery rather than lose the committed message.
Worker writes history, then crashes before inbox writeReplay performs same history and completes inbox/delivery work. Publish projection after writes are durable; stable message IDs absorb duplicates.
Recipient gets seq 104 before 103Buffer briefly and range-fetch the gap; do not advance contiguous to 104. Tombstones/control entries or authorized-range metadata distinguish intentionally hidden positions from missing data.
Gateway / Redis / push provider failureReconnect with , rebuild leased presence, and replay from durable history. / guards prevent an old disconnect from deleting a newer session. Push and typing/presence may be lost; messages remain durable.
Slow consumer or reconnect stormBound per-connection buffer; disconnect with resume cursor, cap per-user sync concurrency and bytes, use exponential backoff with . Shed typing/presence before accepted messages.
Region failure: baseline 3- home-region Survives node/ failures. Asynchronous remote replicas imply nonzero under permanent regional loss; stale remote promotion cannot promise no lost acknowledged messages. State this explicitly.
Zero- regional-loss requirementChange the journal placement to survive a region, e.g. one voter in each of three regions with majority commit. Pay cross-region RTT. Fail over only from a committed prefix; fence old epochs and reconstitute projections.
Network partition / no Minority refuses new sends and membership changes. Clients keep a pending and retry. Previously committed authorized history may remain readable; do not create two sequence authorities.
Reshard, deploy, or schema migration + replay to a ; cut over with routing and fenced owner. Dedup lifetime must cover supported retry/replay windows. Version event schemas; roll forward/back without reinterpreting old sequence numbers.

8 · Operations, security, and interview pressure

  • Measure: send-commit and end-to-end delivery percentiles; health; leader election time; projection lag and oldest unapplied entry; socket reconnect rate; buffer saturation; duplicate suppression; sequence gaps; receipt latency; inbox repair counts and per- throughput. Trace IDs, not plaintext.
  • Protect: authenticate devices and every conversation operation, validate payload size/key , rate-limit account/IP/group abuse, redact logs, encrypt storage/backups, audit membership/device changes, and limit metadata . Treat a signed cursor as a capability requiring user binding and expiry.
  • Cost: separate message bytes, retained journal, history replicas, inbox/receipt amplification, socket fleet, cross-region traffic and media egress. Batch/ receipt writes; compress ciphertext only if the protocol permits useful compression before encryption.
  • Pressure test: two senders race with member removal; the owner dies after commit but before ; the recipient receives a gap; projection lags by 30 seconds; the home region is isolated. For each, identify exact state ownership and the boundary before naming a database.

9 · 90-second final architecture and repeat queue

“I use stateless authenticated gateways for sockets and one fenced ordering authority per conversation. Its replicated journal atomically commits sequence, membership validation, dedup result and delivery intent before acknowledging acceptance. Replayable workers project ordered history and recipient inboxes, then try live delivery using leased presence. Presence and push are best effort; offline sync from durable history repairs delivery. Clients persist before , deduplicate IDs and advance only contiguous per-device cursors. Group membership changes share the conversation order; E2EE keeps plaintext and content keys on devices. I isolate hot chats and bound buffers. A regional covers failures; zero-loss regional failover needs a cross-region and higher latency. I monitor commit latency, projection lag, gap repair and recovery capacity.”

Background reading

The designs and capacity numbers above are proposed interview choices. These primary sources support the underlying patterns, not a claim that Meta uses this exact architecture.

Tradeoffs and alternatives

DecisionTradeoff / alternative and recovery implication
Commit one conversation orderRecover from the committed conversation log. Ordering is within a conversation, not a promise that every conversation shares one global clock.
Repair what a device missedReconnect must combine historical sync with buffered live updates and detect expired history. This uses more state but prevents gaps from being hidden.
Order membership changes with sendsUse a reviewed encryption protocol. Removing a member can protect future sends, but cannot make them forget plaintext they already received.
What happens if a region fails?A cross-region commit adds wide-area latency and partition rejection; asynchronous remote history permits a stated loss window.
Repair message history and inbox gapsAdditional projections speed reads and but create storage amplification, lag and repair responsibility.

Production scars & failure modes

Failure investigation

A member is removed while a send and device reconnect race.

Look for: Compare the committed membership version, message sequence and device sync cursor.

Recovery and invariant: Order membership and sends through the same conversation authority; authorize sync against the allowed history and repair gaps before advancing contiguous cursors.

Component / failureRequired behavior / recoveryOperational implication
Acceptance lost; sender reconnects to another regionRetry same clientMessageId; route to conversation authority and recover the original sequence from durable dedup.Never make the gateway-local cache the only dedup state.
Journal commits, delivery stream is downMessage remains accepted; durable relay catches up.Bound backlog/storage and apply admission control before exhaustion Delay delivery rather than lose the committed message.
Worker writes history, then crashes before inbox writeReplay performs same history and completes inbox/delivery work.Publish projection after writes are durable; stable message IDs absorb duplicates.
Recipient gets seq 104 before 103Buffer briefly and range-fetch the gap; do not advance contiguous to 104.Tombstones/control entries or authorized-range metadata distinguish intentionally hidden positions from missing data.
Gateway / Redis / push provider failureReconnect with , rebuild leased presence, and replay from durable history./ guards prevent an old disconnect from deleting a newer session Push and typing/presence may be lost; messages remain durable.
Slow consumer or reconnect stormBound per-connection buffer; disconnect with resume cursor, cap per-user sync concurrency and bytes, use exponential backoff with .Shed typing/presence before accepted messages.
Region failure: baseline 3- home-region Survives node/ failures.Asynchronous remote replicas imply nonzero under permanent regional loss; stale remote promotion cannot promise no lost acknowledged messages State this explicitly.
Zero- regional-loss requirementChange the journal placement to survive a region, e.g.one voter in each of three regions with majority commit Pay cross-region RTT Fail over only from a committed prefix; fence old epochs and reconstitute projections.
Network partition / no Minority refuses new sends and membership changes.Clients keep a pending and retry Previously committed authorized history may remain readable; do not create two sequence authorities.
Reshard, deploy, or schema migration + replay to a ; cut over with routing and fenced owner.Dedup lifetime must cover supported retry/replay windows Version event schemas; roll forward/back without reinterpreting old sequence numbers.

90-second interview summary

I would use stateless authenticated gateways for connections and one fenced ordering authority per conversation. That authority validates membership, assigns sequence and commits the message, duplicate-request result and delivery intent in a replicated journal before acknowledging the send.

Replayable workers project ordered history into Cassandra and maintain recipient inbox/receipt state. Kafka carries committed delivery work; Redis presence helps find live gateways but is not message truth. If a projection is delayed or a socket drops, durable history still repairs delivery.

Clients persist received messages and acknowledge only a contiguous prefix. Seeing sequence 104 does not allow advancing past missing 103. Reconnect first repairs gaps and closes the race with live delivery. Membership changes share the conversation order, and client encryption uses the effective device/key .

I would isolate hot conversations, bound gateway buffers and watch commit latency, projection lag, sequence gaps and repair age. A across local zones does not promise zero loss of a destroyed region; that needs appropriate cross-region commitment and higher latency. The central tradeoff is a clear ordered acceptance boundary with asynchronous, repairable delivery, rather than confusing socket success or a Cassandra write with a complete conversation protocol.

Explain it without looking

Explain commit one conversation order

Reveal answer

Record the message, sequence, membership check and delivery work at one owner.

Allocating a sequence separately from storing the message can leave gaps or conflicting owners after a crash.

Recover from the committed conversation log. Ordering is within a conversation, not a promise that every conversation shares one global clock.

Explain repair what a device missed

Reveal answer

Save received messages and acknowledge only the complete received sequence.

Writing to a live socket does not prove the device durably stored the message.

Reconnect must combine historical sync with buffered live updates and detect expired history. This uses more state but prevents gaps from being hidden.

Explain order membership changes with sends

Reveal answer

Use the membership and device-key version effective when the send is accepted.

An old cached membership entry can give a removed member access to new content.

Use a reviewed encryption protocol. Removing a member can protect future sends, but cannot make them forget plaintext they already received.

Explain what happens if a region fails?

Reveal answer

Preserve the accepted message order when another region takes over.

Message acceptance, order and membership must retain one meaning across the region switch.

A cross-region commit adds wide-area latency and partition rejection; asynchronous remote history permits a stated loss window.

Explain repair message history and inbox gaps

Reveal answer

Use the committed conversation log to repair missing history and inbox entries.

Durable acceptance and complete user-visible delivery are separate progress boundaries.

Additional projections speed reads and but create storage amplification, lag and repair responsibility.

Revision checklist

Revision checklist

  • Reconstruct commit one conversation order: Record the message, sequence, membership check and delivery work at one owner.
  • Reconstruct repair what a device missed: Save received messages and acknowledge only the complete received sequence.
  • Reconstruct order membership changes with sends: Use the membership and device-key version effective when the send is accepted.
  • Reconstruct what happens if a region fails?: Preserve the accepted message order when another region takes over.
  • Reconstruct repair message history and inbox gaps: Use the committed conversation log to repair missing history and inbox entries.
  • 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 scaleScope message send, live delivery, and offline catch-up. Agree on conversation ordering and what send acknowledgement means.
15–30 minHigh-level designTrace a message from the sender to the fenced conversation owner, replicated journal, delivery workers, and recipient.
30–45 minDeep divesExplain why the journal owns message order and how reconnect replays from a durable cursor. Separate acceptance from delivery.
45–55 minFailure and recoveryWalk through lost acknowledgement or loss of . Retry with the same message ID and name what a standby can safely serve.
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