Course contents

02. Networking and Internet Lesson 9 of 10

Server-Sent Events

Compare polling, long polling and SSE by server load, then follow an event stream through drops, Last-Event-ID resumption, shared logs and proxy pitfalls.

13 minIntermediate8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Polling costs clients ÷ interval requests per second, whether or not anything changed.
  • Long polling answers only when there is news, but still costs a full request per update per client.
  • SSE keeps one text/event-stream response open and writes events to it; load follows updates.
  • EventSource reconnects on its own and sends Last-Event-ID; a shared event log lets any server resume.
  • Send heartbeats, disable buffering and serve over HTTP/2; use ordinary requests for client-to-server messages.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Server-Sent Events (SSE), defined in the WHATWG HTML standard, is a way for a server to push a stream of text events to a client over a normal HTTP response. The browser API is EventSource: it sends a GET with Accept: text/event-stream, the server answers 200 with Content-Type: text/event-stream and keeps writing to the response instead of ending it.

Why it exists

Many features only need the server to tell the client that something changed: prices, notifications, build logs, LLM token streams, dashboards. Polling for that wastes requests and adds delay; WebSockets add a second protocol and more machinery than a one-way feed needs. SSE uses plain HTTP and adds reconnect and resume on top.

How it works

The stream. Each event is a few field: value lines followed by a blank line:

id: 42
event: price
data: {"symbol":"ACME","price":101.5}

data may span several lines; event names a type the client can listen for; id sets the last event id; retry: 3000 tells the client how long to wait before reconnecting. Lines starting with : are comments, used as heartbeats. The format is UTF-8 text only.

Reconnect and resume. If the connection drops, EventSource waits the retry delay and reconnects automatically, adding Last-Event-ID with the last id it received. A server that can look events up by id replays what was missed and continues. A 204 or a non-event-stream response stops reconnection.

Server side. Each open stream is a long-lived response. Event-loop servers (Node.js, Go, async frameworks) hold many cheaply; thread-per-request servers tie up a thread per stream. Servers subscribe to a pub/sub channel or event log and write new events to the relevant streams. For resumption across servers, events go into a shared, ordered log (Redis Streams, Kafka, a database table keyed by id) with enough retention to cover typical disconnects.

Polling and long polling, for comparison. Short polling sends a request every n seconds: load = clients ÷ n, latency up to n. Long polling holds each request until there is news (or a timeout), then the client asks again: latency drops to about one network trip, load becomes about one request per update per client.

When to use it

  • Server-to-client feeds: notifications, live scores and prices, progress and log streaming, LLM response streaming.
  • When you want standard HTTP: existing authentication (cookies, headers via fetch-based clients), proxies, CDNs, HTTP/2 multiplexing.
  • When automatic reconnect and resume matter more than client-to-server latency.

When not to

  • Frequent client-to-server messages or binary data: WebSockets (or WebTransport).
  • Very rare updates where holding connections costs more than an occasional poll, or mobile apps in the background (use push notifications).
  • Servers or proxies that cannot stream responses without buffering.

Trade-offs

Choice You gain You pay
Short polling Simplest, stateless, cacheable Load ∝ clients × rate; staleness up to the interval
Long polling Low latency, works everywhere A full HTTP exchange per update per client; timeouts to tune
SSE One response per client, built-in reconnect and resume, plain HTTP One-way, text only; long-lived connections to manage
WebSockets Two-way, binary, lowest per-message overhead Separate protocol, own reconnect/resume logic, harder through some proxies

Alternatives

  • WebSockets for bidirectional messaging.
  • Streaming fetch (ReadableStream over a chunked or HTTP/2 response) for custom formats, at the cost of writing reconnect yourself.
  • WebTransport for multiplexed streams and datagrams over HTTP/3.
  • Web Push / mobile push for notifications when the page or app is not open.

Failure modes

  • Lost events on reconnect: the reconnect lands on a server that never saw the missed events, or history was not kept.
  • Idle timeouts: proxies and load balancers close quiet streams; without heartbeats, clients churn.
  • Buffering: a proxy or compression layer buffers the response, so events arrive late in bursts.
  • Connection limit on HTTP/1.1: browsers allow six connections per host shared across tabs; extra streams block.
  • Reconnect storms: after a deploy every client reconnects at once; send a retry: value and add server-side jitter or gradual draining.
  • Thread exhaustion on servers that hold a thread per open stream.

