Reliable webhooks require more than an endpoint that returns a successful response. This guide explains how to design webhook retry logic, verify signatures, prevent duplicate processing with idempotency, and route unresolved failures to a dead-letter process you can inspect and replay safely.
Overview
A webhook is an asynchronous request sent by one system when an event occurs. It may notify your cloud app that a payment changed, a user was created, a file finished processing, or an external record was updated. Unlike a direct API call, webhook delivery happens outside the original request flow. The sender and receiver can fail independently, networks can delay requests, and a sender may deliver the same event more than once.
Design your webhook receiver around an “at least once” delivery assumption. In practice, that means your application should expect duplicates, delayed events, retries, out-of-order delivery, malformed requests, and temporary provider outages. A reliable architecture acknowledges valid requests quickly, stores enough information to investigate them, and performs business processing in a controlled worker or queue.
A practical flow looks like this:
- Accept the HTTPS request and enforce a reasonable request timeout.
- Validate required headers, the event identifier, timestamp, and signature.
- Check whether the event has already been accepted or processed.
- Persist the event and its status before starting non-trivial work.
- Return a success response after durable acceptance, not merely after parsing.
- Process the event asynchronously and record the result.
- Retry temporary failures and move exhausted failures to a dead-letter queue or table.
This pattern works with a traditional application server, a serverless function, or a backend-as-a-service stack. For broader API design context, pair it with an OpenAPI documentation workflow for cloud apps.
What to track
1. Define a webhook contract
Before writing the handler, document the fields that make an event identifiable and actionable. At minimum, record:
- Event ID: a provider-generated identifier that should remain stable across delivery attempts.
- Event type: a versioned name such as
invoice.paidoruser.updated. - Occurred-at time: when the source system says the event happened.
- Delivery or received-at time: when your application received it.
- Payload version: the schema version used by the sender.
- Resource reference: the account, tenant, order, or object affected.
- Signature and timestamp headers: retained in a controlled form for verification and investigation.
Keep the original request body available for audit and replay, subject to your privacy and retention rules. Do not log secrets, authorization headers, or unnecessary personal data. If your app is multi-tenant, associate every event with a tenant only after validating the source and resolving the relationship from trusted data. The multi-tenant SaaS architecture checklist provides a useful companion review for isolation and usage limits.
2. Verify signatures before trusting the payload
Signature verification should use the exact raw request body, not a parsed and re-serialized JSON object. Parsing can change whitespace, ordering, or escaping and cause a valid signature to fail. The general process is:
- Read the raw bytes received over HTTPS.
- Extract the provider’s signature and timestamp values.
- Build the signed message according to that provider’s documented format.
- Calculate the expected signature with the configured secret.
- Compare signatures using a constant-time comparison where your runtime supports it.
- Reject requests outside an acceptable timestamp window, if the provider’s scheme includes timestamps.
rawBody = request.rawBody
signedMessage = timestamp + "." + rawBody
expected = HMAC_SHA256(webhookSecret, signedMessage)
if !constantTimeEqual(expected, receivedSignature):
reject(401)
if timestampIsTooOld(timestamp):
reject(401)
acceptForProcessing()This is deliberately provider-neutral pseudocode. Signature algorithms, header formats, timestamp rules, and secret rotation procedures vary. Treat the provider’s current documentation and SDK behavior as the implementation authority, then cover the verification code with tests using captured, non-sensitive fixtures.
3. Store idempotency state
Idempotency prevents a repeated delivery from creating a second charge, duplicate account, repeated email, or conflicting state transition. Store the provider event ID in a database with a unique constraint. A useful event record includes event_id, event_type, tenant_id, status, attempt_count, first_received_at, last_attempt_at, processed_at, and an error summary.
Make the insert atomic. Two concurrent deliveries must not both pass a separate “does this exist?” check and then process the same event. If the insert conflicts with the unique key, return a successful acknowledgment when the existing record represents the same trusted event. If an event ID is reused with a different body or type, flag it for investigation rather than silently merging it.
4. Separate acknowledgment from business processing
Use a queue, job table, or durable task mechanism when processing can take longer than the sender’s timeout or involves several downstream services. The receiver should validate and persist the event, then acknowledge it. A worker can retry the business operation without forcing the sender to resend the entire request.
Track both delivery status and business status. For example, an event may be successfully received but still be waiting for a worker, or it may be permanently rejected because its schema is unsupported. These states should not be collapsed into a single generic “failed” value.
Cadence and checkpoints
Reliability is an operating practice, not a one-time implementation task. Review webhook behavior monthly for active integrations and perform a deeper audit at least quarterly or after a significant schema, infrastructure, or provider change.
At every integration launch
- Test valid signatures, invalid signatures, stale timestamps, malformed JSON, and oversized payloads.
- Send the same event twice and confirm that the business effect occurs only once.
- Deliver events out of order and verify that state transitions follow explicit rules.
- Simulate a timeout after persistence but before acknowledgment.
- Confirm that a worker retry does not repeat an irreversible side effect.
- Document the provider’s retry behavior, timeout expectations, event types, and secret rotation process.
Monthly operational review
Check delivery success rate, acknowledgment latency, queue depth, retry counts, duplicate-event rate, signature failures, processing duration, and dead-letter volume. Break these measurements down by provider, event type, tenant, and deployment version where practical. A rising duplicate rate can indicate slower processing, timeouts, or a sender-side change. A rising signature-failure rate may indicate secret drift, a body-parsing change, clock problems, or hostile traffic.
Quarterly design review
Review event retention, personal-data exposure, access to replay tools, database indexes, queue capacity, alert thresholds, and provider documentation. Reconfirm whether the current retry schedule matches the business action. Also review vendor SDK versions and webhook limits whenever the provider changes its API. If webhook delivery is part of a wider API stack, the cloud app API stack comparison can help structure that review.
Keep retry schedules explicit. A common starting model is short exponential backoff with jitter for transient failures, followed by longer intervals and a maximum attempt count. For example, your policy might retry after approximately one minute, five minutes, fifteen minutes, one hour, and several hours. These are design examples rather than universal defaults: use the sender’s documented expectations and your operation’s tolerance for delay. Never retry permanent validation failures indefinitely.
How to interpret changes
Metrics are most useful when tied to a decision. A low success rate with normal signature validation often points to application errors, unavailable dependencies, or insufficient worker capacity. A high acknowledgment rate with a growing queue means the HTTP endpoint is healthy but downstream processing is not keeping up. A low acknowledgment rate combined with repeated provider deliveries suggests that the receiver is timing out or failing before durable persistence.
Separate transient, permanent, and unknown failures:
- Transient: network errors, temporary database unavailability, rate limits, and dependency timeouts. Retry with backoff.
- Permanent: invalid signatures, unsupported event versions, missing required fields, or an event that violates a known business rule. Quarantine and investigate; do not blindly retry.
- Unknown: unexpected exceptions or ambiguous downstream results. Preserve the event and error context, then use a bounded retry policy.
Dead-letter handling is the safety net for events that cannot be completed automatically. A dead-letter record should include the event ID, original payload reference, failure category, attempt history, last error, timestamps, and the next permitted action. Restrict replay access, require an operator reason, and make replay idempotent. Before replaying, check whether the business effect already happened outside your event record. If it did, mark the event resolved or apply a compensating action rather than running the original operation again.
When an event is delayed, compare its occurred-at time with its received-at time. Delayed delivery may be harmless for an informational update but dangerous for a state transition. If ordering matters, use sequence numbers, resource versions, or a reconciliation job instead of assuming that network arrival order equals event order.
When to revisit
Revisit this implementation before launching each new webhook integration, after changing an event schema, when switching queues or app hosting platforms, and whenever a provider changes signature rules, retry behavior, delivery limits, or SDK guidance. Also schedule a recurring monthly metrics review and a quarterly replay and duplicate-event audit.
Use this compact checklist during each review:
- Can the receiver verify the exact raw body and reject forged or stale requests?
- Is the event ID protected by a database uniqueness constraint?
- Does durable persistence happen before acknowledgment?
- Are business effects safe when a worker runs twice?
- Are retries bounded, observable, and limited to transient failures?
- Can operators inspect, approve, and safely replay dead-letter events?
- Are logs and retained payloads limited to the data needed for support and audit?
- Do alerts identify whether the failure is at delivery, queueing, processing, or a downstream dependency?
Record the answers in your integration documentation and link them to the deployment or schema version. For teams deploying serverless handlers, compare the runtime and timeout characteristics in this serverless functions comparison. A webhook system is ready for production when failures are expected, duplicates are harmless, sensitive requests are authenticated, and unresolved events remain visible rather than disappearing into logs.