Mock design: chat system

Lesson 2.2 · 18 min read · by Vinay C

We'll cover the following

Visual summary

Infographic summarizing Mock design: chat system: Prompt: "Design a chat system: 1:1 and group chat, 500M daily active users, groups up to 1,000 members, media,…

Download imageFree to share, please link back to this lesson.

Prompt: "Design a chat system: 1:1 and group chat, 500M daily active users, groups up to 1,000 members, media, end-to-end encrypted, global with EU and India data residency." This lesson follows the order from the Interview framework lesson: requirements (ACTORS, then SCALED), estimates, APIs and data model, boxes, deep dive, then where it breaks at 10x.

Say the hard part early

What makes this problem special: every conversation needs its own ordering and no-loss guarantee, the content is end-to-end encrypted so the server only ever sees ciphertext, and push is only a hint to wake a sleeping phone, never a carrier of the message. Say this after the requirements and keep all three in view through the design.

MinutesStep and what you produce
0-7Requirements. Two columns on the board, an out-of-scope list, the guarantees said aloud.
7-12Estimation. QPS, text and media storage, concurrent connections, gateway count.
12-18APIs and data model. Connection protocol, HTTP endpoints, tables and keys.
18-28High-level design. Gateway, conversation shard, presence, push, media, regions.
28-40Deep dive. Ordering and no-loss, encryption, group fan-out.
40-45Bottlenecks at 10x. What breaks first, what to monitor.

Step 1: Clarify requirements

State your assumptions with numbers first, then ask the questions in two columns: functional (ACTORS) and non-functional (SCALED).

Functional (ACTORS)

LetterAsked and agreed
ActorsWho uses it? Logged-in end users on phones, each with up to a few devices. No admin or bot users in v1.
Core flowsWhat must it do? (1) Send and receive 1:1 and group messages. (2) Send media. (3) Sent, delivered and read status. (4) Catch up after being offline. Most important: reliable, ordered text.
TriggersHow does work start? A user action over a persistent connection. Opening the app triggers a sync. A push wakes a sleeping phone.
OutputsWhat comes back? Messages appear in the same order for everyone in the conversation, with ticks for sent, delivered and read. Real time when online; a local notification when woken by push.
RulesWhich business rules? Only members can post. Groups have at most 1,000 members. Media has a size cap (say 16 MB). The server keeps messages for up to 30 days, then deletes them.
ScopeWhat is in and out? In: 1:1, groups, media, receipts, offline catch-up. Out (say it aloud): voice and video calls, stories, server-side search, cloud backup, bots, huge broadcast channels, edit and delete-for-everyone.

Non-functional (SCALED)

LetterAsked and agreed
SecurityWhat is sensitive? End-to-end encrypted, no backdoor: the server stores only ciphertext and minimal metadata. Devices authenticate with a device-bound token. Abuse reports are sent from the device, not read by the server.
CountHow big? 5B messages a day, ~50K/s average, ~150K/s peak, ~200M concurrent connections, ~1 PB of media a day. Worked out in Step 2.
AvailabilityWhat must never go down? Sending and receiving survive the loss of a gateway, a shard replica or a zone. A region outage may degrade that region but must not lose acked messages. Receipts and presence may degrade first.
LatencyWhich flows are time-critical? Online delivery under 500 ms at p99. Media upload and catch-up sync can take longer.
ExactnessCan we lose, duplicate or reorder? No loss after the ack. Same order for everyone in a conversation. Delivery is at-least-once; duplicates are removed by id, so each message shows once.
DependenciesThird parties, cost, compliance? APNs and FCM are best-effort wake-ups with their own limits. Media storage and CDN are the largest cost. EU and India residency constrains where data and replicas live.

Step 2: Estimation

Turn the volumes into rates. Use powers of ten, and keep media in the picture.

QuantityCalculation
Messages500M users × 10 per day = 5B per day
Average QPS5B / 10^5 s = ~50K per second (58K exact)
Peak QPS2-3x average = ~150K per second
Text5B × 100 B = 500 GB per day (more with ciphertext and metadata)
Media10% of 5B = 5×10^8 images × 2 MB = 10^15 B = ~1 PB per day raw
Media kept1 PB per day × 30 days = ~30 PB if all of it is kept
ConnectionsDAU is not concurrent. Peak is 30-50% of 500M = ~200M connections
Gateways200M / ~200K per box = ~1,000 boxes (1,200-1,500 with redundancy)
Group sendOne message to 500 members = up to 500 deliveries. Count sends and deliveries separately.

