How do you implement rate limiting for WebSocket connections?
Answer
WebSocket rate limiting must occur at two levels: connection rate (new handshakes per IP/time) and message rate (messages per connection/time). (1) Connection rate limiting at the reverse proxy: NGINX limit_req_zone limits WebSocket upgrade requests per IP; (2) Message rate limiting on the server: implement a token bucket or sliding window algorithm per connection. In Node.js: const rateLimiter = new Map(); ws.on('message', () => { const now = Date.now(); const bucket = rateLimiter.get(ws); if (now - bucket.lastReset > 1000) { bucket.count = 0; bucket.lastReset = now; } if (++bucket.count > MAX_PER_SECOND) { ws.close(1008, 'Rate limit exceeded'); } }); (3) Distributed rate limiting — use Redis with sliding window counters (INCR user:rate:userid with TTL) to share rate limit state across multiple server instances; (4) Backpressure signaling — instead of closing connections, send a rate-limit message and temporarily pause processing to allow legitimate clients to recover.
Previous
What is CRDT (Conflict-free Replicated Data Type) and how does it apply to real-time collaboration?
Next
What are the memory implications of maintaining many WebSocket connections?
More WebSockets & Real-time Questions
View all →- Advanced How do you scale WebSocket servers horizontally?
- Advanced What is the difference between WebSockets and WebRTC?
- Advanced How do you implement end-to-end encryption over WebSockets?
- Advanced What is the actor model and how does it apply to real-time systems?
- Advanced How do you handle WebSocket connections in a Kubernetes environment?