← Back to Blog

WebSocket vs Webhook vs SSE: Choosing Real-Time Communication

Three technologies, three different jobs. A practical guide to who initiates, who sends, and what actually breaks in production, with Node.js code we ran and verified.

Search for "WebSocket vs Webhook vs SSE" and you will find articles that line the three up as competitors. That framing causes real design mistakes. Two of them (WebSocket and SSE) move data between a browser or app and your server. The third (Webhook) moves events between two servers. They overlap less than the names suggest, and most production systems use all three at once.

This post starts from the question that actually decides the choice, walks through each technology with code, and spends most of its time on what goes wrong after launch: dead connections, replayed events, proxies that swallow streams, and clients that reconnect all at once. Every code sample below was executed before publishing (see Section 9 for what we ran and what came out).

1. The Real Question: Who Talks to Whom?

Before comparing features, answer three questions about your data flow:

  1. Who opens the connection? A browser can open an outbound connection to you. Your server usually cannot open one to a browser.
  2. Who sends the data? Only the server, only the client, or both?
  3. How long does the connection live? One request, or minutes and hours?
Direction of data for WebSocket, SSE and Webhook Three lanes. WebSocket: a client and server joined by a two-way arrow over one long-lived connection. SSE: the client opens a request and the server streams events back one way. Webhook: a provider server sends a separate HTTP POST to your server whenever an event happens. WebSocket Browser / App Your server both sides send, any time long-lived connection SSE Browser / App Your server 1 plain GET request events streamed back, one way long-lived response Webhook Provider server Your server HTTP POST per event then the connection ends server to server Same word "real-time", three different shapes: two-way stream, one-way stream, one-shot callback.
Figure 1: The direction and lifetime of each technology
QuestionWebSocketSSEWebhook
Who opens it?Client (HTTP upgrade)Client (normal GET)Provider, to your public URL
Who sends?BothServer onlyProvider only (you reply with a status)
LifetimeLong-livedLong-livedOne request per event
Typical peersBrowser/app ↔ serverServer → browser/appServer → server

The Rule of Thumb

If the receiver is a browser or phone, you can only choose between WebSocket and SSE (or polling), because a phone has no public URL for you to call. If the receiver is another backend, a webhook is almost always the right default.

2. The Baseline You Are Replacing: Polling

Plain HTTP is request-response: the server cannot speak first. The oldest workaround is polling, where the client asks "anything new?" every few seconds. Long polling improves on it: the server holds the request open until it has something to say, then the client immediately asks again.

Do not dismiss polling. For an order-status page that changes a few times an hour, a 30-second poll is trivial to build, cache and debug, and it works through every proxy on earth. Reach for a persistent connection when updates are frequent, latency matters, or the number of wasted "nothing new" requests starts costing real money. Each technology below is a way to stop asking and start being told.

3. WebSocket: Full-Duplex, and Full Responsibility

A WebSocket starts life as an ordinary HTTP/1.1 request carrying an Upgrade: websocket header. The server answers 101 Switching Protocols, and from then on the same TCP connection carries WebSocket frames in both directions. The server proves it understood the request by hashing the client's Sec-WebSocket-Key into a Sec-WebSocket-Accept value. We sent the sample key from RFC 6455 to a running server and got back the status 101 and the sample accept value the RFC specifies.

What About HTTP/2?

The classic upgrade handshake is an HTTP/1.1 mechanism. RFC 8441 defines how to run WebSocket over a single HTTP/2 stream, using an extended CONNECT method and a SETTINGS_ENABLE_CONNECT_PROTOCOL setting. Both the server and any proxy in front of it must support it, so check before you assume your stack does.

A Server That Survives Real Networks

The textbook example stops at "send and receive a message". The version below adds the part that matters in production: a heartbeat that detects dead connections. Mobile clients lose signal without closing the socket, so the server never receives a close and keeps a zombie connection forever.

const http = require("http");
const { WebSocketServer, WebSocket } = require("ws");

const server = http.createServer();
const wss = new WebSocketServer({ server, path: "/socket" });

wss.on("connection", (ws) => {
  ws.isAlive = true;
  ws.on("pong", () => { ws.isAlive = true; });
  ws.on("message", (data) => {
    // broadcast to everyone except the sender (chat style)
    for (const c of wss.clients) {
      if (c !== ws && c.readyState === WebSocket.OPEN) c.send(data.toString());
    }
    ws.send("ack:" + data.toString());
  });
});

