Build a Reliable Private Messaging Backend for Two-Person Chats
System DesignModel answerLast updated
Design a backend for private two-person chats that stores messages durably, keeps them in order, tolerates retries, replays to offline devices, and restricts access to participants.
Private Two-Person Messaging Service
You are asked to design the backend for a messaging product in which exactly two users talk to each other privately. Walk through how messages are sent, stored, fetched, ordered, and delivered to people who are online or offline. Also describe how read state works, how retries are handled, and how the system recovers from failures.
Be explicit about what the service promises when a client reconnects after a drop or sends the same request twice.
Assumptions
- Every conversation has exactly two participants.
- Text content is stored and retained. Large attachments are handled elsewhere and are not part of the core path.
- A user can be signed in on several devices, and any device may be offline for a long time.
- Ordering across different conversations is not needed.
- Anyone who is not a participant must never be able to read a conversation.
Questions worth raising with the interviewer
- Is total order needed inside a conversation, or only per sender?
- Are delivery and read receipts in scope?
- What are the retention and deletion rules?
- What are the expected peak send rate and reconnect surge?
Part 1: API and data model
Define the entities (conversation, message, participant, cursor, receipt) and the APIs for sending and fetching history.
Points to address: client-generated deduplication keys, per-conversation sequence numbers, authorization on every read and write, and cursor-based pagination.
Part 2: Delivery and consistency
Describe the durable write path, the real-time push path, recovery for offline devices, synchronization across a user's devices, and how duplicates are handled.
Points to address: store before acknowledging, at-least-once delivery with client-side deduplication, ordering and resume cursors, and keeping receipts separate from message durability.
Part 3: Scale and failure handling
Cover partitioning, very active conversations, WebSocket gateway design, backpressure, regional outages, and monitoring.
Points to address: a stable partition key, bounded fan-out, stateless gateways with resumable sessions, protection against lag and slow clients, and reconciliation after partial failures.
Hints
Hint 1
Make the send call safe to repeat: the client generates a unique key per message, and the server returns the already-stored message if it sees that key again.
Hint 2
Give each conversation its own monotonically increasing sequence number assigned at write time. Clients resume from 'last sequence I have seen' instead of relying on timestamps.
Hint 3
Treat the database as the source of truth and the live push as an optimization. If a push is lost, the client's next catch-up fetch from its cursor must repair it.
Hint 4
Partition by conversation ID so one conversation's writes stay ordered on one shard, and think about what happens when a single conversation is unusually busy or a client cannot keep up.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach in one paragraph
Treat the durable log of each conversation as the source of truth. Every message gets a per-conversation sequence number when it is committed. Sends are idempotent through client-supplied keys. Real-time push is a best-effort accelerator, and every device recovers by asking for "everything after sequence N". This gives at-least-once delivery, deduplicated on the client, and effectively exactly-once visible results.
Clarifying assumptions
I would state: strict order within a conversation, per-device delivery and read receipts, retention configurable per product (default: keep until user deletes), and a rough scale such as 100M daily users, 50k sends/s average and 3x at peak. Since there are only two participants, fan-out per message is small: at most the recipient's devices plus the sender's other devices.
Part 1: Data model and APIs
Entities
conversation(conversation_id, user_a, user_b, created_at, last_seq). For two-person chats, derive a deterministic ID from the sorted user pair so the same pair never creates two conversations.message(conversation_id, seq, sender_id, client_msg_id, body, created_at). Primary key is(conversation_id, seq). A unique index on(conversation_id, sender_id, client_msg_id)enforces deduplication.participant_state(conversation_id, user_id, last_delivered_seq, last_read_seq). This is the per-user cursor and read state.device_cursor(user_id, device_id, conversation_id, last_acked_seq), needed for multi-device catch-up.- Receipts are folded into the cursors: "read up to seq N" is one monotonic number, not one row per message.
APIs
POST /conversations/{id}/messageswithclient_msg_idandbody. Returns{seq, created_at}.GET /conversations/{id}/messages?after_seq=N&limit=50for catch-up, and?before_seq=Nfor scrolling back. Cursors are sequence numbers, so pagination is stable even while new messages arrive.POST /conversations/{id}/readwithup_to_seq. Only moves forward.- Every call checks that the authenticated user is one of the two participants. Authorization is enforced in the service layer, not only at the gateway, and WebSocket subscriptions are re-checked at subscribe time.
Part 2: Delivery and consistency
Write path
- Gateway authenticates and routes to the shard that owns the conversation.
- The shard, in one transaction, checks the dedup key, increments
last_seq, and inserts the message. If the key exists, return the previously storedseq(idempotent retry). - Only after commit, acknowledge the sender with
seq. - Publish a "new message" event (via a transactional outbox or change stream so it cannot be lost between commit and publish).
Because the sequence is allocated inside the owning shard, there is one writer per conversation at a time, which gives a total order without global coordination.
Live delivery
A push service consumes the event and sends it to every connected device of the recipient, and to the sender's other devices. Devices acknowledge with the highest contiguous seq they have applied. If a device sees a gap (receives seq 12 after 10), it asks for the missing range instead of rendering out of order.
Offline and reconnect
Nothing special is queued per device. On reconnect the device sends its cursor per conversation (or one global sync token) and the server replays everything after it. This is naturally bounded and idempotent. For very long absences, return a summary (conversation list with latest seq and unread count) first and load history lazily.
Duplicates
- Client retries are absorbed by the unique dedup key.
- Duplicate pushes are absorbed by the client, which ignores any
seqit already holds. - Result: at-least-once on the wire, once in the UI.
Receipts
Delivery and read receipts are derived from cursor updates and sent as lightweight events. They are eventually consistent and never block message durability. A lost receipt is repaired by the next cursor update. Cursors only move forward, so reordering is harmless.
Part 3: Scale and failures
Partitioning. Shard by conversation_id (consistent hashing). All messages in a conversation sit together, giving ordered range scans. A wide-column or sharded SQL store works; the access pattern is "append and range-read by seq". Index by user for the inbox list, stored separately (user-keyed table) and updated asynchronously.
Hot conversations. With two participants, true hotspots are rare, usually bots or abuse. Apply per-sender rate limits and per-conversation write limits. If a shard is hot overall, split by moving conversation ranges, not by splitting a conversation.
Gateways. WebSocket gateways are stateless apart from the connection. A presence/routing map (user, device → gateway) lives in a fast store with TTLs. If a gateway dies, devices reconnect to another one and resume from their cursor. No server-side session state is needed beyond that map, and a stale map entry only causes a missed push, which catch-up repairs.
Backpressure. Each connection has a bounded send buffer. If a client is slow, stop pushing, mark the device as "needs sync", and let it pull when ready. Queue consumers are monitored for lag, and push can degrade to "notification only" (a tiny wake-up) under load, because the store has the data.
Regional failure. Replicate the log synchronously within a region (quorum) and asynchronously across regions. On regional loss, failing over may lose the most recent unreplicated messages. If that is unacceptable, use a conversation "home region" and accept a higher write latency for cross-region synchronous replication. State the trade-off explicitly: the sender only received an ack after commit, so on failover reconcile by having clients resend any unacked or unconfirmed messages, which dedup keys make safe.
Observability. Track send latency (p50/p99), commit failures, outbox-to-delivery lag, push success rate, reconnect rate, sequence gaps detected by clients, and dedup hit rate. Run a reconciliation job comparing outbox events to committed messages and comparing cursors to last_seq to find stuck or inconsistent conversations.
Trade-offs and common mistakes
- Using timestamps for ordering. Clock skew breaks it. Use per-conversation sequence numbers.
- Acknowledging before persisting. A crash then loses a message the user thinks was sent.
- Treating push as the source of truth. Always make catch-up from a cursor the recovery path.
- Per-message receipt rows. Expensive and unnecessary; one monotonic cursor suffices.
- Global ordering. Costly and unneeded; order only within a conversation.
- Checking authorization only on connect. Re-check on each read, write, and subscription.
- Exactly-once claims. Be honest: it is at-least-once plus deduplication.
Possible follow-ups
End-to-end encryption (server stores ciphertext, per-device keys, and sequence numbers remain server-assigned metadata), message edits and deletes (as new events referencing a seq), and search (a separate asynchronous index).