Skip to content
Navigation
Dashboard
← All system design problems
Medium · Messaging Systems · About 60 minutes

Design WhatsApp/Messenger - Real-Time Chat System

Understand the requirements. Trace the requests. Explain the trade-offs.

CANDIDATE-LED INTERVIEW WALKTHROUGH

Design WhatsApp: durable acceptance, ordered delivery and private content

A candidate-led conversation about online/offline messaging, device inboxes, groups, encryption and failure recovery. Workloads and service targets are illustrative assumptions.

Interviewer replies, workloads and targets are illustrative assumptions to agree on in an interview. Use this as a study resource: establish scope, draw a complete baseline, then choose the most consequential deep dives with your interviewer.

1. Turn the brand name into a bounded problem

Candidate explains

I would first distinguish the messaging product from a generic socket platform or cryptographic protocol. I will integrate established encryption rather than invent it. Presence and typing can be approximate; accepted messages cannot be treated the same way.

Candidate asksIllustrative interviewer replyDesign consequence
1:1 chat or groups, and how large?Both; groups up to 256 members.Per-conversation order and bounded fan-out.
Text, media, voice/video or payments?Text and media; others excluded.Separate encrypted object path; no call pipeline.
Offline users and linked devices?Yes; retain undelivered envelopes 30 days.Durable per-device inboxes and replay cursors.
What does sent mean?Durably accepted, not just gateway receipt.No success ACK before durable commit.
What privacy and order are expected?End-to-end encryption; consistent conversation order.Server cannot search plaintext; explicit order authority.
What scale and latency?Choose assumptions; optimize online in-region delivery.Separate acceptance, connected delivery and offline delay.

2. Define requirements and success boundaries

Candidate explains

I will support text/media, small groups, online/offline delivery, receipts and linked devices. Presence/typing are best-effort; calls, stories and server-side plaintext search are excluded. Local search is compatible with encrypted server storage.

Acceptance means the encrypted message and delivery intent are durable. Transport is at least once, with stable message IDs and idempotent application. That is not exactly-once networking.

RequirementProposed contract
Online latencyIllustrative p95 below 200 ms from durable acceptance to a connected in-region recipient at admitted load.
Availability99.99% send/read API monthly target; uncertain conversation ownership can temporarily reject writes.
OrderMonotonic sequence per conversation, not a global order.
RetentionUndelivered encrypted envelopes retained for 30 days; older devices need explicit recovery policy.
PrivacyOnly endpoints hold plaintext; device/key lifecycle and metadata privacy are separate concerns.
ReceiptsSent = durable acceptance; delivered = recipient-device ACK; read = optional client-reported state.
MembershipAuthorize against the membership version at acceptance; declare what departing members may receive.

3. Separate logical messages, fan-out and connections

Candidate explains

Assume 10M DAU send 100 messages each per day. One billion logical messages/day does not equal one billion delivery writes: assume three recipient-device envelopes on average. Group-size and linked-device distributions determine this multiplier.

A million idle TLS connections and a million active sends stress different resources. I would benchmark gateway capacity rather than invent a per-machine socket guarantee.

CalculationResultImplication
10M × 100 ÷ 86,40011,574 sends/s average; 115,741/s at assumed 10× peakPartition owners and bound burst admission.
1B × 3 recipient-device envelopes/day3B envelopes/day; 34,722 writes/s averageBudget group and multi-device amplification.
3B envelopes × 1 KB × 30 days90 TB if every envelope is retained for the full windowA conservative logical bound; indexes, replicas and media extra.
1B messages × 1% media × 500 KB5 TB/day media ingress; 150 TB/30 daysDownload fan-out and replication are additional.
1M simultaneous devices ÷ 30-second heartbeat33,333 heartbeats/sJitter and separate ephemeral presence from durable writes.

4. Model accounts, devices and authoritative order

Candidate explains

I separate accounts from devices because each recipient may need several encrypted envelopes and independent delivery state. A device-to-gateway cache is a routing hint, never the only offline-message store.

A logical conversation owner serializes acceptance. Its durable transaction allocates a sequence, inserts the dedup/message record and appends delivery work. A sharded transactional store is a simple baseline. A log-centric or wide-column alternative must preserve the same explicit ownership and acknowledgement rules.

EntityAccess / ownershipInvariant
Conversation + Member(conversationId,membershipVersion)Conversation home partitionMembership and sequencing coordinated at acceptance.
Message(conversationId,sequence,messageId,ciphertextRefs)Range by conversation and sequenceImmutable content and stable accepted order.
Dedup(senderDeviceId,clientMessageId,digest,result)Unique operation key in owner transactionReplayed input returns original result; different input conflicts.
DeviceInbox(deviceId,cursor,messageId,acknowledged)Sequential replay per deviceCursor never skips unpersisted delivery work.
Device/public key directoryAuthorized devices and public prekeysPrivate keys stay on endpoints; revocation changes future delivery.
SessionRoute(deviceId,gateway,epoch,expiry)Ephemeral cacheStale routing cannot erase accepted messages.

5. Specify message, receipt and recovery protocols

Candidate explains

I use an authenticated persistent connection for realtime frames and HTTP for history, media capabilities and device management. Long-lived secrets should not be exposed in logged URLs; use a secure handshake or short-lived connection ticket.

Cursors are opaque and caller-scoped. Knowing a message ID or device ID grants no permission to read it.

