Design a 1:1 Chat System for a Buyer-Seller Marketplace
System DesignModel answerLast updated
Design a real-time direct messaging platform supporting message ordering, delivery receipts, offline notifications, and multi-device sync at marketplace scale.
Context
A social commerce marketplace lets buyers and sellers communicate directly — to clarify product details, agree on pricing, coordinate delivery, and settle disputes. You've been asked to design the 1:1 messaging feature that powers these conversations.
Functional Requirements
- Direct messaging: Any two users can start a conversation and exchange text messages up to 2,000 characters in real time.
- Message ordering and status: Both participants must see messages in strict chronological order. Each message progresses through three states:
sent,delivered, andread. - Offline storage and push notifications: If the intended recipient is offline, the message must be durably stored and a push notification must be sent to their device.
- Multi-device synchronization: A user signed in on both a mobile app and a browser must see a consistent conversation state — including read receipts — across all their devices.
- Commerce context: A message may optionally reference a listing ID or order ID to give it context.
Non-Functional Requirements
- Latency: End-to-end delivery to an online recipient should stay under 200 ms.
- Durability: No message should be lost after the server has acknowledged receipt. Delivery semantics are at-least-once, with client-side deduplication.
- Scale targets:
- 20 million daily active users
- 50 million messages sent per day
- Peak send rate: ~2,000 messages/second
- Peak concurrent WebSocket connections: 5 million
What to Cover
Your design should address:
- Architecture overview — protocol choices, connection management, and how traffic is routed between components.
- Data model and storage — schema for conversations, messages, and delivery state; choice of storage engine and rationale.
- End-to-end message flow — trace a single message from the sender hitting send to the recipient seeing it, including acknowledgements, retries, and deduplication.
- Reconnection and catch-up — how a client recovers missed messages after a disconnect or a device switch.
- Trade-offs — where you made deliberate choices and what you gave up: ordering guarantees vs. latency, connection memory overhead, storage partitioning, and so on.
Hints
Hint 1
Start by separating the stateful problem (holding open connections) from the stateless problem (processing and storing messages). Ask yourself: what does each tier actually need to know?
Hint 2
Message status (delivered, read) doesn't have to be stored per message. Think about what a watermark — a single high-water-mark sequence number per user per conversation — buys you compared to a status column on every row.
Hint 3
Reconnect and multi-device sync are really the same problem: a client needs everything that happened after a cursor it already holds. Design your API and data model so that a fresh connection and a returning device use the exact same code path.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core design tension here is between stateful connection handling and stateless message processing. Keep those two concerns in separate tiers and each becomes tractable. The other thing interviewers listen for is whether you can trace one message end-to-end — including ACKs, retries, and dedup — without hand-waving through the hard parts.
1. Size the System First
Before drawing boxes, put numbers on the problem.
- Write throughput: 50M messages/day ≈ 580/s average, ~2,000/s at peak.
- Delivery fan-out: each message goes to the recipient's devices plus the sender's other devices — roughly 3–4 deliveries per send, so ~8,000 pushes/s at peak. Status receipts (
delivered,read) roughly double the event volume. - Storage: at ~400 bytes per message including metadata, that's ~20 GB/day, ~7 TB/year, and ~21 TB at a replication factor of 3.
- Connections: 5M concurrent WebSockets. At ~50,000 connections per gateway node with comfortable headroom, that's roughly 100–150 gateway machines, each holding 10–20 KB of connection state, so about 100 GB of RAM across the fleet.
The write throughput is manageable. The genuinely hard parts are connection management, ordering, delivery guarantees, and sync.
2. API Design
WebSocket (WSS) — real-time path:
| Frame | Direction | Purpose |
|---|---|---|
send {client_msg_id, conversation_id, body, ref?} | Client → Server | Send a message; client_msg_id is a client-generated UUID for dedup |
ack {client_msg_id, seq, server_ts} | Server → Client | Confirm persistence; transitions status to sent |
message {conversation_id, seq, sender_id, body, ...} | Server → Client | Push incoming message to recipient |
delivered {conversation_id, up_to_seq} | Client → Server | Recipient signals delivery watermark |
read {conversation_id, up_to_seq} | Client → Server | Recipient signals read watermark |
REST over HTTP/2 — stateless operations:
POST /conversations— idempotent; same pair + context returns the existing conversation.GET /inbox?since_version=— returns conversations changed since the client's last-known cursor.GET /conversations/{id}/messages?after_seq=&limit=— paginated catch-up for a single thread.
3. Data Model and Storage
Use a wide-column store (Cassandra, ScyllaDB, or DynamoDB) for messages. The workload is append-heavy with range-scan reads by partition key — exactly the pattern these engines are designed for.
messages PK (conversation_id, bucket) CK seq DESC
sender_id, body, client_msg_id, ref_type, ref_id, created_at
conversations PK conversation_id
participant_ids[], listing_id, last_seq, created_at
members PK (conversation_id, user_id)
last_delivered_seq, last_read_seq, muted
inbox PK user_id CK (last_activity DESC, conversation_id)
last_message_preview, unread_count, inbox_version
dedup PK (conversation_id, client_msg_id) → seq TTL 24h
The watermark insight: don't store a status column on each message row. In a 1:1 conversation, delivered and read are monotonic watermarks — any message with seq ≤ last_read_seq is read. This converts O(messages) status writes into a single small update per conversation per device event, and it makes multi-device read sync trivial: whoever has the higher watermark wins.
Partitioning: messages partition by conversation_id, which co-locates a thread and makes range scans fast. Add a time or size bucket to prevent unbounded partition growth in long-lived seller conversations.
4. Architecture
Client ──WSS──> L4 LB ──> Gateway (stateful) ──gRPC──> Message Service (stateless)
▲ │
│ seq alloc + persist
Session Registry (Redis) ▼
│ Messages DB / Conversations
└──────── Delivery Router ───────┤
├─> Push Notification Svc (APNs / FCM)
├─> Inbox updater
└─> Analytics / Trust & Safety
Each tier has a single responsibility:
- Gateways terminate TLS sockets, authenticate, run heartbeats (~30s), and forward frames. On connect, they register
user_id → {device_id: gateway_id}in Redis with a TTL. They hold no business logic, so a gateway crash only means clients reconnect — no data is lost. - Message Service handles validation, membership checks, rate limiting, dedup, sequence allocation, and persistence. It is stateless and horizontally scalable.
- Delivery Router consumes a Kafka topic (keyed by
conversation_idfor ordering), looks up recipient sessions, and pushes frames to the right gateways through per-gateway channels.
5. End-to-End Message Flow
- The client generates a
client_msg_id(UUID v4), renders the message as pending, and sends it over WSS. - The gateway forwards to the Message Service, which checks the
deduptable. A cache hit returns the existingseqand short-circuits (handles client retries cleanly). - Sequence allocation: an atomic increment on
conversations.last_seqvia DynamoDB conditionalUpdateItemor a Cassandra lightweight transaction. Contention is negligible — a 1:1 conversation sees at most a handful of writes per second. An alternative is shard ownership: hashconversation_idto a service instance that holds an in-memory counter, eliminating the round-trip entirely. - Persist the message at QUORUM (or equivalent strong durability). Only then send the
ackback to the sender. The zero-loss-after-acknowledgement guarantee lives or dies by this ordering. - Publish the event to Kafka, keyed by
conversation_id. This decouples delivery from persistence and gives per-conversation ordering to downstream consumers. - The Delivery Router looks up the recipient's sessions and forwards to every online device plus the sender's other devices. If the recipient has no live session, it triggers APNs/FCM with a collapse key per conversation to coalesce notification bursts.
- The recipient device sends
delivered, advancinglast_delivered_seq. Opening the conversation sendsread, advancinglast_read_seq. Both are propagated back to the sender's devices.
Retry and dedup contract:
- The sender retries unacknowledged frames with the same
client_msg_id. - The server redelivers until the device ACKs.
- Clients deduplicate by
(conversation_id, seq). - Clients sort and render by
seq, never by device clock.
6. Reconnection and Multi-Device Sync
Every change affecting a user increments their inbox_version and updates the inbox row atomically. On reconnect (including a Wi-Fi → LTE switch):
- Reconnect the WebSocket with jittered exponential backoff to avoid a thundering herd after a gateway restart.
- Call
GET /inbox?since_version=<last_known>to retrieve conversations that changed, each carrying its currentlast_seqand watermarks. - For any conversation where
last_seqis ahead of the local value, page throughmessages?after_seq=<local_seq>to pull missed messages. - Resume live pushes. Any overlap between the pulled batch and in-flight pushes is handled by client-side
seqdeduplication.
This means a fresh device and a returning device use the exact same catch-up path.
Key Trade-offs
| Decision | What you gain | What you give up |
|---|---|---|
| Watermarks instead of per-message status | Cheap writes, trivial multi-device sync | Can't express partial delivery within a batch |
| Cassandra/DynamoDB for messages | Write scalability, easy sharding | No cross-conversation joins; analytics needs a separate store |
| Sequence allocation via atomic DB increment | Simple, correct ordering | One extra round-trip per message (mitigated by shard ownership) |
| At-least-once + client dedup | Zero message loss | Clients must handle and discard duplicates |
| Kafka between persistence and delivery | Decoupled, replayable, ordered | Added latency hop; extra infrastructure to operate |
Common Mistakes to Avoid
- Using
created_attimestamps for ordering. Clocks drift across clients and servers. Sequence numbers are the only reliable ordering primitive. - Storing a status field per message row. It creates a write amplification problem and makes multi-device sync a reconciliation nightmare.
- Putting business logic in the gateway. Gateways crash and reconnect constantly at this scale. Keeping them thin means no state is lost when they do.
- Skipping the dedup table. Without it, retries from unreliable mobile networks produce duplicate messages, which are very hard to clean up after the fact.