Md Tarek — Portfolio© 2026

Full-stack Developer

System Design — built to hold up.

dhaka → remote, worldwide

Loading experience

Md TarekTarek
Dev

SSE vs WebSockets: Choosing Real-Time Web App Architecture

By: Md Tarek · 17 Oct 2026

SSE and WebSockets data streams connecting a browser and server
SSE and WebSockets data streams connecting a browser and server

For most read-heavy real-time web apps, choose Server-Sent Events (SSE). Choose WebSockets when the browser and server both need to send frequent application messages over the same live connection. SSE is an HTTP-based, server-to-client stream; WebSockets create a two-way interactive session. [1] [2]

One-way versus bidirectional traffic

SSE uses the browser’s EventSource API. The page opens an HTTP connection and listens while the server emits UTF-8 events with the text/event-stream media type. An event is separated from the next by a blank line and can contain event, data, id, and retry fields. [1] [3] The browser cannot send an application event through that stream. Submit commands with ordinary fetch or forms, then let SSE deliver resulting state changes.

That shape is excellent for an operations dashboard, job-progress view, stock or telemetry display, and notifications. The client mostly consumes facts: “job 42 finished,” “invoice status changed,” or “new alert.” Keeping commands on normal HTTP also makes routing, authorization, and request tracing familiar.

WebSockets expose send() and message events on a persistent, bidirectional connection. [2] The browser can send a chat message, cursor movement, presence update, or collaboration operation and receive messages from other participants without opening a separate request for every action. Chat and collaborative editing are natural fits because each user action needs an immediate path to the server and often to other clients.

A dashboard can use either technology. Prefer SSE when its controls already use HTTP and the live channel only publishes updates. Prefer WebSockets when filters, subscriptions, acknowledgements, presence, or interactive commands are themselves part of a continuous message protocol.

Reconnection and event history

A useful SSE property is built-in reconnection. If an EventSource connection closes, the user agent normally tries again; the server can suggest a delay with retry. [1] When an event includes an id, the browser remembers it. On a subsequent connection, it sends that value in the Last-Event-ID request header. [3] The server can use the ID as a cursor and replay events after it, rather than silently losing updates.

That mechanism is not a complete delivery guarantee. Design event IDs, retention, authorization, and replay semantics deliberately. If the server no longer has the requested history, send a “resync required” response or have the client fetch a current snapshot. Make consumers tolerate duplicates: a reconnect can occur around a boundary where the client has processed an event but the server replays it.

WebSockets do not provide an equivalent browser-managed replay cursor. Your application must decide how to reconnect, authenticate again, detect a missed sequence, and recover state. Include sequence numbers or operation IDs when loss matters, and provide a snapshot or resynchronization endpoint. Add backoff with jitter so a deployment or network outage does not cause every tab to reconnect at once.

Minimal SSE example

The following Node.js example keeps a small in-memory history, replays events after Last-Event-ID, and broadcasts new events. A production implementation would use a durable event store and a bounded retention policy.

// server.mjs
import http from "node:http";

const history = [], clients = new Set();
let nextId = 0;
const format = e => `id: ${e.id}\ndata: ${JSON.stringify(e.data)}\n\n`;

setInterval(() => {
  const event = { id: ++nextId, data: { ready: true } };
  history.push(event);
  if (history.length > 100) history.shift();
  for (const res of clients) res.write(format(event));
}, 5000);

http.createServer((req, res) => {
  if (req.url !== "/events") return res.writeHead(404).end();
  const last = Number(req.headers["last-event-id"] || 0);
  res.writeHead(200, { "Content-Type": "text/event-stream; charset=utf-8",
    "Cache-Control": "no-cache", "Connection": "keep-alive" });
  for (const event of history) if (event.id > last) res.write(format(event));
  clients.add(res);
  req.on("close", () => clients.delete(res));
}).listen(3000);
const stream = new EventSource("/events");
stream.onmessage = ({ data }) => console.log(JSON.parse(data));
stream.onerror = () => console.log("SSE reconnecting");

The example’s replay window is intentionally small; if a client asks for older history, your real service should trigger a snapshot or resync. Send periodic comment lines such as : keep-alive\n\n when intermediaries might close an otherwise quiet stream; the HTML standard documents this as a keepalive technique. [3]

Operations and security

Long-lived connections change infrastructure assumptions. Confirm that reverse proxies, load balancers, and CDNs pass streaming responses without buffering, apply suitable read timeouts, and shut down connections cleanly during deploys. For WebSockets, the infrastructure must support the HTTP upgrade and preserve Upgrade and Connection headers. [4] Monitor open connections, reconnect rates, event-loop or worker pressure, send queues, and abnormal closes. Test browser tab behavior and network transitions instead of assuming a local development connection represents production.

Use HTTPS for SSE and wss:// for WebSockets. A WebSocket has no built-in authentication or authorization model, and browsers can include cookies in the handshake. Validate the Origin header against an explicit allowlist, enforce authorization for each action, expire long-lived sessions, and close connections when access ends. [4] Treat every incoming message as untrusted: validate its schema and size, rate-limit abusive senders, and never use eval to parse data. [4] Do not put bearer tokens in WebSocket URLs, where they can leak into logs; use an authenticated handshake or a carefully designed first message over WSS. [4]

SSE still needs access control, tenant isolation, and careful cache configuration. For cross-origin streams, configure CORS and credentials intentionally. Avoid embedding secrets in event data, and remember that a connected client may receive updates for a long time after its page state changes. Keep event payloads small and send identifiers rather than sensitive records when a follow-up authorized request can fetch details.

Common mistakes

The most common SSE errors are omitting text/event-stream, forgetting the blank line that dispatches an event, buffering output in a proxy, and assuming automatic reconnect means automatic recovery. The most common WebSocket errors are accepting every origin, authenticating only the initial connection, allowing unbounded messages or connections, and failing to design a missed-message recovery path. Another mistake is choosing WebSockets for a one-way feed merely because they sound more “real-time”; the extra protocol and lifecycle work may not solve a real requirement.

FAQs

Is SSE only for simple applications? No. It is a strong fit for one-way updates at scale when your infrastructure handles long-lived HTTP streams and your product has a clear snapshot and replay strategy.

Can I replace WebSockets with SSE for chat? Usually not for interactive chat. SSE can deliver incoming messages, but sending chat messages still needs fetch or another channel, plus a design for acknowledgements and ordering. WebSockets are the simpler single-connection model when both directions are active.

References

[1] Using server-sent events — MDN

[2] WebSocket API (WebSockets) — MDN

[3] Server-sent events — WHATWG HTML Standard

[4] WebSocket Security Cheat Sheet — OWASP