AlgoMaster Logo

Server-Sent Events

Last Updated: January 9, 2026

Ashish

Ashish Pratap Singh

Lets say you are building a dashboard that displays live stock prices. Every second, prices change, and users expect to see updates without refreshing the page. The data flows one direction: from your servers to the browser. Users watch the numbers tick, but they do not send stock prices back.

This is a common pattern. Live sports scores, build pipeline status, social media feeds, breaking news alerts. Data streams from server to client, and the client just listens.

WebSockets can handle this, but they feel like overkill. You do not need bidirectional communication. You do not want to manage a custom protocol. You just want the server to push updates to the browser.

Server-Sent Events (SSE) is designed exactly for this scenario. It provides a simple, standardized way for servers to push data to browsers over a single HTTP connection.

The browser handles reconnection automatically. The protocol is text-based and easy to debug. And it works with your existing HTTP infrastructure.

In this chapter, we will explore:

  • What Server-Sent Events are and how they differ from other approaches
  • How the SSE protocol works under the hood
  • The EventSource API and automatic reconnection
  • Implementation patterns for client and server
  • When SSE is the right choice vs alternatives

What are Server-Sent Events?

Server-Sent Events is a web technology that allows servers to push updates to clients over a persistent HTTP connection. Unlike traditional request-response HTTP where the client initiates every exchange, SSE flips the model: the client opens a connection once, and the server sends data whenever it wants.

The key characteristics of SSE:

  • Unidirectional: Data flows from server to client only
  • Text-based: Uses a simple text protocol over HTTP
  • Persistent: Single connection stays open for multiple messages
  • Auto-reconnecting: Browser automatically reconnects if the connection drops
  • Native browser support: Built into all modern browsers via the EventSource API

Think of SSE as a one-way radio broadcast. The server is the radio station, continuously transmitting. Clients tune in and listen. They cannot talk back through the same channel, but that is fine because they just need to receive.

How SSE Differs from Other Approaches

SSE sits in a specific spot on the real-time communication spectrum. Understanding where it fits helps you choose the right tool.

AspectLong PollingSSEWebSocket
DirectionServer to clientServer to clientBidirectional
ProtocolHTTP (repeated)HTTP (streaming)WebSocket protocol
Connection per messageNew request each timeSingle persistentSingle persistent
Browser APIfetch/XMLHttpRequestEventSourceWebSocket
Auto-reconnectManual implementationBuilt-inManual implementation
Message formatAnyText onlyText or binary
HTTP/2 multiplexingYesYesNo

The comparison with long polling is particularly interesting. Both deliver near real-time updates from server to client. But they work differently:

Long polling creates a new HTTP request for each message. SSE streams multiple messages over a single connection. This makes SSE more efficient for high-frequency updates and eliminates the reconnection gap where messages could be missed.

The SSE Protocol

SSE uses a remarkably simple text-based protocol. The server responds with content type text/event-stream and sends events as plain text separated by blank lines.

Basic Event Format

Each event consists of field-value pairs, one per line:

A blank line signals the end of an event. Here is a concrete example:

Field Reference

FieldRequiredPurpose
dataYesThe event payload. Multiple data lines are concatenated with newlines
eventNoEvent type name. Defaults to "message" if omitted
idNoUnique identifier for resumption after reconnection
retryNoTells browser how long (ms) to wait before reconnecting

Multi-line Data

For payloads that span multiple lines, use multiple data fields:

The browser concatenates these with newline characters, producing: "Line 1 of the log message\nLine 2 of the log message\nLine 3 of the log message".

Comments

Lines starting with a colon are comments and are ignored by the client. These are useful for keeping connections alive:

The EventSource API

Browsers provide the EventSource API for consuming SSE streams. It handles connection management, parsing, and reconnection automatically.

Basic Usage

Connection States

The EventSource object tracks connection state through the readyState property:

StateValueMeaning
CONNECTING0Connection is being established or reconnecting
OPEN1Connection is open, receiving events
CLOSED2Connection is closed, will not reconnect

Automatic Reconnection

The most powerful feature of SSE is built-in automatic reconnection with message resumption. This is functionality you would have to build yourself with WebSockets or long polling.

How It Works

When the connection drops (network issue, server restart, proxy timeout), the browser:

  1. Waits for the retry interval (default 3 seconds, configurable via retry field)
  2. Automatically attempts to reconnect
  3. Sends the Last-Event-ID header with the last received event ID
  4. Server can use this to resume from where the client left off

Server-Side Resumption

The server receives the Last-Event-ID header and should return any events that occurred after that ID:

Configuring Retry Interval

The server can suggest a retry interval by sending the retry field:

This tells the browser to wait 5 seconds before attempting to reconnect after a disconnection. Use longer intervals during known maintenance windows or server overload situations.

Server Implementation Patterns

Implementing an SSE server requires attention to connection management, event formatting, and keeping connections alive.

Basic Node.js Implementation

Keeping Connections Alive

Proxies and load balancers may close idle connections. Send periodic heartbeat comments to keep the connection active:

Architecture for Scale

For production systems with multiple server instances, you need a pub/sub layer to distribute events:

Each server subscribes to a Redis channel. When an event producer publishes, all servers receive it and forward to their connected clients.

SSE vs WebSockets: Making the Choice

This comparison comes up frequently. Here is a framework for deciding:

FactorSSEWebSocket
ComplexityLowerHigher
Browser reconnectionAutomaticManual
Works with HTTP/2Yes (multiplexed)No (separate connection)
Proxy/CDN friendlyYesSometimes blocked
Message overhead~50 bytes2-14 bytes
Client sends dataSeparate HTTP requestSame connection

Many teams default to WebSockets when SSE would serve them better. If your data flow is primarily server-to-client, try SSE first. You can always upgrade to WebSockets if you outgrow it.

Key Takeaways

Server-Sent Events provide an elegant solution for server-to-client streaming that is often overlooked in favor of WebSockets.

  1. SSE is for one-way push. If you need the server to send updates to the client and the client rarely sends back, SSE is simpler than WebSockets.
  2. Automatic reconnection is built-in. The browser handles reconnection and sends Last-Event-ID automatically. This is significant functionality you would need to build yourself with WebSockets.
  3. The protocol is simple. Text fields separated by newlines, blank line ends the event. You can debug by curling the endpoint directly.
  4. Works with existing infrastructure. SSE is just HTTP with a specific content type. Proxies, load balancers, and CDNs handle it naturally (with proper configuration).
  5. HTTP/2 eliminates connection limits. The 6-connection-per-domain limit only applies to HTTP/1.1. With HTTP/2, streams are multiplexed over a single connection.
  6. Use event IDs for reliability. Always send event IDs so clients can resume after disconnection without missing messages.
  7. Consider SSE before WebSockets. Many applications that use WebSockets would be better served by SSE. Bidirectional communication is less common than people think.

For dashboards, feeds, notifications, and any scenario where the server broadcasts and clients listen, SSE delivers real-time updates with minimal complexity.