A customer pays for an order. Your payment provider sends a successful-payment event. Your server updates the order, but the response gets lost before the provider receives it. The provider cannot know whether your code finished, so it tries again.
If the second request runs the same business action again, you might send two fulfilment requests, add account credit twice, or create duplicate records. If you mark the event as handled before the database write is safe, a crash can lose the work instead. The hard part of webhooks is not receiving JSON. It is making the effect safe when delivery and processing fail at awkward moments.
Assume a valid event can be delivered more than once. Verify it, store it durably, acknowledge it, and make the business operation idempotent.
Why webhook retries are normal
A webhook is an HTTP message sent by one system to notify another system that something happened. The sender and receiver do not share a transaction. A network timeout does not tell the sender whether your database committed the change; it only tells the sender that it did not receive a timely response.
That uncertainty creates retries. Stripe documents automatic retries for live-mode events for up to three days, using exponential backoff. It also warns that events are not guaranteed to arrive in the order they were generated. GitHub takes a different approach: its documentation says failed deliveries are not automatically redelivered, so an operator must request a redelivery when needed. These are provider-specific policies, not a universal webhook standard.
Design your receiver for at-least-once delivery even if a provider usually sends each event once. The goal is not to force the network to deliver exactly once. The goal is to make repeated delivery harmless.
Four failure modes to design around
- Duplicate delivery: the sender retries after a timeout, or an operator replays an event.
- Crash after acceptance: your server stores or partly processes the event, then exits before returning a successful response.
- Worker failure: your endpoint acknowledges the event, but a background worker crashes halfway through processing it.
- Out-of-order delivery: a newer state change reaches your app before an older one.
A reliable design gives each failure a safe path: a unique event key, durable storage, retryable processing, and business rules that do not depend on arrival order.
1. Verify the request before trusting the payload
Webhook URLs are public HTTP endpoints. Anyone who discovers one can send it a POST request. Do not trust a payload because it looks like a provider event or contains a familiar customer ID.
- Use the provider's signature verification library where possible.
- Verify the signature against the exact raw request body, before JSON parsing or transformation.
- Keep the signing secret in server-side environment configuration or a secret manager, never in frontend code or a repository.
- Use HTTPS in production and subscribe only to event types the integration actually needs.
For example, Stripe requires the original request body for signature verification. If Express parses the JSON first, the body may no longer match the bytes that were signed. GitHub signs payloads with HMAC-SHA256 in the X-Hub-Signature-256 header and recommends a constant-time comparison rather than ordinary string equality.
Signature verification answers, “Did this request come from someone who knows the signing secret, and has the signed content remained intact?” It does not answer, “Have I already performed this business action?” You still need deduplication and idempotency.
2. Store the event in a durable inbox before acknowledging it
Do not run slow work inside the HTTP request. Sending email, provisioning an account, generating a document, or calling another API can take longer than the provider's timeout. GitHub asks receivers to return a 2xx response within 10 seconds; Stripe also recommends returning success quickly before complex logic.
But “respond quickly” does not mean “put the event in an in-memory array and hope the process stays alive.” If the server acknowledges an event and then restarts, an in-memory queue disappears. The event has been acknowledged but not safely retained.
Use a durable queue or a database-backed inbox. The receiver should:
- Read the raw body and verify the provider signature.
- Validate the event envelope and identify its provider event ID.
- Insert the event into durable storage with a unique key.
- Return 2xx only after that insert or queue operation commits.
If the database or queue is unavailable, return a failure response so the provider can retry according to its documented policy. If the insert succeeds but the response is lost, the retry hits the same unique key and becomes a harmless duplicate.
A small PostgreSQL inbox table
This schema is a starting point for a single provider account. If one database receives events from multiple accounts or endpoints, include a source or account identifier in the unique key too.
CREATE TABLE webhook_inbox (
provider text NOT NULL,
event_id text NOT NULL,
event_type text NOT NULL,
payload jsonb NOT NULL,
status text NOT NULL DEFAULT 'pending'
CHECK (status IN (
'pending', 'processing', 'processed', 'failed'
)),
attempts integer NOT NULL DEFAULT 0,
received_at timestamptz NOT NULL DEFAULT now(),
available_at timestamptz NOT NULL DEFAULT now(),
locked_until timestamptz,
processed_at timestamptz,
last_error text,
PRIMARY KEY (provider, event_id)
);
The primary key is the first deduplication boundary. PostgreSQL's ON CONFLICT DO NOTHING lets concurrent attempts race safely against that unique constraint: only one insert wins. A process-local Set or cache is not a replacement because it is lost on restart and is not shared by multiple server instances.
Example: accept a Stripe event in Express
This example uses Stripe snapshot events, the Stripe Node SDK, Express, and the pg package. Mount this route before any global express.json() middleware so the raw body remains available. If you configure Stripe thin events, use the matching event parser and payload format from the current Stripe documentation.
import express from "express";
import Stripe from "stripe";
import pg from "pg";
const app = express();
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
const pool = new pg.Pool({
connectionString: process.env.DATABASE_URL
});
app.post(
"/webhooks/stripe",
express.raw({ type: "application/json" }),
async (req, res) => {
let event;
try {
event = stripe.webhooks.constructEvent(
req.body,
req.headers["stripe-signature"],
process.env.STRIPE_WEBHOOK_SECRET
);
} catch {
return res.status(400).send("Invalid webhook signature");
}
try {
await pool.query(
"INSERT INTO webhook_inbox " +
"(provider, event_id, event_type, payload) " +
"VALUES ($1, $2, $3, $4::jsonb) " +
"ON CONFLICT (provider, event_id) DO NOTHING",
["stripe", event.id, event.type, JSON.stringify(event)]
);
return res.sendStatus(200);
} catch (error) {
console.error("Webhook intake failed", {
eventId: event.id
});
return res.sendStatus(500);
}
}
);
// Register normal JSON routes after the raw webhook route.
app.use(express.json());
A duplicate insert is not an error here: the endpoint returns 200 because the same event is already safely stored. A failed database write returns 500, because acknowledging an event that was not retained would create a silent-loss window. Do not log the signing secret or dump full payment payloads into ordinary application logs.
3. Let a worker process the inbox
A worker reads pending rows, claims one with a short lease, and processes it outside the request path. In PostgreSQL, SELECT ... FOR UPDATE SKIP LOCKED is a useful building block when several workers poll the same table: one worker can claim a row without waiting for another worker that has already locked it.
Use a lease such as locked_until so a row claimed by a worker that crashes can become eligible again after the lease expires. Increase the lease or renew it for long-running work. Keep the retry schedule in your database rather than sleeping inside an HTTP request.
A worker should follow a state model like this:
| State | Meaning | Next action |
|---|---|---|
pending | Accepted and waiting | Eligible for a worker |
processing | Claimed under a lease | Finish, or reclaim after lease expiry |
processed | Business transaction committed | Never apply the same effect again |
failed | Retry limit reached or event needs intervention | Inspect, fix, then replay deliberately |
For a change that lives in your own database, wrap the business update and the inbox status change in the same database transaction. If the transaction rolls back, neither is committed. If it commits, both are committed. A worker crash before the commit leaves the event eligible for retry; a crash after the commit sees the processed state on the next attempt.
For an external action, such as sending an email or calling a shipping API, a database transaction cannot include the remote system. Use an outbox table: write the intended external action in the same transaction as your local business change, then let a separate dispatcher send it. Give each outbox action a stable idempotency key when the receiving API supports one.
4. Protect the business operation, not just the event ID
Deduplicating by provider event ID handles a repeated delivery of the same event. It does not cover every duplicate business outcome. Stripe notes that, in some cases, two separate Event objects can refer to the same underlying object and event type.
That is why the business database needs its own uniqueness boundary. If an order should be fulfilled once, make the order ID unique in the fulfilment record. If an invoice should grant account credit once, record the invoice ID in a credit-ledger table with a unique constraint. Apply the insert and balance change in one transaction.
CREATE TABLE order_fulfilments (
order_id text PRIMARY KEY,
created_at timestamptz NOT NULL DEFAULT now()
);
-- In the same transaction as the fulfilment state change:
INSERT INTO order_fulfilments (order_id)
VALUES ($1)
ON CONFLICT (order_id) DO NOTHING;
Only perform the fulfilment action when the insert actually created a row. In production, keep the uniqueness check and the local state transition inside one transaction. Do not check first in one query and insert later in another: two concurrent workers can both pass the check.
The inbox key asks, “Have I accepted this provider event?” The business key asks, “Has this order, invoice, or entitlement already received this effect?” For high-value actions, both checks matter.
5. Do not assume events arrive in order
Network retries, parallel workers, and provider behavior can change arrival order. Stripe explicitly says event delivery order is not guaranteed. It also warns that different events can share the same second-level created timestamp, so that field is not a reliable sequence number.
Prefer one of these strategies:
- Read current state: when an event arrives, retrieve the latest object from the provider API before making a state-sensitive decision.
- Use monotonic transitions: design your local state machine so an older event cannot move a completed order back to pending.
- Use provider sequence numbers: if the provider supplies a documented version or sequence field, use it instead of guessing from timestamps.
- Serialize per business object: when order matters, process events for the same subscription or order sequentially while allowing unrelated objects to run concurrently.
Do not globally serialize every event unless you have a measured reason. It creates a bottleneck. Most systems need ordering only within a specific account, order, subscription, or other business entity.
6. Make retries and recovery visible
Use bounded retries with backoff for temporary failures. A malformed payload, invalid signature, or unsupported event is not the same as a temporary database outage; do not retry permanent failures forever. After a configured number of attempts, move the event to a failed or dead-letter state and alert someone who can investigate it.
Record enough metadata to answer operational questions: provider, event ID, event type, received time, attempt count, processing duration, status, and a short sanitized error. Avoid storing unnecessary personal data and never log signing secrets, access tokens, or full payment details.
Build a replay tool that requeues a stored event without deleting its history. Replay should pass through the same idempotency checks as a normal delivery. Also run reconciliation for important records: compare your local order or subscription state with the provider's source of truth, because webhook delivery alone is not a complete audit process.
For GitHub, the X-GitHub-Delivery header identifies a delivery and remains the same when that delivery is manually redelivered. Store that stable identifier with the provider name so a replay is recognized as the same accepted event.
Provider recovery rules differ. Stripe currently documents live-mode automatic retries for up to three days and manual resend windows of up to 15 days in the Dashboard or 30 days with the CLI. GitHub documents manual redelivery for deliveries from the past three days and says it does not automatically redeliver failed deliveries. Check the provider's current documentation rather than assuming its retry policy matches another service.
A failure-focused test checklist
- Send the same valid event twice and confirm the business effect occurs once.
- Send the same event concurrently to two application instances.
- Commit the inbox insert, then simulate the HTTP response being lost.
- Stop a worker after it claims an event and confirm the expired lease makes it recoverable.
- Force a database failure before the inbox insert and confirm the endpoint does not acknowledge the event.
- Deliver two state changes out of order and confirm the local state does not move backwards.
- Replay a failed event and verify the original event history remains visible.
- Send a payload with an invalid signature and confirm it never reaches the worker.
Test the awkward moments between steps, not just the happy path. A handler that works once in a local test has not proved that it can survive a timeout, process restart, duplicate request, or partial failure.
Do you need a queue for every webhook?
No. A low-risk webhook that triggers a quick cache refresh may not need a separate message broker. It still needs signature verification and a clear duplicate policy. For payments, order fulfilment, access provisioning, credits, inventory, or any event that can change money or customer entitlements, a durable inbox and idempotent worker are usually worth the extra structure.
Start with a database-backed inbox if your application already depends on PostgreSQL and traffic is modest. Move to a dedicated queue when you need independent scaling, higher throughput, richer routing, or operational features that your database-backed worker no longer handles comfortably. A queue does not remove the need for idempotency; it only changes how work is buffered and delivered.
The reliable pattern
Webhook reliability is not about preventing every retry. You cannot control the sender's network, your process lifetime, or the moment a remote service times out. You can control what your application does when the same event comes back.
Verify the signature, persist the event under a unique key, acknowledge only after durable acceptance, process it with a retryable worker, and protect the business effect with its own uniqueness constraint or idempotency key. Treat ordering as a separate problem and make failed events visible. That turns webhook handling from a fragile request handler into a recoverable workflow.
If your application uses PostgreSQL, our guide to PostgreSQL indexes and query performance explains another important part of keeping data workflows healthy. For a broader backend decision, see Supabase vs Firebase. Our API security checklist covers authentication, authorization, validation, and rate limits. If you are building a customer-facing platform, explore Raazim Tech's SaaS development work and web development services.