How do Server-Sent Events and WebSockets work on the wire?

A Server-Sent Events stream is an ordinary HTTP response that never finishes. The client sends a GET with Accept: text/event-stream. The server replies 200 OK with Content-Type: text/event-stream and keeps writing UTF-8 text. Each event is a group of field: value lines ended by a blank line. The fields are data, event (a named type), id (a resume cursor) and retry (reconnect delay in milliseconds). A line starting with : is a comment, which is useful as a heartbeat. When the client reconnects, it sends the last id it received in a Last-Event-ID header.

A WebSocket also starts as an HTTP GET, but that request asks to leave HTTP. Once the server answers 101 Switching Protocols, the TCP connection carries binary frames in both directions. Each frame has an opcode for text, binary, ping, pong or close. Frames sent from the client are masked.

SSE response (stays HTTP) WebSocket handshake (leaves HTTP)
HTTP/1.1 200 OK GET /ws HTTP/1.1
Content-Type: text/event-stream Upgrade: websocket
Cache-Control: no-cache Connection: Upgrade
id: 42 Sec-WebSocket-Key: <random base64>
event: order.updated Sec-WebSocket-Version: 13
data: {"orderId":"A17","status":"shipped"} HTTP/1.1 101 Switching Protocols
(blank line ends the event) Sec-WebSocket-Accept: <derived from key>

SSE is HTTP streaming, and that shapes the rest of this comparison. Anything that understands HTTP can carry it, including proxies, HTTP/2 multiplexing, cookies, auth headers and access logs. It only breaks when some hop buffers the response. A WebSocket stops being HTTP after the handshake, so every hop has to recognize the upgrade and forward raw frames.

// Minimal SSE endpoint using only Node's built-in http module.
// Watch the raw stream with: curl -N
const http = require('node:http');

let nextId = 42;

http.createServer((req, res) => {
  if (req.url !== '/events') { res.writeHead(404); return res.end(); }

  // On reconnect the client sends the last id it received.
  // A real server would replay missed events after this cursor.
  const lastId = req.headers['last-event-id'];
  if (lastId) console.log(`client resuming after id ${lastId}`);

  // An ordinary 200 response. It is never ended while the client listens.
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
  });

  // Tell the client to wait 5000 ms before reconnecting after a drop.
  res.write('retry: 5000\n\n');

  // Each event is a set of field lines. A blank line ends the event.
  const push = setInterval(() => {
    res.write(`id: ${nextId++}\n`);
    res.write('event: order.updated\n');
    res.write(`data: ${JSON.stringify({ orderId: 'A17', status: 'shipped' })}\n\n`);
  }, 2000);

  // Lines starting with ':' are comments. Clients ignore them, but they
  // keep idle proxies and load balancers from closing the connection.
  const heartbeat = setInterval(() => res.write(': ping\n\n'), 15000);

  // Stop writing when the client disconnects.
  req.on('close', () => { clearInterval(push); clearInterval(heartbeat); });
}).listen(8080);

A dependency-free Node.js server that writes an SSE stream over a plain HTTP 200 response, using the id, event, data and retry fields, a comment heartbeat, and the Last-Event-ID header the client sends on reconnect.

How does SSE work end to end, from connection to delivery?

The wire format above is one piece. The full lifecycle of an SSE stream runs like this:

  1. Open. Browser code calls new EventSource('/events'). The browser issues a GET and waits for response headers.
  2. Accept or refuse. If the server answers 200 with Content-Type: text/event-stream, the stream is open and the open event fires. Any other status or content type fails the connection, and EventSource does not retry. A 204 No Content response is the standard way for a server to tell a client to stop reconnecting.
  3. Deliver. The server holds the response open. Behind it, the handler usually subscribes to a topic on a broker or reads from a log, and writes each event to the response as it arrives, flushing after every event.
  4. Parse and dispatch. The browser splits the stream on blank lines, joins multi-line data: fields with newlines, and records the latest id:. Events without an event: field go to the onmessage handler. Named events go to listeners registered with addEventListener('order.updated', ...).
  5. Drop and reconnect. When the TCP connection closes or errors, the error event fires and the browser waits for the most recent retry: interval. It then sends a new GET carrying Last-Event-ID.
  6. Resume. The server reads that header, replays everything after the cursor from its buffer or log, and continues with live events.
  7. Close. The client stops the stream with eventSource.close(). The server sees the request close and releases its subscription.