InterfacePayload → resultRetry / error rule
WS SENDconversationId, clientMessageId, membershipVersion, encrypted envelopes → ACCEPTED(messageId,sequence)Persist before ACK; replay same operation; refresh stale membership/key set.
WS DELIVERY_ACK / READAuthenticated device, messageId or contiguous cursor → receipt stateMonotonic/idempotent; respect optional read-receipt privacy.
GET /v1/inbox?cursor=…Bounded encrypted page and next cursorExpired cursor returns recovery-required, not empty success.
GET /v1/conversations/{id}/messages?before=…Authorized encrypted historyRetention bounded; client decrypts.
POST /v1/media/uploadsEncrypted size/type → scoped URL and mediaIdEncrypt client-side; verify object before sharing reference.
POST /v1/conversations/{id}/membersExpected membership version and changes → new versionAuthorization plus required key/session update.

6. Draw the durable baseline

Candidate explains

Gateways connect clients; conversation owners accept messages; a durable outbox creates recipient inbox work. Delivery workers use routing hints for online recipients or send a minimal wake-up push. A push-provider success is not proof a recipient read the message.

When routing is down I can retain accepted messages and degrade realtime delivery. When durable acceptance is unavailable I cannot honestly return a successful sent receipt.

7. Trace a send and a lost acknowledgement

Candidate explains

Alice persists a pending operation locally and reuses clientMessageId across reconnects. I distinguish durable service acceptance, recipient delivery and reading. Bob persists/deduplicates an envelope before delivery ACK. Receipts may also repeat.

  1. Prepare encrypted envelopes

    Use the established protocol and current authorized device/key set. Include conversation and membership versions plus a stable client operation ID.

  2. Validate and serialize

    Check sender/device membership, payload bounds and digest. Route to the fenced conversation owner; atomically allocate sequence and persist message/dedup/outbox.

  3. Acknowledge

    Return ACCEPTED only after commit. If the reply is lost, replay the same operation and return the saved ID/sequence without allocating another.

  4. Materialize inboxes

    Idempotent workers insert recipient-device items using uniqueness on (deviceId,messageId). Durable work does not depend on current socket availability.

  5. Deliver

    Try the session route. Recipient stores once by messageId, then ACKs. Stale routes leave inbox work intact and may trigger a minimal wake-up push.

  6. Aggregate receipts

    Advance per-device/per-recipient receipt state according to the agreed semantics. Define whether group delivered means any recipient or all recipients; never overload one boolean.

8. Recover offline devices and preserve conversation order

Candidate explains

When Bob reconnects, he fetches a bounded page after his safely stored cursor, applies/persists it and acknowledges. A device offline beyond retention receives an explicit gap and a defined history-recovery flow.

Ordering cannot depend on unsynchronized device clocks. A fenced owner assigns canonical sequence; devices detect gaps and request missing data. A sequence gap may also need an authorized tombstone/skip marker rather than exposing content a device cannot read.

  1. Groups

    Accept once, then materialize recipient-device work asynchronously. Bound fan-out and isolate hot groups; the average group size hides tail cost.

  2. Membership

    Pin acceptance to a membership version and define departed-member semantics. Key changes protect future messages, not plaintext already received.

  3. Multiple devices

    Use device-specific encryption sessions and inbox cursors; sync the sender’s other devices. Define how new devices obtain old history without server plaintext access.

  4. Owner failover

    Use a lease/epoch fenced at durable writes. A stale owner cannot allocate conflicting sequences. Reject temporarily while ownership is uncertain.

9. Scale without contradicting encryption

Candidate explains

I partition conversation writes and device-inbox reads separately. Reconnect storms need jitter, backoff, bounded replay and admission limits. I degrade presence before message durability.

Servers cannot perform ordinary plaintext search, media transcoding or content inspection on end-to-end encrypted payloads. Clients process media before encryption and search local history; abuse reporting needs an explicit user-consented disclosure path. Metadata-based rate controls have their own privacy trade-offs.

ChoiceBaselineRevisit when
Small-group fan-outMaterialized per-device inbox itemsLarge channels need shared logs/cursors and a revised workload.
RegionsHome region per conversation with durable replicasActive-active writes require a new order/conflict contract.
MediaPrivate encrypted objects, scoped URLs, keys inside encrypted messagesAlign deletion, backup and recovery policy.
PresenceTTL heartbeats and approximate last-seenAvoid turning every heartbeat into a durable message write.

10. Prove the delivery guarantees

Candidate explains

I monitor acceptance latency, connected-delivery latency, oldest pending inbox age, dedup/replay rates, fan-out backlog and device-key failures. A healthy gateway alone cannot prove delivery.

FailureRecoveryAssertion
Gateway dies after acceptanceReconnect and retry same keyOne accepted message and original sequence.
Worker dies during group fan-outReplay outbox and unique inbox insertsNo skipped eligible devices or duplicate logical item.
Routing cache failsQueue durably; replay on reconnectAccepted messages retained; presence may degrade.
Old owner survives failoverReject stale fencing epochNo conflicting sequence assignment.
Recipient ACK is lostRedeliver and deduplicate on deviceOne visible message; receipts converge.
Keys/membership change during sendReject stale envelope set and refreshFuture delivery uses the current declared policy.

11. Summarize the guarantees

Candidate explains

I separated durable acceptance, delivery and reading. Stable IDs make repeated transport safe; inbox cursors recover offline devices; conversation ownership defines order. Encryption constrains server-side features.

A senior explanation makes those boundaries testable and addresses backpressure/failover. Staff-level discussion explores global ownership, device/key lifecycle, large-group amplification, metadata privacy and migrations of ciphertext without plaintext access.

Technical references

Primary references explain underlying mechanisms. Workloads and architecture choices above remain proposed interview assumptions.