Silent message loss when sending bulk data over the `websocket` transport (backpressure is ignored)
What happens
When a Node application pushes a large amount of data through sock.send() on the websocket transport, a large portion of the messages never reaches the server — and no error is ever raised. send() behaves as if everything was delivered, the connection stays healthy, onclose reports nothing unusual. The data is simply gone.
Environment
- sockjs-client 1.6.2 (
main) - Node.js,
transports: 'websocket' - Server:
[email protected]
Root cause
Underneath the websocket transport, faye-websocket / websocket-driver already implement backpressure: send() returns false once the socket's write buffer is full, and a drain event is emitted once the buffer has been flushed.
sockjs-client discards both. WebSocketTransport.send() ignores the value returned by the underlying send() and never forwards drain, and SockJS#send() consequently always returns undefined.
Because the backpressure signal never reaches the application, a producer such as fs.createReadStream(...).on('data', chunk => sock.send(chunk)) keeps pushing data at full speed. The client's socket write buffer then grows without bound — I measured ~60 MiB queued in the client for a ~64 MiB payload.
The loss happens when the connection goes away while that queue is still pending (server slow / overloaded / OOM / timed out / reset, or the application shutting down): the pending buffer is discarded by the OS/socket layer, silently, which is exactly the message loss reported above. The first chunk or two already handed to the kernel does arrive, which is why the server sees a small partial fraction rather than nothing.
Worth noting this is not a bug in faye-websocket: as long as the connection stays alive, all messages are eventually delivered. The problem is that sockjs-client gives applications no way to observe backpressure, which is what makes the unbounded buffering — and therefore the loss — possible.
Impact
Any application that sends high-volume or high-throughput data over SockJS from Node is affected, with no diagnostic signal at all. In my case it showed up as roughly 86% of a 600k-line file disappearing when transferred through SockJS, which took a long time to track down precisely because nothing errors out.
Expected behaviour
There should be a way for a producer to find out that the transport cannot accept more data and to wait until it can — e.g. send() reporting backpressure and a drain-style notification, matching the contract of Node's Writable#write and of faye-websocket itself, which sockjs-client currently swallows.
Happy to open a PR if you think that's the right direction for the API.
Source: sockjs/sockjs-client