Design a Request-Response Based Instant Messaging Architecture
System DesignModel answerLast updated
Architect a 1-on-1 instant messaging backend relying exclusively on standard HTTP request-response APIs, managing message synchronization, ordering, idempotency, and push delivery at scale.
Architect the backend system for a direct (1-on-1) instant messaging application similar to Messenger, operating under a strict architectural restriction: no persistent bidirectional connections (e.g., WebSockets, gRPC streams, SSE) are allowed.
All client-to-server interaction must occur over standard HTTP request/response paradigms. Users must be able to send text messages, retrieve history across multiple registered devices, and reliably receive incoming messages in correct chronological order.
Core Objectives & Requirements
-
Functional Requirements:
- One-on-one text messaging with multi-device support per user.
- Strict chronological ordering of messages per conversation visible to both sender and recipient.
- Complete message synchronization on new device logins or re-connections.
- Reliable delivery guarantee: zero message loss and duplicate message handling (idempotency).
-
System Constraints & Architectural Boundary:
- No persistent connection channels: Every operation must be an isolated request/response call.
- Explain how active (foreground), background, and offline devices learn about incoming messages without an open channel.
- Define concrete capacity estimations and explain how storage and network infrastructure scale.
Required Discussion Structure
- Part 1: Requirements, Sizing, APIs, and Data Storage Model
- Define system requirements, scale assumptions, HTTP API definitions, database schema, sequence/ordering generation, and end-to-end write lifecycle.
- Part 2: Real-Time Synchronization Without Persistent Sockets
- Contrast alternative real-time delivery mechanics (short polling, long polling, push wakeups).
- Design a delta-sync mechanism (cursor/sequence-based) ensuring gapless state recovery.
- Explain how to make non-blocking/empty status checks scale efficiently.
- Part 3: Multi-Device Fanout, Failure Modes, and Observability
- Multi-device message dispatch, queueing, and idempotency key handling.
- Failure scenarios (network drops, push notification losses, out-of-order retries, long-disconnected devices).
- Monitoring metrics to measure end-to-end latency and missing delivery detections.
Hints
Hint 1
Think about how git or database replication works: if every user has a monotonically increasing sequence ID for incoming events, catching up is just requesting events after a given cursor.
Hint 2
To keep short/long polling cheap on DB resources, use a lightweight layer like Redis or an in-memory key-value cache to hold the latest sequence number per user before touching storage.
Hint 3
Distinguish between foreground sync (low-latency HTTP long polling or optimized adaptive short polling) and background/offline notification (APNs / FCM push triggers).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
System Design: Request-Response Instant Messaging Service
Part 1 — Requirements, Capacity Estimation, APIs, and Storage Layout
1. Requirements & Scale Assumptions
Functional Requirements
- 1-on-1 Chat: Users can initiate chats and send text messages.
- Strict Ordering: Both participants see messages in identical chronological order.
- Multi-Device Support: A single user account can have multiple logged-in devices (phones, laptops, tablets), all staying synchronized.
- Gapless Synchronization: Devices coming online catch up from their last known checkpoint without missing messages.
- No Persistent Channels: No WebSockets, gRPC streaming, or Server-Sent Events (SSE).
Sizing Assumptions
- Daily Active Users (DAU): 100 Million.
- Average Messages Sent per User per Day: 50 messages.
- Total Daily Messages: $100\text{M} \times 50 = 5\text{ Billion messages/day}$.
- Average Write QPS: $\frac{5\text{B}}{86,400} \approx 58,000\text{ writes/sec}$ (Peak QPS $\approx 120,000\text{ writes/sec}$).
- Message Payload Size: $\sim 500\text{ bytes}$ (text body + metadata + envelope).
- Daily Storage Growth: $5\text{B} \times 500\text{B} = 2.5\text{ TB/day}$ (raw data). Over 5 years $\approx 4.5\text{ PB}$ (excluding replication).
2. RESTful API Specs
A. Send Message
POST /v1/conversations/{conversation_id}/messages
Content-Type: application/json
Authorization: Bearer <jwt_token>
{
"client_message_id": "uuid-v4-generated-by-client",
"recipient_id": "user_789",
"text": "Hello, how are you?"
}
Response (201 Created):
{
"message_id": "msg_991823712938",
"client_message_id": "uuid-v4-generated-by-client",
"conversation_id": "conv_123_789",
"sender_id": "user_123",
"created_at": 1700000000123,
"seq_num": 1042
}
B. Fetch Conversation History (Pagination)
GET /v1/conversations/{conversation_id}/messages?limit=50&before_seq=1042
Authorization: Bearer <jwt_token>
Response (200 OK):
{
"messages": [ ... ],
"has_more": true
}
C. Sync User Events (Delta Catch-Up / Polling Endpoint)
GET /v1/users/sync?last_sync_seq=8500&timeout_ms=20000
Authorization: Bearer <jwt_token>
Response (200 OK):
{
"latest_user_seq": 8503,
"events": [
{
"type": "NEW_MESSAGE",
"user_seq": 8501,
"conversation_id": "conv_123_789",
"message": { ... }
}
]
}
3. Data Model & Storage Engine Selection
To achieve fast range scans by sequence number and horizontal scalability, we use a hybrid database design:
- Primary Message Store: Distributed NoSQL wide-column store (e.g., Apache Cassandra or ScyllaDB) partitioned by
conversation_id. - User Event Timeline Log: Partitioned key-value store (or managed DynamoDB / ScyllaDB) storing per-user sequence timelines for device synchronization.
- In-Memory Cache (Redis Cluster): Cache latest user sequence numbers to optimize non-blocking sync calls.
+-------------------------------------------------------------+
| DB Schema Layout |
+-------------------------------------------------------------+
Conversation Messages Table User Inbox Timeline Table
+----------------------------------+ +----------------------------------+
| PK: conversation_id | | PK: user_id |
| CK: seq_num (ASC) | | CK: user_seq (ASC) |
+----------------------------------+ +----------------------------------+
| message_id (UUID/Snowflake)| | user_seq (BIGINT) |
| sender_id (VARCHAR) | | conversation_id (VARCHAR) |
| recipient_id (VARCHAR) | | message_id (UUID) |
| text (TEXT) | | sender_id (VARCHAR) |
| created_at (TIMESTAMP) | | payload_preview (TEXT) |
| client_message_id (UUID) | | created_at (TIMESTAMP) |
+----------------------------------+ +----------------------------------+
Absolute Message Ordering Engine
Monotonically increasing sequence counters are generated via a high-performance distributed counter service (e.g., Redis INCRBY backed by persistent transactional DB per conversation, or explicit linearizable ordering per conversation row via LWT / Raft consensus group).
[Client A] ---> (POST /messages) ---> [ API Server ]
|
1. Reserve Next Seq ID
(e.g., seq = 1042)
|
2. Write to Message Table
|
3. Append to User Timelines
(User A & User B Inbox)
|
4. Commit & Return HTTP 201
Part 2 — Real-Time Synchronization Without Persistent Connections
Without persistent bidirectional channels (WebSockets/SSE/gRPC streaming), we evaluate three patterns for client delivery:
| Strategy | Delivery Latency | Server Load / Bandwidth | Battery / Mobile Usage | Fit for Use Case |
|---|---|---|---|---|
| Short Polling (e.g., fetch every 2s) | High ($1 - 2\text{s}$) | Extremely High (Millions of empty 200/304 HTTP responses) | Aggressive drain | Sub-optimal for active foreground |
| Long Polling (Held Request, 20-30s hold) | Very Low ($< 100\text{ms}$ upon message arrival) | Medium (Low CPU/Bandwidth, high concurrent idle connections) | Efficient while active | Best Choice for Foreground App |
| Push Notifications (APNs / FCM) | Variable ($500\text{ms} - 5\text{s}$) | Very Low (Offloaded to Apple/Google infra) | Best energy conservation | Best Choice for Background / Offline |
+-----------------------------------+
| Client State Delivery Model |
+-----------------------------------+
+-------------------+ Long Polling +--------------------+
| Active App | ======================> | Sync API Service |
| (Foreground) | <====================== | (Held Request 20s) |
+-------------------+ (Immediate HTTP Response) +--------------------+
+-------------------+ Push Triggers +--------------------+
| Suspended App | < - - - - - - - - - - - - | FCM / APNs Provider|
| (Background) | (Silent Data Push) +--------------------+
+-------------------+ ^
|
+--------------------+
| Push Engine Worker |
+--------------------+
1. Gapless Delta-Sync Protocol (last_sync_seq)
Every user account maintains a single, monotonically increasing user_seq counter across all their events. Each client device persists the highest user_seq it has processed locally (local_cursor).
- Client Sync Loop (Foreground):
- Issue request:
GET /v1/users/sync?last_sync_seq=8500&timeout_ms=20000.
- Issue request:
- Server Execution:
- Query Redis for the user's latest sequence number (
redis.get("user_seq:user_789")). - Case A (
latest_seq > 8500): Fetch events between $(8500, \text{latest_seq}]$ fromUser Inbox Timeline Tableand immediately return HTTP 200. - Case B (
latest_seq == 8500): Put request in a suspended state (Long Poll) backed by Redis Pub/Sub listening on channeluser_789.- When a new message arrives, publish event to channel $\rightarrow$ wake held request $\rightarrow$ return HTTP 200 with new data.
- If timer reaches
20000mswithout events $\rightarrow$ return200 OKwithevents: []andlatest_user_seq: 8500.
- Query Redis for the user's latest sequence number (
- State Convergence:
- Because syncing requests data by explicit index offsets ($> \text{last_sync_seq}$), network drops or out-of-order polling retries never lead to dropped events or inconsistent states.
2. Scaling Empty Checks Efficiently
At 100M DAU, holding millions of connection threads can exhaust web server worker pools:
- Asynchronous Non-Blocking HTTP Servers: Use asynchronous, event-driven HTTP frameworks (e.g., Netty, Node.js, enterprise Rust/Go runtimes) where idle long-polling HTTP requests cost only memory for socket context ($\sim 4\text{ KB}$ per held request), avoiding thread-per-request blocking overhead.
- In-Memory Cursor Cache: Avoid querying the primary database for empty polling checks. Redis maintains
user_seq:{user_id}. A database lookup occurs only whenlast_sync_seq < cached_latest_seq.
Part 3 — Scaling, Multi-Device Fanout, Failure Modes & Observability
1. Multi-Device Delivery Engine Architecture
[Sender App]
|
v
[ HTTP Gateway ]
|
v
[ Message Service ] ---> ( Write Msg to DB )
|
v
[ Event Bus (Kafka) ]
|
+----+-------------------------+
| |
v v
[ Timeline Consumer ] [ Push Worker Service ]
| |
+-> Update Recipient Timeline +-> Check Presence / Send FCM/APNs
| (user_seq increment)
+-> Publish to Redis Pub/Sub
(Wakes up active Long Polls)
-
Write Path:
- Message API receives payload $\rightarrow$ writes to
Conversation Messageswith uniqueclient_message_idfor sender-side deduplication. - Produces event
MessageSentEventto Kafka partitioned byrecipient_id.
- Message API receives payload $\rightarrow$ writes to
-
Fan-Out Processor:
- The consumer reads
MessageSentEventand increments the recipient'suser_seq. - Appends an entry into the recipient's
User Inbox Timeline Table. - Fires a notification event to Redis Pub/Sub:
PUBLISH channel:user_789 "NEW_EVENT".
- The consumer reads
-
Multi-Device Sync:
- If User B has 3 active devices (Phone, Tablet, Desktop) all running long-polling loops:
- All 3 held requests are listening to Redis channel
user_789. - The Redis Pub/Sub trigger wakes up all 3 active HTTP long-polling connections simultaneously.
- Each device issues/receives its catch-up response with payload, updating local sqlite DBs independently to sequence number
user_seq.
- All 3 held requests are listening to Redis channel
- If User B has 3 active devices (Phone, Tablet, Desktop) all running long-polling loops:
2. Failure Handling & Edge Case Protocols
Idempotent Delivery (Network Flakes & Retries)
- Senders generate a
client_message_id(UUIDv4) prior to network transmit. - The backend checks a fast Redis cache (
SET NX client_msg:{id} EX 86400) before execution. - If the sender retries due to a timeout response, the API returns the original created message object without duplicating storage writes or incrementing sequences.
Client API Server Redis/DB
| | |
|--- POST (client_msg_id=X) ---->| |
| |--- SETNX client_msg:X ----->| (Success)
| |--- Persist Message -------->|
| <--- ACK Timeout / Drop -------| (DB write succeeded) |
| | |
|--- RETRY (client_msg_id=X) --->| |
| |--- SETNX client_msg:X ----->| (Exists!)
| <--- 201 Created (Cached) -----| |
Missed Push Notifications / Background Drops
- Apple APNs and Google FCM do not guarantee 100% delivery.
- Self-Healing Mechanism: The moment a user transitions the app from background to foreground, the client bypasses push states and immediately executes
GET /v1/users/sync?last_sync_seq=<local_cursor>. Any missing events during background mode are delivered in a single payload.
Long-Disconnected Devices
- If a device has been offline for months (
last_sync_seqfar behind retention limits ofUser Inbox Timeline Table):- The API returns HTTP response
410 Gonewith codeSYNC_CURSOR_EXPIRED. - The client clears local volatile message caches and performs a full bootstrap fetch using pagination endpoints (
/v1/conversations/...).
- The API returns HTTP response
3. Observability & Key Operational Metrics
To verify system health and message delivery SLAs, track the following metrics:
- End-to-End Delivery Latency ($p_{50}, p_{99}$):
- Time delta between sender tap (
created_at) and recipient long-poll ACK completion (sync_acknowledged_at). Target: $p_{99} < 500\text{ms}$ for foreground active users.
- Time delta between sender tap (
- Long Poll Holding Pool Health:
- Gauge of active idle HTTP connections per sync node.
- Timeout vs. Real-Data resolution ratio (e.g., $90%$ timeouts vs $10%$ real events payload delivery).
- Sequence Gap Detection Metric:
- Counter tracking out-of-sequence payload requests from clients (e.g.,
last_sync_seqrequested is greater thanlatest_user_seqin server cache), signaling database replication delay or cache corruption.
- Counter tracking out-of-sequence payload requests from clients (e.g.,
- Push Notification Fallback Rate:
- Percentage of events delivered via APNs/FCM vs direct active HTTP Long-Poll response.