Skip to main content

Client-Server Communication Model (Part-2) - Server Sent Events

This is the second part of the Client-Server Communication Model. You can have a look at the first part where we discussed Polling, Long Polling, and Webhooks. Here, we will focus on Server-Sent Events.

4. Server-Sent Events (SSE)

Server-Sent Events (SSE) are based on server push technology enabling a client to receive automatic updates from a server via an HTTP connection. The clients make a persistent long-lived connection with the server. Then, the server uses this connection to send the data to the client. It is important to note that the client can’t send the data to the server using the SSE. It is a unidirectional way to flow data from the server to the client. The request-response flow of SSE is:
  1. The client issues an HTTP GET request to the server, with the request headers Accept: text/event-stream and Connection: keep-alive. The inclusion of  Accept: text/event-stream in the request informs the server that the client aims to initiate an SSE connection.
  2. The server replies with ContentType: text/event-stream and Transfer-Encoding: chunked, formally establishing the persistent connection between the server and the client.
    • The server acknowledges the SSE connection request from the client by sending Content-Type: text/event-stream.
    • Transfer-Encoding: chunked enables the server to maintain an HTTP persistent connection.
  3. Upon the occurrence of an event on the server, it transmits the event over the same persistent connection back to the client. The client-side code can then use these fields to take appropriate actions based on the received data. List of predefined Event fields:
    • event: The event field specifies the type or name of the event. It allows clients to categorize events and handle them differently based on their types. For example: event: update

    • data: The data field contains the payload or message of the event. This is where the actual content of the event is placed. For example: data: This is a message for the client.

    • retry: The retry field is optional and specifies the reconnection time in milliseconds. It indicates how long a client should wait before attempting to reconnect if the connection is lost. For example: retry: 300

    • id: The id field is also optional and provides a unique identifier for the event. It can be used for tracking the order of events and ensuring that clients receive events in the correct sequence. For example: id: 123

  4. Either the client or the server can close the connection as necessary.

Advantages:

  • SSE maintains a persistent connection, eliminating the need for repeated HTTP requests. This results in more efficient resource utilization and reduced server load compared to traditional polling approaches.
  • SSE facilitates real-time communication between the server and the client, enabling instant updates without the need for continuous polling.
  • SSE allows for the specification of different event types through the "Event" field, providing a way to categorize and handle various types of events on the client side.
  • SSE includes automatic reconnection mechanisms, ensuring that the client can re-establish a connection in case of interruptions or network issues.
  • SSE does not require additional libraries or complex configurations. It can be implemented using standard web technologies, making it accessible and widely compatible. SSE data is transmitted as plaintext, making it human-readable and easy to debug as well.

Limitations:

  • SSE is designed for server-to-client communication only. It lacks bidirectional capabilities, which means the client cannot easily send messages or data back to the server using the same SSE connection.
  • SSE is designed for sending textual data. It does not provide native support for sending binary data, limiting its suitability for applications that require the transmission of binary content.
  • SSE lacks built-in mechanisms for handling backpressure, which means that if the server sends updates faster than the client can process them, there may be latency or potential resource issues on the client side.
  • The SSE protocol has a predefined set of fields (e.g., "event," "data") for events. Customizing headers beyond these fields is limited, which may restrict certain use cases that require more flexible header structures.
  • SSE relies on the underlying HTTP connection, and interruptions in the connection, such as network issues or server restarts, may lead to temporary loss of updates. Automatic reconnection mechanisms are provided, but they may not be instantaneous.

Real-Life Applications:

  • SSE is utilized to push real-time updates such as new posts, comments, or live stream events to users' timelines without the need for constant refreshing.
  • SSE is employed to provide real-time updates on stock prices, market changes, and financial news to traders and investors.
  • SSE delivers live scores, match updates, and other relevant information to sports enthusiasts in real-time.
  • SSE provides instant notifications about ticket availability, reservation confirmations, or changes to users planning to attend an event or make a reservation.
  • SSE facilitates the real-time display of system metrics, status updates, or sensor readings on monitoring dashboards.
In the next part, we will explore WebSockets—a bidirectional mode of communication allowing both the client and server to interact.

Comments

Popular posts from this blog

CAP Theorem - Debunking Myths

The CAP theorem is a widely recognized idea in the field of distributed systems. It represents three key concepts: Consistency, Availability, and Partition Tolerance. While most of us are familiar with its definition, the devil lies in the details. In this discussion, we'll clarify common myths and misunderstandings. We'll start by explaining the CAP theorem in detail, and then explore various scenarios that may challenge the common interpretation of it. CAP theorem also known as Brewer's theorem states that any distributed data store can provide only two of the following three guarantees: Consistency:  For every read request, the system should provide the most recent write or an error. Note that this consistency is different from the consistency of the  ACID theorem Availability:   For every request, the system should provide a response, even if it’s not the latest data.  In other words, all non-failing (healthy) nodes in the distributed system return a valid ...

Understanding Merkle Tree

A Merkle Tree is a cryptographic tree structure used in computer science and distributed systems to efficiently verify the integrity of large sets of data (accuracy and consistency of data over its lifecycle).  Merkle Tree, also known as Hash Tree is a tree of hash values.  It has a tree structure in which each leaf node is a hash of a small portion of the data, and each non-leaf node is a hash of its children. It is used in applications such as  NoSQL databases, Git, Cryptocurrencies,  File Systems, etc. Some key characteristics of Merkle Tree are: Binary Tree Structure:  The Merkle Tree is a binary tree, where each leaf node represents a hash of data. Leaf Nodes: The data set is divided into fixed-size blocks or "leaves". Each leaf node contains the hash of a specific data block or piece of information. Non-Leaf Nodes: Non-leaf nodes in the tree represent the hash of the concatenation of their child node's hashes.  If the number of leaves is odd...

Event Driven Architecture - SAGA Pattern (Part-1 : Choreography Model)

The Saga pattern is a distributed transactional pattern used in microservices architecture to maintain data consistency across multiple services. It helps manage long-running transactions involving multiple services by breaking them down into smaller, more manageable work units. There is a famous Database per Service  pattern in the Microservice world. Under this paradigm, each service maintains its own dedicated database. Some business transactions, however, span multiple services so we need a mechanism to implement transactions that span through services. Take, for instance, the scenario of placing an online order, which involves actions like inventory verification and item reservation till payment completion. Since services such as Orders, Inventory, and Payment operate on separate databases, the application cannot simply use a local ACID transaction. 2 Phase Commit Protocol  is one of the options being used for ensuring transactions across services. However, it has se...