The timeout that leaves two systems disagreeing
Your application creates an invoice after receiving a payment webhook. The invoice is saved, but the response to the sender times out. A few seconds later, the same notification arrives again. Should the application create another invoice?
The sender knows whether it received an acknowledgment. It cannot know whether your application finished the work before the connection failed. Webhooks are therefore delivered at least once, and receivers have to cope with duplicates, delays and gaps.
This article follows an event through a reliable receiver: verify it, store it, acknowledge it, process it once, handle disorder and failure, and check the result against the source.
Verify before you trust
A webhook endpoint is a public URL, so anyone can post to it. Providers sign their requests, usually with an HMAC of the payload and a timestamp using a shared secret. The receiver should:
- Compute the signature over the raw request body exactly as received. Parsing and re-serializing the JSON changes bytes and breaks the check.
- Compare in constant time, using the language's secure comparison function.
- Reject timestamps outside a short window, for example five minutes, to limit replayed requests.
- Reject invalid signatures before anything is queued.
Keep secrets per endpoint or per account, and plan rotation: most providers allow two active secrets during a change. Stripe documents signature verification, duplicate deliveries, asynchronous processing and the absence of an event-order guarantee in its webhook guide. Check the equivalent contract for every provider you connect, because signing schemes and retry rules differ.
Acknowledge fast, process later
Keep the public endpoint short: verify, store the event in a durable inbox table or queue, and return a 2xx response. A background worker does the slow work.
Durable matters. An in-memory task that vanishes on restart is not enough, because after you acknowledge, the sender will not deliver again. Store the provider event ID, the account it belongs to, the event type, receipt time, a processing state and the payload for as long as troubleshooting and data-retention rules justify.
Return a non-2xx response only when you could not store the event, so the sender retries. Responding 200 to a payload you failed to save is the most common way to lose events.
Deduplicate the event and protect the action
Let the database arbitrate. A unique constraint on provider, account and event ID means two workers cannot both accept the same event as new:
CREATE UNIQUE INDEX webhook_events_unique
ON webhook_events (provider, account_id, event_id);
INSERT INTO webhook_events (provider, account_id, event_id, payload, state)
VALUES ($1, $2, $3, $4, 'received')
ON CONFLICT DO NOTHING;
A check followed by an unprotected insert fails when two requests pass the check at the same moment. If the insert reports no new row, acknowledge and stop.
An event ID is not the whole business rule, though. Two questions are different:
- Have we processed this exact notification before?
- Have we already created the invoice for this payment?
A second event about the same payment must not create a second invoice merely because its notification ID differs. Give each action a stable business key, such as the payment ID plus the action type, with its own unique constraint. When the action runs in another API, pass an idempotency key to that API where it supports one, keep the key identical across retries and check how long the provider remembers it.
Keep completion separate from the attempt
Imagine a worker that marks an event done and then calls the invoicing API. If it crashes between those steps, the event is skipped and no invoice exists. Reverse the order and a crash leaves an invoice with no completion record, so a retry repeats the call.
Within one database, put the business change and the completion marker in the same transaction. Across systems, record the attempt, the external result and the external ID, and let the business key and the destination's idempotency rules absorb the retry. Give genuinely ambiguous outcomes a reconciliation path instead of guessing.
Expect events out of order
A customer-updated event can arrive before the customer-created event. An older subscription event can arrive after a newer one. Pick a strategy per data type:
- Status mirror: on each event, fetch the current object from the source API and store that, instead of applying payloads in arrival order.
- Versioned object: store the version or sequence number the source provides and ignore anything older than what you hold.
- Ledger: every transaction matters. Keep all events, and make order-independent totals or reorder by a source-provided sequence.
- Missing parent: park the event and retry it after a delay, instead of failing permanently.
Do not assume a timestamp alone is a safe total order, since clocks and retries break it. Contract changes between versions are a separate concern covered in API versioning.
Retries, backoff and the dead-letter queue
Your own worker will fail too: a downstream timeout, a locked row, a bug. Retry with exponential backoff and jitter so a hundred failed events do not all return at the same second. An illustrative schedule: about 30 seconds, 2 minutes, 10 minutes, 1 hour, then 6 hours, each randomized by plus or minus 20 percent. Cap the attempts and separate errors:
- Transient (timeout, rate limit, 5xx): retry on the schedule.
- Permanent (validation failure, unknown account): do not retry blindly; route to review.
- Poison (crashes the worker every time): stop after the cap.
After the final attempt, move the event to a dead-letter state or queue with the error, attempt count and last stack trace, and alert on its size. An event that disappears after the last retry is worse than one that fails loudly.
Replay, support and reconciliation
Make recovery something support can use. A failed-events screen should show the account, the action, the error and whether retrying could repeat an external effect. Offer replay of a single event or a filtered range, going through the same idempotent path as live traffic. "Retry all" is a poor substitute for knowing what already happened.
Finally, accept that some webhooks never arrive: the sender had an outage, your endpoint was down past their retry window, or the provider dropped an event type. Run a scheduled reconciliation job that lists recent objects from the source API, compares them with your records and enqueues the differences as ordinary events. Daily is often enough for billing data; critical states may need hourly.
Checklist and what to do first
- Signature checked on the raw body, with a timestamp window.
- Event stored durably before any 2xx is returned.
- Unique constraint on provider, account and event ID, plus a business key for the action.
- A defined policy for out-of-order and parent-missing events.
- Backoff with jitter, a retry cap and a dead-letter state with alerts.
- Replay tooling and a reconciliation job.
For your next integration, sketch four failure cases beside the normal flow: a duplicated delivery, two workers on one event, a crash after the external action and a late event. Run each in a test environment before enabling live traffic. Email providers send delivery events by webhook too, so transactional email delivery is a practical place to apply this. Our systems integration work includes these recovery paths alongside the API connection itself.


