Build a Persistent Real-Time Messaging Service with Reliable Sync
System DesignModel answerLast updated
Design a text messaging service where conversations are stored durably, messages arrive live, and clients recover cleanly from disconnects, retries, and duplicate events.
Design a messaging service in which users exchange text messages in real time and can later reopen any conversation to see its full history.
Walk through each of the following:
- Client state: what the app keeps locally, and how it shows a message before the server has confirmed it.
- APIs: the requests and events needed to send messages, load history, and sync.
- Delivery path: how a message travels from sender to recipients, and what "sent" and "delivered" mean in your design.
- Reconnect behavior: how a client that was offline or briefly disconnected catches up without losing or duplicating messages.
The requirements leave several things open: conversation size, encryption, attachments, and delivery guarantees. Begin by stating a bounded initial scope (for example, text only, small conversations), then explain how the design would grow beyond it.
Questions you should settle or call out as assumptions:
- What ordering guarantee is needed inside one conversation?
- Are edits, deletes, and read receipts in scope?
- How do offline clients catch up?
- What exactly distinguishes sent from delivered?
Hints
Hint 1
Give every conversation its own monotonically increasing sequence number assigned by the server. It can serve as the ordering key, the pagination cursor, and the reconnect checkpoint.
Hint 2
Let the client generate a unique ID for each outgoing message, so a retried send can be recognized and de-duplicated on the server.
Hint 3
Treat the persistent store as the source of truth and the real-time channel as a hint. After any reconnect, the client asks for everything after its last known sequence number.
Hint 4
Define a clear state progression for each message (pending, sent, delivered, read) and decide which component is responsible for each transition.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Scope
Start with text-only messages, 1:1 chats and small groups (up to about 100 members), and per-conversation ordering. Delivery is at-least-once on the wire, and the client de-duplicates so users see each message exactly once. End-to-end encryption, attachments, and huge channels are deferred, with a note on how each would be added.
Core data model
- users:
user_id, profile. - conversations:
conversation_id, type,last_seq. - memberships:
(conversation_id, user_id), role,last_read_seq. - messages: primary key
(conversation_id, seq), plusmessage_id(server),client_msg_id,sender_id,body,created_at.
A unique index on (conversation_id, sender_id, client_msg_id) enforces idempotency.
The key idea is a per-conversation sequence number. Global ordering is unnecessary and expensive. Within one conversation, a single monotonically increasing seq gives a total order, a pagination cursor, and a sync checkpoint. Wall-clock timestamps are for display only, since clocks drift.
A wide-column store partitioned by conversation_id and clustered by seq fits well. A relational database sharded by conversation_id also works at moderate scale.
APIs
POST /conversations/{id}/messageswith{client_msg_id, body}returns{seq, message_id, created_at}. A retry with the sameclient_msg_idreturns the original result.GET /conversations/{id}/messages?before_seq=N&limit=50for scrolling back, and?after_seq=Nfor catch-up. Cursor pagination onseqis stable even while new messages arrive, unlike offset pagination.GET /sync?cursors=...or per-conversationafter_seqcalls to refresh a list of conversations.POST /conversations/{id}/readwith{up_to_seq}.- A persistent WebSocket (with long-polling fallback) carries server-pushed events:
message.new,receipt.update.
Every call is authenticated, and the server verifies membership before reading or writing.
Send and delivery path
- The client creates
client_msg_id(a UUID), appends the message locally with state pending, and renders it immediately (optimistic UI). - It sends the message over the socket or HTTP to a gateway, which routes to the chat service.
- The chat service checks membership, then atomically allocates
seq(incrementlast_seqon the conversation partition, or use a per-partition single writer) and writes the message. A duplicateclient_msg_idhits the unique index and returns the existing row. - After the durable write succeeds, the service acks the sender with
seq. The client moves the message to sent and replaces its temporary ordering with the realseq. - The service publishes the message to a pub/sub layer (for example a partitioned log or Redis streams) keyed by conversation. Gateways holding sockets for the other members consume it and push
message.new. - The recipient client acks receipt, and the server records delivered. When the user views the thread, the client sends
read up_to_seq, producing read.
For offline users, the message is already stored. Optionally a push notification (APNs/FCM) is sent, carrying only a wake-up hint, not trusted content.
Definitions: sent means durably stored by the server. Delivered means at least one of the recipient's devices acknowledged it. Read means the user's last_read_seq has advanced past it. Persist before publish, so a published event never refers to a lost message.
Client state
Per conversation, the client keeps an ordered list keyed by seq, a map of pending messages by client_msg_id, and last_seen_seq. Incoming events are applied idempotently: if seq is already present, ignore it. If the event's seq is greater than last_seen_seq + 1, a gap exists, so fetch the missing range instead of guessing. A failed send shows a retry control, and retries reuse the same client_msg_id.
Reconnect and catch-up
The real-time channel is best effort, and the database is authoritative. On reconnect:
- Re-authenticate and open the socket.
- For each active conversation, call
after_seq=last_seen_seq, page until caught up, and merge idempotently. - Resend any still-pending messages with their original
client_msg_id. - Then resume live events. Subscribe first and then fetch, de-duplicating by
seq, so nothing falls between the fetch and the subscription.
Use exponential backoff with jitter on reconnect to avoid thundering herds after a gateway restart. Heartbeats detect dead connections.
Scaling and trade-offs
- Gateways are stateless apart from socket mappings. A presence/routing table (user to gateway) lets the pub/sub layer target the right nodes.
- Hot conversations: single-writer-per-conversation keeps seq allocation simple. Very large channels need fan-out-on-read (clients pull) rather than pushing to every member.
- Multi-device: each device tracks its own
last_seen_seq; read state is per user. - Storage: roughly 100 bytes of metadata plus the body per message. At 1B messages per day that is on the order of 200 GB per day, so plan for partitioning and tiered storage of old history.
- Edits/deletes: model them as new events with their own
seqthat reference the target, so sync stays append-only. - Encryption would move ciphertext through the same pipeline, but server-side search and previews are lost.
Exactly-once delivery is not achievable over an unreliable network, so combine at-least-once delivery with idempotent writes and client de-duplication.
Common mistakes
- Ordering by client or server timestamps, which breaks under clock skew.
- Using offset pagination, which shifts as new messages arrive.
- Treating the WebSocket as the source of truth, so missed events are never recovered.
- No client-generated ID, so retries create duplicate messages.
- Publishing before the durable write, so recipients can see messages that later vanish.
- Skipping membership checks on history fetches.