StackMonkey
Home / Templates / Chat Service

Chat Service System Design: 500k WebSockets, Epoll Limits & Pub/Sub Routing

A complete architectural breakdown of a Discord / Slack / WhatsApp scale real-time messaging cluster: stateful TCP/WebSocket connection pooling, Linux epoll file descriptor limits, Redis Pub/Sub session affinity routing, and Cassandra time-series commit logs.

Peak Concurrent Sockets
500,000
Persistent Full-Duplex TCP
Message Throughput
5,000 /s
Peak ingress message rate
Gateway Socket RAM
5.0 GB
10KB kernel buffers / socket
P99 Delivery Latency
< 20 ms
End-to-end hop over Pub/Sub
Step 1 of 4

Socket Memory & Epoll Capacity Math

Why naive HTTP REST polling melts infrastructure at 500k concurrent users, and how operating systems budget RAM and file descriptors for long-lived WebSockets.

The Polling Catastrophe

Short Polling HTTP Breakdown

If 500,000 active mobile clients poll for new messages once every 2 seconds, the gateway cluster receives an unsustainable request barrage:

500,000 users 梅 2 sec = 250,000 QPS
Avg HTTP Header Overhead: 800 bytes
Ingress Wastage: 250k 脳 800B = 200 MB/sec
99.8% of responses are empty HTTP 304s
Result: Ingress gateways spend 95% of CPU cycles terminating TLS handshakes and parsing headers for empty checks.
Socket Memory Budget

Linux Kernel TCP Overhead

Unlike stateless HTTP, each WebSocket holds a permanent TCP socket descriptor and kernel buffers in gateway memory:

Read Buffer (rmem): 4 KB
Write Buffer (wmem): 4 KB
TLS Session Context: ~2 KB
Per-Socket Total: 10 KB / connection
500,000 脳 10 KB = 5.0 GB RAM
Split across 10 gateway pods = 50,000 connections and 500 MB RAM per pod. Easily fits in standard 4GB container limits.
OS Parameter Tuning

Epoll & File Descriptors

Default Linux distributions cap process file descriptors at 1,024, immediately rejecting connection 1,025 with EMFILE: Too many open files.

nofile ulimit: 1,048,576
fs.file-max: 2,097,152
net.core.somaxconn: 65,535
tcp_max_syn_backlog: 32,400
Event loop: Go / Rust epoll non-blocking I/O event loops sleep until I/O events fire, incurring 0% idle CPU for parked sockets.
Step 2 of 4

Session Affinity & Inter-Gateway Pub/Sub

Alice is connected to Gateway Pod 02. Bob is connected to Gateway Pod 09. How does Gateway Pod 02 route a message to Bob in sub-millisecond time without broadcasting to every server?

Component A 路 Central Session Map O(1) Lookup

Distributed Session Registry (Redis)

When a client connects and completes TLS negotiation, the gateway writes an ephemeral session record into Redis Cluster:

KEY: user_session:bob_9918
{
"gateway_id": "gw-pod-09",
"pod_ip": "10.0.9.45",
"connected_at": 1718001024,
"ttl": 90
}

Clients emit heartbeat pings every 45s to extend the 90s TTL. If a gateway node dies without sending a disconnect event, stale sessions expire naturally within 90 seconds.

Component B 路 Message Dispatch < 5ms Hop

Inter-Gateway Message Bus (Redis Pub/Sub)

Each gateway pod subscribes to its own unique topic channel: channel:gw-pod-09.

  1. Alice sends message destined for Bob to Gateway 02.
  2. Gateway 02 checks Redis: Bob is on gw-pod-09.
  3. Gateway 02 publishes payload to channel:gw-pod-09.
  4. Gateway 09 receives event, finds Bob's local socket descriptor, and flushes frame.

If Bob has no active Redis key, Gateway 02 immediately drops an event onto RabbitMQ to trigger Apple APNs / Google FCM mobile push alerts.

Step 3 of 4

The Reconnect Thundering Herd Storm

What happens when a cell tower blip drops 50,000 mobile devices simultaneously, and all 50,000 attempt to reconnect within 1 second?

The TLS Cryptographic CPU Spike

Maintaining an established TCP connection costs near-zero CPU. However, establishing a TLS 1.3 connection requires Diffie-Hellman asymmetric key exchange (ECDHE curve computation) and RSA signature verification.

TLS Handshake Computation:
CPU time per TLS 1.3 handshake: 2.5 ms (0.0025 sec)
Concurrent Reconnecting Sockets: 50,000 clients
Total CPU Work: 50,000 脳 0.0025s = 125 CPU core-seconds
On a 16-core cluster: 125 梅 16 = 7.8 seconds of 100% CPU lockup!

The Cascade Death Spiral

  1. Event Loop Lockup: Gateway CPU reaches 100% saturation. Event loop lag surges from 2ms to over 4,000ms.
  2. Liveness Probe Failure: Kubernetes kubelet checks GET /healthz. The blocked thread cannot respond within 3 seconds.
  3. Pod Termination: Kubernetes kills 4 of the 10 gateway pods for failing health checks.
  4. Cascading Pod Collapse: Remaining 6 pods instantly absorb the entire 50k handshake queue, freeze, and are killed in turn. The cluster enters an endless CrashLoopBackOff.
Step 4 of 4

The Resilient Production Architecture

How StackMonkey models the fault-tolerant Chat Service topology with Layer 4 load balancing, session affinity registries, Redis Pub/Sub, and ScyllaDB time-series storage.

01 路 Layer 4 Anycast Load Balancer
AWS NLB / Maglev L4
Distributes TCP SYN packets based on 5-tuple hash (`src_ip, src_port, dst_ip, dst_port, tcp`). Performs no TLS termination; passes raw TCP streams directly to gateway pods.
02 路 Stateful WebSocket Gateways
Go / Rust Epoll Workers
Terminates TLS, upgrades HTTP to RFC 6455 WebSockets, maintains 50,000 persistent socket descriptors per pod, and emits 45s heartbeat pings.
03 路 Session Affinity Registry
Redis Cluster (Key-Value)
Stores `user_id -> gateway_pod_id` mapping in memory with 90s TTL. Enables any gateway worker to resolve the physical destination node of any recipient in <1ms.
04 路 Inter-Gateway Message Bus
Redis Pub/Sub / Kafka
Point-to-point pub/sub channels (`channel:gw-pod-X`). Decouples senders from receivers so gateway nodes can dispatch packets directly across cluster instances.
05 路 Wide-Column Message Store
ScyllaDB / Apache Cassandra
Partition key `((channel_id), bucket_month)` clustered by `message_id TIMEUUID`. Appends chat messages with zero locking and provides sequential range scans for chat scroll history.
06 路 Mobile Push Notification Worker
RabbitMQ + APNs / FCM Dispatcher
When recipient has no active session key in Redis, message buffers into a RabbitMQ priority queue. Asynchronous background workers deliver Apple APNs and Google FCM alerts.
Interactive Discrete Event Simulation

Simulate the Chat Service Topology Live

Stress test 500k concurrent WebSocket sessions, inject network disconnect waves to simulate thundering herd reconnects, and verify queue depth thresholds live in your browser.