In production

Serve SSE over HTTP/2 or HTTP/3. Disable buffering for the stream route (for nginx, proxy_buffering off or the X-Accel-Buffering: no response header) and avoid compression that waits for full blocks. Send comment heartbeats every 15–30 s, below the shortest idle timeout on the path. Give every event a monotonically increasing id and keep a shared log with a retention window; if a client asks for an id older than the window, send a "reload" event so it fetches a fresh snapshot. Use an async server, cap streams per client, and drain gradually on deploys.

Common misconceptions

  • “SSE is just long polling.” Long polling ends the response after each update; SSE keeps one response open for many events.
  • “SSE needs special servers.” Any server that can flush a streaming HTTP response works.
  • “EventSource can’t send headers, so SSE can’t be authenticated.” Cookies work with EventSource, and fetch-based SSE clients can send any header.
  • “WebSockets are always better for real time.” For one-way feeds SSE is simpler and resumes on its own.

Interview angle

When a design needs live updates, compare the options out loud: polling (cost = clients ÷ interval), long polling, SSE and WebSockets, and pick by direction and frequency. For SSE, mention Last-Event-ID resumption backed by a shared log, heartbeats against idle timeouts, HTTP/2 for connection limits, and what happens when a server with many open streams is redeployed.

Model assumptions

The request load is simulated; the exchanges are scripted. In the simulation each request is one HTTP request costing about 20 ms of worker time (lognormal, cv 0.4) on two API servers with 8 workers each (about 800 req/s together). The traffic levels are derived, not emergent: 2,400 tabs, updates about every 10 s, polling every 4 s (600 req/s), long polling one request per tab per update (240 req/s), and SSE streams recycled about every 5 minutes (about 8 req/s). Held requests and open streams are assumed cheap (an event-loop server) and are not simulated, so latency metrics for long polling and SSE do not include the holding time. The scripted packets use 15 ms between tabs and the load balancer and 2 ms inside the data centre, and a 500 ms retry delay to keep the animation short; browsers default to a few seconds. Numbers are illustrative.