Three conclusions. Text is small, and media dominates storage by about 2,000x, so never leave it out. Connections, not QPS, decide the gateway fleet. And fan-out multiplies deliveries, which is why group size is capped. Also remember that plaintext size is not stored size: add ciphertext overhead and metadata.

Step 3: APIs and data model

Real-time traffic uses one persistent WebSocket per device. Everything that is not latency-critical uses plain HTTP.

Over the socket

  • Client sends send with conversation_id, client_msg_id, ciphertext, type and an optional media_ref. The client generates client_msg_id, so a retry is safe.
  • Server replies sent with client_msg_id and seq. The message is stored on a majority of replicas: one tick.
  • Server pushes message with conversation_id, seq, sender and ciphertext to an online recipient.
  • Client sends ack with conversation_id and seq once it has the message (the double tick), and read with up_to_seq. Each one moves the device cursor forward.
  • On connect the client sends sync with its cursors, and the server replays everything after them.

Over HTTP

  • POST /v1/media/uploads returns a pre-signed URL. The client encrypts the file with a random key, uploads the blob, and sends the key inside the message.
  • GET /v1/conversations/{id}/messages returns a page of messages after a given after_seq. Paged catch-up for long gaps.
  • POST /v1/conversations creates a group.
  • POST /v1/devices registers a device with its push token and public key.
  • GET /v1/users/{id}/keys fetches a recipient's public keys.
TableKey and fieldsStore and why
messagesKey (conversation_id, seq). Fields: ciphertext, client_msg_id, sender, type, media_ref, 30-day TTL.Wide-column store partitioned by conversation. Stored once per conversation, never once per recipient.
conversationsKey conversation_id. Fields: type, members, owner shard, home region.Small and strongly consistent. Membership changes need ordering too.
device_cursorKey (user, device, conversation). Field: last acked seq.Key-value. This is what makes replay exact.
devicesKey (user, device). Fields: push token, public key, last seen.Key-value, cached. Read on every offline delivery.
presenceUser and device to gateway, with a TTL.Redis. Cheap, rebuildable, never the source of truth.
media blobsBlob keyed by id, with a TTL.Object store plus CDN. The server cannot read it, because the key is inside the encrypted message.

Step 4: High-level design

Now draw the boxes. Here is the whole picture, then the same flow in words. The numbers on the diagram match the numbered list below.

Architecture diagram with seven numbered steps. Alice's phone connects through GeoDNS and a load balancer to Gateway 1 over a WebSocket (step 1). Gateway 1 routes to the conversation's shard leader, which assigns a sequence number and replicates to follower replicas until a majority has it (steps 2 and 3, the hard part). The replicas persist to a message store and a cursor store. The leader looks up Bob in a presence registry and forwards the message to Gateway 2, which delivers it to Bob's phone (step 4). If Bob is offline, the leader asks the push service for a content-free wake-up (step 5). Bob's phone reconnects and syncs from its cursor (step 6). Media goes separately through a media API, an object store and a CDN, with the key inside the message (step 7).
High-level design. One owner per conversation, push is only a wake-up, media is a separate path. Open full size
  1. Alice's phone encrypts the message and sends it over its WebSocket. GeoDNS and the load balancer put her on the nearest region and Gateway 1, which holds the connection.
  2. Gateway 1 looks up which shard owns this conversation and forwards the message to that shard's leader. Any gateway can reach any shard.
  3. The leader assigns seq, copies the message to the replicas, and acks Alice (one tick) once a majority has it. This is the hard part: one owner gives one order, and a majority gives no loss after the ack. Messages and per-device cursors are stored once per conversation.
  4. Delivery. The leader asks the presence registry which gateway holds Bob, and forwards the message to Gateway 2, which pushes it down Bob's WebSocket. Alice and Bob can be on different gateways.
  5. Offline. If Bob is not connected, the leader asks the push service for a content-free wake-up. The message itself is already stored.
  6. Sync. Bob's phone reconnects with its cursor (say 41), the shard replays 42 onward, Bob decrypts locally and acks, and Alice sees two ticks.
  7. Media takes a separate path: the phone gets a pre-signed URL from the media API, uploads an encrypted blob to the object store, and recipients download it from the CDN. The key travels inside the message.
Sending to a recipient who is offline

Sequence between Alice phone, a gateway, the conversation shard, the push service and Bob phone. Alice sends an encrypted message to the gateway, which forwards it to the conversation shard. The shard assigns the next sequence number, replicates it to a majority and acks, so Alice sees one tick. Bob is offline, so the shard asks the push service for a content-free wake-up. Bob phone wakes, connects and sends its cursor 41. The shard replays message 42, Bob acks and Alice sees two ticks.

