
SitePoint SponsorsPublished inDeveloper Tools·
November 20, 2026
The AI briefing for Developers
Stay up to date with AI tools, model releases, and developer workflows that matter.
Weekly. Free. One click to leave.
SitePoint Premium
Stay Relevant and Grow Your Career in Tech
- Premium Results
- Publish articles on SitePoint
- Daily curated jobs
- Learning Paths
- Discounts to dev tools
7 Day Free Trial. Cancel Anytime.
OpenAI, Anthropic, Gemini, and Cursor are all sending webhooks now, and all four built them on Standard Webhooks, the open spec Downloads of the spec’s npm package went from 1.7 million a month in September 2025 to 220 million a month currently
This may be boring to hear for the nth time, but the reason is agents. An individual person checks on a running job a few times. An agent told to watch for changes checks every resource, every minute, for as long as it runs, and almost every one of those requests comes back with nothing new. An agent that starts a job, polls until it finishes, and then starts the next one spends most of its time waiting: six steps with 15 seconds of polling each add 90 seconds, even when every operation is fast. Polling more often adds load, and polling less often adds delay, so there’s not really a sweet spot.
An event-driven API gets rid of that trade-off. It tells consumers when something changed or finished, so they stop asking. That matters most for work that runs for minutes or hours, like batch inference, fine-tuning, and video generation, and many APIs still don’t offer it. Of the 57 AI APIs with long-running jobs that Svix reviewed for its State of Webhooks 2027 report, 19 make you poll for the result.
Webhooks are how most APIs push those events, and you can get a v1 out pretty fast. Making it dependable is an infrastructure problem, which is a class of problem that requires more time by default. Before you ship webhooks, you need an append-only event log behind every delivery, a fixed event format, signed payloads, retries with backoff, event IDs receivers can deduplicate on, per-endpoint isolation, and delivery logs your customers can read. If you skip one of these things, a customer is just going to bring it up later.
Each section below covers one of them with adaptable code, and Standard Webhooks works with existing verification libraries in most languages.
Write every event to a log
If the request handler that changes the data also sends the webhook, a crash between the commit and the HTTP call loses the event, and nothing records that it should have gone out. A customer whose endpoint was down for longer than your retry window has no way to find out what they missed.
Both problems go away if you write each event to an append-only table, scoped per customer, in the same transaction as the change. Webhooks are delivered from that table, and the same table backs an HTTP endpoint customers can read from a cursor. Svix calls this design POKE (Publish Once, Kickoff Everywhere). Build the log first: a consumer who misses a webhook needs somewhere to resume from.
CREATE TABLE events (id bigserial PRIMARY KEY,customer_id bigint NOT NULL,event_type text NOT NULL,payload jsonb NOT NULL,created_at timestamptz NOT NULL DEFAULT now());CREATE INDEX events_customer_idx ON events (customer_id, id);Every code path that changes state calls one helper inside its own transaction:
// events.jsexport async function emitEvent(tx, customerId, type, data) {await tx.query("SELECT pg_advisory_xact_lock($1)", [customerId]);await tx.query("INSERT INTO events (customer_id, event_type, payload) VALUES ($1, $2, $3)",[customerId, type, data],);}
const tx = await db.connect();try {await tx.query("BEGIN");await tx.query("UPDATE invoices SET status = 'paid' WHERE id = $1", [invoiceId]);await emitEvent(tx, customerId, "invoice.paid", { id: invoiceId, status: "paid" });await tx.query("COMMIT");} catch (err) {await tx.query("ROLLBACK");throw err;} finally {tx.release();}Pass the helper the transaction handle. An insert through the connection pool commits separately, so you can end up with the event and no change, or the change and no event.
The advisory lock prevents a subtler bug. Postgres assigns sequence values at insert time, but rows only become visible at commit. With two concurrent writers, a reader can see ID 102, store it as its cursor, and then never see ID 101 when the slower transaction commits. Holding a per-customer lock until commit makes each customer’s events visible in ID order.
Reading the log is one indexed range query. The endpoint returns a cursor even when there are no new events, so a client can always store it and ask again later:
app.get("/events", authenticate, async (req, res) => {const after = String(req.query.after ?? "0");if (!/^d+$/.test(after)) return res.status(400).send("invalid cursor");const { rows } = await db.query(`SELECT id::text, event_type AS type, created_at AS timestamp, payload AS dataFROM eventsWHERE customer_id = $1 AND id > $2ORDER BY idLIMIT 100`,[req.customerId, after],);res.json({ data: rows, cursor: rows.length ? rows.at(-1).id : after });});authenticate stands in for the middleware that already protects your API and sets req.customerId. That scoping stops one customer from reading another’s events. A customer who was offline for a week asks for events after their last cursor and gets everything they missed, in order. Publish your retention period, since it limits how far back that works. The same log can also serve synthetic created events for existing records when a new integration needs to load its initial state.
Settle the event format quickly
Customers write handlers against your payloads, so you’ll be supporting every field you ship.
Give each event an id, type, timestamp, and data. Use the log row’s ID as the event ID so webhooks and the pull endpoint agree. Name types as a reatalog with an example payload for each type
{"id": "1042","type": "invoice.paid","timestamp": "2026-11-18T14:03:22Z","data": {"id": "inv_8f2k1","customer_id": "cus_19x","status": "paid","amount": 4900,"currency": "usd","updated_at": "2026-11-18T14:03:22Z"}}Emit an event for each state change a consumer would otherwise poll for. Deletions are the ones teams forget most. Long-running jobs need completion and failure events, such as export.completed and export.failed.
Put enough in the payload for the receiver to act without calling you back: identifiers, the fields that changed, and an updated_at or version number so a receiver can order two events about the same object. An event that only says “invoice changed” forces a fetch every time, and the receiver is back to polling. Sending the whole object saves the fetch, but the copy can be stale when it arrives and may include fields the subscriber isn’t allowed to read through your API.
Adding a field is safe. Removing or renaming one breaks handlers, so ship a new type such as invoice.paid.v2 and keep sending the old one until customers have moved over.
Sign every payload
Anyone who finds a customer’s webhook URL can POST a fake invoice.paid to it. A signature lets the receiver confirm the request came from you, wasn’t modified in transit, and isn’t an old request being replayed.
Standard Webhooks signs the string id.timestamp.body with HMAC-SHA256, using a separate secret for each endpoint. Including the timestamp is what lets receivers reject old requests. Generate secrets with "whsec_" + crypto.randomBytes(24).toString("base64").
// webhooks.jsimport crypto from "node:crypto";export function signWebhook(secret, id, timestamp, body) {const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");const signature = crypto.createHmac("sha256", key).update(`${id}.${timestamp}.${body}`).digest("base64");return `v1,${signature}`;}Send the result in three headers. The ID comes from the log and stays the same on every retry. The timestamp is the time of the current attempt, so each retry gets a new signature.
// event is a row from the log: { id, type, timestamp, data }const timestamp = Math.floor(Date.now() / 1000);const body = JSON.stringify(event);const headers = {"content-type": "application/json","webhook-id": event.id,"webhook-timestamp": String(timestamp),"webhook-signature": signWebhook(endpoint.secret, event.id, timestamp, body),};Receivers need the matching check, so put it in your docs:
export function verifyWebhook(secret, headers, rawBody, toleranceSeconds = 300) {const id = headers["webhook-id"];const timestamp = Number(headers["webhook-timestamp"]);const received = headers["webhook-signature"];if (!id || !timestamp || !received) return false;const age = Math.abs(Date.now() / 1000 - timestamp);if (age > toleranceSeconds) return false;const expected = Buffer.from(signWebhook(secret, id, timestamp, rawBody).slice(3),"base64",);return received.split(" ").some((entry) => {const [version, signature] = entry.split(",");if (version !== "v1" || !signature) return false;const candidate = Buffer.from(signature, "base64");return (candidate.length === expected.length &&crypto.timingSafeEqual(candidate, expected));});}The function takes the raw body because frameworks that parse JSON and serialize it again change the bytes, and the signature stops matching. It compares with crypto.timingSafeEqual, since === returns faster on an early mismatch and leaks timing information. It rejects requests more than five minutes old to block replays. The signature header is a space-separated list so that during a secret rotation you can send one signature per secret and the receiver accepts either.
That code shows how the scheme works. In production, use a Standard Webhooks library on both ends. It implements the same algorithm:
import { Webhook } from "standardwebhooks";const wh = new Webhook(secret);const event = wh.verify(rawBody, req.headers); // throws if the signature is invalidSet a retry schedule
Receiving endpoints go down during deploys and outages, and they return errors when they’re rate limited. If you only try once, each of those is a lost webhook.
Count any non-2xx response as a failure, redirects included. Following a redirect to an arbitrary host is a security problem in its own right. Count slow responses as failures too. The code below gives up after 15 seconds. Publish whatever limit you pick, because customer handlers have to respond within it.
const RETRY_DELAYS_SECONDS = [0, 5, 5 * 60, 30 * 60, 2 * 3600, 5 * 3600, 10 * 3600, 10 * 3600,];export async function attemptDelivery(url, headers, body) {try {const res = await fetch(url, {method: "POST",headers,body,redirect: "manual",signal: AbortSignal.timeout(15_000),});return res.status >= 200 && res.status < 300;} catch {return false;}}export function nextAttemptAt(attemptsMade, lastAttemptAt = Date.now()) {const delay = RETRY_DELAYS_SECONDS[attemptsMade];return delay === undefined ? null : lastAttemptAt + delay * 1000;}These delays match the schedule Svix runs in production: eight attempts over a little more than 27 hours. The early retries cover restarts. The later ones give someone time to notice an outage and fix it. After each failure, pass the number of attempts so far to nextAttemptAt, and when it returns null, mark the delivery as failed. The event is still in the log, so once the customer fixes their server they can replay it or read it from the pull endpoint.
Store attempt state in a table next to the log. Timers in process memory disappear when the process restarts, and you don’t need a message broker to avoid that.
Decide what happens to endpoints that never come back. Svix disables an endpoint after five days of continuous failure and emits an event so the sender can tell the customer. Pick your own threshold, notify the customer when you disable their endpoint, and let them turn it back on.
Make duplicate deliveries harmless
Retries mean some events arrive twice. Usually the receiver processed the event but timed out before you saw its response, so you sent it again. Senders accept this at-least-once behavior because the alternative is dropping events, and receivers handle the duplicates.
Receivers deduplicate on webhook-id, which doesn’t change between retries. The insert that stores the event can also be the duplicate check:
// server.jsimport express from "express";import pg from "pg";import { verifyWebhook } from "./webhooks.js";const app = express();const db = new pg.Pool();const secret = process.env.WEBHOOK_SECRET;app.post("/webhooks",express.raw({ type: "application/json" }),async (req, res) => {const rawBody = req.body.toString("utf8");if (!verifyWebhook(secret, req.headers, rawBody)) {return res.status(401).send("invalid signature");}await db.query(`INSERT INTO webhook_inbox (id, payload)VALUES ($1, $2)ON CONFLICT (id) DO NOTHING`,[req.headers["webhook-id"], rawBody],);res.status(204).end();},);app.listen(3000);webhook_inbox needs a text primary key id and a jsonb column payload. The handler verifies the signature, stores the event, and returns 204. A background worker processes the inbox, so the handler responds well within the sender’s timeout. express.raw gives the route the unparsed body that verification needs.
Put this pattern in your docs with a note about ordering. Events in the log have a fixed order, but webhook deliveries don’t always arrive in it. A retried invoice.created can land after invoice.paid. Receivers should keep whichever event has the newer updated_at, or read the pull endpoint when they need strict ordering.
Don’t tolerate noisy neighbors
With a shared worker pool, one customer’s hanging endpoint can tie up every worker for the full timeout while other customers’ events wait. Limit concurrent deliveries per endpoint, and slow down delivery to endpoints that keep failing.
Customer-supplied URLs are also an attack surface. Someone can register http://169.254.169.254/ or an internal hostname and get your servers to call your cloud metadata service or private network. This is server-side request forgery (SSRF). Resolve the hostname before connecting, reject private and loopback addresses, and don’t follow redirects. The delivery code sets redirect: "manual" for this reason.
Give customers a way to debug deliveries themselves
Without a self-serve view, every “did you send it?” question goes to an engineer who has to search logs.
Give customers a page to add and remove endpoints, choose event types, and rotate secrets. For each message, show every attempt with its timestamp, status code, and response body. The response body usually contains the customer’s own error message. Add buttons to replay a failed message and to send a test event.
Expose the same operations in your API. Creating an endpoint and choosing its event types should take one authenticated request, because scripts and AI agents now set up a lot of integrations and can’t click through a dashboard.
This is the biggest item here because it needs a UI, and it’s the one teams most often leave out of the first release.
When to build vs. buy
You can build all of this yourself, and many teams have. It comes down to the fact that it’s cheap to manage delivery for 99% of your webhooks, but it’s nontrie UX side such as offering the customer portal for your customers to manage their webhooks in
Svix, which sponsored this article, handles webhook delivery. You keep the event log and decide what goes in it. A small relay reads new rows and passes each one to Svix:
import { Svix } from "svix";const svix = new Svix(process.env.SVIX_AUTH_TOKEN);// Once, when a customer signs upawait svix.application.create({ name: "Acme Inc.", uid: "customer-19" });// For each new row in the event logawait svix.message.create("customer-19",{ eventType: event.type, payload: event },{ idempotencyKey: `event-${event.id}` },);If the relay crashes before saving its position, it will resend some rows when it restarts. The idempotency key makes Svix treat each resend as the original message. Svix signs each message, delivers it to every endpoint subscribed to that event type, retries on the schedule described above, and disables endpoints after five days of failures. Signatures follow Standard Webhooks, so your customers can verify them with any Standard Webhooks library or with the Webhook class in the svix package.
Svix also hosts the debugging portal. This call returns a single-use link where the customer can manage endpoints, read delivery logs, and replay messages:
const portal = await svix.authentication.appPortalAccess("customer-19", {});console.log(portal.url);The free tier includes 50,000 messages a month and doesn’t require a credit card.
Questions to answer before launch
Before the first customer registers an endpoint, you should be able to answer yes to each of these:
- Is every event written to an append-only, per-customer log in the same transaction as the change?
- Can customers read that log from a cursor over HTTP, is retention documented, and do webhooks carry the same event IDs?
- Is there a published catalog of event types, including deletions and job completions, and a policy for breaking changes?
- Does each payload include enough to act on, plus an
updated_ator version? - Is every payload signed over the event ID, timestamp, and raw body with a per-endpoint secret, and can customers rotate that secret without missing events?
- Do your docs include code for verifying signatures and deduplicating events?
- Do failed deliveries retry with backoff for at least a day, from storage that survives a restart, with a published timeout?
- Do endpoints that fail for days get disabled, and does the customer hear about it?
- Is each endpoint limited so a slow one can only delay its own deliveries, and do you block private addresses and redirects?
- Can a customer create an endpoint with one API call, see every delivery attempt, replay a message, and send a test event without contacting you?
Sponsored posts are provided by our content partners. Thank you for supporting the partners who make SitePoint possible.