Over HTTP/2, the same lifecycle runs as one stream on a shared connection, so many streams and ordinary API requests share a single TCP connection to the origin.

A WebSocket's lifecycle is shorter on paper: handshake, exchange frames, close with a close frame. Steps 5 and 6 don't exist in the protocol, so detecting drops, reconnecting and resuming are left to the application.

Why should SSE be the default for one-way backend push?

Look at what most push features actually do. Notifications, job progress, live dashboards, activity feeds and LLM token streaming all send data from server to client. The client's side of the conversation is small and infrequent: mark as read, cancel the job, change a filter. Those actions fit ordinary HTTP requests, where they get the routing, validation, rate limiting and idempotency handling your API already has. A bidirectional socket adds nothing for this traffic, and it means writing a second message protocol on top of the socket.

The teams that gain the most are those already running HTTP infrastructure: reverse proxies, CDNs, API gateways and auth middleware. An SSE endpoint is a normal route that returns a text/event-stream response, so it passes through the same stack and produces logs in the same format.

The browser EventSource API also handles reconnection for you. When the connection drops, it reconnects on its own. It waits for the interval set by the most recent retry: field. If the stream has been tagging events with id:, it sends the last one back in the Last-Event-ID request header. With WebSockets, you write all of that client code yourself.

There is a caveat. Last-Event-ID only tells the server where the client stopped. Resumption works only if the server can serve events from that point, which requires either a replay buffer with bounded retention or a per-stream offset into a durable log. Without one, a reconnecting client silently misses everything sent while it was disconnected. That gap exists under either protocol. SSE just gives you a standard place to close it.

const http = require('node:http');

const MAX_BUFFER = 1000;   // bounded retention: oldest events fall off
const buffer = [];         // in-memory replay buffer of { id, data }
const clients = new Set();
let nextId = 1;

const send = (res, e) => res.write(`id: ${e.id}\ndata: ${e.data}\n\n`);

function publish(payload) {
  const event = { id: nextId++, data: JSON.stringify(payload) };
  buffer.push(event);
  if (buffer.length > MAX_BUFFER) buffer.shift();
  for (const res of clients) send(res, event);
}

http.createServer((req, res) => {
  if (req.url !== '/events') return res.writeHead(404).end();
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
  });
  res.write('retry: 3000\n\n'); // EventSource waits 3s before reconnecting

  // EventSource sends this header on reconnect, using the last id: it saw.
  const header = req.headers['last-event-id'];
  if (header !== undefined) {
    const lastId = Number(header);
    // Requested point has aged out of the buffer: tell the client to refetch state.
    if (buffer.length && lastId < buffer[0].id - 1) res.write('event: resync\ndata: {}\n\n');
    for (const e of buffer) if (e.id > lastId) send(res, e); // replay the gap
  }

  clients.add(res);
  req.on('close', () => clients.delete(res));
}).listen(8080);

setInterval(() => publish({ jobId: 'job-123', progress: Math.random() }), 1000);

A minimal Node.js SSE endpoint that tags events with id:, sets a retry: hint, and uses a bounded replay buffer to resume from Last-Event-ID, sending a resync event when the gap is older than the buffer.

SSE vs WebSockets: feature and operational cost comparison

Dimension Server-Sent Events WebSockets
Direction Server to client only; client uses ordinary HTTP requests to send Full duplex over one connection
Payload UTF-8 text (text/event-stream); binary must be encoded, e.g. Base64 Text or binary frames
Reconnect and resume Built into EventSource: automatic retry, server-tunable retry: delay, Last-Event-ID sent on reconnect None; you write it
Proxy and CDN fit Plain GET response; intermediaries must not buffer it Every hop must forward Upgrade and tolerate long idle connections
Headers and auth Standard request semantics; browser EventSource sends cookies but not custom headers Handshake only; browser API can't set custom headers
Connection limits Subject to per-origin limits on HTTP/1.1; multiplexed as streams on HTTP/2 One TCP connection per socket in most deployments
Observability and WAF Status codes, headers, tracing and WAF rules apply to the request Tooling sees the handshake and a 101; frames are opaque to it
Per-hop config Disable buffering, raise read timeouts Upgrade forwarding, timeouts, sometimes sticky routing