// Heartbeat: ping everyone; terminate whoever did not answer the last ping
setInterval(() => {
  for (const ws of wss.clients) {
    if (!ws.isAlive) { ws.terminate(); continue; }
    ws.isAlive = false;
    ws.ping();
  }
}, 30000);

server.listen(3000);

In our test we used a 300 ms sweep and a client that never answered pings. It was terminated on the second sweep, exactly as the logic says: the first sweep marks it and pings, the second finds no answer. In production use 20 to 30 seconds, and keep the interval below the idle timeout of every proxy and load balancer in the path, which is often around 60 seconds by default. Check yours; do not assume.

A Client That Reconnects Politely

Networks drop, deployments restart servers, and WebSocket has no built-in reconnect. If every client retries at a fixed interval, a server restart becomes a thundering herd: thousands of clients hit the fresh server in the same second. Use exponential backoff with jitter.

function connectWithBackoff(url, onMessage) {
  let attempt = 0;
  const open = () => {
    const ws = new WebSocket(url);
    let openedAt = 0;
    ws.onopen = () => { openedAt = Date.now(); };
    ws.onmessage = (e) => onMessage(e.data);
    ws.onclose = () => {
      // Reset only after a connection that stayed up for a while. Otherwise a server
      // that accepts and instantly drops us would keep the delay at its minimum.
      if (openedAt && Date.now() - openedAt > 10000) attempt = 0;
      const cap = Math.min(30000, 50 * 2 ** attempt); // exponential, capped
      const delay = Math.random() * cap;              // full jitter
      attempt++;
      setTimeout(open, delay);
    };
    ws.onerror = () => {};
  };
  open();
}

We ran this against a server that dropped the first two connections, and the client connected on the third attempt. Against a server that accepts and instantly drops, the backoff cap grew 50, 100, 200, 400 ms as intended. After a connection that stayed up, the next retry went back to the 50 ms cap. The reset happens only after a stable connection, not on open or on the first message, because a flapping server would otherwise keep the delay at its minimum forever.

Production Concerns Most Tutorials Skip

4. Webhook: Reliable Server-to-Server Delivery

A webhook is just an HTTP POST that a provider sends to a URL you registered, whenever something happens on their side. There is no connection to maintain, which is its strength. The weakness is that you do not control the sender: events can arrive twice, late, out of order, or forged by anyone who learns your URL.

The Bug in Most Webhook Tutorials

A very common example parses the body with express.json(), then verifies the signature. This looks right and is wrong. The provider signed the exact bytes it sent. After parsing, you hold an object, and serializing it again with JSON.stringify does not reproduce those bytes: whitespace, key order spacing and Unicode escapes can all differ. The signature never matches, or the developer gives up and skips verification.

We tested this directly. We sent a correctly signed event whose JSON contained extra spaces and a é escape. The parse-then-re-serialize route rejected the genuine request with verified: false. Verifying against the raw body accepted it.

const express = require("express");
const crypto = require("crypto");

const SECRET = process.env.WEBHOOK_SECRET;
if (!SECRET) throw new Error("WEBHOOK_SECRET is not set");
const TOLERANCE_SEC = 300; // reject events older than 5 minutes
const seen = new Set();    // use Redis or a DB unique key in production

function sign(ts, rawBody) {
  return crypto.createHmac("sha256", SECRET).update(`${ts}.${rawBody}`).digest("hex");
}

function verify(req) {
  // express.raw only fills req.body (with a Buffer) when the Content-Type matches
  if (!Buffer.isBuffer(req.body)) return "unsupported_content_type";

  const ts = req.header("X-Timestamp");
  const sig = req.header("X-Signature") || "";
  const t = Number(ts);
  // NaN > 300 is false, so a bare comparison would let a non-numeric timestamp through
  if (!ts || !Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > TOLERANCE_SEC) {
    return "stale_or_missing_timestamp";
  }
  const expected = Buffer.from(sign(ts, req.body.toString("utf8")), "hex");
  const given = Buffer.from(sig, "hex");
  if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) {
    return "bad_signature";
  }
  return null;
}

const app = express();