The lesson as textEvery step of the simulation, written out.
  1. 1. Asking “anything new?” every four seconds

    *Simulated.* A live price page is open in 2,400 tabs. Each tab polls GET /prices every 4 seconds: 600 requests per second, each costing the API about 20 ms (auth, session lookup, checking for changes). The two API servers run about 75% busy.

    Updates are published only about every 10 seconds, so most polls come back with nothing new, yet a new price still waits up to 4 seconds to be seen. Polling faster makes updates fresher and the load worse; polling slower does the opposite.

    Scene: Browser tabs send 600 polling requests per second through the load balancer to two API servers, which are about 75% busy. Most responses contain no new data.

    Key idea: Polling ties load to the number of clients × poll rate, not to how often data changes.

  2. 2. Long polling: hold the request until there is news

    *Scripted exchange, simulated load.* With long polling the server does not answer immediately: it holds the request until an update exists (or a timeout of 20–30 s), then answers, and the browser sends the next request at once. Updates now arrive within one network trip.

    But every update still costs a full request and response per tab, with headers and auth: about 2,400 ÷ 10 s ≈ 240 requests per second, and the API drops to about 30% busy. With frequent updates, long polling approaches polling again. (Held requests are assumed cheap here, as on an event-loop server.)

    Scene: A tab’s request is held by API 1 until an update exists, answered, and immediately replaced by a new request that API 2 holds until the next update. Simulated load drops to 240 requests per second; the API servers are about 30% busy.

    Key idea: Long polling removes empty answers and delay, but still pays one full HTTP exchange per update per client.

  3. 3. Server-Sent Events: one request, many events

    *Scripted stream, simulated load.* With SSE the browser opens new EventSource("/prices"): one GET with Accept: text/event-stream. The server answers 200 with Content-Type: text/event-stream and never finishes the response. Each update is a few lines of text: id: 42, data: {…}, then a blank line.

    Requests now happen only when a stream is (re)opened. If proxies recycle streams about every 5 minutes, that is 2,400 ÷ 300 s ≈ 8 requests per second: the API is nearly idle, and updates arrive one network trip after they are published.

    Scene: A tab opens one event-stream request to API 1, which keeps the response open and pushes four events down it. Simulated load falls to about 8 requests per second and the API servers are nearly idle.

    Key idea: SSE turns one HTTP response into a long-lived, one-way event stream; load follows updates, not polls.

  4. 4. Drops are expected: reconnect and resume

    *Scripted.* Streams break: a proxy times out, a server is redeployed, the laptop sleeps. After event 42 the connection is reset. EventSource reconnects automatically after the retry: delay the server sent (500 ms here; browsers default to a few seconds) and adds a header: Last-Event-ID: 42.

    The server replays events 43 and 44, published while the tab was away, then continues live with 45. Nothing is lost and no client code was needed, as long as the server can look events up by id.

    Scene: Events 41 and 42 arrive, then the connection is reset. After the 500 ms retry delay the tab reconnects with Last-Event-ID 42; API 1 replays events 43 and 44 and continues with 45.

    Key idea: EventSource reconnects by itself and sends Last-Event-ID, so the server can resume exactly where the client left off.

  5. 5. The reconnect lands on another server

    *Scripted.* The balancer sends the reconnect to API 2, which never saw events 43 and 44: they existed only in API 1’s memory. Without shared history, those events are silently lost.

    So servers append events to a shared event log (Redis Streams, Kafka, a database table keyed by id) and every server can read from any id. API 2 reads “after 42”, replays 43 and 44, then follows the log live. Keep enough history to cover realistic disconnects; beyond that, tell the client to reload a snapshot.

    Scene: API 1 appends events 43 and 44 to a shared event log. The tab reconnects to API 2 with Last-Event-ID 42; API 2 reads the log after 42, replays 43 and 44 and then streams 45 live.

    Key idea: Resumption only works if any server can find events by id: keep a shared, ordered event log.

  6. 6. Proxies, buffers and connection limits

    *Scripted.* Long-lived responses meet infrastructure built for short ones. Idle connections are closed by proxies and load balancers (often after 60 s), so the server sends a comment line (: ping) every 15–30 s. Buffering proxies and compression can hold events back: disable response buffering for the stream (for nginx, X-Accel-Buffering: no).

    Over HTTP/1.1 browsers allow only six connections per host, shared by all tabs: the seventh tab’s stream hangs. Over HTTP/2 each stream is one of ~100 concurrent streams on one connection, so serve SSE over HTTP/2 or HTTP/3.

    Scene: API 1 sends regular heartbeat comments down the stream, with a real event in between, so the load balancer never sees the connection idle.

    Key idea: Send heartbeats below the shortest idle timeout, disable buffering, and serve SSE over HTTP/2.

  7. 7. Client to server: just use HTTP

    *Scripted.* SSE is one-way. When the user places an order, the page sends an ordinary POST /orders (on HTTP/2, over the same connection as the stream). The server answers 202 Accepted at once; the result, “order filled”, arrives later as an event on the stream.

    Compared with WebSockets: SSE is text only and server-to-client only, but it is plain HTTP (works with existing auth, proxies, CDNs and HTTP/2), reconnects and resumes on its own, and needs no special server. Choose WebSockets when the client also sends frequent, low-latency messages or binary data.

    Scene: The tab sends a POST request and gets 202 Accepted immediately. Later the order result arrives as an event on the existing stream.

    Key idea: SSE for server → client, ordinary requests for client → server; WebSockets only when both directions are frequent.

  8. 8. Choosing how to push updates

    Polling: simplest, load grows with clients × poll rate, latency up to the interval. Long polling: fresh updates, but a full request per update per client. SSE: one HTTP response per client, events as they happen, built-in reconnect with Last-Event-ID. WebSockets: two-way, binary, more to build and operate.

    For SSE in production: a shared event log for resumption, heartbeats, no buffering, HTTP/2, and jittered reconnects after a mass disconnect.

    Scene: Tabs hold event streams to two API servers backed by a shared event log; the servers handle only about 8 requests per second.

    Key idea: Match the mechanism to the direction and frequency of updates.