Most of the cost difference comes from the rows about reconnect and observability. With SSE, the browser already handles retry, and the event ID sent on reconnect feeds directly into the resume offset. Your work is to store IDs and replay from them.

With WebSockets, you build several pieces yourself:

  • reconnect detection
  • exponential backoff with jitter, so a deploy doesn't trigger a synchronized reconnect storm
  • a resume handshake carrying the last seen offset
  • heartbeats to detect half-open connections

After the 101 Switching Protocols response, the connection leaves HTTP semantics. Access logs, request-level WAF rules and per-request authorization never see individual messages. Message validation, rate limiting, audit logging and re-checking expired credentials all move into your application code. For one-way push, that work buys you nothing.

How can SSE save engineering time?

The savings come from code you don't write and infrastructure you don't change. For a one-way push feature, choosing SSE over WebSockets removes these pieces of work:

  • Client reconnection logic. EventSource already detects drops, waits for the server-specified retry: delay and reconnects. You don't write, test or maintain a reconnect state machine in every client.
  • A resume protocol. The id: field and the Last-Event-ID header are the resume handshake. The server-side work narrows to keeping a replay buffer or log offset, which you need under either transport.
  • A message envelope. With WebSockets, you usually design a framing convention: a type field, a routing key, request/response correlation IDs. SSE already has event: for types and id: for ordering, and client-to-server actions stay as normal API endpoints with their existing schemas.
  • A parallel auth and policy path. The stream is a normal HTTP route, so existing session middleware, authorization checks, rate limiting and WAF rules apply to it. With WebSockets, per-message validation and authorization have to be rebuilt inside the socket handler.
  • New observability. Access logs, status codes, request tracing and latency dashboards already cover HTTP routes. Frames inside a WebSocket need custom logging and metrics to become visible.
  • Proxy and gateway changes. SSE needs buffering turned off and timeouts raised on the stream route. WebSockets need upgrade forwarding at every hop, and sometimes sticky routing.
  • Debugging tools. curl -N against the endpoint shows the raw event stream exactly as the browser receives it. Browser developer tools display SSE responses as ordinary network requests.

The time saved is largest in teams with mature HTTP tooling, because SSE reuses all of it. It shrinks when you already operate a WebSocket gateway with reconnect and resume handled by an existing client library. In that case, the WebSocket costs listed above have already been paid.

How do you implement SSE behind proxies, load balancers and HTTP/2?

A minimal endpoint does four things. It responds with Content-Type: text/event-stream and Cache-Control: no-cache, so nothing between the server and client stores or transforms the stream. It writes each event as id: and data: lines terminated by a blank line, then flushes immediately. Without the flush, your framework's write buffer holds events until it fills. It gives every event a monotonically increasing id, such as a sequence number or log offset. On reconnect, it reads the Last-Event-ID request header and replays everything after that offset before switching to live events. The browser sends that header automatically, so replay is the server's job. Keep a bounded backlog, and decide what happens when a client asks for an offset that has already expired.

Proxies break this more often than application code does. In nginx, set proxy_buffering off on the stream location, or send X-Accel-Buffering: no from the application. Disable gzip for text/event-stream, because compressors also buffer output. Raise proxy_read_timeout above your heartbeat interval so the proxy doesn't close quiet streams. Apply the equivalent idle-timeout setting on your load balancer.

The per-origin connection limit

Over HTTP/1.1, browsers cap concurrent connections per origin, typically at six. Each tab holding an SSE stream consumes one of those connections. With enough tabs open, ordinary API requests queue behind them and appear to hang, while the server sees nothing unusual. HTTP/2 multiplexes many streams over a single connection, which removes most of this limit. Terminate HTTP/2 at the edge for the origin that serves your streams.

upstream events_backend {
    server 10.0.0.12:8080;   # placeholder app server
    keepalive 32;
}

upstream api_backend {
    server 10.0.0.13:8080;   # placeholder API server
}

