How Do You Build Reliable Webhook Pipelines That Survive Retries?

Web Dev
November 30, 2026 13 min read

Webhooks look like ordinary HTTP requests, but production reliability depends on treating them as messages delivered across an unreliable boundary. Providers retry, events arrive twice, deployments interrupt workers, and a callback can arrive after newer state has already been applied. In 2025 and 2026, this matters across payments, authentication, commerce, AI job callbacks, live game operations, and automation platforms. A dependable design must authenticate each delivery, store it durably, process it idempotently, and give operators a safe way to inspect and replay failures.

Key Takeaways
  • Assume every webhook can be duplicated, delayed, reordered, or delivered during an outage.
  • Verify signatures against the raw request body before trusting parsed fields.
  • Persist accepted events before returning success, then process them asynchronously.
  • Enforce deduplication with a database uniqueness constraint, not an in-memory check.
  • Build observability and controlled replay into the first production version.

Why Do Apparently Simple Webhooks Fail in Production?

A webhook starts with a simple promise: when something changes, one system sends an HTTP request to another. The difficulty is that the sender and receiver do not share a transaction. The provider cannot know whether a timed-out request failed before storage, failed after processing, or succeeded while the response disappeared. Retrying is therefore the safest behavior for the sender, even when it creates duplicate deliveries for the receiver.

This produces an at-least-once delivery model in practice. The same event might arrive immediately, several minutes later, or after the receiving service has restarted. Two instances of the application may receive equivalent deliveries concurrently. An older event can also arrive after a newer one because one request followed a slower network path or entered a provider retry schedule. None of these cases should be treated as exceptional.

Failures also happen inside the receiving system. A handler might update the database and then crash before returning a response. It might call a second service that succeeds, while the local status update fails. A deployment can terminate a request midway through processing. Rate limits, expired credentials, database contention, schema changes, and malformed payloads create additional failure modes. Simply wrapping the controller in a try and catch block does not resolve these consistency problems.

The useful mental model is a small distributed messaging system. The HTTP endpoint is only the transport adapter. Behind it, the application needs authentication, an event envelope, durable ingestion, deduplication, asynchronous processing, retry policy, dead-letter handling, metrics, and replay controls. Once those responsibilities are explicit, webhook behavior becomes much easier to reason about and test.

What Contract Should a Webhook Endpoint Enforce?

Start by documenting the endpoint as a protocol rather than an incidental controller. Define the HTTP method, content type, maximum body size, required headers, signature algorithm, supported event types, and expected response codes. If the provider publishes a webhook contract, preserve its event identifier and timestamp instead of replacing them with locally generated values. Those fields become essential during deduplication and incident investigation.

A useful event envelope normally includes an immutable event ID, an event type, a creation time, a schema or API version, and a resource identifier. The payload should represent either the changed data or enough information to retrieve the authoritative resource. Snapshot payloads reduce follow-up calls, but lookup-based payloads can avoid acting on stale embedded state. The correct choice depends on whether historical event state or current resource state drives the business rule.

Validation should happen in layers. First enforce transport constraints such as request size and content type. Next authenticate the raw delivery. Then parse the envelope and confirm that required identifiers are present. Deep business validation belongs in the worker, after durable storage, unless the provider explicitly expects permanent rejection of invalid payloads. Mixing all validation into the request path increases latency and makes transient dependency failures look like bad requests.

Version contracts conservatively. Accept unknown JSON fields, add new fields as optional, and avoid changing the meaning of an existing event type. When a breaking change is unavoidable, introduce a new endpoint version or event type and support both during migration. A short contract table covering event types, versions, retry behavior, and ownership is often more valuable than a large controller because it gives backend developers, operators, and integration partners the same model.

How Do You Verify Authenticity Without Breaking Legitimate Retries?

TLS protects a request while it travels across the network, but it does not prove that the request came from the expected provider. Most mature webhook systems attach a keyed signature to the body, often using HMAC. The receiver computes the expected signature with a shared secret and compares it with the supplied value. This check must use the exact raw bytes received, before JSON parsing or reserialization changes whitespace, encoding, or property order.

Use a constant-time comparison function to reduce timing leakage. If the signature scheme includes a timestamp, enforce a documented tolerance to limit replay attacks. The tolerance should reflect real delivery behavior, and verification should distinguish a stale signature from a malformed one. Store the provider event ID after successful authentication so a captured request cannot trigger the business operation again within the accepted time window.

Secret rotation needs an explicit plan. During rotation, the verifier may need to accept both the current secret and the next secret for a limited period. Secrets belong in a managed secret store or protected runtime configuration, never in source control, client-side code, logs, or an operations dashboard. Different environments and webhook providers should have separate credentials so one leak does not compromise every integration.

