You might not need WebSockets

https://news.ycombinator.com/rss Hits: 24
Summary

What’s a WebSocket? If you’re new to web development or you haven’t heard of a WebSocket before, they’re a way to open a two-way communication channel between the client and server using HTTP as the transport protocol. In less nerdy terms, it’s a way to keep an open line of communication between the client and server so that both can send and receive messages at any time. (MDN Reference) Because of how it’s advertised on the tin, it’s natural to think of a WebSocket as the best (and sometimes only) way to orchestrate a long-living stream of data between client and server, like for instance a real time application. In practice though, it turns out there are a few reasons why you might not want to use them: WebSocket messages aren’t transactional I see a lot of instances where WebSockets are used as the way of maintaining consistency for some kind of state object. For instance, you use the transmitting side of the socket to represent mutations to some object, and the receiving side of the socket to represent state as it gets changed by those mutations. That way if you have multiple clients listening to the same object, they’ll all see the same state changes without having to refresh the page. # Client 1 >>> { command: "increment", amount: 5 } <<< { event: "count", value: 5 } >>> { command: "decrement", amount: 2 } <<< { event: "count", value: 3 } # Client 2 <<< { event: "count", value: 5 } <<< { event: "count", value: 3 } But what if you placed some kind of invariant condition on the state object? For instance, you want to make sure that the count is never negative: <<< { event: "count", amount: 5 } >>> { command: "decrement", amount: 6 } <<< { error: "count cannot be negative" } The issue here is that there’s no association between the mutation and error message since the error message will be received on the same stream as every other message. We can’t reliably say “the next message” received on the stream is the result of the previous command since the server could...

First seen: 2025-04-11 23:50

Last seen: 2025-04-12 22:56