server {
    listen 443 ssl;
    http2 on;                 # multiplex streams; avoids the 6-per-origin HTTP/1.1 cap (nginx 1.25.1+)
    server_name events.example.com;

    ssl_certificate     /etc/nginx/tls/events.example.com.crt;
    ssl_certificate_key /etc/nginx/tls/events.example.com.key;

    location /stream {
        proxy_pass

        # Persistent HTTP/1.1 to the upstream; clear Connection so keepalive works
        proxy_http_version 1.1;
        proxy_set_header Connection "";

        # Deliver each event as soon as the app flushes it
        proxy_buffering off;
        proxy_cache off;

        # Compressors buffer output, so never gzip the stream
        gzip off;

        # Keep this above the app's heartbeat interval so quiet streams stay open
        proxy_read_timeout 300s;

        # Last-Event-ID is a normal request header and is forwarded by default;
        # the upstream reads it to replay missed events on reconnect.
    }

    location /api/ {
        proxy_pass
    }
}

An nginx server block that terminates HTTP/2 at the edge and proxies an SSE location with response buffering, caching and gzip disabled and a read timeout longer than the heartbeat interval.

How should you handle authentication and security for long-lived connections?

The browser EventSource API accepts only a URL and a withCredentials flag. It cannot set an Authorization header and always issues a GET. In practice that leaves three options:

  • Cookies. Session cookies are attached automatically, and withCredentials sends them cross-origin. Because the browser attaches them without any script involvement, you inherit CSRF-style concerns. Use SameSite attributes and validate Origin on the stream endpoint.
  • Query-string tokens. These work everywhere but leak into access logs, proxy logs and browser history. If you must use them, exchange a bearer token for a short-lived, single-use ticket through an authenticated POST, then open the stream with that ticket.
  • A fetch-based streaming client. fetch with a readable body stream lets you set any header or method. You lose what EventSource gives you for free: automatic reconnection, retry intervals and the Last-Event-ID header. You have to reimplement all three, including backoff.

Browser WebSockets have the same header limitation, and cookies ride along on the handshake. A malicious page can therefore open a socket to your server using the victim's session. This attack is called cross-site WebSocket hijacking. Same-origin policy does not block it, so the server must check the Origin header against an allowlist before upgrading.

Connections that outlive tokens

A connection authenticated at open time stays trusted until it closes, even after the token expires or is revoked. To bound that window:

  • Cap each connection's lifetime at the token's remaining validity, then close it.
  • Have the client reconnect with fresh credentials.
  • For WebSockets, you can instead accept an in-band re-auth message before the deadline.

Treat revocation as an event that closes matching connections immediately.

import http from 'node:http';
import { WebSocketServer } from 'ws';

// Comma-separated list of allowed page origins, supplied through configuration.
const ALLOWED_ORIGINS = new Set(
  (process.env.ALLOWED_ORIGINS || '').split(',').filter(Boolean)
);
const server = http.createServer();
const wss = new WebSocketServer({ noServer: true });

// Placeholder: look up and consume a single-use ticket issued by an authenticated POST.
// Returns { userId, expiresAt } (expiresAt in ms since epoch) or null.
function verifyTicket(ticket) { return null; }

server.on('upgrade', (req, socket, head) => {
  // Cookies ride along on the handshake and same-origin policy does not block it,
  // so reject cross-site pages before upgrading (cross-site WebSocket hijacking).
  if (!ALLOWED_ORIGINS.has(req.headers.origin)) {
    socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
    return socket.destroy();
  }
  const query = req.url.includes('?') ? req.url.slice(req.url.indexOf('?') + 1) : '';
  const session = verifyTicket(new URLSearchParams(query).get('ticket'));
  if (!session) {
    socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
    return socket.destroy();
  }
  wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req, session));
});

wss.on('connection', (ws, req, session) => {
  // Trust granted at open time must not outlive the credential:
  // close at expiry so the client reconnects with fresh credentials.
  const ttl = Math.max(0, session.expiresAt - Date.now());
  const timer = setTimeout(() => ws.close(4001, 'token expired'), ttl);
  ws.on('close', () => clearTimeout(timer));
});

server.listen(8080);

A Node.js WebSocket server using the ws library that checks Origin against an allowlist and validates a short-lived ticket before upgrading, then closes each connection when its credential expires.

How do you scale and keep alive thousands of open connections?

Scaling looks the same for SSE and WebSockets. Every open connection holds a file descriptor, kernel socket buffers and some per-connection application state. A thread-per-connection server runs out of memory long before the network is saturated, so the nodes that hold connections should run an event loop. Producers should never write to sockets directly. Put a pub/sub layer, such as a message broker, between them and the edge:

Producers → Broker (topics/channels) → Edge nodes (hold sockets) → Clients