IP allowlists can add defense in depth, but they should not replace cryptographic verification. Provider address ranges can change, and forwarding infrastructure may obscure the original source. Also consider the opposite direction: if event data can influence a URL that your worker fetches, validate the destination to prevent server-side request forgery. Authentication failures should be logged without recording secrets or full sensitive payloads, and repeated failures should produce an alert rather than disappear into ordinary request logs.

How Do Idempotency and Deduplication Work Together?

Deduplication answers whether the receiver has already accepted a particular delivery. Idempotency answers whether repeating an operation produces the same intended result. They overlap, but they are not identical. A unique event ID can suppress an exact duplicate, while a business operation may still need protection against two different events requesting the same action. Reliable systems address both levels.

At ingestion, create an inbox table with a unique constraint on a scoped key such as provider plus event ID. The insertion and durable payload storage should be one atomic database operation. A preliminary query followed by an insert is unsafe because two application instances can both observe that the row is absent. Let the database resolve the race through its uniqueness guarantee.

[HttpPost("webhooks/provider")]
public async Task<IActionResult> Receive(CancellationToken ct)
{
    using var reader = new StreamReader(
        Request.Body,
        Encoding.UTF8,
        leaveOpen: true);

    var rawBody = await reader.ReadToEndAsync(ct);

    if (!_signatures.IsValid(rawBody, Request.Headers))
        return Unauthorized();

    var envelope = JsonSerializer.Deserialize<WebhookEnvelope>(rawBody);

    if (envelope is null || string.IsNullOrWhiteSpace(envelope.Id))
        return BadRequest();

    var inserted = await _inbox.TryInsertAsync(
        envelope.Id,
        envelope.Type,
        rawBody,
        ct);

    return Ok(new
    {
        received = true,
        duplicate = !inserted
    });
}

The sample assumes that TryInsertAsync uses a database uniqueness constraint and stores the event durably. A duplicate still receives a successful response because the provider has fulfilled its delivery responsibility. Returning an error would only encourage another retry. The stored payload should be immutable, while processing attempts and status changes can live in related records.

Business idempotency usually requires another key or invariant. A payment capture, entitlement grant, email request, or job completion should have a stable operation key and a uniqueness rule at the domain level. Keep deduplication records at least as long as the provider may retry, plus an operational margin. If records must expire, archive enough metadata to investigate late deliveries without retaining sensitive payloads indefinitely.

Why Should Acknowledgment Be Separated From Processing?

A webhook provider usually expects a response quickly. Business processing may involve database locks, third-party APIs, file operations, email delivery, or expensive calculations. Performing all of that inside the HTTP request increases timeout risk. A timeout encourages the provider to retry, which creates more work precisely when the receiver is already slow. The safer pattern is authenticate, validate the envelope, store it durably, and return success.

A background worker can then claim pending inbox records and execute the business handler. Each attempt should record its start time, completion time, error category, and retry schedule. Use bounded exponential backoff with jitter for transient failures. Permanent failures, such as an unsupported event version or an impossible state transition, should move to a dead-letter state instead of retrying forever.

The boundary matters. Do not return success after merely placing an event in process memory. A restart between acknowledgment and persistence would lose the event permanently because the provider believes delivery succeeded. Durable storage can be a message broker, a managed queue, or a transactional database inbox. For modest systems, an inbox table with careful worker locking is often enough and keeps the architecture understandable.

Synchronous processing can still be appropriate for a small internal integration with a fast, local, transactional operation. Even then, enforce timeouts and idempotency. As dependencies or traffic grow, preserve the ability to move work behind a queue without changing the public webhook contract. Teams that need help designing this boundary can use Exoa's web application, backend, and API development services for integration architecture and implementation.

Backpressure should also be deliberate. Monitor queue age and pending depth, cap worker concurrency around downstream limits, and pause a failing event type when necessary. Controlled delay is safer than allowing retries to amplify an outage across every connected system.

How Should Out-of-Order Events Change Your Data Model?

Arrival time is not a trustworthy statement of business order. Event A can be created before event B and still arrive later. A provider may retry A while B succeeds on its first attempt. Multiple provider regions or partitions can add more reordering. If a handler blindly overwrites current state with every payload, an old event can restore a status that the resource has already left.

Prefer explicit versions or sequence numbers when the provider supplies them. Store the highest applied version for each resource and ignore any older snapshot. If only timestamps are available, treat them cautiously because clock precision and semantics vary. Fetching the current resource from the provider can be safer when the event is merely a notification that something changed, although this adds rate limits and availability dependencies.

