SSE – Server-Sent Events

In the current age of fast mobile networks and very high internet speed, people are getting accustomed to frequent updates about their area of interest. They need the data to be pushed to them frequently – may it be social media like Facebook or Snapchat or it could be stock updates. Most common technology to get such updates was “Pull” by the client – primarily through AJAX request. However, there’s a better mechanism that is available but is rarely known – “Server-Sent Events”

Server-Sent Events
Server-Sent Events used for real-time stock price update

What are Server-Sent Events?

This is essentially a one-way communication from server to client. The client initiates the connection and then simply waits for an event to be triggered by the server. When the server has some update, it triggers the event and pushes data to the client as “event-stream”. The client then parses the data and takes required action such as displaying the updated information to the client. Once the data is processed, the client continues to wait for the next event. In all this communication, the client never sents a request to pull the data from the server. The server has the complete onus of sending the update, whenever available. And hence the name – “Server-Sent Events”.

How is this better than traditional Pull method?

In traditional Pull method, the client needs to send an update request to the server periodically. When the server receives the request, it may or may not have any update requested by the client. If there’s no update, the only thing client receives is an empty response. In all this, there is an overhead of forming HTTP request and sending an empty response. This gets avoided using Server-Sent Events.

Server-Sent Events
Server-Sent Events [Source: https://streamdata.io/blog/server-sent-events/]

But wait, why don’t you use WebSockets?

You are right. WebSockets provide full duplex communication and could easily replace SSE. However, we need to consider following points:

  • Not all servers support WebSockets as yet. This is new protocol built on top of HTTP and is yet to become widely popular.
  • Most of the use cases where SSE is useful, WebSockets may be overkill. Usually, the client doesn’t need to send anything in real time to the server and hence full duplex communication may not be required.

Use Cases of SSE

  • Stock price updates
  • Friend’s update in social app such as Facebook
  • Likes and retweets count update on Twitter

For details about the implementation and other technical details, read this article on HTML5Rocks website.

Related Links

Related Keywords

WebSockets, HTTP, Internet Protocols, Event Driven Architecture, Networking

One Reply to “SSE – Server-Sent Events”

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.