Design a Real-Time Messaging Platform with High-Velocity Group Analytics
System DesignModel answerLast updated
Architect a low-latency chat platform supporting 1:1 and large group channels, with real-time state synchronization and live streaming identification of high-activity groups.
Architect a global real-time messaging system supporting both 1:1 direct chats and large public/private channels. The platform needs to handle millions of simultaneous socket connections while maintaining strict low-latency guarantees.
A critical product requirement is real-time detection of high-velocity groups (the Top 100 "trending" or "hot" chat rooms based on recent activity), providing these stats via API without impacting core messaging throughput or primary database performance.
Key Requirements
Functional:
- Real-time message exchange for 1:1 and group chats (up to 10,000 members per room).
- Multi-device state synchronization and persistent offline backfills.
- Live delivery status and read receipts.
- Continuous identification of the Top 100 most active groups globally over a moving window (e.g., last 5 minutes).
Non-Functional:
- Latency: $p_{99} \le 200\text{ ms}$ for real-time delivery across connected devices globally.
- Scalability & Availability: Scale to tens of millions of concurrent connections; fault-tolerant under network partitions.
- Consistency: Per-channel strict message ordering guarantees; eventual cross-channel consistency.
Expected Scope
Your design should present:
- Scale estimates and resource projections.
- System architecture diagram and payload schemas.
- Storage strategy (relational vs. wide-column vs. ephemeral state stores).
- Connection state management for stateful WebSocket clusters.
- Fan-out optimization for large groups ($N=10,000$).
- Stream-processing pipeline for real-time Top-K analytics.
Hints
Hint 1
Decouple the ingestion/persistence layer from message delivery using an event streaming platform (e.g., Kafka) partitioned by conversation ID to maintain per-room message ordering.
Hint 2
Avoid publishing group messages to recipient sockets one-by-one; instead, perform local fan-out at the connection server level or leverage gateway-level pub/sub topics.
Hint 3
Use a stream processing framework (e.g., Apache Flink) with sliding windows and a Heavy-Hitters algorithm (Count-Min Sketch + Min-Heap) to maintain Top-K analytics off the primary storage hot path.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Capacity Estimation & Traffic Projections
To ground the architectural decisions, we establish the following scale assumptions:
- Daily Active Users (DAU): 500 Million
- Peak Concurrent Connections (PCC): 20 Million active WebSocket connections.
- Daily Message Volume: 10 Billion messages/day.
- Average Ingestion Throughput: $\sim 115,000\text{ msg/sec}$
- Peak Ingestion Throughput ($3\times$): $\sim 350,000\text{ msg/sec}$
- Average Message Size: 200 bytes raw text/payload + metadata $\approx$ 1 KB total payload.
- Ingress Storage Overhead: $\approx 10\text{ TB/day}$ raw payload ingestion (or $\sim 30\text{ TB/day}$ with $3\times$ replication).
- Fan-Out Factor: Average group fan-out multiplier is $5\times$, but peak burst channels reach up to $10,000$ members. Peak egress delivery can reach tens of millions of messages pushed per second.
- Gateway Scale: Assuming each stateful edge server maintains $100,000$ concurrent TCP/WebSocket connections, the edge fleet requires at least $200$ to $300$ active gateway instances.
2. API & Communication Protocols
Protocols
- Client $\leftrightarrow$ Edge Gateways: WebSockets over TLS for duplex state streaming. Fallback to HTTP Long-Polling for restrictive networks. Binary serialization (Protobuf) is preferred over JSON to minimize payload overhead and parsing CPU cost at scale.
- Client $\leftrightarrow$ REST Services: Standard HTTP/2 HTTPS for non-realtime bootstrapping (authentication, fetching initial payload/channel history, media uploads).
Data Contracts (Protobuf / JSON Schemas)
WebSocket Inbound Frame (Client $\rightarrow$ Server)
{
"client_msg_id": "uuid-v4-9a8f7b",
"channel_id": "group_10928",
"payload": "Hello everyone!",
"client_timestamp": 1700000000123
}
WebSocket Outbound Frame (Server $\rightarrow$ Client)
{
"server_msg_id": 108293021,
"channel_id": "group_10928",
"sequence_id": 40291,
"sender_id": "user_4492",
"payload": "Hello everyone!",
"timestamp": 1700000000140
}
Synchronizing History (REST GET Endpoint)
GET /v1/channels/{channel_id}/messages?after_seq=40200&limit=50
Response: Array of message frames with sequence_id > 40200.
3. High-Level System Architecture
+-----------------------+
| Push Notification |
| Gateway (APNs / FCM) |
+-----------^-----------+
| (Offline)
+---------+ +-----------------+ +------+----------------+
| Client |<---->| L4 Load Balancer|<--->| Connection Gateway |
+---------+ TLS +-----------------+ WS | Fleet (Stateful) |
+----------^------------+
| Pub/Sub
+----------v------------+
| Ingestion & Logic |
| Service (Stateless) |
+----------+------------+
|
+----------------v----------------+
| Distributed Event Stream |
| (Kafka - Keyed by Channel ID) |
+---+-----------------+-----------+
| |
+-------------------+ +-------------------+
v v v
+------------------------+ +-------------------+ +--------------------+
| Persistence Workers | | Fan-Out Workers | | Flink Stream Engine|
+------------+-----------+ +---------+---------+ +---------+----------+
| | |
v v v
+------------------------+ +-------------------+ +--------------------+
| ScyllaDB / Cassandra | | Redis Cluster | | Redis Sorted Set |
| (Message History) | | (Presence/Routing)| | (Top 100 Hot) |
+------------------------+ +-------------------+ +--------------------+
Component Breakdown
- L4 Load Balancers: Distribute incoming WebSocket handshakes using consistent IP hashing or least connections to the Gateway fleet.
- Connection Gateway Fleet: Stateful nodes managing persistent WebSocket connections. Maps connected
user_id$\rightarrow$ socket descriptors. - Ingestion & Logic Service: Stateless microservices that validate, authenticate, enforce rate-limits, and append idempotency tokens.
- Kafka Message Bus: Acts as the primary partition boundary. Partitioning by
channel_idguarantees that all messages for a specific chat room arrive in strict temporal order at a single consumer partition. - Persistence Engine (ScyllaDB / Apache Cassandra): Optimized for continuous append-only write throughput and efficient range scans by sequence key.
- Fan-Out Workers: Distributed consumers responsible for discovering recipient presence state and routing messages to appropriate Gateway instances.
- Flink Analytics Engine: Continuous stream processing job calculating rolling message counts across sliding windows to determine hot channels.
4. Storage Architecture & Data Schema
Storage Engine Selection
- Relational Database (Sharded PostgreSQL): Manages user profiles, authentication, authorization policies, and group membership rosters. Writes are infrequent compared to read activity.
- Wide-Column NoSQL Store (ScyllaDB / Apache Cassandra): Holds historical message payloads. Append-heavy workload; partition keys map to individual channels.
- In-Memory Cache Cluster (Redis Enterprise / KeyDB): Stores dynamic connection routing metadata (
user_id$\rightarrow$gateway_id) and top-K heat indices.
Database Schema (ScyllaDB)
CREATE KEYSPACE chat_system WITH replication = {
'class': 'NetworkTopologyStrategy',
'us-east': 3,
'eu-west': 3
};
-- Messages Table: Clustered by sequence_id to support efficient range fetches
CREATE TABLE chat_system.messages (
channel_id text,
bucket int, -- YYYYMM format to limit partition size for massive groups
sequence_id bigint,
sender_id text,
payload text,
created_at timestamp,
PRIMARY KEY ((channel_id, bucket), sequence_id)
) WITH CLUSTERING ORDER BY (sequence_id DESC);
-- Last Read Cursors for Sync & Receipts
CREATE TABLE chat_system.read_cursors (
user_id text,
channel_id text,
last_read_sequence_id bigint,
updated_at timestamp,
PRIMARY KEY (user_id, channel_id)
);
5. Detailed Component Mechanisms
Connection Routing & Gateway Architecture
Because Gateways are stateful, sending a message from User A to User B requires knowing which Gateway server holds User B's open socket.
+-----------------------------------------------------------------------------------+
| Gateway Node 102 |
| - Active Socket: User 8812 (Device A) |
| - Subscribed to Local Pub/Sub Channel: "gw:node_102" |
+-----------------------------------------------------------------------------------+
^
| Publish { Recipient: User 8812, Payload }
+------------------------------------+----------------------------------------------+
| Redis Routing Registry |
| Key: "user:8812" ---> Value: { "gw_id": "node_102", "last_heartbeat": 170000021 } |
+-----------------------------------------------------------------------------------+
- Session Setup: When a user connects to
Gateway_102, the gateway writes an entry to the Redis Routing Table:user:{user_id} -> { gateway_id: "node_102", device_id: "dev_99" }with an expiring TTL (e.g., 60 seconds). - Heartbeats: Sockets send keep-alive frames every 20 seconds. Gateways extend the Redis key TTL.
- Termination/Disconnection: If the connection drops or heartbeat times out, the Redis routing key expires.
- Routing Message Delivery: The Fan-Out worker queries Redis for
user:{recipient_id}. If present, it posts the payload to internal pub/sub topicgw:{gateway_id}.Gateway_102receives the event and writes to the local socket connection.
Large Channel Fan-Out Optimization ($N = 10,000$)
Naively fetching $10,000$ member IDs from storage and dispatching $10,000$ individual point-to-point network requests creates a severe bottleneck.
Naive Approach:
Message --> [Fan-out Worker] --(10,000 queries)--> [Redis Store]
--(10,000 pushes)---> [Gateways] (High Latency & Overhead)
Optimized Approach:
Message --> [Fan-out Worker] --(1 Grouped Pub/Sub)--> [Gateway Cluster]
Gateway filters connected members locally
Execution Strategy for Scaled Channels:
- Gateway-Level Local Room Subscriptions:
When a user connects to a Gateway and joins active channels, the Gateway registers local interest:
Gateway_102addsuser_Ato local key setchannel_10928_sockets. IfGateway_102has at least one connected member inchannel_10928, it subscribes to the message bus channel topicroom:channel_10928. - Broadcast Reduction:
When a message is posted to
channel_10928, the Fan-Out worker publishes one single payload envelope to the cluster channelroom:channel_10928. Instead of $10,000$ individual gateway notifications, the platform broadcasts only to the subset of active Gateway instances housing those channel members (e.g., 30 Gateway nodes). - Local Multiplexing: Each recipient Gateway node receives the single envelope and writes it locally across all mapped local sockets for that channel in parallel.
- Throttled Read Receipts: In large rooms ($N > 100$), individual read receipts are not immediately broadcast. Read cursor movements are batched at the client level, pushed asynchronously, aggregated by background workers, and delivered as periodic counter updates (e.g., "Read by 4,210 members").
Real-Time "Hot Group" Stream Processing Architecture
To find the Top 100 most active channels globally without bombarding primary databases, the system uses a decoupled event-stream analytical processing pattern.
Kafka Topic ("messages")
|
+---> [ Flink Job: Sub-Window Aggregators (Parallel Workers) ]
|
| Emits partial Top-K counts every 5 seconds
v
[ Flink Job: Global Aggregator Node ]
|
| Merges local heaps -> Maintains overall Top 100
v
[ Redis Key: "hot_groups_top100" (Sorted Set) ]
|
+---> Serving Path: GET /v1/hot-groups (Edge Cache)
Stream Pipeline Breakdown (Apache Flink)
- Ingress Event Stream: Every valid published message emits a lightweight metric tuple into the Kafka topic:
(channel_id, timestamp, 1). - Sliding Window Count Calculation: A Flink streaming job consumes this topic, applying a 5-minute sliding window with a 5-second slide interval: $$\text{WindowSize} = 300\text{ seconds}, \quad \text{SlideInterval} = 5\text{ seconds}$$
- Heavy Hitters Optimization (Count-Min Sketch + Min-Heap):
- High cardinality (millions of concurrent active groups) makes storing explicit counts for every group in memory expensive.
- Workers process events using a Count-Min Sketch probabilistic data structure to track approximate event counts with low memory overhead ($O(\log N)$ space complexity).
- Concurrently, each Flink task worker maintains a local Min-Heap bounded to $K=100$ channels.
- Global Consolidation: Every 5 seconds, downstream aggregation nodes combine the candidate local Min-Heaps from all worker tasks, resolving the global Top 100 active rooms.
- Caching & API Serving Layer:
The consolidated Top 100 list is written to a Redis Sorted Set (ZSET) (
key: "hot_groups_top100"). API services respond to client requests (GET /v1/hot-groups) directly from local edge caches populated by this Redis ZSET, ensuring zero database lookup overhead on the primary write path.
6. Resilience, Edge Cases & Consistency Rules
| Potential Failure Mode | Mitigation Strategy |
|---|---|
| Gateway Crash / Connection Drop | Client automatically reconnects to a new Gateway instance via L4 LB. Client sends its last known sequence_id via /v1/sync REST request to fetch missed history from ScyllaDB. |
| Out-of-Order Message Arrival | Sequence IDs are generated monotonically per channel using a centralized Sequence Generator or atomic Redis sequence increment (INCR channel:{id}:seq) backed by single-partition Kafka ordering per channel. |
| Duplicate Delivery (Network Glitch) | Clients generate a client_msg_id UUID prior to sending. The stateless Ingestion Layer checks an in-memory dedup cache (Redis key with 60-second TTL). Identical client_msg_id requests return original ACK without repeating fan-out logic. |
| Massive Fan-Out Spikes (Flash Crowds) | If a channel experiences high message rates, fan-out logic switches to a debounced delivery mode: local gateway buffers messages for $50\text{ ms}$ and pushes them in a single aggregated payload array over the WebSocket connection. |
7. Operational & Latency Verification ($p_{99} \le 200\text{ ms}$)
[ Client A Send ]
| (~15 ms network propagation)
[ Ingestion API & Auth ]
| (~5 ms Redis dedup & validation)
[ Kafka Publish ACK ] ==> (Sender ACK returned to Client A: ~20 ms total)
| (~10 ms queue latency)
[ Fan-Out Worker ]
| (~5 ms Redis gateway lookup / PubSub)
[ Edge Gateway ]
| (~10 ms socket buffer flush & dispatch)
[ Client B Receive ]
--------------------------------------------------
Total End-to-End Latency Target: ~45 ms - 65 ms (p99 well under 200ms)
This architecture separates stateful WebSocket connections, stateless API validation, asynchronous message fan-out, and decoupled analytics. This design guarantees low latency, system stability, and high operational availability at scale.