We are going to design a WebSocket scale-out strategy that uses:
- Sharded Brokers: We'll have multiple WebSocket brokers (each can be a process or a set of processes) and we'll shard the connections across them.
- Sticky Sessions: To maintain the same WebSocket connection to the same broker for a given client, we'll use sticky sessions at the load balancer level.
- Failover Playbooks: We'll have a way to detect broker failures and redistribute the shards (and their connections) to other brokers.
Steps:
-
Sharding Strategy:
- We'll use a consistent hashing ring to assign each client (based on a client identifier, e.g., user ID or session ID) to a broker.
- The consistent hashing ring will have multiple virtual nodes for each physical broker to ensure even distribution.
-
Sticky Sessions:
-
The load balancer (like HAProxy, Nginx, or a cloud load balancer) will use a hash of the client's IP or a cookie to route the client to the same broker for the session.
-
However, note that the load balancer's sticky session might not align with our consistent hashing. We can do one of two things:
a) Let the load balancer do sticky sessions by IP (or cookie) and then have the brokers use the same hashing algorithm to determine which broker should own the connection. But if the load balancer and the broker's consistent hashing are not the same, we might have a mismatch.
b) Alternatively, we can have the load balancer forward to any broker and then the broker will check if the client's hash belongs to it. If not, it will redirect the client (or the initial HTTP upgrade request) to the correct broker. This adds an extra hop for the first connection.
-
We can also have the load balancer use the same consistent hashing algorithm as the brokers. This requires the load balancer to be stateful (know about the ring) and update when brokers are added/removed.
-
Failover:
-
Each broker will have a health check (e.g., a heartbeat) to a monitoring system (or a shared storage like Redis) to indicate it's alive.
-
When a broker fails, the monitoring system (or a separate orchestrator) will detect the failure and then:
a) For each shard (virtual node) that was on the failed broker, reassign it to another broker (using the consistent hashing ring, but note that the ring will change because we remove the failed broker and then add new virtual nodes to other brokers?).
b) We have two options for handling the existing connections on the failed broker:
Option 1: The clients will try to reconnect and then the load balancer (with updated consistent hashing) will route them to the new broker. This is simple but requires the client to reconnect (and possibly lose state).
Option 2: We can have a mechanism where the failed broker's connections are migrated to another broker. This is complex and requires state transfer.
-
We'll go with Option 1 for simplicity: when a broker fails, we update the consistent hashing ring (remove the failed broker and redistribute its virtual nodes to the remaining brokers). Then, when clients reconnect, they will be routed to the new broker.
-
Broker Implementation:
- Each broker will maintain connections for its shard of clients.
- They will also have a way to communicate with other brokers (if needed for global operations, but ideally we want to avoid cross-broker communication for scalability). However, for broadcasting messages to all clients, we might need a pub/sub system.
-
Message Routing:
-
If a broker receives a message for a client that is not connected to it (because of sharding), it must forward the message to the correct broker. This requires each broker to know the consistent hashing ring and the location of each client (or at least be able to compute the hash and know which broker is responsible for that hash). Alternatively, we can have a central routing service (like a shared Redis hash table) that maps client IDs to broker addresses. But that central service becomes a bottleneck and a single point of failure.
-
Instead, we can use the consistent hashing ring and have each broker know the ring. They can compute the hash of the client ID and then know which broker is responsible (by looking at the ring). Then they can forward the message to that broker (over a TCP connection or via a message bus).
-
State Management:
-
Each broker is responsible for the state of its clients (e.g., session data). If a broker fails, that state is lost unless we replicate it. We can replicate state to other brokers (or to a database) but that adds complexity.
-
We can design for stateless brokers and store all state in a shared database (or Redis). Then, when a client reconnects to a new broker, the new broker can load the state from the shared database. This is a common pattern.
-
Load Balancer Configuration:
-
We'll use a load balancer that supports consistent hashing (like HAProxy with the hash directive) or we can implement our own routing in the application layer.
-
Alternatively, we can have the clients connect directly to the brokers (bypassing a load balancer) by having the client compute the broker address from the consistent hash. But that requires the client to know about the ring and the broker addresses.
-
Orchestration and Monitoring:
-
We need a way to add and remove brokers dynamically. We can use a configuration service (like ZooKeeper, etcd, or Consul) to store the current ring and have all brokers and the load balancer watch for changes.
-
When a new broker is added, it will get a portion of the virtual nodes from the existing ring. The load balancer and existing brokers will update their ring.
-
When a broker is removed (or fails), the same process happens.
-
Failover Playbook:
- Detection: Health checks (from the load balancer and/or an external monitor) detect broker failure.
- Action:
a) Remove the failed broker from the configuration service (or mark it as down).
b) The configuration service will update the ring (or we have a separate ring manager that does this).
c) The load balancer and all brokers will get the updated ring (via watching the configuration service).
d) Clients that try to reconnect will be routed to the new broker (according to the updated ring) by the load balancer (if using load balancer with consistent hashing) or by the broker that receives the initial connection (if we do the redirect method).
-
Considerations:
- During a failover, some messages might be lost if the broker fails before forwarding them. We might need to implement message persistence (acknowledgements) at the application level.
- We must handle the case where a client is connected to a broker that is no longer responsible for it (because the ring changed). The broker should disconnect the client (or close the WebSocket) and then the client will reconnect and get routed to the correct broker.
- We must ensure that the consistent hashing ring is the same for all brokers and the load balancer. We can have a central configuration service that stores the ring and all components watch it.
Implementation Outline:
-
Configuration Service: We'll use etcd to store the ring. The ring is a list of virtual nodes, each virtual node is mapped to a physical broker.
Example ring structure in etcd:
{
"ring": [
{"vnode": "broker1#1", "broker": "broker1", "address": "broker1:8080"},
{"vnode": "broker1#2", "broker": "broker1", "address": "broker1:8080"},
{"vnode": "broker2#1", "broker": "broker2", "address": "broker2:8080"},
...
]
}
We also need to know the physical brokers and their addresses. We can store the physical brokers in a separate key.
-
Broker Startup:
- When a broker starts, it registers itself in etcd (if not already) and then watches the ring key.
- It computes which virtual nodes it owns (based on the current ring and its own address) and accepts connections only for clients whose hash falls into its virtual nodes.
-
Load Balancer:
-
We can configure the load balancer to use the same consistent hashing algorithm and have it watch the etcd ring. However, not all load balancers support watching a dynamic ring. Alternatively, we can have a sidecar that updates the load balancer configuration (like HAProxy) when the ring changes.
-
Or, we can have the load balancer do simple round-robin and then each broker does the consistent hashing check. This is the redirect method:
Client -> Load Balancer (round-robin) -> Broker A
Broker A computes the hash of the client ID and sees that it should be on Broker B.
Broker A sends an HTTP 302 redirect (or a custom WebSocket handshake response) with the address of Broker B.
But WebSocket upgrade doesn't support redirects easily. Alternatively, we can have the broker close the connection and send a message with the correct broker address, and the client reconnects.
-
We'll go with the load balancer using consistent hashing that matches the ring. We can use a custom load balancer that watches etcd and updates its hash table.
-
Message Routing:
-
Each broker knows the ring. When it receives a message for a client, it computes the hash of the client ID and looks up the broker address for that hash. If the message is for a client that is not connected to it, it forwards the message to the responsible broker (over a TCP connection between brokers, using a simple protocol).
-
We need to establish connections between brokers (a mesh or a central router). We can have each broker connect to every other broker (mesh) or we can have a central message bus (like Redis Pub/Sub or Kafka) but that might be a bottleneck.
-
Alternatively, we can have the brokers communicate via the same consistent hashing ring: each broker knows the addresses of all brokers, so they can connect to each other.
a) **Initialization**:
- Set up etcd with a ring key that contains a list of virtual nodes (each virtual node is a hash and the broker address). We can generate the ring by having each broker claim some virtual nodes (based on its weight) and then sort by hash.
b) **Broker**:
- On startup, register itself (if not already) and then watch the ring key.
- When the ring changes, the broker computes which virtual nodes it owns (by looking at the ring and its own address). It then starts accepting connections for clients whose hash (of the client ID) falls in its virtual nodes.
c) **Load Balancer**:
- We can have a custom load balancer that also watches the ring and uses the same consistent hashing algorithm to route the initial connection.
d) **Message Routing**:
- Each broker has a connection to every other broker (or uses a message bus). When it receives a message for a client not in its range, it forwards to the broker that owns that client (according to the ring).
e) **Failover**:
- When a broker fails, it is removed from the ring (by the ring manager or by the monitoring system). The ring in etcd is updated (without the failed broker's virtual nodes). All brokers and the load balancer get the updated ring.
- Clients that were connected to the failed broker will disconnect and then reconnect. The load balancer (with the updated ring) will route them to the new broker (the next in the ring for their hash). The new broker will load their state from Redis and resume.
f) **Adding a Broker**:
- When a new broker is added, it registers and then the ring manager (or the new broker itself) adds virtual nodes for the new broker and removes an equivalent number of virtual nodes from the existing brokers (or we can just add and then the ring size increases). Then update the ring in etcd.
11. Alternative without Load Balancer:
- We can have the client compute the broker address from the hash and connect directly. But then we need to expose all broker addresses to the client and the client must handle the ring changes (which is complex).
-
Implementation Complexity:
- This design requires a consistent hashing library, a configuration service (etcd), a shared state store (Redis), and a way for brokers to communicate (direct TCP or message bus).
-
Simplification:
- We can use a cloud load balancer that supports consistent hashing (like AWS ALB with target group stickiness and a custom header for the hash) but then the load balancer must be updated when the ring changes.
- Alternatively, we can use a service mesh (like Istio) that can do consistent hashing and has integration with service discovery.
Given the complexity, we might want to consider using an existing WebSocket broker that supports clustering (like Socket.IO with Redis adapter, or EMQ X). But the requirement is to engineer a strategy.
- Failover Playbook:
**Detection**:
- Health checks from the load balancer and a separate monitoring process (that pings the broker's health endpoint).
**Response**:
- Step 1: Mark the broker as failed in the monitoring system.
- Step 2: Remove the broker from the ring in etcd (using a transaction to remove all virtual nodes for that broker).
- Step 3: Wait for the load balancer and brokers to update their rings (by watching etcd).
- Step 4: Notify the operations team (if needed) and start an instance to replace the broker (if using auto-scaling).
**Recovery**:
- The new broker (if auto-scaled) will start and register itself. Then the ring manager will add virtual nodes for it and remove an equivalent number from the other brokers (to keep the total virtual nodes constant, or we can let the ring grow). Then update the ring.
**Manual Intervention**:
- If the failure is due to a temporary issue, we might want to wait for the broker to recover and then re-add it to the ring. But in that case, we would have to re-add the broker and then reassign some virtual nodes from the other brokers to it.
15. Testing:
- We must test the failover by killing a broker and ensuring that clients reconnect and messages are not lost (with proper acknowledgements).
- Monitoring:
- Monitor the ring size, the number of connections per broker, the health of brokers, and the message latency between brokers.
Given the complexity, this design is for a large-scale WebSocket deployment. For smaller scales, we might use a single broker with a load balancer and sticky sessions without sharding.
Let me know if you need more details on a specific component.
I'll design a comprehensive WebSocket scale-out strategy using the requested components. Here's a production-ready architecture:
Architecture Overview
Clients → Load Balancer → Sharded WebSocket Brokers → Shared State/Message Bus
↑ ↑
Sticky Sessions Horizontal Scaling
| |
Failover Detection Shard Management
1. Sharded Brokers Strategy
Sharding Mechanism
Sharding Algorithm: Consistent Hash Ring
- Virtual Nodes: 100-500 per physical broker
- Hash Key: client_id or session_id
- Replication Factor: 2-3 (for failover within shard group)
Broker Groups:
Group A (Shard 0-3): Handles clients with hash(0-25%)
Group B (Shard 4-7): Handles clients with hash(25-50%)
Group C (Shard 8-11): Handles clients with hash(50-75%)
Group D (Shard 12-15): Handles clients with hash(75-100%)
Broker Configuration
Broker Specifications:
- Minimum: 4 vCPU, 16GB RAM, 10Gbps NIC
- Connections per broker: 50K-100K (optimized)
- WebSocket library: tokio-tungstenite/ws (Rust) or Netty (Java)
- OS tuning:
- net.core.somaxconn = 65535
- net.ipv4.tcp_tw_reuse = 1
- fs.file-max = 2000000
Process Model:
- Single broker process with multiple threads/event loops
- No multi-process per broker (reduces cross-process coordination)
2. Sticky Sessions Implementation
Load Balancer Configuration (HAProxy Example)
frontend ws_frontend
bind *:443 ssl crt /etc/ssl/certs/websocket.pem alpn h2,http/1.1
mode http
option httplog
# Sticky session using consistent hash (matches broker sharding)
stick-table type string size 1M expire 30m store conn_cur
# Use client_id cookie if available, fallback to source IP
stick on cookie(JSESSIONID) if { req.cook(JSESSIONID) -m found }
stick on src if { src -f /etc/haproxy/trusted_ips.lst }
# Consistent hash for initial routing (matches ring)
http-request set-var(req.ring_hash) req.cook(JSESSIONID)
http-request set-var(req.ring_hash) src if { var(req.ring_hash) -m str "" }
use_backend %[var(req.ring_hash),hash(/etc/haproxy/ring.map),mod(4)] if { var(req.ring_hash) -m found }
default_backend ws_brokers
backend ws_brokers
mode http
balance roundrobin # Fallback if hash fails
option httpchk GET /health
http-check expect status 200
# Server list with weights (adjust per capacity)
server broker1 10.0.1.1:8080 weight 10 check inter 2s rise 2 fall 3
server broker2 10.0.1.2:8080 weight 10 check inter 2s rise 2 fall 3
server broker3 10.0.1.3:8080 weight 10 check inter 2s rise 2 fall 3
server broker4 10.0.1.4:8080 weight 10 check inter 2s rise 2 fall 3
# Retry configuration
retries 3
option redispatch # Route to another broker if selected one fails
Ring Mapping File (ring.map)
# Format: <hash_prefix>\t<broker_name>
0\tbroker1
1\tbroker1
...
25\tbroker2
26\tbroker2
...
3. Failover Playbooks
3.1 Automated Failover (Primary)
Trigger Conditions:
- Broker health check failure (3 consecutive failures)
- TCP connection timeout > 30s
- Memory usage > 90% for 2 minutes
- CPU throttling detected
Automated Response:
1. Detection (5s):
- Monitoring system (Prometheus/Thanos) alerts
- Load balancer marks broker as down (drain connections)
2. Isolation (10s):
- Remove broker from ring in etcd/Consul
- Revoke broker's TLS certificates
- Stop accepting new connections on broker
3. Recovery (30s-5min):
- Existing connections: allow graceful disconnect (30s timeout)
- Clients auto-reconnect (exponential backoff: 1s, 2s, 4s, 8s)
- Load balancer reroutes to new broker via updated ring
4. Verification (60s):
- Check client reconnection rate (>95% should reconnect)
- Monitor message latency (should return to baseline)
- Validate state consistency with Redis/DB
5. Documentation:
- Create incident ticket automatically
- Log timestamps for SLA calculation
- Capture broker core dump if available
3.2 Manual Failover (Secondary)
#!/bin/bash
# failover-handler.sh
BROKER_ID=$1
REASON=$2
# 1. Prepare
etcdctl put /ring/status/$BROKER_ID "draining"
haproxyctl set server ws_brokers/$BROKER_ID state drain
# 2. Wait for connections to drain (max 60s)
timeout 60s ./wait-for-drain.sh $BROKER_ID
# 3. Remove from ring
./update-ring.py --remove $BROKER_ID
# 4. Optional: force disconnect remaining connections
# Only if drained connections > threshold after timeout
if [ $(get-connection-count $BROKER_ID) -gt 100 ]; then
./force-disconnect.sh $BROKER_ID
fi
# 5. Post-failover validation
./validate-ring.sh
./check-client-sessions.sh
# 6. Alert team
./notify-team.sh "Broker $BROKER_ID failed: $REASON"
3.3 Recovery Playbook
Broker Recovery Steps:
1. Fix Root Cause:
- Hardware failure → Replace instance
- Software bug → Deploy fix + rollback plan
- Resource exhaustion → Increase limits + add capacity
2. Rejoin Ring:
- Ensure broker health endpoint returns 200
- Run: ./join-ring.py --broker $BROKER_ID --virtual-nodes 100
- Verify: etcdctl get /ring/status/$BROKER_ID == "active"
3. Gradual Ramp-up:
- Start with weight 1 in HAProxy
- Increase weight 10% every 5 minutes if healthy
- Monitor: connection count, error rate, latency
4. Validation:
- Send test messages through broker
- Verify state sync with Redis
- Check metrics: gc_pause_seconds, open_fds
5. Cleanup:
- Remove stale virtual nodes from ring
- Rebalance if needed (./rebalance-ring.py)
4. State Management & Consistency
Shared State Store (Redis Cluster)
Configuration:
- 6 nodes (3 masters, 3 replicas)
- Sharding: client_id % 1024
- Persistence: AOF every 1 second
- Memory: 64GB total (32GB data, 32GB for replication buffer)
Data Structure:
- User sessions: HSET session:{client_id} data payload
- Presence: SET presence:{client_id} broker:timestamp
- Message queues: LIST queue:{client_id}:pending
Replication:
- Asynchronous with wait 1 for write acknowledgments
- Cross-datacenter replication for DR: 1 replica in secondary DC
Message Routing
Client → Broker A (shard 5)
Broker A not responsible? → Check Redis for correct broker → Forward via broker mesh
Broker mesh: Direct TCP between brokers (gossip protocol)
Fallback: Redis Pub/Sub channel for broadcast messages
5. Monitoring & Alerting
Key Metrics
Per-Broker Metrics:
- websocket_connections_active
- websocket_messages_received_total
- websocket_messages_sent_total
- websocket_frame_processing_time_seconds
- memory_usage_bytes
- file_descriptors_used
- tcp_retransmits_total
Ring Metrics:
- ring_virtual_nodes_total
- ring_migrations_in_progress
- client_distribution_stddev (should be < 0.1)
SLOs:
- Connection establishment: <500ms p99
- Message delivery: <100ms p99
- Failover time: <60s (detection to reroute)
- Availability: 99.99%
Alert Rules (Prometheus)
- alert: BrokerDown
expr: up{job="ws_broker"} == 0
for: 30s
annotations:
description: "Broker {{ $labels.instance }} is down"
playbook: "failover-primary"
- alert: ClientReconnectRateHigh
expr: rate(websocket_reconnects_total[5m]) / rate(websocket_connections_active[5m]) > 0.1
for: 2m
annotations:
description: "Reconnection rate >10% indicates problems"
- alert: ShardImbalance
expr: stddev(websocket_connections_active by (shard)) > 10000
for: 5m
annotations:
description: "Shard imbalance detected - consider rebalancing"
6. Deployment & Infrastructure
Kubernetes Deployment (Optional)
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: ws-broker
spec:
serviceName: ws-broker
replicas: 4 # Initial, can scale
selector:
matchLabels:
app: ws-broker
template:
metadata:
labels:
app: ws-broker
spec:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: app
operator: In
values:
- ws-broker
topologyKey: kubernetes.io/hostname
containers:
- name: broker
image: ws-broker:1.2.3
ports:
- containerPort: 8080
name: websocket
resources:
limits:
memory: "12Gi"
cpu: "2"
requests:
memory: "8Gi"
cpu: "1"
readinessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
livenessProbe:
httpGet:
path: /live
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
Infrastructure Requirements
Network:
- All brokers in same L2/L3 segment (low latency <1ms)
- Dedicated NIC for broker-to-broker traffic (optional)
- Load balancer with 10Gbps+ capacity
Storage:
- Local NVMe for logs (10GB/day per broker)
- Network storage for state (Redis cluster)
Security:
- Mutual TLS between brokers
- mTLS for client connections (optional)
- Network policies: brokers only talk to Redis and each other
7. Operational Procedures
Daily Checks
# 1. Ring consistency
etcdctl get /ring --prefix | jq '.' > ring.json
./validate-ring-hash.py ring.json
# 2. Connection distribution
redis-cli --cluster check | grep "slot"
# 3. Broker health
for broker in $(get-brokers); do
curl -s http://$broker:8080/health | jq .
done
# 4. Failover test (canary)
./test-failover.sh --broker broker1 --graceful
Scaling Procedures
# Scale up (add broker):
./add-broker.py --broker broker5 --virtual-nodes 100
# Wait for ring propagation (30s)
./rebalance-traffic.py --target-weight 1.0
# Scale down (remove broker):
./drain-broker.py --broker broker1
./wait-for-drain.sh broker1
./remove-broker.py --broker broker1
# Wait 5 minutes, then destroy instance
8. Disaster Recovery
Multi-Region Setup
Region A (Primary):
- 4 brokers (shards 0-7)
- Redis master cluster
- Load balancer A
Region B (DR - Passive):
- 4 brokers (standby, no traffic)
- Redis replica (async, 1-5s lag)
- Load balancer B (hot standby)
DR Activation:
1. Promote Redis replica in Region B
2. Update DNS/lb to point to Region B
3. Boot brokers in Region B (1-2 minutes)
4. Clients reconnect to new region (TLS handshake)
5. Drain Region A (optional)
Backup Strategy
Redis:
- RDB every 6 hours to S3
- AOF every minute (ship to S3)
- Retention: 30 days
Broker Configs:
- etcd/Consul state backed up hourly
- HAProxy configs in Git
Recovery Time Objective (RTO):
- Single broker: 2 minutes (auto-failover)
- Full region: 15 minutes (manual DR activation)
9. Limitations & Trade-offs
Trade-offs Made
- Sticky Sessions vs. Perfect Distribution: Sticky sessions may cause minor imbalances (10-15%) but are essential for connection state.
- Eventual Consistency: Redis async replication means brief inconsistency during failover (<1s).
- No Cross-Broker Messaging: Brokers don't directly message each other; all routing via Redis reduces complexity.
- Client Reconnection Required: During broker failover, clients must reconnect (loss of in-flight messages).
Limitations
- Large Broadcasts: Broadcasting to 1M clients requires Redis Pub/Sub (may drop messages if subscriber lag).
- Chatty Applications: Per-message Redis lookups add ~1-2ms latency.
- Client State Loss: If broker crashes before persisting to Redis, state lost (use client-side acks).
When to Avoid This Architecture
- <10K concurrent connections (use single broker + LB)
- Real-time gaming (<50ms latency requirement) → Consider dedicated game servers
- Strict message ordering across shards → Requires sequence numbers + replay
10. Cost Optimization
Cost Saving Opportunities:
1. Spot Instances for Brokers:
- Use with 60s termination notice
- Maintain 20% buffer capacity
- Auto-replacement via ASG/Cluster Autoscaler
2. Redis Sizing:
- Start with 3 nodes (2 masters, 1 replica)
- Scale horizontally as needed
- Use reserved instances for 1-3 year commitment
3. Broker Right-sizing:
- Monitor connections per broker
- Target 70% utilization during peak
- Scale at 80% CPU or 85% memory
Estimated Monthly Cost (us-east-1, 1M concurrent connections):
- 8 x m5.2xlarge brokers: $1,152
- Redis cluster: $800
- Load balancer: $200
- Monitoring/etcd: $100
- Total: ~$2,252/month
Implementation Roadmap
Phase 1: Foundation (Week 1-2)
- Deploy Redis cluster
- Implement basic broker with sharding
- Set up HAProxy with basic round-robin
- Create ring manager in etcd
Phase 2: Sticky Sessions (Week 3)
- Implement consistent hash in LB
- Add cookie-based affinity
- Test client reconnection
Phase 3: Failover (Week 4)
- Build health checks
- Implement automated failover script
- Test graceful degradation
- Document playbooks
Phase 4: Scale Testing (Week 5)
- Load test to 250K connections
- Chaos testing (kill brokers randomly)
- Measure reconnection rates
- Tune parameters
Phase 5: Production (Week 6)
- Deploy to canary environment
- Gradually shift traffic
- Monitor 72 hours
- Full production cutover
This strategy balances complexity with reliability. The key is automating failover and maintaining sticky sessions while allowing horizontal scaling. Start with 4 brokers, monitor shard distribution, and expand as needed.