Getting Started with Server-Sent Events and understanding when to use Polling, WebSockets, and SSE

A brief history of how data sharing over the internet evolved with real-time use cases for HTTP polling, WebSockets, and SSE.

Arpan Banerjee
CodeX
6 min readJul 3, 2021

--

In this article, I will describe a bit of the backstory of how data sharing over the internet evolved over time with emerging demands. I will introduce you to SSE and explain in which use cases you should go for SSE and avoid the overhead of web sockets.

In an upcoming article, I will explain to you, a use case in my Project where I needed to use SSE and, I will walk you through a POC developed using Spring Boot and React to demonstrate the idea.

Here is the use case that I was talking about: “ On file upload, display a real-time progress bar that shows how much the server has processed so far, without hitting endpoints repeatedly in the progress bar.”

A Brief History of Data Sharing over the Internet

It all started with the HTTP one of requests and responses. One entity opens a connection and requests a resource or service, then the other response, either with the requested resource or an error response if it isn’t available. After each request-response cycle, the connection is closed.

HTTP request-response cycles

With HTTP a stateless protocol, if the same two entities need to communicate again, it occurs over a new connection.

This is one of the drawbacks of this kind of communication. For event-driven applications, HTTP — in its natural form — doesn’t quite cut it.

Take Stock pricing as an example. The application would request current share pricing from a data provider and display it on the webpage in the HTTP scenario. However, the concept of ‘updates’ is non-existent in HTTP land. If the app requires more recent data, the logical step is to refresh the page and send out a new HTTP request. While it vaguely does the job, frequently sending out requests is not ideal for implementing this and is also energy-intensive.

To enable these real-time communications let's see what options do we have.

HTTP Polling/ Short Polling

Short polling is an AJAX-based timer that calls at fixed delays. Here using the REST endpoints constant requests are made to the server to see if new information has arrived. So, basically, the client makes requests on a set frequency, it results in a lot of requests and often the server comes back with the same “stale” response. So, it is not that beneficial.

HTTP Polling

Here is how you would go about this in JavaScript.

HTTP Polling

HTTP Long Polling

An improvement to HTTP-Polling is HTTP Long Polling. Here response to a request is returned only when new data appears, made possible by persisting the connection.

The only difference to basic polling, as far as the client is concerned, is that a client performing basic polling may deliberately leave a small time window between each request to reduce its load on the server, and it may respond to timeouts with different assumptions than it would for a server that does not support long polling. With long polling, the client may be configured to allow for a longer timeout period (via a Keep-Alive header) when listening for a response – something that would usually be avoided seeing as the timeout period is generally used to indicate problems communicating with the server.

So it’s almost the same thing, we have to open new HTTP requests every time for fetching new data, it is not bi-directional at all.

For more details on its limitations visit- https://stackoverflow.com/questions/21676324/hard-downsides-of-long-polling

HTTP Long Polling

HTTP Streaming

HTTP Streaming is a push-style data transfer technique that allows a web server to continuously send data to a client over a single HTTP connection that remains open indefinitely. Technically, this goes against HTTP convention, but HTTP Streaming is an efficient method to transfer all kinds of dynamic or otherwise streamable data between the server and client without reinventing HTTP.

SSE builds on top of HTTP Streaming which is the standardization of what was before ‘loosely defined’ in terms of HTTP Streaming. It also introduced easier browser APIs to handle this. It uses the JavaScript EventSource API in order to subscribe to a stream of data in any popular browser.

HTTP Streaming

Web Sockets

WebSocket connections employ TCP/IP in the transport layer to provide a full-duplex connection. Both communicating parties can now send messages in both directions — simultaneously. The connection is persistent, meaning that it is kept open for as long as the application runs. The connection is also stateful — the server can initiate a message or vice-versa.

Use cases-

  • Messaging App
  • Multiplayer Games
  • Collaborative editing/coding
  • Location-based apps

I encourage you to go through the MDN doc, it explains WebSocket in detail.

WebSockets

Introduction To Server-Sent Events

While WebSockets solves most of the real-time use cases out there, but sometimes it might well be overkill. Like in scenarios where we do not need bi-directional communication, SSE might be the way to go.

SSE is a lightweight protocol on top of HHTP Streaming that allows super light-weight subscribe-only capabilities to clients. Unlike WebSockets, SSE does not provide the capability of two way communication, but can be used by the server to push data to the clients in real-time.

Server-Sent Events (SSE) is a server push technology enabling a client to receive automatic updates from a server via an HTTP connection. The Server-Sent Events EventSource API is standardized as part of HTML5 by the W3C.

It provides a memory-efficient implementation of XHR streaming. Unlike a raw XHR connection, which buffers the full received response until the connection is dropped, an SSE connection can discard processed messages without accumulating all of them in memory.

SSE is designed to use the JavaScript EventSource API in order to subscribe to a stream of data in any popular browser. Through this interface, a client requests a particular URL to receive an event stream. SSE is commonly used to send message updates or continuous data streams to a browser client.

In a nutshell, a server-sent event is when updates are pushed (rather than pulled, or requested) from a server to a browser.

Use Cases:

SSE can be particularly used when the client is just interested in subscribing to a stream of data without needing to communicate back to the server in the same connection.

  • Subscribing to a feed of cryptocurrency or stock prices
  • Subscribing to a Twitter feed
  • Receiving live sports scores
  • News updates or alerts

For more details please visit this MDN article on SSE.

Server-Sent Events

That’s all for this blog. Thanks for reading!

Here is the demo of the POC, which I mentioned earlier.

Implementation of Server-Sent Events and EventSource- Live Progress Indicator using React and Spring Boot, explains the POC in detail with a code walk-through.

If you liked this blog, follow me on Medium, Linkedin, and GitHub for more blogs like this.

--

--

Arpan Banerjee
CodeX
Writer for

Software Engineer III @ Walmart | Java | JavaScript | Spring | React | Docker | Linkedin : https://www.linkedin.com/in/banerjee-arpan7/