Often you need to receive data from the server, or exchange it, quickly and continuously — and the usual answer is WebSockets. But if your task only involves receiving data from the server without sending anything back, there’s a good alternative that is undeservedly forgotten: Server-Sent Events. You can read about the differences and trade-offs here:

➡️ https://blog.bitsrc.io/websockets-vs-server-sent-events-968659ab0870

My take:

I started wondering whether SSE was actually convenient after reading a long read (link) about designing a system for “live comments” (i.e., comments on live streams). The design applies to any high-load service with live commenting, such as YouTube, Twitch, or Facebook. The article explains in some detail why SSE was chosen over the other alternatives (which it also discusses). It’s hard to summarize everything here, so you’re better off reading it yourself. But keep one thing in mind: WebSockets aren’t the only way — there are alternatives.

From my own experience with WebSockets, I can point to two problems:

1. Scaling WebSocket servers

Or rather, the lack of it out of the box. If you don’t want to pull in third-party libraries, your only option is to write your own 🙃 With third-party libraries, scaling can be configured (socket.io has an adapter for this, for example), but it takes extra effort from both developers and DevOps. By the way, back in the day the socket.io MongoDB adapter didn’t work correctly, and I ended up writing my own.

2. Incompatibility with proxy servers

Proxy servers often simply don’t support WebSockets because of their technical nature (WebSockets run over TCP, which makes supporting them harder for proxies). Once again you have to fall back on third-party solutions with long-polling support, like the aforementioned socket.io (link)

So it’s worth thinking carefully about whether your task really requires setting up and maintaining WebSockets, or whether something like SSE would solve it more simply. By the way, in NestJS it’s easy to set up — see this example

#websockets #sse