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:
- Who opens the connection? A browser can open an outbound connection to you. Your server usually cannot open one to a browser.
- Who sends the data? Only the server, only the client, or both?
- How long does the connection live? One request, or minutes and hours?
| Question | WebSocket | SSE | Webhook |
|---|---|---|---|
| Who opens it? | Client (HTTP upgrade) | Client (normal GET) | Provider, to your public URL |
| Who sends? | Both | Server only | Provider only (you reply with a status) |
| Lifetime | Long-lived | Long-lived | One request per event |
| Typical peers | Browser/app ↔ server | Server → browser/app | Server → 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
- Authentication. The browser
WebSocketAPI cannot set custom headers such asAuthorization. Use a cookie, or fetch a short-lived single-use ticket over HTTPS and pass it in the URL or the first message. - Origin checks. Browsers do not apply the same-origin policy to WebSocket handshakes. Verify the
Originheader on the server, or a malicious page can open a socket using the victim's cookies (cross-site WebSocket hijacking). - Back-pressure. A slow client lets queued messages pile up in server memory. Watch
bufferedAmountor the socket's write queue and drop or disconnect slow consumers. - Horizontal scaling. A connection lives on one server instance. To message a user connected elsewhere you need a pub/sub layer (Redis, NATS, Kafka) between instances. Sticky sessions help the handshake but do not solve fan-out.
- Deploys. Every deploy drops every connection. Plan graceful draining, and make clients resume from the last message they saw.
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:
| Request | Result | Why |
|---|---|---|
| Valid signed event | 200 accepted | Signature and timestamp are good |
| Same event again | 200 duplicate_ignored | Idempotency by event id |
| Body changed after signing | 400 bad_signature | Tampering detected |
| Correct signature, 1 hour old | 400 stale_or_missing_timestamp | Replay window enforced |
| Parse-then-re-serialize route | 400 verified: false | Re-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
- Acknowledge fast, process later. Verify, store the raw event, return 2xx, and let a worker do the real work. Providers time out and retry slow endpoints, which creates the duplicates you then have to handle.
- Assume at-least-once delivery. Make handlers idempotent. In production the dedupe key belongs in a database unique constraint or Redis, not in process memory, because the in-memory
Setabove is lost on restart and is not shared between instances. - Do not trust ordering. A
payment.refundedevent can arrive beforepayment.succeeded. Use object versions or timestamps, or fetch the current state from the provider's API when an event arrives. - Reconcile. Webhooks can be lost during your outages. Run a periodic job that compares your records with the provider's API, so a missed event is a delay and not a permanent inconsistency.
- Keep the secret out of the repo. Load it from the environment or a secret manager, and support two active secrets during rotation.
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
- Connection limit on HTTP/1.1. Browsers allow about six connections per origin, shared across all tabs, so a user with several tabs open can exhaust them. On HTTP/2 the limit is the negotiated number of concurrent streams, 100 by default. Serving SSE over HTTP/2 removes the problem.
- No custom headers.
EventSourceonly sends a GET and cannot setAuthorization. Use cookie authentication, or usefetch()with a streaming reader (or a library that wraps it), which also lets you use POST. We confirmedfetchcan read the same stream and sendLast-Event-IDby hand. - Text only. Events are UTF-8 text. Send binary data as base64 (with the size cost) or use WebSocket.
- One direction. Anything the client needs to send goes through a normal HTTP request. For many apps (notifications, progress, live feeds, streamed AI responses) that is exactly the right split, and it keeps your normal auth, logging and rate limiting working unchanged.
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.
| Concern | WebSocket | SSE | Webhook |
|---|---|---|---|
| Direction | Two-way | Server → client | Provider → your server |
| Protocol | WebSocket (ws/wss) after an HTTP upgrade | Plain HTTP response | Plain HTTP request |
| Data format | Text and binary | UTF-8 text | Usually JSON |
| Reconnect | You build it | Built into EventSource | Provider retries |
| Resume after gap | You build it | Last-Event-ID (you supply the replay) | Retries plus your reconciliation job |
| Browser auth options | Cookie or ticket (no custom headers) | Cookie (or fetch for headers) | Not applicable: signature verification |
| Proxy and firewall friendliness | Needs upgrade support | Works anywhere HTTP works (if buffering is off) | Needs a public HTTPS endpoint |
| Delivery guarantee | None: lost on disconnect | None, unless you add ids and replay | At-least-once, unordered |
| Best for | Chat, games, collaboration | Notifications, feeds, progress, streamed text | Payments, Git events, integrations |
7. How Each One Fails
Choosing a technology is choosing a set of failure modes. Compare them before you commit.
| Failure | WebSocket | SSE | Webhook |
|---|---|---|---|
| Network drop | Silent half-open socket until a heartbeat finds it | Browser reconnects, resumes by id | Provider sees a timeout and retries |
| Server deploy | All connections drop, reconnect storm | All drop, but resume is automatic | Brief 5xx, retries cover it |
| Slow consumer | Memory grows unless you cap the queue | Same: cap the write buffer | Provider times out and retries |
| Proxy interference | Upgrade blocked or idle timeout | Buffering delays events | Rarely an issue |
| Duplicates | Possible on resend after reconnect | Possible on replay | Expected: design for it |
| Spoofing | Hijacked sockets (check origin and auth) | Unauthorized stream access | Forged POSTs (verify signature) |
8. How to Choose, and How They Combine
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:
- 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.
- 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.
- 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.
| Test | Observed |
|---|---|
| WebSocket upgrade with the RFC 6455 sample key | Status 101 and the RFC's sample accept value |
| Broadcast and acknowledge between two clients | Other client received the message; sender received the ack |
| Client that never answers pings | Terminated by the heartbeat sweep |
| WebSocket client reconnect with jitter | Connected 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 scenarios | Accept, 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 framing | text/event-stream with ids, event names and heartbeat comments |
SSE resume via Last-Event-ID | Events 1 to 6 received in order across three forced reconnects |
| SSE client cleanup on disconnect | Removed 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
| Area | WebSocket | SSE | Webhook |
|---|---|---|---|
| Transport | wss:// only | HTTPS only | HTTPS endpoint |
| Who is calling? | Authenticate at handshake; check Origin | Authenticate the request; authorize per stream | Verify HMAC over the raw body |
| Abuse | Message size and rate limits; connection caps per user | Connection caps per user | Timestamp tolerance; dedupe by event id |
| Revocation | Close sockets when access is removed | Close streams when access is removed | Rotate secrets; accept old and new during rotation |
| Data exposure | Validate every incoming message | Never stream data the user may not see | Do 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.