Hacker News new | ask | show | jobs
by RyanZAG 3877 days ago
> Why does everyone run to websockets even when they only need server-to-client pushing? Probably because it's difficult to get longpolling right.

Definitely not. Longpolling adds a huge amount of overhead when messages are sent relatively frequently. For each longpoll request, the client needs to send all the headers and cookies every time. Each response includes all headers and connection setup. A websocket connection has zero overhead after the initial http upgrade. If you have websocket available, you should always prefer websocket to long polling. In most cases where websocket would be blocked by infrastructure, long polling would be forced to retry extremely quickly because of forced timeout.

2 comments

WebSockets are superior from a technical perspective, no arguing that. But, long-polling makes for more straightforward APIs, which could be valuable if you're more concerned about developer UX than the number of bytes on the wire.

For example, long-polling can actually be RESTful, so it fits in well with conventional API practices. It's also naturally resilient to network issues since each re-poll heals the stream. Users are very unlikely to lose data due to forgetting about some corner case.

Websockets can be RESTful too. I've seen the following:

  GET /orders - fetch all orders
  GET /orders Upgrade: websocket - streaming view of all new orders
The problem with this type of RESTful integration though is the connection limit imposed by browsers. Of course, long poll has the identical problem. You can't long poll more than a couple endpoints.
True, you can use URI paths with WebSockets which at least makes the streams resource-oriented. CBIX does it: https://www.cbix.ca/api-websocket

I think calling this RESTful is a bit of a stretch though, at least in any conventional sense of what that means to people.

There's also EventSource, which I've had some luck with. It's more REST-y, I find.