What is backpressure in WebSocket communication?
Answer
Backpressure occurs when the sender produces data faster than the receiver can process it, causing memory buildup. In WebSocket, the ws.bufferedAmount property (client-side) shows how many bytes are queued in the browser's send buffer but not yet transmitted. If you call ws.send() faster than the network can carry the data, bufferedAmount grows unboundedly, eventually crashing the browser tab. The solution: implement flow control by checking bufferedAmount before sending — if (ws.bufferedAmount < THRESHOLD) ws.send(data). On the server side (Node.js), the ws.send() callback and the drain event on the underlying socket signal when buffered data has been sent. For high-throughput scenarios (video streaming, game state), implement a producer-consumer pattern where the producer pauses when the buffer is full.
More WebSockets & Real-time Questions
View all →- Intermediate How do you implement a WebSocket server in Node.js using the `ws` library?
- Intermediate What are Socket.IO rooms and namespaces?
- Intermediate How do you handle WebSocket reconnection logic?
- Intermediate What is the difference between Socket.IO and raw WebSockets?
- Intermediate How do you authenticate WebSocket connections?