A webhook lets one system notify another system about an event through an HTTP request. Instead of repeatedly polling for new payments, users, orders, or delivery updates, a receiving application can react when the event occurs. The apparent simplicity is misleading: production webhook integrations must handle network failures, timeouts, duplicate deliveries, out-of-order events, manual replays, and untrusted input.
The correct goal is not to receive every event exactly once. Most providers do not promise that guarantee. A more practical design accepts an at-least-once delivery model, makes repeated processing harmless, persists accepted events durably, and provides a controlled way to retry or replay failures.
Model the delivery lifecycle first
In a typical flow, a provider creates an event, sends an HTTP POST to your endpoint, and evaluates the response. A successful 2xx response normally means that the delivery was accepted. If the connection fails, the endpoint times out, or the application returns a 5xx response, the provider may attempt delivery again. Stripe documents automatic retries for up to three days in live mode and explicitly states that event ordering is not guaranteed. Its webhook documentation is a useful reference for these behaviors.
Design the consumer with these assumptions:
- The same event can arrive more than once.
- Different event types can arrive concurrently or in an unexpected order.
- A timeout does not prove that the provider failed to deliver the request.
- Previously delivered events may be sent again manually.
- The request body is external, untrusted input.
Verify the raw request and its signature
Do not trust a webhook merely because its JSON is valid. An attacker could send a structurally correct request claiming that a payment succeeded or an account was activated. A provider-generated signature helps prove that the request was created with the expected secret or key.
Signature verification usually depends on the unmodified raw body. Parsing JSON, changing whitespace, reordering fields, normalizing encoding, and serializing the object again can produce different bytes and invalidate the signature. Stripe specifically requires the raw request body for verification; its signature troubleshooting guide explains common framework-related failures.
A robust verification sequence is:
- Read the raw request bytes before a general JSON parser modifies them.
- Extract the signature header and, where applicable, the key identifier.
- Check the signature timestamp against an acceptable clock-skew window.
- Use the provider’s official library or a carefully reviewed cryptographic implementation.
- Reject the request before business processing if verification fails.
For HMAC-based schemes, keep the endpoint secret exclusively on the server. Never place it in client-side code, source control, or verbose logs. Plan key rotation explicitly. During a short migration window, an endpoint may need to accept signatures made with both the old and new secrets, followed by a definite retirement date for the old key.
Make event handling idempotent
Processing an event twice can create duplicate charges, grant access twice, send repeated emails, or decrement inventory more than once. Store the provider’s unique event identifier and enforce uniqueness at the database level.
CREATE TABLE webhook_events (
provider_event_id TEXT PRIMARY KEY,
event_type TEXT NOT NULL,
status TEXT NOT NULL,
received_at TIMESTAMP NOT NULL,
processed_at TIMESTAMP NULL
);A simple “check, then insert” sequence is vulnerable to a race condition. Two workers can check simultaneously, both find no record, and both start the side effect. Prefer an atomic insert, upsert, or transaction protected by a unique constraint. A uniqueness conflict should be treated as a normal duplicate path, not as an unexplained application failure.
Idempotency must cover the entire side-effect chain. If processing calls an email provider, fulfillment service, or internal command endpoint, that downstream operation must also be safe to repeat. Pass the original event ID as an idempotency key when the downstream API supports it. Otherwise, create a durable outbox record with a unique business key and dispatch it through a worker.
Acknowledge quickly, process asynchronously
The public webhook route should perform only the work required to authenticate and durably accept the message. After signature and basic schema validation, write the raw payload, event ID, and relevant metadata to a durable queue or database table. Then return a fast 2xx response. A worker can perform the expensive business operation afterward.
This pattern reduces provider timeouts and prevents long-running work from exhausting request threads or connection pools. Durability matters, however. Do not return success after placing the event only in an in-memory list. If the process crashes before persistence, the provider may stop retrying even though your system lost the event.
The acceptance transaction should have a clear boundary: either the event is durably stored and acknowledged, or the endpoint returns an error that allows the provider to retry. If the queue is unavailable, failing closed is usually safer than reporting success and silently discarding the notification.
Separate retryable failures from permanent failures
Not every failure deserves the same response. Temporary network errors, database saturation, and third-party outages can often be retried. Invalid signatures, malformed payloads, and unsupported event types are generally permanent failures for that delivery.
| Condition | Recommended action | Operational note |
|---|---|---|
| Temporary network error | Retry with exponential backoff | Add jitter to avoid synchronized load. |
| Invalid payload | Move to a dead-letter queue | Alert operators and preserve the payload safely. |
| Duplicate event | Skip the side effect and mark it accepted | Measure the duplicate rate. |
| Permanent business-rule failure | Hold for manual review | Keep enough context for replay or correction. |
Define a maximum attempt count, a retry delay ceiling, and a dead-letter policy. Record the attempt number, last error, and next eligible time. Without these fields, a poison message can consume worker capacity indefinitely and make incident diagnosis difficult.
Do not depend on event order
Providers may deliver events out of order. An update can arrive before a creation notification, or two updates can be processed by different workers at the same time. A handler that assumes perfect ordering may overwrite newer state with an older snapshot.
For critical state transitions, retrieve the current object from the provider’s API when the event indicates that the local record may be stale. For less critical notifications, the payload may be sufficient. You can also use resource versions, sequence numbers, or timestamps to reject older updates.
Fetching the source object for every event increases latency and API usage, so make the decision per event type. The important principle is to distinguish an event as a notification that something changed from the authoritative current state of the resource.
Build observability and replay into the design
HTTP status codes alone do not explain whether a webhook integration is healthy. Track at least these signals:
- Success and failure rates by event type
- Endpoint response time and queue wait time
- Duplicate delivery rate
- Dead-letter message count
- Time from receipt to completed processing
- Provider delivery ID, event ID, and internal correlation ID
Mask personal data, tokens, and payment details in logs. Keep diagnostic fields such as event type, verification result, attempt count, and correlation ID. GitHub documents both validation and redelivery workflows, providing a practical operational example in its delivery validation guide and redelivery guide.
Replay should be deliberate rather than an uncontrolled button that runs production side effects again. A replay tool should identify the original event, show its current status, support a dry run where possible, and use the same idempotency protections as normal processing.
Production checklist
- Expose the endpoint over HTTPS and restrict administrative access separately.
- Verify the signature against the raw body before business logic.
- Enforce a database uniqueness constraint on the provider event ID.
- Do not acknowledge until the event is durably stored.
- Move expensive work to a queue-backed worker.
- Distinguish transient errors from permanent validation failures.
- Use bounded retries and a dead-letter queue.
- Never assume event order; fetch authoritative state when necessary.
- Support secret rotation without exposing keys in logs.
- Test duplicates, timeouts, concurrent deliveries, malformed bodies, and replay.
Conclusion: A reliable webhook consumer is a small distributed system. Signature verification establishes authenticity, idempotency neutralizes duplicates, durable queuing protects delivery, bounded retries handle temporary faults, and observability makes recovery possible. Designing these properties up front produces an integration that remains predictable when networks, providers, and application processes behave imperfectly.
0 Comments