// express.raw keeps the body as a Buffer: the exact bytes that were signed
app.post("/webhook/payment", express.raw({ type: "application/json" }), (req, res) => {
  const err = verify(req);
  if (err) return res.status(400).json({ error: err });

  let event;
  try { event = JSON.parse(req.body.toString("utf8")); }
  catch { return res.status(400).json({ error: "invalid_json" }); }
  if (typeof event?.id !== "string") return res.status(400).json({ error: "invalid_event" });

  if (seen.has(event.id)) return res.status(200).json({ status: "duplicate_ignored" });
  seen.add(event.id);

  // Persist or enqueue the event here, then acknowledge immediately.
  res.status(200).json({ status: "accepted", id: event.id });
});

The signature scheme here (HMAC-SHA256 over timestamp.body) follows the common pattern used by major providers. Header names and exact formats differ per provider, so follow your provider's documentation for the real values. We ran five requests against this handler:

RequestResultWhy
Valid signed event200 acceptedSignature and timestamp are good
Same event again200 duplicate_ignoredIdempotency by event id
Body changed after signing400 bad_signatureTampering detected
Correct signature, 1 hour old400 stale_or_missing_timestampReplay window enforced
Parse-then-re-serialize route400 verified: falseRe-serialized bytes differ from the signed bytes

Providers commonly use a five-minute tolerance: wide enough for clock skew and slow proxies, narrow enough that a captured request cannot be replayed later. The timestamp is part of the signed text, so an attacker cannot simply refresh it. A short window does not stop a replay inside the window, which is why the duplicate check by event id matters as well.

Two details in this code come from hostile-input testing, not from the happy path. First, Number("abc") is NaN, and NaN > 300 is false, so a tolerance check written as a bare comparison silently accepts a non-numeric timestamp. The code checks Number.isFinite first. Second, express.raw fills req.body only when the Content-Type matches. With any other type, req.body is undefined in Express 5 and a handler that calls req.body.toString() throws and returns a 500. The code checks for a Buffer, and wraps JSON.parse so a malformed body is a 400 and not a crash. Bodies larger than Express's default 100 kB limit are rejected with a 413 before your code runs, which is usually what you want for a webhook.

Designing the Receiver

If You Are the Sender

When your own product sends webhooks to customers, the roles flip and so do the risks. Customers give you URLs, and your servers will call them. Block private and internal address ranges (and re-check after DNS resolution and redirects) to prevent server-side request forgery. Set strict timeouts and body-size limits, sign every payload, retry with exponential backoff, and give customers a delivery log and a manual replay button. These are what separate a webhook feature people trust from one they work around.

5. Server-Sent Events: One-Way Streaming That Reconnects Itself

SSE is a long-lived HTTP response with the content type text/event-stream. The server writes lines of text, and the browser's EventSource parses them and fires events. Its quiet superpower is that the protocol has recovery built in: each event can carry an id, and when the connection drops, EventSource reconnects automatically and sends the last id it saw in a Last-Event-ID header, so the server can resume where it left off.

A Server With Heartbeat and Resume

const express = require("express");
const app = express();

const clients = new Set();
const history = []; // small replay buffer
let nextId = 1;

function write(res, { id, data, event }) {
  res.write(`id: ${id}\n${event ? `event: ${event}\n` : ""}data: ${JSON.stringify(data)}\n\n`);
}

function publish(data, event) {
  const id = nextId++;
  history.push({ id, data, event });
  if (history.length > 100) history.shift();
  for (const c of clients) write(c, { id, data, event });
}

app.get("/events", (req, res) => {
  res.writeHead(200, {
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache, no-transform",
    "X-Accel-Buffering": "no", // tell nginx not to buffer the stream
  });
  res.write("retry: 2000\n\n"); // reconnect delay in milliseconds

  // Resume: replay anything the client missed
  const last = Number(req.header("Last-Event-ID") || 0);
  for (const h of history) if (h.id > last) write(res, h);

  clients.add(res);
  req.on("close", () => clients.delete(res));
});

// Heartbeat: a comment line is ignored by the client but keeps proxies from timing out
setInterval(() => { for (const c of clients) c.write(": ping\n\n"); }, 20000);

Two details differ from many tutorials. First, we do not send a Connection: keep-alive header: it has no meaning on HTTP/2, where connection-specific headers are not allowed, and HTTP/1.1 keeps connections alive by default anyway. Second, no-transform and X-Accel-Buffering stop intermediaries from buffering or compressing the stream, which is the most common reason SSE "works locally but not in production": events arrive in a burst at the end instead of live.

We tested resume with the browser-standard EventSource against a server that deliberately dropped the connection after every two events. The client reconnected on its own, and the Last-Event-ID header on the four successive requests was: none, 2, 4, 6. The events 1 to 6 arrived in order with none missing and none duplicated. On the server, a disconnected client was removed from the set a few milliseconds after the abort, not instantly, so do not assert on the client count in the same tick of a test.