Each edge node subscribes only to the topics its clients care about. Any producer can then reach any client without knowing which node holds the connection.

Heartbeats

Load balancers, NAT gateways and mobile carriers drop connections that stay silent too long. To keep the path alive, SSE servers send a comment line (: followed by a newline), which clients ignore. WebSocket servers send ping frames and expect pongs. Heartbeats also expose dead peers: if a write fails or a pong never arrives, close the connection and free its resources.

Illustrative estimate: assume 100,000 connections, a 30-second interval and about 100 bytes on the wire per heartbeat after TCP/TLS overhead. That works out to roughly 3,300 heartbeats per second and about 2.7 Mbit/s across the fleet. The cost is small, but it scales linearly with connection count and with shorter intervals.

Deploys and autoscaling

During a deploy, drain each node: stop accepting new connections, then close existing ones gradually. Clients must reconnect with jittered exponential backoff. Without jitter, every client reconnects at the same moment and overloads the remaining nodes in a reconnect storm.

Long-lived connections stay pinned to the node they first reached. New nodes added by autoscaling receive only new connections, so load does not rebalance until clients reconnect. Keep per-connection state reconstructible from the broker so you can deliberately close connections on overloaded nodes and let clients redistribute.

When should SSE be avoided?

SSE is a poor fit in these cases, even for features that look like push:

  • Clients send frequent or latency-sensitive messages. Chat typing indicators, collaborative cursors and game input generate a steady upstream flow. Sending each one as a separate HTTP request adds per-request overhead, and requests can arrive out of order relative to the stream. WebSockets carry both directions on one ordered connection.
  • Payloads are binary. The stream is UTF-8 text. Encoding audio, images or protobuf messages as Base64 inflates them and adds encode/decode work on both ends.
  • Some hop buffers responses and you can't change it. Corporate proxies, some antivirus software and misconfigured CDNs hold the response until a buffer fills. Events then arrive late or in bursts. If you can't fix the hop, use long polling.
  • You are stuck on HTTP/1.1 and users open many tabs. Each stream consumes one of the browser's per-origin connections. Without HTTP/2 at the edge, ordinary requests queue behind open streams.
  • The consumer is a server, or can't hold a connection. Backend integrations are better served by webhooks. Backgrounded mobile apps lose their sockets when the OS suspends them, so they need a platform push channel.
  • You need custom request headers from the browser and can't use cookies. EventSource can't set Authorization. The fetch-based workaround removes the built-in reconnection and resume, which is most of what SSE offers over a WebSocket.

The reverse also holds: avoid WebSockets when traffic is one-way. You take on the reconnect, resume, framing and observability work described earlier without getting anything back for it.

When should you choose WebSockets, long polling or webhooks instead?

Transport choice comes down to who talks, what they send, and what sits between client and server.

Requirement Best fit Why
One-way text events to browsers over existing HTTP infrastructure SSE Plain HTTP response, built-in reconnection and resume, works with standard auth and routing
Chat, collaborative editing, multiplayer state WebSockets Client messages are frequent and latency-sensitive; a separate POST per keystroke adds request overhead and ordering problems
Binary payloads (audio, images, protobuf frames) WebSockets SSE is text-only, and base64 inflates payloads by about a third and costs CPU on both ends
Middleboxes you don't control that buffer responses Long polling or WebSockets A buffering proxy holds SSE events until the buffer fills, which breaks delivery timing
Server-to-server or clients that can't hold connections Webhooks or long polling The receiver needs no open socket; webhooks push to an endpoint it already exposes
Backgrounded mobile apps Platform push channel as fallback The OS suspends background sockets, so any long-lived connection dies

A few points the table leaves out:

  • Bidirectional traffic is a matter of degree. If clients send an occasional acknowledgement or filter change, SSE plus ordinary requests is simpler to operate. Switch to WebSockets when upstream traffic is continuous or ordering across both directions matters.
  • Corporate and mobile carrier networks are the usual home of buffering proxies. If your users sit behind them, test from those networks before committing to SSE, and keep long polling as a degraded mode.
  • Webhooks shift reliability work to you. You need retries, signatures, and idempotent receivers, because the consumer may be down when you send.
  • Mobile fallbacks should carry a signal, not the data. Send a small "something changed" notification and let the app fetch state when it reopens its stream.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to sse vs websockets, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.