Model important workflows as valid state transitions rather than arbitrary assignments. For example, a completed operation should not return to processing simply because a delayed processing event arrives. The domain layer can reject stale or impossible transitions while recording that the delivery was understood. This is different from a technical failure and should not trigger endless retries.

When strict ordering is truly required, choose a stable partition key such as account ID, order ID, user ID, or job ID. Serialize events within that key while allowing unrelated keys to process concurrently. A global lock is rarely necessary and harms throughput. Optimistic concurrency, row versions, or compare-and-set updates can protect each aggregate without forcing the whole integration through one worker.

Deletion requires special care. If a deleted resource can later be recreated with the same external identifier, include a generation, version, or creation marker. Keep tombstone metadata long enough to prevent a delayed update from resurrecting removed state. The data model, not the controller's arrival order, should define which facts are authoritative.

What Should You Log and Monitor for Webhook Operations?

Good observability follows one event from receipt through every processing attempt. Use structured fields for provider, event ID, event type, schema version, resource ID, receipt time, processing status, attempt count, and correlation ID. Include a safe error category and handler version when useful. Avoid writing signatures, secrets, authorization headers, or complete payloads into general logs.

Measure both transport and processing. Transport metrics include request count, authentication failures, malformed payloads, duplicate rate, response latency, and response status. Processing metrics include pending event count, age of the oldest pending event, attempt duration, retry count, permanent failure count, and throughput by event type. Queue age is especially important because a stable queue depth can still hide work that has been stuck for hours.

Distributed tracing can connect the inbound request, durable inbox record, worker execution, database changes, and downstream calls. Because asynchronous processing breaks the original request lifetime, propagate a correlation value explicitly. The provider event ID is useful, but a local trace ID can group several internal actions without exposing an external identifier everywhere.

An operations dashboard should answer practical questions: Is delivery currently healthy? Which event types are failing? Is one tenant or resource causing repeated errors? How old is the backlog? Which deployments correlate with the change? Alerts should focus on actionable symptoms, such as sustained authentication failures, rising queue age, or an unusual permanent failure rate, rather than firing for every individual retry.

Retention policies must balance debugging with privacy and cost. Store only fields needed for processing and investigation, encrypt sensitive payloads, and restrict who can view or replay them. A replay action is a privileged production command, so log who requested it, which events were selected, what code version handled them, and whether the operation was a dry run.

How Can You Test and Roll Out a Webhook Pipeline Safely?

Build tests from captured or provider-supplied fixtures, but remove personal and secret data before committing them. Contract tests should cover every supported event type and version. Security tests should modify one payload byte, omit headers, use an invalid signature, submit an expired timestamp, and exceed the body size limit. Parsing tests should include unknown fields and optional fields so additive provider changes do not cause avoidable outages.

Reliability tests need duplicates, concurrency, and failure injection. Deliver the same event twice and confirm that the business effect occurs once. Send two copies simultaneously to separate application instances. Crash the worker after the external action but before local completion, then verify that the retry remains safe. Simulate database unavailability, downstream timeouts, rate limits, and an event that always fails.

Test ordering independently. Deliver newer state before older state, interleave events for several resources, and confirm that per-resource serialization does not block unrelated work. Verify that stale events become successful no-ops or recorded domain rejections rather than technical failures. If deletion exists, include delayed updates after a tombstone.

A replay tool should operate from stored event IDs, preserve the original payload, and create a new processing attempt without pretending a new provider delivery occurred. Add filters, maximum batch sizes, confirmation steps, authorization, and a dry-run mode. The dry run can parse and classify events, but it must not call external services or mutate production state.

Roll out schema and handler changes with backward compatibility. Deploy readers that understand old and new formats before enabling a provider version change. For risky logic, run a shadow handler that calculates the proposed result without applying it, then compare decisions. Keep rollback safe by ensuring the previous release can still read newly stored inbox records.

Before launch, confirm secret rotation, retry limits, queue alarms, dead-letter ownership, payload retention, and provider contact details. The endpoint is not production ready merely because a test request returned 200. It is ready when duplicates, delays, outages, reordering, deployments, and operator replay all have predictable outcomes.

References & Further Reading

webhooks backend architecture API reliability idempotency
Anthony KOZAK

Written by

Freelance Unity developer and game engineer with 16+ years of professional experience. Former Ubisoft developer: Eagle Flight Arcade (Ubisoft Montreal) and Rabbids Coding (Ubisoft Lille, Games for Change Award 2020, Best Learning Game). Unity Asset Store publisher with 16+ commercial plugins. Available for freelance game development, Unity consulting, VR/MR development, and technical training.

Need help with web dev?

I'm a senior developer with 16+ years experience, including AAA projects at Ubisoft. Let's discuss how I can help with your project.

Start a Conversation