This demo simplifies two things. It keeps one global stream and one in-memory history, whereas a real service keeps history per user or topic, authorizes before replaying anything, and stores it somewhere shared (Redis Streams, or a table with a sequence) so a reconnect that lands on a different instance sees the same ids. And to make EventSource stop reconnecting for good, for example after access is revoked, answer with HTTP 204: per the WHATWG specification that ends the reconnection loop.

const es = new EventSource("/events");

es.addEventListener("order", (e) => {
  const update = JSON.parse(e.data);
  console.log("status:", update.status);
});

es.onerror = () => {
  // EventSource retries by itself. readyState tells you whether it is
  // reconnecting (CONNECTING) or has given up (CLOSED).
};

Limits to Know Before You Choose SSE

6. The Corrected Comparison

The comparison tables you usually see mix up transport features with message-delivery guarantees. Here is a version organized around what you will actually have to build or operate.

ConcernWebSocketSSEWebhook
DirectionTwo-wayServer → clientProvider → your server
ProtocolWebSocket (ws/wss) after an HTTP upgradePlain HTTP responsePlain HTTP request
Data formatText and binaryUTF-8 textUsually JSON
ReconnectYou build itBuilt into EventSourceProvider retries
Resume after gapYou build itLast-Event-ID (you supply the replay)Retries plus your reconciliation job
Browser auth optionsCookie or ticket (no custom headers)Cookie (or fetch for headers)Not applicable: signature verification
Proxy and firewall friendlinessNeeds upgrade supportWorks anywhere HTTP works (if buffering is off)Needs a public HTTPS endpoint
Delivery guaranteeNone: lost on disconnectNone, unless you add ids and replayAt-least-once, unordered
Best forChat, games, collaborationNotifications, feeds, progress, streamed textPayments, Git events, integrations

7. How Each One Fails

Choosing a technology is choosing a set of failure modes. Compare them before you commit.

FailureWebSocketSSEWebhook
Network dropSilent half-open socket until a heartbeat finds itBrowser reconnects, resumes by idProvider sees a timeout and retries
Server deployAll connections drop, reconnect stormAll drop, but resume is automaticBrief 5xx, retries cover it
Slow consumerMemory grows unless you cap the queueSame: cap the write bufferProvider times out and retries
Proxy interferenceUpgrade blocked or idle timeoutBuffering delays eventsRarely an issue
DuplicatesPossible on resend after reconnectPossible on replayExpected: design for it
SpoofingHijacked sockets (check origin and auth)Unauthorized stream accessForged POSTs (verify signature)

8. How to Choose, and How They Combine

Decision flowchart for choosing a real-time technology Start: who receives the update. If another backend, use a webhook. If a browser or app: if the client must send frequent low-latency messages on the same channel, use WebSocket; if updates are rare, use polling; otherwise use SSE. Who receives the update? another backend Webhookverify, dedupe, ack fast browser or app Does the client sendfrequent, low-latency messages? yes WebSocketchat, games, co-editing no Do updates arrive often?(more than every ~30s) yes SSEfeeds, progress, notifications no Pollingsimple wins
Figure 2: A decision path for choosing between the three (plus polling)

Two related options are worth knowing. If both ends are your own backend services and you need typed contracts and streaming between them, gRPC is often a better fit than WebSocket; we covered it in gRPC Explained: From a .proto File to a Working Rust Server. If you need unreliable, low-latency delivery for something like game state, WebTransport is now worth evaluating: it offers independent streams plus unreliable datagrams, and industry reports say it reached Baseline browser support in 2026 once Safari 26.4 shipped it in March. Server-side tooling is generally less mature than WebSocket's, so confirm support for your audience and keep a fallback.

Worked Example: A Food Delivery App

Real systems combine the three. Consider the flow of one order:

