Build a Real-Time Direct Messaging Backend for Millions of Users
System DesignModel answerLast updated
Design a horizontally scalable direct-messaging backend with live delivery, stored history, presence, per-conversation ordering and fault tolerance for 10 million daily users.
Direct Messaging Backend
You are asked to design the backend for a mobile and web messaging app in which two people exchange private text messages. The service must remain responsive as it grows to 10 million daily active users, with messages arriving at the recipient in well under a second.
What users must be able to do
- Send a message to another user and have it appear on their screen almost immediately when they are online.
- Open a conversation and scroll through earlier messages.
- See whether the other person is currently online, or when they were last seen.
Qualities the system must have
- Availability: the loss of one server must not take the service down or lose messages.
- Latency: delivery should feel instant to both parties.
- Ordering: within a conversation between two users, messages must appear in the order they were sent.
- Scale: the design has to hold up at 10M DAU with a large number of simultaneous open connections.
What to cover in your answer
- Capacity estimates that justify your choices.
- API design: the real-time protocol and any request/response endpoints for history, sync and presence.
- Data model: how users, conversations and messages are stored, and why.
- Architecture: how clients, load balancers, connection servers, application services and storage fit together.
- Delivery paths: what happens when the recipient is online, and what happens when they are offline.
- Trade-offs: relational vs. non-relational storage for messages, and at-least-once vs. exactly-once delivery.
Group chats, media, voice/video and end-to-end encryption can be treated as out of scope, though you may mention how the design would be extended.
Hints
Hint 1
Begin with rough numbers: messages per user per day, average and peak write rate, and the number of simultaneous connections. Ask yourself which of these is actually the hardest part to scale.
Hint 2
Split responsibilities: servers that merely hold long-lived connections should be separate from the services that sequence, store and route messages, and you need a fast lookup that says which connection server a given user is attached to.
Hint 3
Think about what makes retries safe and what gives a single, trustworthy order per conversation. A client-generated message ID and a per-conversation sequence number each solve one of those problems.
Hint 4
For offline users, ask what must already be true before the sender is told the message was accepted, and how a returning client can discover what it missed.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify scope and estimate load
Scope: 1:1 text, history, presence. Multi-device, groups and media are later extensions.
Assumptions and results:
| Metric | Estimate |
|---|---|
| DAU | 10M |
| Messages per user per day | ~40, so ~400M messages/day |
| Average write rate | 400M / 86,400, about 4.6K/s |
| Peak (about 5x) | about 25K/s |
| Concurrent connections (~30% of DAU) | ~3M |
| Connection servers (~50K sockets each, 2x headroom) | ~120 |
| Storage (~200 B per message) | ~80 GB/day raw, ~240 GB/day at replication factor 3, ~90 TB/year |
Takeaway: the workload is append-heavy and the write rate is modest. The hard part is keeping millions of long-lived connections alive and routing a message to the right one, not raw throughput.
2. API design
Real-time channel (WebSocket, JSON or protobuf frames):
- Client to server:
send_message {client_msg_id, conversation_id, recipient_id, body},ack {conversation_id, seq, type},heartbeat. - Server to client:
message {conversation_id, seq, sender_id, body, server_ts},send_ack {client_msg_id, seq},receipt {conversation_id, up_to_seq, type},presence {user_id, status, last_seen}.
HTTP endpoints (stateless):
GET /conversations?cursor=for the conversation list with last message.GET /conversations/{id}/messages?before_seq=&limit=50for paginated history.GET /sync?since=for everything missed while offline.GET /presence?user_ids=for bulk presence lookup.
client_msg_id is a client-generated UUID that acts as an idempotency key, so a retried send never creates a duplicate.
3. Data model
- Users (small, rarely changing, needs integrity): a relational DB such as PostgreSQL,
users(user_id, phone, display_name, created_at). - Messages in a wide-column store (Cassandra or ScyllaDB). Partition key is
(conversation_id, bucket), wherebucketis e.g. a month to cap partition size, clustered byseqdescending. Columns:sender_id, client_msg_id, body, server_ts. Theconversation_idis deterministic, e.g. a hash of the sorted pair of user IDs, so both sides resolve to the same conversation. - Per-user inbox:
user_conversations(user_id, conversation_id, last_seq, last_read_seq, updated_at). This powers the conversation list and gives each client a cursor for sync. - Session registry and presence in Redis:
session:{user_id} -> gateway_idandpresence:{user_id} -> {status, last_seen}, both with TTLs.
History for a conversation is then one sequential read of an already sorted partition.
4. Architecture
Clients connect over WebSocket through an L4 load balancer to a fleet of gateways. Gateways only terminate connections and hold no durable state. Behind them sits a stateless chat service that validates, sequences, persists and routes. It uses Kafka (partitioned by conversation_id) as a durable, ordered buffer, Cassandra for messages, Redis for sessions and presence, and a push service (APNs/FCM) for offline users.
If a gateway dies, its clients reconnect to another and sync from their last known seq. If a chat service instance dies, another picks up its Kafka partitions.
5. Message flow
- Alice sends
send_messagethrough her gateway. - The chat service dedupes on
(conversation_id, client_msg_id)and assigns the nextseq. - It persists before acknowledging: write to Kafka, then the message store, and update
last_seqfor both users. - It returns
send_ackto Alice (single check mark). - It looks up Bob's session in Redis:
- Online on another gateway: forward over internal RPC or pub/sub, the gateway pushes it down Bob's socket, Bob's client acks, and a delivered receipt goes back to Alice.
- Offline: nothing is lost because the message is already durable. Send a push notification. When Bob reconnects, his client calls
/syncwith its last seenseqper conversation and receives the gap.
- If an online delivery is not acked within a timeout, retry; if the session turns out to be stale, fall back to push plus sync.
Ordering comes from three things together: a single writer per conversation (Kafka partitioning), a monotonic per-conversation seq, and clients that render by seq rather than by arrival time or device clock. A gap in seq triggers a fetch.
Presence: clients heartbeat about every 30 seconds, and the server refreshes a key with a ~60 second TTL. Expiry means offline and records last_seen. Do not broadcast every status flip to all contacts. Push updates only to users who currently have that chat open, and let others fetch lazily.
6. Trade-offs
SQL vs. NoSQL for messages. Messages are append-only, read by key range (conversation plus seq), never joined, and reach tens of TB per year. A Cassandra-style store scales writes linearly, replicates (RF=3 with LOCAL_QUORUM) and has no single point of failure. The cost is weak cross-partition transactions, which this workload does not need. Keep user and account data in SQL.
At-least-once vs. exactly-once. True exactly-once over flaky mobile networks is impractical. Use at-least-once delivery with idempotent handling: senders retry with the same client_msg_id and the server dedupes, and receivers dedupe on (conversation_id, seq). Users experience this as exactly-once.
Other trade-offs:
- Stateful gateways complicate deploys. Use connection draining and jittered client reconnects to avoid thundering herds.
- Persist-before-ack costs a few milliseconds but guarantees no acknowledged message is lost.
- A hot conversation is bounded by two users, so partition skew is not a real concern here.
7. Common mistakes
- Using client clocks for ordering.
- Acknowledging before the message is durable.
- Polling instead of persistent connections.
- Broadcasting presence changes to every contact.
- Claiming exactly-once delivery without explaining deduplication.
- Treating the gateway as the source of truth for messages instead of keeping it stateless.
8. Extensions
Multi-device (track a cursor per device), groups (fan-out on write for small groups, on read for large ones), media (object storage plus signed URLs), and end-to-end encryption (store only ciphertext).