The problem, stated properly
Design the backend of a chat app at WhatsApp scale: 1-on-1 and group messages, online presence, delivery guarantees (sent, delivered, read ticks), media sharing, and offline delivery, for billions of users who expect messages to arrive in under a second anywhere on Earth. The shape that emerges: a massive persistent-connection layer, surprisingly little data in flight, and a storage layer optimized for write-heavy, chat-history access.
Scale first
WhatsApp published enough over the years to anchor real numbers:
- Messages: ~100 billion/day. That is roughly 1.2 million messages/sec average, several million at peak (New Year's Eve is the famous stress test).
- Connections: 2+ billion users. If 50% are online at peak, you need 1 billion concurrent connections. A single tuned server holds roughly 1-2 million connections (WhatsApp ran FreeBSD + Erlang and famously supported ~2M connections per box with ~50 engineers total), so the connection tier is ~500-1,000 boxes, not 100,000.
- Storage: text messages are tiny (~100 bytes), so 100B/day is ~10 TB/day of text before media. Media dominates: with even 10% of messages carrying a 100 KB average image, that is ~1 PB/day. Media goes to blob storage with CDN; only references live in the message store.
Why WebSockets (and why not HTTP polling)
Chat is bidirectional and latency-sensitive. The server must push "user X is typing" and incoming messages instantly. HTTP polling means every client asks "anything for me?" every few seconds: at 1 billion online users even a 5-second poll is 200 million requests/sec of mostly-empty responses, and it still adds up to 5 seconds of latency. Long-lived WebSocket (or a custom TCP protocol, which is what WhatsApp actually runs) keeps one connection per client and pushes events in milliseconds, at the cost of holding connection state on servers.
The connection tier's job is deliberately thin: hold connections, authenticate, forward envelopes. No business logic, so it scales horizontally and a dead node just triggers client reconnect to another.
The message path, step by step
- Alice sends to Bob: client encrypts (Signal protocol, end-to-end) and pushes the envelope over its WebSocket.
- Her connection server hands it to the message service, which assigns a monotonically increasing message ID (per conversation, Snowflake-style or Lamport clocks), persists it to the store, and ACKs Alice. Her client shows one tick (sent).
- The service looks up Bob's active connection (a routing directory, often Redis-backed: user_id maps to server_id) and pushes the envelope to that server, which delivers it. Bob's device ACKs, and Alice's client gets two ticks (delivered).
- If Bob is offline, the message waits in a per-user queue in the store. On reconnect, his client syncs pending messages, ACKs them, and the queue drains. Read receipts (blue ticks) are just another tiny message flowing back through the same pipe.
Notice what is not here: no fan-out at write time for 1:1 chat. The message is stored once, delivered once. Fan-out pain belongs to groups.
Groups: where fan-out actually lives
WhatsApp caps groups at 1,024 members. Each group message fans out to every member's delivery queue (or, for offline members, sits in their pending store). A 1,024-member group at 1 message/sec is 1,024 deliveries/sec from one message, so the cap exists precisely to bound fan-out cost. Broadcast lists and channels (one-to-millions) need a different model entirely: fan-out on read or a pub/sub tier, because writing a copy per follower does not scale.
Presence and typing indicators
Online/offline status changes constantly and must reach contacts fast, but it is ephemeral: never write presence to the main store. A separate presence service keeps it in memory (Redis with TTL heartbeats: client pings every N seconds, key expires if pings stop) and fans changes out to watchers over the same connection tier. Accept staleness here; "last seen 1 minute ago" being 30 seconds wrong harms nobody.
Tradeoffs worth naming
- Eventual vs strong consistency: cross-device ordering is best-effort. WhatsApp uses per-conversation sequencing; a globally ordered timeline is impossible without killing availability.
- ACK-at-every-hop costs bandwidth but gives the tick UI users trust, and drives the retry logic that makes delivery at-least-once. Clients dedupe by message ID.
- Erlang/BEAM (WhatsApp's choice): millions of lightweight processes map beautifully to millions of connections, and hot code reloading means deploying without dropping a billion sockets. The cost: a niche talent pool.
Production failure modes
- Reconnect storms: a connection node dies and 2 million clients reconnect at once, DDoS-ing the remaining tier. Defenses: exponential backoff with jitter on clients, and a load-balancing layer that spreads reconnects.
- Offline-queue bloat: a user offline for months accumulates a huge pending store. Real systems cap retention (~30 days) and drop older messages.
- Hot group: one very active group pins load to the partition that owns it. Group IDs must hash evenly across shards, and abusive groups get rate-limited.
- Clock skew breaking order: never trust client clocks for ordering. Server-assigned sequence numbers only.
Common interview traps
- Suggesting HTTP polling for message delivery. It is the single most penalized answer in this question.
- Fan-out-on-write for channels with millions of followers without questioning the cost.
- Storing presence in the database. It is ephemeral state; it belongs in memory with TTLs.
- Forgetting that offline delivery is the hard half: anyone can deliver to a connected socket.
Interview Q&A
Q: How do you guarantee exactly-once delivery?
A: You don't, and saying so is the right answer. You guarantee at-least-once (persist before ACK, retry until ACK) and make clients idempotent: every message carries a unique client-generated ID, and the receiver dedupes on it. Exactly-once delivery over unreliable networks is provably impossible; exactly-once processing is what you actually build, via idempotency.
Q: How does WhatsApp scale to billions of users with so few servers?
A: Three compounding choices: one lightweight process per connection via Erlang (millions per box instead of thousands per box with threads), a deliberately thin connection tier with zero business logic, and aggressive separation of concerns (media to blob storage, presence to in-memory stores, messages to a write-optimized store). Each layer scales independently on its own bottleneck.
Problem ko sahi se samjho
WhatsApp scale ka chat app ka backend design karo: 1-on-1 aur group messages, online presence, delivery guarantees (sent, delivered, read ticks), media sharing, aur offline delivery, billions of users ke liye jo expect karte hain ki message 1 second ke andar duniya ke kisi bhi corner mein pahunche. Jo architecture niklega: ek massive persistent-connection layer, surprisingly kam data in flight, aur write-heavy chat history ke liye optimized storage.
Pehle scale
WhatsApp ne saalon mein kaafi numbers public kiye hain, unhi se anchor karte hain:
- Messages: ~100 billion/day. Matlab average ~1.2 million messages/sec, peak pe kai million (New Year's Eve famous stress test hai).
- Connections: 2+ billion users. Agar peak pe 50% online hain, to 1 billion concurrent connections chahiye. Ek tuned server ~1-2 million connections hold karta hai (WhatsApp FreeBSD + Erlang pe ~50 engineers ke saath ~2M connections per box chalata tha), matlab connection tier ~500-1,000 boxes ka hai, 100,000 ka nahi.
- Storage: text messages chhote hain (~100 bytes), to 100B/day matlab ~10 TB/day text, media se pehle. Media dominate karta hai: agar sirf 10% messages mein average 100 KB image hai, to ~1 PB/day. Media blob storage + CDN mein jaata hai; message store mein sirf reference rehta hai.
WebSockets kyun (aur HTTP polling kyun nahi)
Chat bidirectional aur latency-sensitive hai. Server ko "X is typing" aur incoming messages turant push karne hain. HTTP polling ka matlab: har client har kuch second mein poochta hai "mere liye kuch hai?". 1 billion online users pe 5-second polling bhi 200 million requests/sec hai, zyadatar khali responses ke saath, aur phir bhi 5 second tak ki latency. Long-lived WebSocket (ya custom TCP protocol, jo WhatsApp asal mein chalata hai) per client ek connection rakhta hai aur milliseconds mein events push karta hai, bas connection state servers pe hold karni padti hai.
Connection tier ka kaam jaan boojh ke patla rakha gaya hai: connections hold karo, authenticate karo, envelopes forward karo. Koi business logic nahi, isliye horizontally scale hota hai aur ek dead node pe client bas doosre pe reconnect karta hai.
Message ka safar, step by step
- Alice Bob ko bhejti hai: client encrypt karta hai (Signal protocol, end-to-end) aur apne WebSocket pe envelope push karta hai.
- Uska connection server envelope message service ko deta hai, jo monotonically badhta message ID assign karta hai (per conversation, Snowflake-style ya Lamport clocks), store mein persist karta hai, aur Alice ko ACK deta hai. Uski screen pe ek tick (sent).
- Service Bob ka active connection dhundhti hai (routing directory, aksar Redis-backed: user_id se server_id) aur envelope us server ko push karti hai, jo deliver karta hai. Bob ka device ACK karta hai, Alice ko do ticks (delivered).
- Agar Bob offline hai, message uske per-user queue mein store mein wait karta hai. Reconnect pe uska client pending messages sync karta hai, ACK karta hai, queue drain. Read receipts (blue ticks) bhi bas isi pipe se wapas jaate chhote messages hain.
Dhyan do kya nahi hai: 1:1 chat mein write-time fan-out nahi. Message ek baar store, ek baar deliver. Fan-out ka dard groups ka hai.
Groups: asal fan-out yahan rehta hai
WhatsApp groups ko 1,024 members pe cap karta hai. Har group message har member ke delivery queue mein fan-out hota hai (offline members ke liye pending store mein). 1,024-member group mein 1 message/sec matlab sirf ek message se 1,024 deliveries/sec, isliye cap exist karta hai: fan-out cost bound karne ke liye. Broadcast lists aur channels (one-to-millions) ko alag model chahiye: fan-out on read ya pub/sub tier, kyunki har follower ke liye ek copy likhna scale nahi hota.
Presence aur typing indicators
Online/offline status lagatar badalta hai aur contacts tak jaldi pahunchna chahiye, par ye ephemeral hai: ise kabhi main store mein mat likho. Ek alag presence service ise memory mein rakhti hai (Redis with TTL heartbeats: client har N second mein ping, ping ruka to key expire) aur changes ko watchers tak same connection tier se fan-out karti hai. Yahan staleness accept karo; "last seen 1 minute ago" 30 second galat ho to kisi ka nuksaan nahi.
Tradeoffs jo naam dene layak hain
- Eventual vs strong consistency: cross-device ordering best-effort hai. WhatsApp per-conversation sequencing use karta hai; globally ordered timeline availability maare bina impossible hai.
- Har hop pe ACK bandwidth khaata hai par tick UI deta hai jispe users trust karte hain, aur retry logic drive karta hai jo delivery ko at-least-once banata hai. Clients message ID se dedupe karte hain.
- Erlang/BEAM (WhatsApp ka choice): millions of lightweight processes millions of connections pe beautifully map hote hain, aur hot code reloading ka matlab billion sockets giraye bina deploy. Cost: niche talent pool.
Production mein kya tootta hai
- Reconnect storms: ek connection node mara aur 2 million clients ek saath reconnect, baaki tier ka DDoS. Defenses: clients pe exponential backoff with jitter, aur load-balancing layer jo reconnects spread kare.
- Offline-queue bloat: mahino offline user ka pending store bahut bada. Real systems retention cap karte hain (~30 din) aur purane messages drop.
- Hot group: ek bahut active group us partition pe load pin karta hai jo use own karta hai. Group IDs shards pe evenly hash hone chahiye, abusive groups rate-limited.
- Clock skew ordering tod deta hai: ordering ke liye client clocks pe kabhi bharosa mat karo. Sirf server-assigned sequence numbers.
Common interview traps
- Message delivery ke liye HTTP polling suggest karna. Is sawaal mein sabse zyada penalize hone wala jawab yahi hai.
- Millions of followers wale channels ke liye bina cost soche fan-out-on-write bolna.
- Presence ko database mein likhna. Ye ephemeral state hai; memory mein TTL ke saath rehti hai.
- Ye bhoolna ki offline delivery hi aadha mushkil kaam hai: connected socket pe deliver to koi bhi kar lega.
Interview Q&A
Q: Exactly-once delivery kaise guarantee karoge?
A: Nahi karoge, aur ye bolna hi sahi jawab hai. Tum at-least-once guarantee karte ho (ACK se pehle persist, ACK tak retry) aur clients ko idempotent banate ho: har message pe unique client-generated ID, receiver uspe dedupe karta hai. Unreliable networks pe exactly-once delivery provably impossible hai; jo tum asal mein banate ho wo exactly-once processing hai, idempotency se.
Q: WhatsApp itne kam servers pe billions of users kaise chalata hai?
A: Teen compounding choices: Erlang se per connection ek lightweight process (threads ke hazaron ke bajaye millions per box), jaan boojh ke patla connection tier jisme zero business logic, aur concerns ka aggressive separation (media blob storage mein, presence in-memory store mein, messages write-optimized store mein). Har layer apne bottleneck pe independently scale hota hai.