Building a Durable Messaging Backend: Endpoints, Schema, Sync
System DesignModel answerLast updated
Design the endpoints, data model, and core flows of a basic messaging service with durable sends, safe retries, ordered history, live push, and catch-up after a dropped connection.
You are asked to design the backend core of a simple messaging product. Focus on three things: the public API, the database model, and the main flows. Do not spend time on global scale or invented traffic numbers.
Scope and assumptions
- Users are authenticated. Messages are durable text stored inside conversations.
- State clearly whether you support one-to-one conversations, group conversations, or both, and design accordingly.
- A send counts as successful once the message is durably stored. Treat delivered to a device and read by a user as separate states, not part of "sent".
- Media attachments, end-to-end encryption, search, and very large scale are optional extensions that would need extra requirements.
- No latency SLA or traffic target is given. Aim for a coherent baseline.
Questions worth raising with the interviewer
- Can membership change over time, and should a newly added member see older messages?
- Must messages be ordered within a conversation? What should a retry do after a send times out?
- Are delivered and read receipts required, or only durable sends plus history?
- Should live events reach every device a user is signed in on?
Part 1: API contract
Define endpoints to create (or join) a conversation, send a message, and fetch history. Cover authentication, membership checks, pagination, and retry behavior.
Your answer should include:
- Identifiers for conversations and messages, plus who is allowed to do what.
- A client-generated idempotency key so a retried send does not duplicate.
- Stable pagination for history, and a clear line between "stored" and "pushed live".
Part 2: Database model
Define tables or collections, primary keys, useful indexes, and transaction boundaries.
Your answer should include:
- Users, conversations, memberships, and messages, related so that access checks are simple.
- A per-conversation ordering mechanism and an index that serves history queries.
- Uniqueness enforcement for retried sends, and a consistent message plus outbox write if fanout is asynchronous.
Part 3: Flows and failure handling
Walk through:
- A successful send to an online recipient.
- A send to an offline recipient.
- A reconnect after a live connection dropped.
Your answer should include:
- The order of authorization, durable commit, acknowledgement, and notification.
- How missed or duplicated live events are reconciled against stored history.
- How a timeout that happens after the commit is resolved without creating a second message.
Hints
Hint 1
Pick one conversation model (for example, groups, with a 1:1 chat as a group of two) and make the schema, authorization, and fanout all follow from it.
Hint 2
Give every message a per-conversation sequence number assigned inside the commit transaction, and add a unique constraint on (sender, client-generated message id) so retries collapse to a single row.
Hint 3
Treat the live channel as a best-effort hint. The database is the source of truth, so a client that reconnects asks for everything after the last sequence number it saw, and de-duplicates by message id.
Hint 4
Write the message row and an outbox row in one transaction, and let a separate worker publish from the outbox. This avoids the case where a message is stored but never announced.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
I support both one-to-one and group chats with one model: a 1:1 chat is a conversation with exactly two members. Membership can change; new members see only messages from the point they joined (a joined_seq marker). Ordering is required per conversation, not globally. "Sent" means durably committed. Delivered and read are tracked separately and are optional. Live events go to every active device of each member.
Part 1: API
All calls carry an auth token; the server derives user_id from it and never trusts one in the body.
POST /conversationswith{member_ids, type}creates a conversation. For 1:1, look up an existing pair first, using a unique key on the sorted pair of user ids, to avoid duplicates.POST /conversations/{cid}/membersadds a member (group only, admin-checked).POST /conversations/{cid}/messageswith{client_msg_id, body}sends a message.client_msg_idis a UUID generated on the client and reused on every retry. Response:201 {message_id, seq, created_at}. A replay with the same key returns the original result with200, not a new message.GET /conversations/{cid}/messages?after_seq=N&limit=50returns messages in ascending order;?before_seq=Npages backward for scrollback.GET /conversationslists the user's conversations with last message and unread hint.- Optional:
POST /conversations/{cid}/receiptswith{up_to_seq}for delivered/read.
Every conversation endpoint checks membership first and returns 403 (or 404 to avoid leaking existence) otherwise. Pagination uses the sequence number as a cursor, not an offset, so inserts during paging never shift results or duplicate rows.
Part 2: Data model
users(user_id PK, ...)conversations(conversation_id PK, type, last_seq bigint default 0, created_at)memberships(conversation_id, user_id, role, joined_seq, left_at, PK(conversation_id, user_id))with a secondary index on(user_id)to list a user's conversations.messages(conversation_id, seq, message_id UNIQUE, sender_id, client_msg_id, body, created_at, PK(conversation_id, seq)), plusUNIQUE(conversation_id, sender_id, client_msg_id).outbox(id PK, conversation_id, seq, payload, published_at NULL)read_state(conversation_id, user_id, last_delivered_seq, last_read_seq, PK(conversation_id, user_id))for receipts as a high-water mark rather than one row per message.
The primary key (conversation_id, seq) makes history a contiguous range scan, which is the main read path.
Ordering: in one transaction, UPDATE conversations SET last_seq = last_seq + 1 WHERE conversation_id = ? RETURNING last_seq, then insert the message with that value. The row lock serializes writers per conversation, which gives a gap-free order. That is fine for a baseline; a hot room would later need a sequencer or partitioned log.
Idempotency: the unique constraint on (conversation_id, sender_id, client_msg_id) is the enforcement. On a conflict, the handler reads the existing row and returns it. Doing this in the database rather than a cache means it survives restarts and races between two concurrent retries.
Transaction boundary: one transaction does the membership check, the seq increment, the message insert, and the outbox insert. Either all commit or none do.
Part 3: Flows
Send to an online recipient
- Client sends the POST with
client_msg_id. - Server authenticates and checks membership.
- Server commits the transaction (message + outbox).
- Server returns the ack to the sender. This is the "sent" moment.
- An outbox worker reads unpublished rows, publishes to a pub/sub channel keyed by conversation, and marks them published. Gateway servers holding WebSocket connections for members receive the event and push
{message_id, seq, ...}to each connected device. - Recipient devices may send a delivered receipt (
up_to_seq), which updatesread_state.
Offline recipient Steps 1 to 4 are identical. The push finds no live connection, so nothing is sent live. Optionally the worker triggers a mobile push notification with minimal content. The message stays in the table. Nothing is queued per user, because history is the queue.
Reconnect after a dropped connection
The client remembers the highest seq it has per conversation. On reconnect it re-authenticates, resubscribes, then calls GET .../messages?after_seq=<last_seen> for each active conversation (or a single batch sync endpoint returning per-conversation deltas). It merges results by (conversation_id, seq) and drops anything it already has. Because it subscribes before fetching, there is no window where a message is missed; overlap is harmless thanks to de-duplication. If the client sees a seq gap in live events (for example, gets 12 then 14), it fetches the missing range.
Timeout after commit
The server committed but the response was lost. The client retries with the same client_msg_id. The unique constraint hits, the server returns the stored message with its seq, and the client reconciles its pending local bubble with the real id. No second message is created. If the client instead never retries, the message still shows up on the next sync, so the UI should match by client_msg_id.
Delivery semantics
Network delivery is at-least-once with client-side de-duplication, giving effectively-once display. I would not claim exactly-once delivery. Outbox publishing can repeat an event after a worker crash, which is why consumers key on message_id/seq.
Trade-offs
- A per-conversation counter row is simple and correct but serializes a very busy group. Alternatives include a log partitioned by conversation.
- Receipts as high-water marks are cheap but cannot express "read message 5 but not 4". That is acceptable for chat.
- Polling the outbox adds a small delay. Change-data-capture on the table avoids polling at the cost of more infrastructure.
Common mistakes
- Using timestamps for ordering, which breaks under clock skew and ties.
- Offset pagination, which duplicates or skips rows as new messages arrive.
- Publishing to the live channel before the commit, so recipients see messages that later roll back.
- Publishing after the commit with no outbox, so a crash between the two loses the notification.
- Treating the live channel as the source of truth instead of the database.
- Idempotency checked in application memory rather than enforced by a unique constraint.
- Conflating sent, delivered, and read.
- Not handling membership changes, so removed users keep reading or new users see everything.