Architect a Real-Time Direct Messaging Backend
System DesignModel answerLast updated
Design a backend for private two-person messaging that stays durable, ordered and deduplicated, with online and offline delivery, presence, and a justified split between Kafka and Redis.
You are asked to design the backend for a messaging product where two people exchange private text messages in real time.
Scope
- Only direct, person-to-person conversations. Group chats, channels, and threads are out of scope.
- Text messages only. A user may be signed in on several devices at once.
Before drawing anything, state your assumptions about:
- user count and message volume,
- latency targets for online delivery,
- durability and reliability expectations.
Then cover the following in your design
- The main flows for sending a message and for receiving one.
- How messages are stored and how history is fetched.
- Delivery when the recipient is connected.
- Delivery when the recipient is not connected.
- How the system decides whether someone is online.
- Where client sessions and WebSocket connections are tracked, and how they are managed through crashes and deploys.
- Ordering, retries, deduplication, and delivery/read acknowledgements.
- Where Kafka fits, where Redis fits, and the trade-offs between the two.
- The Kafka internals that matter for this design: partitions, per-partition ordering, offsets, and consumer groups.
Expect to justify your choices and discuss failure cases.
Hints
Hint 1
Pick numbers first (daily users, messages per user, concurrent connections) and derive messages per second, gateway count, and daily storage growth from them.
Hint 2
Treat the database as the source of truth and the message bus as only a notification path. That makes the offline case a catch-up read rather than a separate queue.
Hint 3
Give each conversation its own monotonically increasing sequence number and make every acknowledgement a cursor over that sequence, not a per-message status row.
Hint 4
Ask what is lost if Redis or a gateway dies, and what the client does next. Use client-generated message IDs, idempotent writes, and TTL-based session entries to answer.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Assumptions
Scale
- 100M daily active users, about 50 messages each: roughly 5B messages/day, about 60K msgs/s average and about 200K/s at peak.
- About 30M concurrent WebSockets. At about 100K connections per gateway host that is about 300 hosts; provision about 500 for headroom and deploys.
- About 1 KB per message with metadata gives about 5 TB/day before replication.
Latency and reliability
- Online delivery p99 under 300 ms; the sender sees a "sent" ack in under 100 ms.
- Once "sent" is acknowledged, the message is never lost.
- Delivery is at-least-once on the wire; client-side dedup yields exactly-once display.
- Ordering is guaranteed per conversation only, not globally.
- Presence may be a few seconds stale.
2. Interfaces
Real-time traffic goes over a persistent WebSocket: send {client_msg_id, conversation_id, recipient_id, body}, ack {delivered_seq | read_seq}, and a 30 s heartbeat. History and recovery use REST: an inbox listing, paged messages (before_seq, limit), and a sync call taking the last-known seq per conversation.
3. Data model
- Conversation ID is a deterministic hash of the sorted pair of user IDs, so no lookup is needed.
- Messages in a wide-column store (Cassandra/Scylla): partition key
conversation_id, clustering keyseq DESC. "Latest N" is one single-partition read. Bucket by month if a partition grows too large. - Conversation state:
last_seqplus each user'sdelivered_seqandread_seq. Acks are cursors, not per-message rows. - Inbox table keyed by user, sorted by last activity, with a preview for the conversation list.
- Redis (ephemeral only): session map
user -> {device -> gateway, conn}with TTL, presence key with TTL, dedup key(sender, client_msg_id)with a 24 h TTL, and optionally the per-conversation seq counter.
4. Architecture and flows
Client, then load balancer, then a stateful gateway (holds sockets), then a stateless chat service, which writes to the DB and publishes to Kafka (topic keyed by conversation ID). Separate consumer groups handle live delivery, push notifications, and inbox/analytics.
Send
- Client generates a UUID
client_msg_idand sends. - Chat service does an atomic set-if-absent on the dedup key. If it already exists, it returns the original ack.
- It assigns the next
seqfor the conversation (RedisINCR, reseeded from the DB maximum after a failover; per-conversation write rates are tiny, so a compare-and-set on the state row also works). - It writes to the DB at QUORUM, then emits the event and returns "sent".
- The DB write and the Kafka publish are a dual write, so use a transactional outbox or CDC to guarantee that every persisted message eventually produces an event.
Receive, online: the delivery consumer reads the event, looks up the recipient's sessions, calls each hosting gateway, which writes to the socket. The device acks delivered_seq; the server advances the cursor and informs the sender.
Receive, offline: with no live session, the push consumer sends an APNs/FCM-style notification (a preview, collapsed per conversation). On reconnect the client calls sync with its per-conversation seqs and pulls everything newer from the DB. Because the DB is the source of truth, no separate store-and-forward queue is needed. A lost push or lost event only delays delivery until the next sync.
5. Sessions and connections
- Each gateway keeps an in-memory
conn_id -> socketmap. On auth it writes the session entry to Redis with a ~90 s TTL, refreshed on heartbeat and deleted on clean close. - If a gateway crashes, entries expire. Clients reconnect with exponential backoff and jitter (avoiding a thundering herd), re-register, and sync.
- A stale route is handled by the gateway replying "not here"; delivery deletes the entry and falls back to push.
- Routing can be gateway RPC or one pub/sub channel per gateway, never a topic per user.
- Deploys drain connections gradually and send a "reconnect elsewhere" frame.
6. Presence
Online means a presence key exists, set with a ~60 s TTL and refreshed by heartbeats. On expiry record last_seen. To avoid fan-out storms, do not broadcast every change; clients subscribe only to contacts visible on screen, and updates are debounced (about 5 s) to absorb flapping networks.
7. Ordering, retries, dedup, acks
- Ordering: the per-conversation
seqis authoritative and clients render by it. Gaps (for example from a failed write) are tolerated; a client that sees a gap fills it via sync. - Retries: the client resends with the same
client_msg_idwith backoff until it sees "sent". The dedup key makes this idempotent, with a DB uniqueness constraint as backstop. - Receive-side dedup: consumer replays and dual paths (socket plus sync) cause repeats, so clients drop anything with a seq or message ID already seen.
- Acks: sent (durably stored), delivered (device advanced
delivered_seq), read (read_seq). All are monotonic cursors, so they are cheap, idempotent, and tolerate reordering.
8. Kafka vs Redis
| Kafka | Redis | |
|---|---|---|
| Role | Durable, replayable event log; fan-out to independent consumers | Fast ephemeral state: sessions, presence, dedup, counters |
| Durability | Replicated, disk-based | Weak; loss is tolerable by design |
| Latency | Low tens of ms | Sub-ms |
| Weakness | Poor for point lookups and per-key TTLs | Pub/sub is fire-and-forget; no replay |
Use Kafka for the event path and Redis for lookups. Do not use Redis pub/sub as the only delivery mechanism, because a missed message is gone. Do not use Kafka as the message store of record or a session registry.
9. Kafka internals that matter
- Partitions are the unit of parallelism and ordering. Keying by
conversation_idhashes all events of a conversation to one partition, so they stay in order. Choose a generous partition count up front (for example 256 to 1024), because changing it later remaps keys and breaks ordering during the transition. - Ordering is guaranteed only within a partition. That is enough here because we need per-conversation order. Enable idempotent producers (and
acks=all) to avoid duplicates and reordering from producer retries. - Offsets track a consumer's position. Commit after processing, which yields at-least-once; the idempotent client and cursor design absorb replays.
- Consumer groups give each partition to one consumer in the group, scaling horizontally, while different groups (delivery, push, analytics) each get the full stream independently. A rebalance briefly pauses consumption; use cooperative rebalancing.
- A hot partition is unlikely with 1:1 chats, since keys are plentiful and per-key rates low.
Common mistakes
- Treating Kafka as the only copy of messages, or acking "sent" before the DB write.
- Per-message delivery-status rows instead of cursors.
- Using a Redis counter with no recovery plan after failover.
- Ignoring the dual-write problem between DB and Kafka.
- Broadcasting presence to all contacts.
- Forgetting multi-device delivery, and reconnect storms after a gateway failure.