Skip to content

Instantly share code, notes, and snippets.

@groundwater
Last active December 18, 2015 00:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save groundwater/5698884 to your computer and use it in GitHub Desktop.
Save groundwater/5698884 to your computer and use it in GitHub Desktop.

Server-Sent Events

I recommend using SSEs like an event-stream only. Do not send data through the stream, only events the client may be interested in. Clients can obtain data they are interested in by making additional HTTP calls to the server.

This keeps the data accessible via HTTP; it does not shard our API into two pieces, one HTTP-based, and one websocket based. We can check any of our endpoints with CURL, and all our routes are stateless. Even our event-stream is relatively stateless, because the server can fire-and-forget events as they occur.

Websockets are fragile. Their protocol is complciated, and the most popular websocket library socket.io is prone to memory leaks. Websockets do not cross proxies well, and debugging websocket issues is a large effort. SSEs are 100% HTTP. They can be dropped into place without re-architecting. SSEs are a simple protocol, they can be composed and parsed by hand, with very little chance of causing leaks.

You could treat websockets like an event-stream, i.e. not send data down the pipe, only events. Most people will not; most people will use the websocket for all future data requests from the client. I cannot say why this is popular, but usually I am met with words like "it's more efficient". I hope we can all admit this is an optimization, and pre-mature at best.

If we are really trying to optimize, just use SPDY. SPDY re-uses your existing TCP connection whenever possible. An SSE stream will keep your SPDY connection open as long as the server is sending events. That means future HTTP requests will traverse the same pipe, and you save re-issuing the TCP connection handshake. If you're still worried about the latency between sending the event, and the client obtaining the data, use SPDY-push.

For example, if the server sends the client an event like "New Message ID=34", it seems resonable that the client will momentarily be asking for the message with ID=24. With SPDY you can pre-emptively fill the clients cache with that request, saving a round-trip and having the message appear almost instantly to the client. Thus we can accomplish as "efficent" a connection as our websocket without losing HTTP and spliting our API.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment