A chat messenger lets two people (or a group) exchange messages that arrive in under a second, show "sent / delivered / read" ticks, and still work when the recipient's phone is off. Unlike the URL shortener, the hard part is not storage. It is keeping a hundred million phones connected at once, knowing which server each phone is attached to, and delivering every message exactly once and in order. This lesson walks the full eight-step interview framework and the reasoning to say aloud at each step.
Detailed Notes
How to use this lesson
Treat this as a 45-minute interview. Every step is one block of the conversation. The numbers are assumptions you state out loud, not facts about any real company. The interviewer checks that your estimates drive your design, not that they match WhatsApp.
Step 1: Clarify Requirements
Start with: "Let me agree on what messaging features we need, how big this is, and what I can leave out."
Functional requirements
1:1 chat: a user sends a text message to another user and the recipient receives it in near real time.
Group chat: a user sends a message to a group (up to 256 members) and every member receives it.
Delivery states: the sender sees sent (server has it), delivered (recipient's device has it) and read (recipient opened it).
Offline delivery: if the recipient is offline, the message waits and arrives when they reconnect. A push notification (a message from the phone vendor's service that wakes the device or shows an alert) tells them something is waiting.
Media: send images, videos and files.
Message history: a user can scroll back through old messages.
Extended requirements
Mention, then ask before designing:
Presence: "online" and "last seen".
Typing indicators: "Alice is typing...".
Multi-device: the same account on a phone and a laptop.
End-to-end encryption (E2EE): only the sender and recipients can read messages, not our servers.
Non-functional requirements
Low latency: a message to an online user arrives in under 500 ms at p99 (99 of every 100 messages are faster).
Reliability: a message the server acknowledged is never lost. Durability matters more than speed.
Ordering: messages in one conversation appear in the same order for everyone.
No duplicates: a retry after a network blip must not show the message twice.
High availability: 99.99% for sending and receiving.
Scale: hundreds of millions of daily users and tens of millions of simultaneous connections.
Consistency decision. We need ordering and durability per conversation, not a global order across all conversations. Saying "total order across the whole system is unnecessary" is the idea that makes this design scalable.
Out of scope
Voice and video calls, status/stories, payments, contact discovery, spam detection and message search. Name them so the interviewer can redirect you.
Interview tip. Candidates often say "I'll use HTTP and a database" and forget that the server must push messages to phones. Ask early: "How does a message reach a phone that is just sitting there?" That question leads straight to WebSockets.
Step 2: Estimate Scale
Back-of-the-envelope estimation means rough calculations that show which parts will be hard. Round everything so the arithmetic is easy to say aloud.
Assumptions to state
500 million daily active users (DAU).
Each user sends 40 messages a day.
20% of DAU are connected at the peak moment, so 100 million simultaneous connections.
Average message record is 200 bytes (text plus ids and timestamps). Real text is smaller, metadata is the rest.
On average each message has 2 recipients (many 1:1 chats, some groups).
5% of messages carry media, averaging 200 KB.
A day has about 100,000 seconds, and peak traffic is 3x the average.
Message rate
text
500M users x 40 messages = 20 billion messages per day
20B / 100,000 seconds = 200,000 messages per second
200,000 x 3 peak factor = 600,000 messages per second at peak
Deliveries: 200,000 x 2 recipients = 400,000 per second (1.2M at peak)
Messenger: Estimate the ScaleEstimation
Request load
500Mdaily active users
given
20Bmessages / day
× 40 each
200K/smessages avg
÷ 100,000 s
600K/smessages at peak
× 3 peak factor
100Mconnections at peak
× 20% of DAU
Gateways
~1,500
100M ÷ 100K per gateway = 1,000, plus 50% headroom
A large stateful tier plus a session registry
Storage
4 TB/day
20B messages × 200 bytes (1.5 PB/year)
Partition by conversation; tier old data
Media
200 TB/day
1B files × 200 KB (5% of messages)
Object storage, never the chat path
Key point. The binding constraint is 100 million open connections, not message volume: that makes the gateway tier stateful and large.
Two assumptions drive everything: 500 million daily users sending 40 messages each, and 20% of them connected at peak.
So what: 600K writes per second is far beyond one database, so we partition (split data across machines) from day one. And every message must be delivered, so a routing layer that finds the recipient's connection matters as much as storage.
Concurrent connections and WebSocket gateways
A WebSocket is a long-lived two-way connection between a phone and a server, opened once and kept open, so the server can push data at any moment (covered in the real-time lesson). The servers holding these connections are WebSocket gateways.
text
Concurrent connections = 500M x 20% = 100 million
One gateway holds = about 100,000 connections (conservative)
Gateways needed = 100M / 100,000 = 1,000
With 50% headroom = about 1,500 gateways
One gateway could technically hold a million connections, but we plan for 100K because each connection costs memory (buffers, TLS state) and a crash drops every connection on that machine. Fewer, bigger gateways mean a bigger reconnect storm when one dies.
So what: this is a stateful tier. Unlike the stateless services in earlier lessons, a gateway remembers which phones are attached to it. So we need a session registry that records "user Bob is on gateway 42".
Keep-alive traffic
text
100M connections, one tiny heartbeat every 60 s = about 1.7M heartbeats per second
A heartbeat is a small ping that proves a connection is still alive. 1.7M per second is more than our 600K peak messages. It is cheap per request, but it is why presence features must be designed carefully (see the deep dive).
Storage
text
Text: 20B messages x 200 bytes = 4 TB per day
Year: 4 TB x 365 = about 1.5 PB
x3 replicas = about 4.5 PB per year
Media: 20B x 5% = 1B files x 200 KB = 200 TB per day
Text is large only because of volume. Media is 50x bigger than text, so media must never flow through the chat path. It goes to object storage (cheap bulk file storage addressed by key).
Bandwidth and registry size
text
Inbound text: 600K/s x 200 B = 120 MB/s
Outbound text: 1.2M/s x 200 B = 240 MB/s (about 2 Gbps)
Session registry: 100M x 100 bytes = 10 GB
Text bandwidth is modest. The registry is only 10 GB, so it fits in the memory of a small in-memory cluster.
Interview tip. The classic miss is estimating messages per second and stopping. Interviewers want to hear connections: "100 million connections is the real constraint, and it makes the gateway tier stateful."
Step 3: Define the APIs
Most traffic uses a WebSocket, because the server must push. Ordinary HTTP is used for everything that is request and response: login, history, media upload URLs. First the real-time protocol. Each message is a small JSON frame (a binary format is common in production, but JSON is easier to read).
Design decision: client message id. The phone generates client_msg_id (a UUID) before sending. If the connection drops and the phone retries, the server sees the same id and returns the original ack instead of storing a second copy. This is the idempotency key idea from the retries lesson, and it is how we get "no duplicates" on an unreliable mobile network.
The recipient replies with {"type":"delivered","conversation_id":"conv_8841","up_to_seq":42} and later {"type":"read", ... }. Acks name a sequence number (up_to_seq), not a single message: "I have everything up to 42". Section 6 explains why.
Other frames
typing: {"type":"typing","conversation_id":"conv_8841"}, fire and forget, never stored.
sync: sent when a device reconnects, {"type":"sync","cursors":{"conv_8841":41}}, meaning "I have conversation 8841 up to 41, send me the rest".
HTTP APIs
http
POST /v1/media/upload-url -> { "media_id": "m_91", "upload_url": "https://..." }
GET /v1/conversations/{id}/messages?before_seq=42&limit=50 # history
POST /v1/conversations # create a group
POST /v1/devices # register a push token
Status codes that matter: 201 on creating, 400 for a malformed request, 401 for an unauthenticated user, 403 if the caller is not in the conversation, 429 when rate limited. Over the WebSocket, errors are frames with an error code, because there are no HTTP status lines.
How the API shapes the architecture
Three facts decide everything: (1) the server must push, so we need persistent connections; (2) every action is scoped to one conversation, so we can partition by conversation; (3) acks and sync use sequence numbers, so each conversation needs its own counter.
Step 4: Define the Data Model
Start with access patterns:
Append a message to a conversation (600K per second at peak).
Read the latest N messages of a conversation, and page backwards.
Read everything after sequence X for a conversation (sync after being offline).
List my conversations with unread counts.
Find the gateway that holds user U (the session registry).
Fields and why each exists
messages.conversation_id is the partition key: all messages of one conversation live together, so history and sync are single-partition range reads.
messages.seq is the clustering key (the sort order inside a partition): a counter that goes 1, 2, 3 within the conversation. It also defines display order.
messages.message_id is a time-ordered unique id (like the snowflake ids in the unique-ids lesson). It is a globally unique name for the message, used for replies, reports and media references.
messages.client_msg_id plus sender_id supports idempotent sends.
messages.body is an opaque encrypted blob. With E2EE the server cannot read it.
memberships.last_delivered_seq and last_read_seq are per-user cursors per conversation. Delivery and read receipts are one number, not one row per message. This is how a 256-person group stays cheap.
devices stores the push token per device, for offline notifications and multi-device.
sessions (in the in-memory registry) maps a device to its gateway, with a TTL so dead entries disappear.
The Data ModelData model
messagesWide-column store
PKconversation_idbigint
partition key; keeps a chat together
SKseqbigint
per-conversation counter; defines order
UQmessage_idbigint
time-ordered unique id
sender_idbigint
IDXclient_msg_iduuid
idempotent send; with sender_id
bodyblob
encrypted; server cannot read
media_idvarchar
reference to object storage
created_attimestamp
Append-only. Add a bucket to the partition key for very large groups.
membershipsWide-column store
PKconversation_idbigint
SKuser_idbigint
reverse index lists my chats
last_delivered_seqbigint
delivered cursor
last_read_seqbigint
read cursor
Receipts are two numbers per member, not a row per message.
devicesRelational DB
PKuser_idbigint
SKdevice_iduuid
push_tokenvarchar
APNs / FCM token
public_keyblob
for E2EE
Small table; one row per device.
sessionsIn-memory registry
PKuser_idbigint
SKdevice_iduuid
gateway_idvarchar
where the socket lives
ttlseconds
~2 min; refreshed by heartbeat
About 100M rows, 10 GB; entries vanish when heartbeats stop.
messages.conversation_idmemberships.conversation_id· one to many
memberships.user_iddevices.user_id· one to many
sessions.device_iddevices.device_id· one to one
Key point. Partition messages by conversation_id and cluster by seq: history and sync are single-partition range reads.
Messages are stored once per conversation. Each member has cursors instead of per-message receipt rows.
Why not one row per message per recipient?
It is tempting to give every recipient their own copy ("inbox" style). For a 256-member group that is 256 writes per message, and read states multiply. Storing the message once per conversation and tracking each member's position with a cursor turns that into one write plus small cursor updates.
Which database?
Access is by conversation, ordered by sequence, with huge append volume and no joins. That is a wide-column store (a NoSQL family from the nosql lesson, such as Cassandra or HBase), built for partitioned, append-heavy, range-read workloads.
1.5 PB per year needs automatic horizontal partitioning and replication.
The session registry needs sub-millisecond reads and writes with expiry: an in-memory key-value store.
Users, groups and device metadata are small and relational: a normal relational database, or the same wide-column store.
Trade-off thinking. A relational database gives joins and transactions but needs manual sharding at 600K writes per second. A wide-column store gives easy scale and fast range reads but no joins, and sequence assignment must be handled by our service. Our access patterns have no joins, so wide-column wins.
Step 5: High-Level Design
The central idea: keep connections in one tier, keep logic in another, and keep the "who is where" map in a third.
High-Level DesignArchitecture
Key point. Connections, logic and routing data live in three separate tiers, so each can scale on its own.
Gateways hold connections, the chat service holds logic, the registry says who is where.
Components and why each exists
Load balancer: accepts new connections and spreads them over gateways. A load balancer distributes incoming connections across identical servers and skips unhealthy ones.
WebSocket gateways: hold the persistent connections, authenticate the user once at connect time, and forward frames. They contain no business logic, so they stay simple and light.
Chat service: stateless service holding the logic: validate, deduplicate, assign sequence numbers, store, route. Because it is stateless, we scale it by adding instances.
Message store: the partitioned wide-column database.
Delivery queue: a durable buffer (see the queues lesson) for work that must not block sending: push notifications and large group fan-out.
Push service: calls APNs (Apple) and FCM (Google), the vendor services that wake phones.
Object storage: holds media; clients upload and download directly using short-lived signed URLs.
Key point. Sent means stored. Delivered and read are separate acks from the recipient.
The sender's ack waits only for the durable write, not for the recipient.
Request flow: sending to an online user
Alice's phone sends a send frame over her WebSocket to gateway 17.
The gateway forwards it to the chat service.
The chat service checks the client_msg_id for duplicates, assigns the next seq for the conversation and writes the message to the store.
It returns ack(status=sent) to Alice. The ack is sent only after the durable write, so "sent" means "we will not lose it".
It looks up Bob in the session registry (gateway 42) and pushes the message to him.
Bob's phone stores it and replies delivered. The server updates his cursor and tells Alice. When Bob opens the chat, read flows the same way.
Step 6: Deep Dive
Interviewers choose the part they find hardest. For messaging the usual targets are connection management, ordering, delivery guarantees and fan-out.
6.1 WebSocket gateways and the session registry
When Bob's phone connects, the load balancer picks a gateway. The gateway authenticates him, then writes sessions[bob, device_1] = gateway-42 into the registry with a TTL (time to live, an expiry) of about 2 minutes. Each heartbeat refreshes the TTL. If the phone vanishes without saying goodbye (subway tunnel, dead battery), the entry simply expires and nobody keeps routing to a ghost.
Finding the Right GatewayArchitecture
GatewaysAlicephoneBobphoneGateway 17holds AliceGateway 42holds BobChat serviceroutes messageSessionregistrybob = gateway 421 send2 where is Bob?3 deliver
Key point. One registry lookup turns 'deliver to Bob' into one call to one gateway out of 1,500.
Alice and Bob are connected to different gateways. The registry tells the chat service where Bob is.
How the chat service delivers a message to Bob:
Look up sessions[bob] and get every device's gateway id.
Send the frame to those gateways (gateway-to-gateway or service-to-gateway over an internal network).
The gateway finds the right socket in its in-memory table and writes the frame.
If the gateway answers "not connected" (the registry was stale) or the key is missing, treat Bob as offline.
Key points to say aloud:
Gateways are stateful, so make them dumb. They only hold sockets. If one crashes, its ~100K users reconnect elsewhere within seconds, re-register, and sync missed messages.
Reconnect storms. If a gateway dies, 100K phones reconnect at once. Phones use exponential backoff with jitter (waits that grow and are randomized, from the retries lesson) so the load balancer and registry are not flattened.
Registry consistency. It may briefly point to a dead gateway. That is fine, because the message is already durably stored; a failed live delivery just falls back to "deliver on next sync".
Registry partitioning. Partition by user id with consistent hashing (the partitioning lesson). 10 GB fits on a few nodes; replicate for failover.
Draining on deploys. Never restart all gateways at once. Remove a gateway from the load balancer, tell clients to reconnect elsewhere, then restart.
Trade-off thinking. Why not skip the registry and broadcast every message to all 1,500 gateways? That wastes 1,499 of 1,500 calls. A registry costs 10 GB of memory and one lookup, and reduces fan-out to exactly the gateways that matter.
6.2 Ordering with per-conversation sequence numbers
Timestamps are unreliable: phone clocks drift and two messages can share a millisecond. Instead, each conversation owns a counter. When the chat service stores a message it assigns seq = last_seq + 1, and the client sorts by seq.
To make the counter safe, one writer at a time must own each conversation:
Route all writes for conversation_id to the same chat-service shard (hash the id), or store the counter next to the data and increment it with an atomic compare-and-set (a write that succeeds only if the value is what we expected).
Because the counter is per conversation, 600K messages per second spread across hundreds of millions of conversations. No single counter is hot.
Sequence numbers also give us gap detection: if a phone has 40, 41, 43, it knows 42 is missing and asks the server for it. This makes delivery robust to dropped frames.
6.3 Delivery states: sent, delivered, read
Sent (one tick): the server wrote the message durably and acked the sender.
Delivered (two ticks): the recipient's device received the message and sent delivered(up_to_seq).
Read (blue ticks): the recipient opened the conversation and sent read(up_to_seq).
Because acks are cursors ("everything up to 42"), they are idempotent: repeating or reordering them is harmless, and one frame can acknowledge 200 messages after a long offline period. In a group, the sender sees "delivered" when all members' last_delivered_seq >= seq and "read" the same way. Group info screens show per-member detail by comparing each member's cursor with the message's seq.
What if the ack is lost? Delivery is at-least-once: the server resends until acked. Receivers deduplicate by seq (they already have 42, so they ignore a second copy). At-least-once plus dedup behaves like exactly-once to the user.
6.4 1:1 versus group fan-out
Fan-out means one incoming message producing many outgoing deliveries.
Group Fan-Out: Two Ways to DeliverComparison
Copy to every inbox
fan-out on write
1
Message arrives
group of 256 members
2
Write a copy per member
256 inbox rows
3
Track receipts per copy
256 status rows
4
Deliver from each inbox
one read per member
Each user's inbox read is one simple query
256x write amplification
Storage grows with group size
Slow for big groups
Costly at 600K messages per second
Store once, push live
one log per conversation
1
Message arrives
group of 256 members
2
Append one row, assign seq
single write
3
Look up members online
registry, in a batch
4
Push; others sync by cursor
last_delivered_seq
One write per message
Receipts are two cursors per member
Same path for sync and history
Needs a registry lookup per member
Large groups need queue workers
Chosen: cheap writes, simple sync
Key point. Store once per conversation and track a cursor per member. Fan out only the live delivery.
For a 256-member group, the difference is 1 message write versus 256.
1:1: one recipient, delivered inline by the chat service as described.
Small and medium groups (up to 256): store the message once, then for each member look up the registry and push. About 256 registry lookups and pushes is fine at 200K messages per second only if most traffic is 1:1; our average of 2 recipients reflects that.
Large groups or channels (thousands of members): do not loop inline. Write one job to the delivery queue and let fan-out workers deliver in parallel batches. Members who are offline are not individually notified in the write path; they pick the message up on sync.
6.5 Offline users and push notifications
If the registry has no session for Bob:
The message is already stored, with seq. Nothing else is needed for correctness.
The chat service puts a notification job in the queue.
The push service sends it to APNs/FCM using Bob's device token from the devices table. The payload is only "new message" (or the encrypted preview), never plaintext, because those vendors are third parties.
When Bob opens the app, it opens a WebSocket and sends sync with its cursors. The server returns every message after those cursors, in order.
Chat serviceRegistryPush serviceBob's phone1where is Bob?message 42 already stored2no session3notify Bobvia queue, batched4push: new message5connect + sync(41)last seq he has6register session7messages 42..458delivered up_to 45
Key point. If push is lost, nothing is lost: Bob syncs from his cursor the moment he reconnects.
The push only nudges. Correctness comes from syncing after the last sequence number Bob has.
Important details:
Push is a hint, not a guarantee. APNs/FCM can drop or delay notifications. Correctness comes from the sync on reconnect, not from push.
Batching and collapsing. If Bob has 30 unread messages, send one notification ("30 new messages"), not 30.
Retention of undelivered messages. The message stays in the store anyway; we do not need a separate "pending" copy. For E2EE messages that a server only relays, keep them up to 30 days, then drop.
6.6 Idempotent send
Mobile networks drop connections constantly. The phone cannot know whether the server saw its message, so it retries with the same client_msg_id.
text
chat service on send(conversation, sender, client_msg_id):
if dedup key exists -> return the stored ack (same seq)
else -> assign seq, write message, set dedup key (TTL 24h), return ack
The dedup check and the write must be atomic. A simple approach: make (conversation_id, sender_id, client_msg_id) a unique constraint using a conditional write ("insert only if absent"). The retry hits the conditional failure and returns the first result.
6.7 Message storage and history
Partition key:conversation_id. Clustering key:seq (descending for newest-first reads).
"Last 50 messages" is a single-partition read of the newest 50 rows. "Everything after 41" is a contiguous range on the same partition.
Hot or huge conversations. A group with millions of messages would make a very wide partition. Add a bucket to the partition key, for example (conversation_id, seq / 100000), so each partition stays bounded.
Tiering. Messages older than a few months are rarely read. Move them to cheaper storage and load them lazily when the user scrolls.
Replication. 3 replicas across zones with quorum writes (the consistency lesson) so an acknowledged message survives a machine loss.
6.8 Media through object storage
Never push a 5 MB video through a WebSocket gateway; that would block thousands of small messages behind it.
The phone asks the API for an upload URL (a time-limited signed URL pointing at object storage).
It uploads the file directly, in chunks so a drop can resume.
It sends a normal chat message containing the media_id, a thumbnail, and the decryption key (encrypted inside the message).
The recipient downloads the file from object storage, ideally through a CDN.
The chat path only carries tiny references. That is why 200 TB per day of media costs us no extra gateway capacity. For E2EE, the phone encrypts the file before upload, so object storage only holds bytes it cannot read.
6.9 End-to-end encryption (overview)
With E2EE, messages are encrypted on the sender's device and decrypted only on recipients' devices. Our servers store and relay ciphertext (scrambled bytes they cannot read).
Each device generates a key pair (public and private key). The private key never leaves the device. The server stores public keys.
To start a chat, Alice fetches Bob's public key and derives a shared secret (a key only the two devices can compute). Modern protocols (the Signal protocol) then rotate keys per message, so a stolen key exposes only a little.
Groups: the sender encrypts once with a group key and distributes that key to each member's device, or encrypts per member.
What the server still sees: who talks to whom, when, and message sizes (metadata). It cannot search or moderate content.
In an interview, a clear overview is enough: "keys live on devices, servers relay ciphertext, we lose server-side search and backups but gain privacy."
6.10 Presence and typing indicators
Presence is the "online / last seen" status. It looks cheap but is the most expensive optional feature.
text
Naive: every status change pushed to every contact
100M online users x 200 contacts x 1 change per 5 minutes = about 67M updates per second
That would dwarf our whole message traffic (600K per second). Practical rules:
Subscribe, do not broadcast: only users who currently have a contact's chat open (or on screen) receive that contact's presence.
Derive presence from the registry: "online" means a live session exists. We write nothing extra.
Last seen is coarse: update only when the user disconnects, and show "last seen recently" rather than exact seconds.
Typing indicators are ephemeral: sent only to the conversation's online members, rate limited to one every few seconds, never stored, and dropped if the recipient is slow. Losing one is harmless.
Trade-off thinking. Exact, instant presence for everyone is expensive and rarely valuable. Approximate presence, delivered only to those watching, cuts load by orders of magnitude.
6.11 Multi-device sync
Each account has several devices (phone, laptop). The registry holds one session per device, and cursors are tracked per device as well as per user.
A message to Bob is delivered to every online device and queued for offline ones through that device's cursor.
Because history lives on the server as an ordered log per conversation, a brand-new device simply syncs from seq = 0 (or recent history).
Messages Alice sends from her phone must also appear on her laptop: treat Alice's other devices as extra recipients.
With E2EE, the sender encrypts for each recipient device, so adding a device means distributing keys to it.
Read state is merged by taking the maximum last_read_seq across devices, so reading on the laptop clears the phone's badge.
Step 7: Bottlenecks and Failure Handling
Bottlenecks
Gateway memory and connections.Cause: too many sockets per machine. Mitigation: cap near 100K per gateway, autoscale on connection count, and reject new connections gracefully when full.
Registry hot path.Cause: every delivery needs a lookup. Mitigation: partition by user, replicate, cache nothing stale for long, and keep the entry tiny.
Hot conversations.Cause: a giant group or a viral channel. Mitigation: queue-based fan-out, partition buckets, rate limit senders.
Heartbeat load.Cause: 1.7M per second. Mitigation: 60-second intervals, adaptive intervals on cellular, and let the connection itself (TCP keepalive) signal liveness.
Gateway crash. Users reconnect to other gateways with jitter, re-register, and sync from their cursors. No message is lost because everything acked was already stored.
Chat service instance crash mid-send. The phone never got an ack, so it retries with the same client_msg_id. The dedup check stops a duplicate.
Registry node loss. Entries re-fill as heartbeats arrive within a minute. Until then deliveries fall back to push and sync.
Store node loss. Replicas serve reads; quorum writes keep succeeding.
Network partition between phone and server. Phone queues messages locally with their client_msg_ids and sends them in order when it reconnects.
Out-of-order or duplicate delivery. Handled by seq on the client: ignore seen, request gaps.
Poison message that breaks a worker: after retries, move it to a dead-letter queue (a side queue for messages that keep failing) and alert.
What to monitor
Connected sockets per gateway and total (the key business metric).
End-to-end delivery latency p50 and p99 (sent to delivered).
Registry lookup latency and miss rate.
Delivery-queue depth and consumer lag.
Reconnect rate (a spike means a gateway or network problem).
Solid arrows are synchronous requests. Dashed arrows are asynchronous or fallback paths.
Request flow
Send: Alice's phone, load balancer (at connect time), WebSocket gateway, chat service (dedup, sequence, durable write), ack sent back to Alice. Deliver: chat service looks up Bob in the registry, forwards to Bob's gateway and socket, Bob acks delivered, later read, and cursors update. Offline: no session found, notification job queued, Bob syncs from his cursor on reconnect.
Data flow
Messages live in the wide-column store, partitioned by conversation and ordered by seq. Cursors live in memberships. Sessions live in the registry with a TTL. Media bytes live in object storage and only references travel through chat. Push jobs and group fan-out flow through the queue to workers.
Background processing
Fan-out workers for large groups. Push notification workers with batching and backoff. Retention jobs that delete expired relay data and tier old messages to cheap storage. Media thumbnail and virus scanning jobs.
Critical design decisions
Persistent WebSocket connections in a dumb gateway tier, because the server must push.
A session registry (user to gateway), so each delivery touches exactly one gateway.
Per-conversation sequence numbers, for ordering, gap detection and cursor-style acks.
Store once per conversation, track cursors per member, so groups cost one write.
Ack after durable write plus client message id, giving no-loss and no-duplicate behaviour on flaky networks.
Media out of band in object storage, keeping the chat path tiny.
Push as a hint, sync as the guarantee, so notification failures never lose messages.
If time remains, discuss multi-region: keep each conversation's home region, route cross-region deliveries through region-to-region links, and let users connect to the nearest region's gateways.