Server-Sent Events vs Polling

Ajax polling adds a lot of HTTP overhead since it is constantly establishing and tearing down HTTP connections. As HTML5 Rocks puts it “Server-Sent Events on the other hand, have been designed from the ground up to be efficient.”

Server-sent events open a single long-lived HTTP connection. The server then unidirectionally sends data when it has it, there is no need for the client to request it or do anything but wait for messages.

One downside to Server-sent events is that since they create a persistent connection to the server you could potentially have many open connections to your server. Some servers handle massive numbers of concurrent connections better than others. That said, you would have similar problems with polling plus the overhead of constantly reestablishing those connections.

Server-sent events are quite well supported in most browsers, the notable exception of course being IE. But there are a couple of polyfills (and a jQuery plugin) that will fix that.

If you are doing something that only needs one-way communication, I would definitely go with Server-sent events. As you mentioned Server-sent events tend to be simpler and cleaner to implement on the client-side. You just need to set up listeners for messages and events and the browser takes care of low-level stuff like reconnecting if disconnected, etc. On the server-side it is also fairly easy to implement since it just uses simple text. If you send JSON encoded objects you can easily turn them into JavaScript objects on the client via JSON.parse().

If you are using PHP on the server you can use json_encode() to turn strings, numbers, arrays and objects into properly encoded JSON. Other back-end languages may also provide similar functions.

Leave a Comment