The user wants a system design for a real-time WebSocket system at scale.
The key requirements are:
- Connection Fanout: How to send messages to many users (broadcasting).
- Presence: Tracking online/offline status.
- Backpressure: Handling slow consumers or fast producers.
- Shard/Region Routing: Distributing connections across servers/regions.
- Graceful Degradation: What happens when things fail or overload.
1. High-Level Architecture:
- Clients connect via WebSockets.
- Need a load balancer (L7/L4).
- Need "Connection Nodes" (stateful servers holding the sockets).
- Need a "Message Broker" (Pub/Sub) to decouple senders from receivers.
- Need a "Presence Service" (Redis/Database).
- Need an API for incoming messages (REST/gRPC) to trigger the WebSockets.
2. Detailed Breakdown by Requirement:
3. Structuring the Design:
- Introduction: Define the scope (e.g., a global chat or notification system).
- Architecture Diagram (Mental or ASCII): LB -> WS Nodes -> Redis/Kafka.
- Key Components:
- L7 Load Balancer (Nginx/Envoy).
- Connection Servers (Stateful).
- Coordination/Discovery (Redis/Zookeeper).
- Message Bus (Kafka/NATS).
- Section 1: Connection Management & Routing (Sharding/Regions)
- DNS load balancing.
- Consistent Hashing for distributing users.
- Handling "Hot" shards.
- Section 2: The Fanout Engine (Pub/Sub)
- Topics/Channels.
- Subscription management.
- Section 3: Presence System
- Storage (Redis Sorted Sets/BitMap).
- Heartbeats.
- Section 4: Backpressure & Flow Control
- The "Slow Consumer" problem.
- Buffer management.
- Dropping messages intelligently.
- Section 5: Graceful Degradation & Reliability
- Rolling updates (Draining connections).
- Fallbacks.
4. Refining the details (Self-Correction during drafting):
-
Question: Should the WebSocket server handle business logic?
-
Correction: No, keep it a "Dumb Pipe". It should just manage the socket and push/pull from the broker. Business logic goes in a separate Stateful Service. This makes the WS server easier to scale and crash-restart.
-
Topic: Cross-Region Routing:
- If I am in US and subscribe to a channel, but the publisher is in EU.
- Option A: Global Cluster (Spanner/Global Redis).
- Option B: Bridge. WS Node in US -> Local Broker -> Replicates to EU Broker -> WS Node in EU.
- Let's recommend Option B (Regional bridges) to keep latency low for local interactions and absorb WAN failures.
-
Topic: Draining:
- During deployment, we can't just kill sockets.
- Send
GOAWAY frame or a custom "Reconnect" message.
- Client side needs logic to handle immediate reconnect.
5. Final Polish:
Organize with clear headings. Use standard terminology. Focus on scale (millions of connections). Mention specific technologies (Netty, Go, Envoy, Redis, Kafka).
Drafting the content steps:
- High-Level View: The Gateway + The Dipper + The Bus.
- Connection Lifecycle: Handshake -> Mapping (Redis) -> Register.
- Fanout: Fanout via Redis Pub/Sub or Kafka Topics.
- Presence: Heartbeats + CAS (Compare-and-Set) in Redis.
- Backpressure: IO Reactor patterns (Netty), dropping dirty data.
- Degradation: Circuit breakers, feature flags.
Let's write this out.
Designing a real-time WebSocket system at scale requires shifting from a traditional request/response mindset to an event-driven, stateful architecture. The core challenge is managing millions of concurrent stateful connections across a distributed cluster.
Here is a comprehensive system design covering connection fanout, presence, backpressure, routing, and degradation.
1. High-Level Architecture
At scale, you cannot bind a specific user to a specific server. You need an abstract layer that decouples the connection from the business logic.
The Components:
- L7 Load Balancer (L7 LB): Terminates TLS, performs sticky sessions (session affinity), and upgrades HTTP to WebSocket.
- Connection Pool (The "Dipper"): A fleet of stateless nodes (e.g., Go/Netty/Node.js) holding the open sockets. These nodes only handle the socket lifecycle and framing. They do not execute business logic.
- Control Plane (Orchestrator): A service registry (e.g., Redis, Etcd, Zookeeper) mapping
UserID -> [ConnectionNode_ID, ...].
- Message Bus (The Backbone): A high-throughput durable queue (e.g., Apache Kafka or NATS JetStream).
- Presence Service: A specialized low-latency store (e.g., Redis Cluster) for user state.
2. Connection Fanout (1:Many Messaging)
Sending a message from one user to millions (e.g., a live stream chat or stock ticker) requires a Fanout Architecture to prevent the "thundering herd" problem on your database.
The "Topic" Subscription Model:
Instead of pushing data to users directly, users subscribe to "Topics" (channels).
- Subscription: When a client connects to a Connection Node, the node subscribes to a specific topic on the Message Bus (e.g., Kafka topic
ticker:NASDAQ).
- Ingestion: A publisher (API) pushes one message to the
ticker:NASDAQ topic.
- Distribution: The Message Bus delivers that single message to every Connection Node that has a subscriber for that topic.
- Egress: Each Connection Node iterates over its local list of connected clients for that topic and writes the frame.
Why this scales: The heavy lifting is done by the Message Bus. Your API only sends 1 message; the infrastructure handles the copy to N nodes.
3. Shard and Region Routing
In a global system, latency and data sovereignty require routing intelligence.
A. Regional Isolation (Geo-Routing):
- DNS/LB Layer: Use GeoDNS to route
ws.example.com to the nearest region (US-East vs. APAC).
- Cross-Region Relay: If User A (US) messages User B (APAC), the US Connection Node publishes to a global Kafka cluster (or uses Kafka MirrorMaker/Confluent Cluster Linking). The message replicates to the APAC cluster, where User B’s node consumes and delivers it.
B. Shard Routing (Tenant Isolation):
To prevent "noisy neighbor" issues (one heavy client crashing a node), use Consistent Hashing.
- The LB routes connections for
Tenant_ID: X to a specific subset of nodes (Shard 1).
- If
Tenant X explodes in traffic, only Shard 1 crashes, leaving other tenants unaffected.
- Hot Key Mitigation: If a specific channel (e.g., "SuperBowl") is too hot for one node, use Splitting: Subscribe to
channel:superbowl:shard_1 through shard_10. The client randomly picks a shard, and the publisher fans out to all 10 internal shards.
4. Presence System (Online/Offline)
Tracking millions of users in real-time is expensive. Do not store presence in a relational database.
The Strategy:
- Heartbeats: Clients send a lightweight ping (application-level) every 30s.
- TTL (Time-To-Live): The Connection Node updates a key in Redis Cluster:
SETEX user:123:status 60 "online"
Note: The TTL is slightly longer than the heartbeat interval (e.g., 60s TTL vs 30s beat) to account for network jitter.
- Optimization (Write-Behind):
At extreme scale (10M+ concurrents), writing to Redis on every heartbeat is too heavy.
- Architecture: Connection Nodes aggregate status locally.
- Protocol: Nodes send a "bulk sync" to Redis every 10s listing active User IDs.
- Trade-off: Presence becomes "eventually consistent" (user appears online within 10s of connecting), but infrastructure load drops by 10x.
5. Backpressure Management
This is the most critical reliability feature. What happens when a producer sends 100k msgs/sec but a client (on 3G) can only consume 1k/sec?
A. Consumer-Side (Client Buffer Overflow):
- Buffer Monitoring: The Connection Node maintains a send buffer per socket.
- Threshold: If the buffer exceeds N messages or X bytes:
- Drop (Non-Critical): If the data is transient (e.g., live location, stock tick), drop the oldest frame and push the newest.
- Disconnect (Critical): If the data is critical (e.g., Chat), close the WebSocket connection. The client must reconnect with a fresh buffer. It is better to disconnect a slow consumer than to OOM the server.
B. Producer-Side (Ingress Throttling):
- Rate Limiting: The Ingestion API checks Redis counters before accepting messages.
- Circuit Breaker: If the Message Bus lag grows too high, the ingestion API rejects new messages with
503 Service Unavailable or 429 Too Many Requests.
6. Graceful Degradation & Reliability
A. Connection Draining (Zero-Downtime Deploys):
When deploying new code, you cannot just kill open sockets.
- SIGTERM: The orchestrator sends a termination signal to the Connection Node.
- Drain Mode: The node stops accepting new connections (L7 LB stops routing here) but keeps existing sockets open.
- Rebalance: The node pushes a "Reconnect" message to clients (or waits for idle timeout).
- Shutdown: Once sockets close (or timeout reached), the node exits.
B. The "Circuit Breaker" for Dependencies:
If the Message Bus (Kafka) goes down, the Connection Nodes should not crash.
- Logic: Node switches to Degraded Mode.
- Behavior: It accepts pings (keep-alive) but returns
503 for message sending or simply queues locally (short term) before dropping. The UI shows "Connecting..." status rather than failing completely.
C. Fallback Transport:
Not all networks allow WebSockets (strict corporate firewalls).
- Implement: HTTP Long-Polling or Server-Sent Events (SSE) as a fallback.
- Library: Use libraries like
Socket.IO or SignalR which handle this transport negotiation automatically.
Summary Checklist
| Concept | Solution |
|---|
| Discovery | Redis (mapping UserID -> NodeID) |
| Fanout | Kafka / NATS (Pub/Sub) |
| Presence | Redis SETEX with Heartbeats |
| Backpressure | Drop frames or Disconnect slow consumers |
| Routing | GeoDNS + Consistent Hashing |
| Degradation | Drain mode on deploy + Fallback to Long-Polling |