Search⌘ K
AI Features

Server-Sent Events (SSE)

Explore how to implement Server-Sent Events (SSE) for unidirectional server-to-client streaming in system design. Understand SSE’s HTTP-based protocol, automatic reconnection using event IDs, and its advantages over WebSockets and long polling. Learn trade-offs, scaling considerations, and practical usage to design resilient real-time applications.

The previous lesson explored WebSockets, which solve bidirectional communication but introduce stateful connection management, protocol upgrade handshakes, and sticky session requirements that are unnecessary when data flows in only one direction.

Server-sent events
Server-sent events

In this lesson, we'll explore Server-Sent Events (SSE), which provide an HTTP-native solution purpose-built for this unidirectional server-to-client streaming pattern. SSE leverages existing HTTP infrastructure, avoids protocol upgrades, and delivers built-in reconnection semantics, making it a simpler, operationally lighter alternative when the communication pattern is strictly server-push.

How SSE works under the hood

SSE operates on a straightforward mechanism. The client opens a standard HTTP GET request and includes an Accept: text/event-stream header. The server responds with Content-Type: text/event-stream, and instead of closing the connection after sending a response body, it keeps the connection open. The server then writes events as plain-text frames, each separated by a double newline.

The following sequence diagram illustrates the lifecycle of an SSE connection, including the automatic resumption of events after a network drop:

SSE communication flow highlighting the initial handshake, data multiplexing via event types, and the automatic resumption of the stream
SSE communication flow highlighting the initial handshake, data multiplexing via event types, and the automatic resumption of the stream

The SSE text protocol

...