Structuring cross-region communication
For cross-region rooms, I'll select a leader region for each room while others connect through inter-region mesh. I'll be using consistent hashing with replication, making sure to handle region failover effectively.
I want to ensure graceful degradation—this means limiting features like message rates, turning off typing indicators, and implementing admission control to limit new connections. Reliability is crucial, so I'll differentiate between at-most-once and at-least-once acknowledgments for critical events.
Security-wise, I'll implement auth tokens and rate limiting while providing a structured document discussing choices and tradeoffs, considering capacity planning and connection management.Planning Kubernetes deployment
I need to ensure that I mention operational aspects like deploying on Kubernetes and implementing autoscaling based on connections and outgoing bytes. I want to avoid the thundering herd problem, so a rolling deploy with drained connections, similar to GOAWAY style, is essential.
For graceful draining, I’ll send a "server_going_away" message before closing, and I'll also consider using connection migration and resume tokens. Alright, let's craft this efficiently!
1) Goals and assumptions
You’re building a WebSocket platform that must handle:
- Millions of concurrent connections (long‑lived TCP/TLS)
- Fanout (user → all devices, room/channel → many users, broadcast subsets)
- Presence (online/offline, “active”, last seen, per-room counts)
- Backpressure (slow clients, bursty producers, overloaded regions)
- Shard + region routing (low latency, locality, multi-region resilience)
- Graceful degradation (keep core messaging working under stress)
Key design stance: treat WebSockets as connection transport, and build a separate, scalable routing/fanout layer with bounded queues and explicit shedding.
2) High-level architecture (data plane)
Components (per region)
-
Edge Load Balancer (L4/L7)
- Terminates TCP/TLS (or passes TLS through to gateways)
- Supports sticky routing (consistent hash on
userId or sessionId) where possible
-
WebSocket Gateways (WSG)
- Own actual WS connections; mostly stateless beyond in-memory connection state
- Authenticate, maintain keepalive, manage subscriptions, enforce per-connection quotas
- Expose a small control API to other services (or subscribe to message bus)
-
Routing + Fanout layer
- Responsible for “send to user”, “send to room”, “send to topic”
- Sharded by stable keys (e.g.,
userId, roomId) and scalable horizontally
- Publishes to the correct gateways efficiently
-
Presence service
- Ephemeral state with TTL leases
- Emits presence events and supports queries (with clear consistency expectations)
-
Message fabric (internal pub/sub)
- NATS / Kafka / Redis Streams / Pulsar (choice depends on ordering/durability needs)
- Used for: fanout to gateways, presence events, cross-service signals
- Important: pick a fabric that supports backpressure (bounded buffers, credits, consumer lag metrics)
-
Control plane (global)
- Region selection, shard maps, routing policies, feature flags for degradation
- Optional: global directory for “user home region”, failover orchestration
3) Connection handling at scale
3.1 Gateway responsibilities
Each WebSocket Gateway should:
- Track connection metadata in memory:
connId, userId, deviceId, auth scopes, subscribed topics/rooms, last activity
- Enforce:
- Max subscriptions per connection
- Max outbound buffered bytes per connection
- Rate limits per user/device/IP
- Send keepalive:
- Server ping interval (e.g., 25–45s); client pong required
- Provide drain behavior for deploys:
- Stop accepting new conns
- Mark instance “draining”
- Optionally send “reconnect” hint with new endpoint
- Close idle conns first; hard-stop after timeout
3.2 Sizing rule of thumb
- Gateways are limited by file descriptors, RAM per connection, and egress bandwidth.
- Typical memory footprint per connection (metadata + buffers) can range widely (few KB → tens of KB).
- Design for “gateway handles X connections” and autoscale using:
- active connections
- outbound queue pressure
- CPU + network
4) Connection fanout patterns
You generally need three addressing modes:
A) Send to user (fanout to all devices)
- Key idea: user-level routing shard
- Maintain a mapping:
userId -> {connId(s) on gateway(s)}
- Implementation options:
- Directory-backed fanout
- Gateways register
userId -> gatewayId with TTL
- Fanout service queries directory then publishes to those gateways
- Shard-owned user routing
- Consistent-hash
userId to a “User Router shard”
- Gateways send
CONNECT(userId, connId, gatewayId) to that shard
- “Send to user” goes to shard, shard emits to gateways
Tradeoff: directory lookup adds read load; shard-owned routing keeps the hot path append-only/event-driven.
B) Send to room/channel (potentially huge fanout)
Naively storing full membership everywhere explodes. Prefer:
- Room shards: consistent-hash
roomId → shard owns membership + fanout decisions.
- Gateways forward
JOIN/LEAVE(roomId, userId, connId, gatewayId) to the room shard.
- When publishing to room:
- Publisher sends one message to the room shard
- Room shard fans out by gateway, not by connection:
- build
gatewayId -> [connId list] (or gatewayId -> count + filters)
- send a single envelope per gateway with multiple recipients (batching)
This reduces N×M amplification and lets the shard enforce room-level backpressure policies.
C) Broadcast / topic fanout
For “everyone online” or large topics:
- Avoid per-connection enumeration when possible.
- Use hierarchical fanout:
- Topic root shard → per-gateway batch → gateway local delivery
- Consider sampling or partial delivery under load (graceful degradation).
5) Presence at scale (and what “presence” really means)
Presence is not one thing. Define tiers:
- Transport presence: connection exists (WS is up)
- App presence: authenticated + subscribed to relevant scope
- Active presence: recent activity (typing, foreground, heartbeat)
- Room presence: “online in room” membership + active
5.1 Presence storage model (recommended)
- Presence is ephemeral, stored with TTL leases.
- Each gateway writes heartbeats for its local connections:
presence:{userId}:{deviceId} -> {gatewayId, region, lastSeen, status} with TTL (e.g., 60–120s)
- Disconnect:
- Best-effort delete + publish event
- TTL is the safety net
Store can be Redis Cluster / Aerospike / DynamoDB (if you accept higher latency) depending on needs.
5.2 Presence events
- Publish
PRESENCE_UP/DOWN/ACTIVE/IDLE onto a fabric topic keyed by userId (or roomId for room presence).
- Subscribers (friends lists, room rosters) often do not need perfect accuracy:
- aim for eventual consistency
- allow duplicates/out-of-order; include sequence + timestamp
5.3 Room presence counts
Per-room online counts are expensive if you do precise membership at huge scale.
Options:
- Exact within shard: if room shard owns membership, maintain counts there.
- Approximate:
- per-gateway counts + periodic aggregation
- probabilistic structures (less common, but useful at extreme scale)
- Under load: degrade to “~N online” or remove counts entirely.
6) Backpressure: the critical survival feature
Backpressure must exist at every boundary:
6.1 Per-connection backpressure (inside the gateway)
Each connection has a bounded outbound buffer:
- If buffer exceeds threshold:
- Coalesce (keep only latest state for presence/typing)
- Drop low-priority messages first
- If still growing: disconnect slow consumer (with reason code)
Define message classes:
- P0: critical (chat message, trading order ack)
- P1: important (delivery receipts)
- P2: best-effort (typing, presence flaps)
- P3: debug/telemetry
Policies:
- Never drop P0 (prefer disconnecting the client if necessary)
- Drop/coalesce P2/P3 aggressively
6.2 Gateway-level backpressure (protect the node)
Gateways should have bounded queues from the internal fabric:
- If gateway cannot keep up:
- stop accepting new subscriptions
- signal “overloaded” to routing/fanout layer (credits)
- shed best-effort topics
- as last resort, close a fraction of connections (least recently active)
6.3 Fanout shard backpressure (protect the system)
Room/user shards must bound:
- inbound publish rate
- membership mutation rate
- outbound per-gateway batches
When overloaded:
- Delay or reject JOINs (brownout)
- Drop presence/typing fanout
- Cap room fanout rate (token bucket per room)
- Return “accepted but delayed” semantics where the app can tolerate it
6.4 Fabric-level backpressure (protect cross-service links)
Pick a fabric with observable and enforceable lag:
- Consumer lag metrics drive autoscaling
- Enforce max pending bytes per consumer
- Prefer pull/credit-based consumption for gateways if available
7) Shard + region routing
7.1 Client → region selection
Typical approach:
- Geo DNS / Anycast → nearest region
- On connect, gateway may redirect if:
- user has a “home region”
- room/channel affinity requires it
- region is overloaded
Return a 307 (HTTP) for initial upgrade endpoint selection, or an app-level “RECONNECT to wss://…” instruction.
7.2 “Home region” strategy
To avoid cross-region chatty presence:
- Assign each user a home region (sticky for days/weeks)
- Presence + user routing lives in home region
- Other regions proxy as needed (or encourage clients to connect to home region)
7.3 Room routing across regions
Common patterns:
-
Leader region per room
roomId -> leaderRegion via consistent hash / directory
- Publishes go to leader; leader fans out to all participants
- Remote participants either:
- connect to leader region directly (best), or
- stay local and receive via inter-region gateway relay (adds latency)
-
Multi-region rooms (rare, expensive)
- Replicate membership and messages via CRDT/event log
- Complex ordering/consistency; only justify if required
7.4 Inter-region transport
Use a dedicated inter-region mesh:
- gRPC streams or pub/sub replication
- Rate limited and metered separately
- Apply strict message class filtering (don’t ship typing storms cross-region)
8) Message semantics (ordering, delivery guarantees)
Be explicit; WebSockets do not guarantee delivery beyond TCP’s connection.
Recommended:
- At-most-once for ephemeral events (presence, typing)
- At-least-once for important messages (chat):
- include
messageId, sequence, dedupe window
- optional client ACKs for end-to-end confirmation
- Ordering:
- guarantee ordering within a key (roomId or conversationId) by routing all publishes for that key through the same shard/partition
- do not promise global ordering
9) Graceful degradation (“brownout” plan)
Define operational modes you can switch dynamically (per region and per product surface):
9.1 Degradation ladder (example)
- Normal
- Drop/coalesce best-effort
- disable typing indicators
- coalesce presence to “online/offline only”
- Subscription throttling
- cap rooms per user
- delay JOIN/LEAVE processing
- Fanout throttling
- token bucket per room/topic
- reduce broadcast frequency
- Admission control
- reject new WS connections with retry-after
- or accept but only allow core channels
- Fallback transport
- instruct clients to switch to HTTP long-polling for non-critical updates
- Load shedding
- disconnect a percentage of clients (least active / anonymous) to preserve core users
9.2 Implementation hooks
- Feature flags pushed from control plane to gateways/shards
- “Overload signals” (queue depth, send buffer pressure) auto-trigger steps
- Per-message-class drop rules centrally defined
10) Observability and operations
Must-have metrics
- Connections: current, connects/sec, disconnect reasons, reconnect storms
- Gateway: outbound buffer utilization, dropped messages by class, write latency
- Fabric: consumer lag, pending bytes, publish latency
- Shards: membership size, fanout batch sizes, queue depth
- Presence: TTL expirations vs explicit disconnects, event lag
- Region: p95 RTT to clients, cross-region traffic
Failure modes to design for
- Gateway crash: presence TTL cleans up; clients reconnect
- Fabric partition: isolate best-effort; preserve core messaging by bypass path if needed
- Hot room: shard detects and applies per-room throttles; optionally split/shard room (advanced)
- Reconnect storm after deploy: staged drain + jittered reconnect + exponential backoff
11) A concrete reference flow (room message)
- Client sends
SEND(roomId, payload) to its gateway.
- Gateway authenticates/authorizes, then publishes to room shard keyed by
roomId.
- Room shard:
- validates rate limits
- builds
gatewayId -> recipients[] batch map
- publishes one batched envelope per gateway
- Each destination gateway:
- enqueues to per-connection buffers
- applies priority/backpressure rules
- writes to sockets
Presence updates follow a similar path but are lower priority and aggressively coalesced/dropped.
12) Key design choices (quick recommendations)
- Gateways are dumb-ish (own connections, enforce per-conn backpressure), while routing/fanout shards are smart.
- Batch by gateway for large fanout; avoid per-recipient publishes.
- Presence is TTL-based and eventually consistent; define tiers of presence.
- Backpressure is policy-driven with message classes and bounded queues everywhere.
- Region routing uses a home-region strategy; rooms have a leader region unless you truly need multi-leader replication.
- Graceful degradation is a first-class feature, not an afterthought.
If you share your expected scale (concurrent connections, largest room size, message rate per user, number of regions, and whether chat delivery must be durable), I can propose concrete shard counts, fabric choice, and specific queue/threshold values.