$ cat ~/field-notes/webhooks-vs-websockets.md
Webhooks vs WebSockets: The Difference and When to Use Each
"Should we use a webhook or a WebSocket?"
That sounds like a choice between two ways of doing the same thing. It isn't. One is a message sent to a server when an event happens. The other is a connection kept open between a client and a server.
The confusion causes expensive designs. Teams build WebSocket infrastructure so a payment provider can notify their backend. Or they expose a webhook endpoint and expect it to update a browser in real time. Both can work around the edges, but neither is the right shape for the job.
Here is the short answer:
Need to notify another server about an event? → Webhook
Need a connected client and server to talk live? → WebSocket
Need both? → Use both
The Difference in One Diagram
A webhook is an ordinary HTTP request, normally a POST, initiated by the system where an event happened. The receiver does not need to keep a connection open.
payment succeeds
↓
payment provider ── POST /webhooks/payments ──→ your backend
A WebSocket starts as an HTTP request, then upgrades into one persistent, two-way connection. Either side can send messages while it remains open.
browser ←──────────────────────────────────→ your backend
one long-lived connection
The first is about delivery of an event. The second is about live communication with a currently connected client.
| Webhook | WebSocket | |
|---|---|---|
| Direction | One HTTP request per event, sender to receiver | Both sides can send over one connection |
| Typical peers | Server to server | Browser/mobile app to server |
| Connection | Short-lived | Persistent |
| Best for | Payment events, CI notifications, third-party integrations | Chat, multiplayer games, collaboration, live controls |
| If the receiver is down | Sender can retry later | Client reconnects, but missed messages need an explicit strategy |
| Main operational concern | Authentication, retries, idempotency | Connection lifecycle, heartbeats, fan-out, reconnection |
Use a Webhook When an Event Should Reach Another System
Imagine a payment processor confirms a payment. It must tell your backend even if no user is looking at your site, no browser is open, and your API received no recent request.
That is exactly what a webhook does:
POST /webhooks/payments HTTP/1.1
Host: app.example.com
Content-Type: application/json
X-Webhook-ID: evt_019a
X-Webhook-Timestamp: 1785412800
X-Webhook-Signature: sha256=...
{
"id": "evt_019a",
"type": "payment.succeeded",
"data": {
"payment_id": "pay_123",
"order_id": "ord_456"
}
}
The sender owns the event and initiates delivery. The receiver exposes a stable endpoint and acknowledges it quickly.
Webhooks are a good fit for:
- payment, billing, and subscription changes
- Git pushes, CI completion, and deployment notifications
- a SaaS integration notifying a customer's backend
- an internal service publishing a business event to another service
- asynchronous work that must happen even when no end user is connected
The important property is not speed. It is durable intent: if the receiving system is temporarily unavailable, the sender should retry instead of silently forgetting the event.
Use a WebSocket When the Client Must Participate Live
WebSockets are for a conversation with a connected client. A chat application needs the browser to send a message, the server to deliver it to another browser, and both sides to respond without opening a new request for each message.
// Browser
const socket = new WebSocket('wss://app.example.com/chat');
socket.addEventListener('open', () => {
socket.send(JSON.stringify({ type: 'join', roomId: 'engineering' }));
});
socket.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
renderMessage(message);
});
The same connection can carry many messages in either direction:
browser → join room
server → current room state
browser → send message
server → message accepted
server → another participant wrote a message
Use a WebSocket when the client needs to send live actions or receive frequent, low-latency updates:
- chat and presence indicators
- collaborative documents and whiteboards
- multiplayer games
- trading or operations screens with interactive controls
- terminals, remote-control interfaces, or live dashboards that accept commands
For server-to-browser updates only, do not assume WebSockets are necessary. Server-Sent Events are usually simpler for notifications, feeds, and progress updates because the browser already handles the streaming connection and reconnection.
The Most Common Misunderstanding
"We need real time" is not enough information to choose a protocol.
Ask these questions instead:
- Who needs to receive the event? Another backend points to a webhook. A connected browser or app points to WebSockets or SSE.
- Does the receiver need to send messages back on the same connection? If yes, use a WebSocket. If no, SSE may be the smaller solution.
- Must the event survive a receiver outage? You need a durable event record, retry policy, and idempotent processing. A WebSocket alone does not supply those.
- Is the update for one user interface, or an integration? User interfaces commonly use SSE or WebSockets. Integrations commonly use webhooks.
That last distinction matters. A WebSocket is a poor substitute for a webhook when the other system may be offline for minutes or days. Keeping a connection open does not create a delivery guarantee.
They Often Work Together
The most useful architecture uses both protocols at different boundaries.
For example, a payment provider tells your backend that a charge succeeded through a webhook. Your backend records the payment and, if the customer has an order page open, pushes the new status to that browser over SSE or a WebSocket.
payment provider
│ webhook: payment.succeeded
▼
your backend ── stores payment + queues work
│
├── email receipt
├── update inventory
└── WebSocket/SSE → customer's open browser
The webhook is the reliable system-to-system fact. The WebSocket is a best-effort live view for a person who happens to be connected. If the browser disconnects, it can reload the current order state from the normal API.
This separation makes failures much easier to reason about. A missed UI notification is inconvenient; losing a payment.succeeded event is a business incident.
A Webhook Receiver Must Be Boring and Defensive
A webhook endpoint is public by design. Treat it as an untrusted network boundary, even when the sender is a company you know.
First, verify the signature against the raw request body. Parsing and reserializing JSON can change the bytes that were signed. Use the provider's SDK and documented format. For a custom protocol, this example signs the timestamp, a period, and the exact body bytes; the signed timestamp limits replay to five minutes.
const crypto = require('crypto');
function verifySignature(rawBody, signature, timestamp, secret) {
if (typeof signature !== 'string' ||
!/^sha256=[0-9a-f]{64}$/.test(signature) ||
typeof timestamp !== 'string' || !/^\d{10}$/.test(timestamp)) {
return false;
}
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;
const expected = crypto
.createHmac('sha256', secret)
.update(timestamp + '.')
.update(rawBody)
.digest();
const actual = Buffer.from(signature.slice('sha256='.length), 'hex');
return actual.length === expected.length &&
crypto.timingSafeEqual(actual, expected);
}
// Register before express.json(); require WEBHOOK_SECRET at startup.
app.post('/webhooks/payments', express.raw({ type: 'application/json', limit: '64kb' }), async (req, res, next) => {
if (!Buffer.isBuffer(req.body) || !verifySignature(
req.body, req.headers['x-webhook-signature'],
req.headers['x-webhook-timestamp'], process.env.WEBHOOK_SECRET
)) {
return res.sendStatus(401);
}
let event;
try {
event = JSON.parse(req.body.toString('utf8'));
} catch {
return res.sendStatus(400);
}
if (!event || typeof event.id !== 'string' || typeof event.type !== 'string') {
return res.sendStatus(400);
}
try {
// queue is the application's durable queue, configured to persist before resolving.
await queue.add({ source: 'payments', event });
return res.sendStatus(204);
} catch (error) {
return next(error); // Return a failure so the sender can retry.
}
});
Authenticate the event identity in the body rather than trusting an unsigned ID header. This custom signature format is illustrative, not a drop-in verifier for a payment provider. For example, Stripe documents its own signature verification and replay protection.
Then design for at-least-once delivery. The sender may time out after you completed work and retry the same event. Store the provider's stable event ID behind a unique constraint, or otherwise make processing idempotent.
INSERT INTO processed_webhook_events (source, event_id, received_at)
VALUES ('payments', :event_id, now())
ON CONFLICT (source, event_id) DO NOTHING
RETURNING event_id;
In the queue consumer, commit that insert and the business update in the same transaction, and apply the update only if the insert returned a new row. A separate committed deduplication marker can lose work if the worker crashes before its side effect. For external effects, use the downstream system's idempotency mechanism or an outbox. A duplicate delivery should receive a successful response. Do not rely on a provider delivering events once, in order, or immediately.
For a fuller receiver checklist—signatures, timeouts, retries, and delivery logs—see Webhooks: How to Build Reliable Event Delivery.
A WebSocket Needs a Disconnect Plan
With WebSockets, the first message is the easy part. Production is mostly about everything that happens after the network breaks.
Connections can disappear because a phone changes networks, a browser sleeps, a proxy closes an idle socket, or a deployment restarts your process. Plan for all of them:
- authenticate when the connection opens and authorize every action
- send heartbeats where your infrastructure needs them
- reconnect with capped exponential backoff and jitter
- resubscribe after reconnecting
- decide whether missed messages are replayed, fetched from an API, or intentionally dropped
- route events through shared infrastructure when multiple server instances can own clients
Do not put an irreplaceable business event only on an in-memory socket. Write it durably first. The transactional outbox is a useful pattern when a database change and an event must not drift apart.
For the WebSocket-specific connection and scaling details, read WebSockets in Production.
What About Polling?
Polling is not obsolete. A client asking GET /orders/ord_456 every 30 seconds is often the right answer when updates are infrequent, a little delay is fine, and a persistent connection would add more complexity than value.
It becomes inefficient when many clients repeatedly ask for nothing, or when an update must appear quickly. At that point, choose the lightest push mechanism that meets the requirement:
infrequent updates, delay is fine → polling
server → browser only → SSE
browser ↔ server, live interaction → WebSocket
server → server after a business event → webhook
The Decision
Use a webhook when an event in one system should trigger work in another system. Make it authenticated, idempotent, observable, and retryable.
Use a WebSocket when an active client and server need a continuing two-way conversation. Make it reconnectable, scalable, and clear about what happens to missed messages.
Use both when a durable backend event should also make an open user interface feel immediate. That is not duplication. It is giving each boundary the tool it actually needs.