Alice phoneencrypts for Bob
GatewayWebSocket
Shardowner of the conversation
APNs / FCMwake-up only
Bob phonewas asleep
  1. Send and save
  2. Alice phone → Gatewaysend(ciphertext, client_msg_id)
  3. Gateway → Shardforward to the owner of this conversation
  4. ShardAssign seq=42, replicate to a majority
  5. Shard → Alice phoneack: one tick
  6. Bob is offline
  7. Shard → APNs / FCMcontent-free wake-up for Bob devices
  8. APNs / FCM → Bob phonewake the app
  9. Bob syncs
  10. Bob phone → Shardconnect with cursor 41
  11. Shard → Bob phonereplay seq=42
  12. Bob phoneDecrypt locally, show notification text
  13. Bob phone → Shardack 42
  14. Shard → Alice phonedelivered: two ticks
Single tick
The message is stored on a majority of replicas.
Double tick
The receiver device has acked, which is the only proof of delivery.

Step 5: Deep dive on the hard parts

You will not cover everything below in 12 minutes. Start with ordering and no-loss, then encryption, and give the rest one sentence each unless the interviewer pulls you in.

5a. Ordering and no-loss

  • Do not order by timestamp. Clocks disagree. The owning shard assigns a per-conversation seq, and everyone sees messages in seq order.
  • Store before you decide who is online. The shard writes the message and replicates it to a majority, then acks the sender. A recipient who looked offline, or went offline a moment later, still gets it.
  • Retries are safe. If an ack is lost, the client resends with the same client_msg_id and the shard returns the existing seq instead of creating a duplicate.
  • Delivery is proven by the device ack, not by the socket write. Each device has a cursor, so a reconnect with cursor 41 replays 42, 43 and so on. See Ordering, acks and delivery guarantees.
  • Say it plainly: ordering and acked messages need consistency. A blanket "availability over consistency" answer is wrong here.

5b. End-to-end encryption

  • The sender encrypts to the recipient's public key, and only the recipient's device holds the private key. Do not reverse the roles. The server sees only ciphertext.
  • Never put message text in the push payload. Push carries a content-free wake-up. The phone connects, syncs, decrypts locally and builds the notification text itself.
  • Groups: encrypt once with a shared group (sender) key and distribute that key to each member device, instead of encrypting 1,000 copies. Rekey when membership changes.
  • Multi-device: each device has its own key pair and its own cursor, and the sender encrypts for every recipient device.
  • Keys, groups and rotation are covered in End-to-end encryption and key management.

5c. Group fan-out and presence

  • One ciphertext, one seq per group message. Look up each online member's gateway in the presence registry, group members by gateway, and send one batch per gateway.
  • Offline members get a content-free push, then cursor sync later.
  • Cap group size (1,000), because every send multiplies into deliveries.
  • Presence is a hint. If the registry is stale, the cost is one wasted delivery attempt, because the message is already stored and cursor sync is the backstop.

5d. Media

  • The message carries only a reference and the decryption key. The blob goes to object storage through a pre-signed URL, so the shards never carry bytes.
  • Uploads are chunked and resumable. Orphan blobs from abandoned uploads are cleaned up by TTL.
  • Because every blob uses its own key, the server cannot deduplicate identical media. Accept that cost, and cut it by resizing and compressing on the client.

5e. Regions and residency

  • Each user has a home region (EU and India stay local). A conversation's owner lives in one region.
  • Replicate synchronously across zones, so an ack means durable, and asynchronously across regions. Say what the async gap does to the recovery point.
  • Data of an EU or India user is only replicated to regions that are allowed to hold it.
  • A conversation between an EU user and an India user needs a stated rule for where its data lives. Say that out loud.
Check yourselfA message was acked to the sender with one tick, then the shard's primary crashed. Is the message lost?

No. The ack is sent only after the message is stored on a majority of replicas. A replica becomes the new owner, the recipient syncs with its cursor and gets the message, and if the sender retried with the same client_msg_id the shard returns the existing seq instead of creating a duplicate.

The four what-ifs, per box

Once the boxes exist, ask four questions of each one: what if it is slow, down, duplicated, or 100x bigger? This is the part candidates skip.

Gateway

  • Slow: shed idle connections and apply backpressure per socket.
  • Down: clients reconnect to another gateway with backoff and jitter, so there is no reconnect storm. Cursor sync fills the gap.
  • Duplicated: a repeated frame is dropped by client_msg_id and seq.
  • 100x: add gateways, ~200K connections per box.