Food delivery architecture using all three technologies A payment gateway sends a webhook to the backend API. The backend marks the order paid in the database and publishes an event to a pub/sub bus. Realtime nodes subscribed to the bus stream the order status to the customer app over SSE. Separately, the customer app and the delivery partner's app each hold a WebSocket connection to a chat server. Payment gateway Backend API Pub/sub (Redis) Realtime nodes Database webhook mark Paid publish Customer apporder status via SSE chat via WebSocket Customer app Chat server Delivery partner The webhook is the source of truth for payment. SSE only tells the customer what already happened. WebSocket carries only what needs two-way talk.
Figure 3: One order touches all three technologies
  1. The payment gateway sends a webhook to your backend. The backend verifies it, marks the order Paid in the database, and publishes an event to a pub/sub bus.
  2. The realtime nodes subscribed to that bus push the new order status to the customer's app over SSE. The customer only needs to be told, so one-way is enough, and reconnect and resume come for free.
  3. When the delivery partner is assigned, the two of them chat over a WebSocket, because both sides send.

Note what the design avoids. The status screen never depends on a WebSocket. The payment state never depends on a browser being open. And the database, not the stream, is the source of truth: a client that reconnects fetches the current state first and then listens for changes.

9. What We Ran

Every claim about behavior in this article was checked against running code, using Node.js 22 with ws 8.22 and Express 5.3.

TestObserved
WebSocket upgrade with the RFC 6455 sample keyStatus 101 and the RFC's sample accept value
Broadcast and acknowledge between two clientsOther client received the message; sender received the ack
Client that never answers pingsTerminated by the heartbeat sweep
WebSocket client reconnect with jitterConnected on the third attempt after two drops; backoff cap grew 50, 100, 200, 400 ms against an instantly-dropping server and reset after a stable connection (stability threshold shortened for the test)
Signed webhook, five scenariosAccept, dedupe, tamper reject, replay reject, and the re-serialization bug reproduced
Hostile webhook input (non-numeric timestamp, wrong content type, invalid JSON, empty body, missing or malformed signature)All answered with a 4xx; none crashed the handler
SSE headers and event framingtext/event-stream with ids, event names and heartbeat comments
SSE resume via Last-Event-IDEvents 1 to 6 received in order across three forced reconnects
SSE client cleanup on disconnectRemoved within about 100 ms of the abort

What We Did Not Test

These tests ran on localhost with no proxy. Load balancer idle timeouts, proxy buffering behavior and horizontal scaling depend on your infrastructure. Treat the figures we mention for those (such as a 60-second default timeout) as things to check in your own stack, not guarantees.

10. Security Checklist

AreaWebSocketSSEWebhook
Transportwss:// onlyHTTPS onlyHTTPS endpoint
Who is calling?Authenticate at handshake; check OriginAuthenticate the request; authorize per streamVerify HMAC over the raw body
AbuseMessage size and rate limits; connection caps per userConnection caps per userTimestamp tolerance; dedupe by event id
RevocationClose sockets when access is removedClose streams when access is removedRotate secrets; accept old and new during rotation
Data exposureValidate every incoming messageNever stream data the user may not seeDo not log secrets or full payloads with personal data

11. Questions Engineers Ask

Is SSE a "lesser" WebSocket?

No. It is a different trade. For one-way streams it is often the better engineering choice: it uses plain HTTP, reconnects automatically, resumes by id, and reuses your existing auth, logging and rate limiting. WebSocket earns its extra complexity only when the client needs to send frequently on the same channel.

Can a webhook replace WebSocket for a mobile app?

No. A phone is not a reachable server, so a provider cannot POST to it. A webhook can feed your backend, and your backend then pushes to the phone through SSE, WebSocket or a push notification service.

Should I use push notifications instead?

Push (such as FCM, which we covered in Understanding Firebase Cloud Messaging) reaches users who have the app closed. SSE and WebSocket only work while the app is open and connected. Many apps use push for "come back" alerts and a live connection for the active session.

Is a webhook really "real-time"?

It is event-driven, usually within seconds, but delivery can be delayed, retried or reordered. It is a notification mechanism between systems, not a latency guarantee.

How many connections can one server hold?

It depends on memory per connection, your message rate and the operating system's file descriptor limits, so measure with realistic load rather than trusting a figure from the internet. Whatever the number, design so that adding a node and a pub/sub layer is the scaling path.

12. Conclusion

The three technologies are not rivals. They answer different questions: WebSocket for a two-way conversation with a client, SSE for a one-way stream to a client, and Webhook for a notification between servers. Start from who talks to whom, then pick the simplest tool that fits, and often that is plain polling.

What separates a demo from a production system is rarely the happy path. It is the heartbeat on the WebSocket, the Last-Event-ID replay on the stream, and the raw-body signature check, timestamp window and idempotency key on the webhook. Build those in from the first version, and keep your database as the source of truth so a client that missed something can always catch up.

Official References

← Back to All Articles