Conversation shard

  • Slow: the client times out and retries with the same client_msg_id.
  • Down: a replica takes over by consensus. Only majority-stored (acked) messages are promised.
  • Duplicated: client_msg_id returns the existing seq.
  • 100x: shard by conversation id, and cap group size to avoid a hot partition.

Presence registry

  • Slow: fall back to push plus cursor sync.
  • Down: rebuild from gateway reconnects. Nothing is lost, because it is only a hint.
  • Duplicated: last write wins, and the TTL expires stale entries.
  • 100x: shard by user id, and use one lease per gateway instead of per-user heartbeats.

Push service

  • Slow: the wake-up arrives late. The next app open syncs anyway.
  • Down: messages wait in the store and sync on the next connect.
  • Duplicated: a second wake-up is harmless because it has no content.
  • 100x: batch per device and collapse wake-ups per conversation.

Media store

  • Slow: resumable, chunked uploads.
  • Down: retry the upload. The message is not sent until the blob is stored.
  • Duplicated: an orphan blob, removed by TTL.
  • 100x: object storage scales. Control cost with compression and retention.

Step 6: Where it breaks at 10x

Name the bottleneck, then the fix. Say it before the interviewer asks.

  • Media storage and egress. ~10 PB a day raw is the biggest cost line. Levers: client-side compression, a shorter retention for media, and deleting a blob once every recipient has acked it.
  • Presence heartbeats. 200M connections refreshing a TTL every 30 seconds is ~6.7M writes per second, and 10x makes it worse. Write presence on connect and disconnect, and let each gateway hold one lease for all its connections instead of per-user heartbeats.
  • Connections. ~2B concurrent connections is ~10,000 gateways. Connection setup is expensive (TLS plus auth), so protect it with reconnect backoff and connection-draining deploys.
  • Hot conversations. A huge group concentrates writes on one shard. Keep the cap, and shard the delivery fan-out separately from the ordering.
  • Shard rebalancing. Use consistent hashing, so adding capacity moves only a small share of conversations.

Monitoring, next steps and trade-offs

What I would monitor

  • Send-to-ack latency and send-to-delivery latency at p50, p99 and p99.9.
  • Gateway connection count, reconnect rate and error rate.
  • Replication lag per shard and per region, and the invariant that there are no seq gaps.
  • Undelivered backlog per cursor (how far behind devices are) and the push failure rate.
  • Media upload failure rate, storage growth and per-region capacity.

What I would build differently with more time

  • Server-side search is impossible under E2EE, so build on-device search and encrypted backup with a user-held key.
  • Better multi-device linking and key verification (safety numbers).
  • Abuse handling without reading content: reports sent from the device, rate limits on new accounts and bulk sending.
  • A staged rollout for protocol changes, because clients upgrade slowly and both versions must work.

Trade-offs to say aloud

  • One owner per conversation gives total order and simple dedupe, at the cost of a failover pause when the owner moves.
  • Store-then-deliver adds a write to the latency path, but it is the only way to promise no loss after the ack.
  • E2EE means no server-side search or media dedupe, and a harder multi-device story. That is the price of "no backdoor".
  • Async cross-region replication keeps latency low but widens the recovery point.

Common mistakes in this design

  • Reversing the key roles in end-to-end encryption.
  • Ordering by timestamp, or answering with a blanket "availability over consistency".
  • Deciding whether the recipient is online before storing the message.
  • Putting message text in the push payload.
  • An arithmetic slip that is off by 1000x, an assumed 95% concurrency, or forgetting media (about 1 PB per day).
  • Leaving no-loss and ordering out of the non-functional requirements. They are the heart of a chat system and must be stated up front.

Where the general lessons live

  • Keys, groups and media: End-to-end encryption and key management.
  • Order, acks, duplicates, cursor replay: Ordering, acks and delivery guarantees.
  • Waking a sleeping phone: Protocols, real-time options and pagination.
  • The arithmetic traps: Back-of-envelope estimation.

Summary: say it in the interview

  • "I will assume 500M daily users sending about 10 messages each a day, 10% of them with an image of about 2 MB, and each user having a few linked devices. Tell me if any of that is off."
  • Say the guarantees out loud: "no loss after the ack, one order per conversation, and the server cannot read content." They drive every later choice.
  • "What made this problem special? Ordering and no-loss per conversation, end-to-end encryption, and a push that is only a hint."