Web & DataComplete guide

Webhook Patterns

Webhooks are HTTP callbacks a third-party platform sends to your endpoint when something happens on their side. Receiving them reliably requires signature verification, fast acknowledgement, idempotent processing, and a durable handoff to background work.

Overview

Payment providers, source-control platforms, and SaaS products push events to a registered HTTPS endpoint instead of waiting for polling. The receiver must limit the request, capture the exact raw bytes, validate provider headers and timestamp policy, recompute the documented HMAC with a separately managed secret, decode the supplied digest, and compare digest bytes in constant time. Signature success authenticates the delivery source; it does not authorize blindly trusting every payload field. Before acknowledging, the service durably stores the delivery identifier, event type, raw payload, and processing state under a uniqueness constraint. A bounded queue or polling worker then performs idempotent business processing, records attempts and outcomes, and supports replay or dead-letter operations. Providers can retry after timeouts, deliver duplicates, arrive out of order, rotate secrets, and pause delivery, so monitoring age, failure, duplicate rate, queue depth, and last successful receipt is essential. The acknowledgement code must follow the provider contract: 2xx only after durable acceptance, 4xx for permanent invalid deliveries, and carefully chosen 5xx for retryable receiver failures.

What you will learn

  • Verify a webhook signature over the exact raw request bytes using HMAC and fixed-time comparison.
  • Separate source authentication from payload validation and business authorization.
  • Persist an inbox record before returning a successful acknowledgement.
  • Handle duplicate, delayed, retried, and out-of-order deliveries idempotently.
  • Process accepted deliveries through bounded background work with observable states.
  • Operate secret rotation, replay, retention, alerting, and provider-specific response policies.

Prerequisites

  • HTTP request bodies, headers, status codes, and UTF-8 encoding.
  • HMAC shared-secret basics, durable storage, uniqueness constraints, and background services.
  • ASP.NET Core Minimal APIs and a .NET 10 SDK for the dedicated sample.

When to use Webhook Patterns

Good fit

  • Use webhooks when a provider owns the event source and low-latency push reduces polling.
  • Use a durable inbox when acknowledgement must survive process or queue failure.
  • Use one provider-specific adapter when headers, signatures, retries, or event schemas differ.

Choose another approach when

  • Do not acknowledge before durable acceptance if losing the event is unacceptable.
  • Do not parse or reserialize before verifying a signature defined over raw bytes.
  • Do not execute expensive or non-idempotent business logic inside the receiving request.
  • Do not trust payload-selected URLs, object IDs, prices, or state without local authorization and validation.

Key concepts

Signature verification

The sender includes an HMAC signature computed from the raw request body and a shared secret. The receiver recomputes the signature and rejects the request if it does not match, preventing spoofed events.

Immediate acknowledgement

Return HTTP 200 within seconds of receiving the webhook — most platforms retry if they do not get a quick response. Business logic runs asynchronously after the acknowledgement, not inside the receiving request.

Idempotent processing

The same webhook event may be delivered more than once. The processor records processed event identifiers and skips re-execution when a duplicate arrives, preventing double charges, double emails, or duplicate records.

Raw-byte contract

Signatures commonly cover the exact transmitted bytes, so decoding, normalization, or reserialization before verification can invalidate a genuine request.

Delivery state machine

Pending, processing, completed, and failed states make retries, recovery, replay, and operations observable.

Ordering and freshness

Timestamps, sequence numbers, aggregate versions, and reconciliation protect against stale or out-of-order events.

Secret rotation

A bounded overlap can validate current and previous provider secrets while deployment and provider configuration converge.

Durable handoff

The receiving endpoint writes the raw payload to a durable store — a database outbox or a queue — before responding. A background worker processes it, decoupling reception from business logic and surviving restarts.

Architecture

The inbound webhook endpoint verifies the signature, writes the raw payload to an outbox, returns 200, and a background worker processes the event idempotently from the outbox.

Third-party platform
Webhook endpoint
Durable outbox / queue
Idempotent processor

Conceptual architecture · Adapt to your system context

Implementation walkthrough

The dedicated sample accepts order webhooks only after bounded metadata and exact-byte HMAC verification, atomically persists a file-backed inbox before returning 202, ignores duplicate delivery IDs, and processes pending records with a hosted worker. The file store demonstrates the boundary; production should use a transactional database or durable broker.

  1. 01
    Isolate provider endpoints

    Give each provider a clear route, request limit, header contract, secret, and monitoring dimension.

  2. 02
    Capture exact bytes

    Read the bounded body once without string normalization and retain it for verification and durable storage.

  3. 03
    Verify authenticity

    Validate required headers, timestamp or replay window where supported, HMAC algorithm, encoding, length, and fixed-time digest equality.

  4. 04
    Persist idempotently

    Insert the provider and delivery ID under a unique constraint with raw payload and pending state before acknowledgement.

  5. 05
    Acknowledge deliberately

    Return the provider-documented 2xx only after persistence; classify permanent invalid and transient receiver failures consistently.

  6. 06
    Process in background

    Use bounded workers, deserialize allow-listed event types, authorize local effects, and commit effect plus processed marker atomically.

  7. 07
    Operate recovery

    Track age, attempts, failures, duplicates, queue depth, secret version, replay, retention, and reconciliation.

Code example

The endpoint reads the raw body before model binding, verifies the HMAC signature using the shared secret, stores the payload durably, and returns 200 — all before any business logic runs.

WebhookEndpoint.cs
app.MapPost("/webhooks/payments", async (
    HttpRequest request,
    AppDbContext db,
    IConfiguration config,
    CancellationToken ct) =>
{
    // Read raw body before any model binding
    using var reader = new StreamReader(request.Body);
    var rawBody = await reader.ReadToEndAsync(ct);

    // Verify HMAC-SHA256 signature
    var signature = request.Headers["X-Signature-256"].ToString();
    var secret = config["Webhooks:PaymentSecret"]!;

    if (!IsValidSignature(rawBody, signature, secret))
        return Results.Unauthorized();

    // Idempotency: reject already-processed events
    var eventId = request.Headers["X-Event-Id"].ToString();
    if (await db.ProcessedWebhooks.AnyAsync(w => w.EventId == eventId, ct))
        return Results.Ok(); // Already handled

    // Durable handoff — write to outbox before responding
    db.WebhookInbox.Add(new WebhookInboxEntry(
        EventId: eventId,
        Source: "payments",
        Payload: rawBody,
        ReceivedAt: DateTime.UtcNow));

    await db.SaveChangesAsync(ct);
    return Results.Ok();
});

static bool IsValidSignature(string body, string signature, string secret)
{
    var key = Encoding.UTF8.GetBytes(secret);
    var hash = HMACSHA256.HashData(key, Encoding.UTF8.GetBytes(body));
    var expected = $"sha256={Convert.ToHexString(hash).ToLowerInvariant()}";
    return CryptographicOperations.FixedTimeEquals(
        Encoding.UTF8.GetBytes(expected),
        Encoding.UTF8.GetBytes(signature));
}

public sealed record WebhookInboxEntry(
    string EventId, string Source,
    string Payload, DateTime ReceivedAt);

Testing strategy

Webhook tests must preserve byte-level and failure-ordering behavior.

  • Sign the exact UTF-8 bytes used by the HTTP content and include non-ASCII payload tests.
  • Reject missing, malformed, wrong-length, wrong-secret, or stale signatures before persistence.
  • Assert accepted deliveries exist durably before the response and eventually complete.
  • Send the same delivery ID twice and prove the business attempt count remains one.
  • Restart or recreate the processor and prove pending records are discovered.
  • Exercise malformed JSON, unknown event types, transient failures, replay, and retention behavior.

Security considerations

A webhook is an internet-facing privileged integration, not a trusted internal callback.

  • Store provider secrets outside source, scope them per endpoint, rotate them, and never log signatures or bodies by default.
  • Verify raw bytes and use CryptographicOperations.FixedTimeEquals on decoded equal-length digests.
  • Enforce body and header limits before allocation and apply provider-supported timestamp replay windows.
  • Treat event data as untrusted input and re-check local object, tenant, amount, and state rules.
  • Use HTTPS, restrict outbound calls, and never fetch arbitrary payload-selected URLs.

Performance and scalability

The synchronous path stays short and bounded; throughput belongs in durable workers.

  • Set server and endpoint body limits before buffering.
  • Use bounded channels or broker consumers so memory cannot grow without limit.
  • Batch or partition background work only when ordering and idempotency rules permit.
  • Index provider plus delivery ID and pending-state age in a production inbox.
  • Measure acknowledgement latency separately from processing latency and backlog age.

Deployment and operations

Webhook delivery depends on public routing, provider configuration, durable storage, workers, and secrets changing safely together.

  • Register the final HTTPS URL and verify proxy forwarding, certificates, body limits, and timeouts.
  • Provision durable shared inbox storage before scaling to multiple instances.
  • Deploy worker compatibility before accepting new event versions.
  • Rotate secrets with an explicit overlap and removal window supported by the provider.
  • Smoke-test a signed delivery, duplicate, status transition, and recovery path after deployment.
  • Create runbooks for provider outage, backlog, poison event, replay, and endpoint compromise.

Common problems and fixes

Every delivery fails signature validation.

Likely cause: The wrong secret, header, algorithm, prefix, or transformed body is being verified.

Fix: Capture safe metadata, verify the provider procedure, and compute HMAC over the exact received bytes.

Valid non-ASCII payloads fail.

Likely cause: Sender and receiver signed different encodings or the body was decoded and re-encoded.

Fix: Keep the raw byte array from the request and use it for both HMAC and persistence.

The provider retries despite successful processing.

Likely cause: Acknowledgement exceeded its timeout or returned a non-success status.

Fix: Persist quickly, return the documented 2xx, and move business work behind the durable boundary.

One event causes duplicate effects.

Likely cause: Delivery identity is not unique or the processed marker is separate from the business transaction.

Fix: Enforce a durable unique key and commit the effect and completion marker atomically.

Accepted events disappear after restart.

Likely cause: The service acknowledged an in-memory queue before durable persistence.

Fix: Write the inbox first and have startup recovery enqueue pending records.

The backlog grows continuously.

Likely cause: Workers are failing, undersized, blocked downstream, or receiving poison events.

Fix: Alert on oldest pending age, inspect redacted errors, isolate poison records, and scale only after fixing bottlenecks.

Best practices

  • Always use a constant-time comparison such as CryptographicOperations.FixedTimeEquals when comparing HMAC signatures — standard string equality is vulnerable to timing attacks.
  • Read and verify the raw request body before any model binding or middleware transforms it; some frameworks buffer or modify the body stream, which invalidates the signature.
  • Persist the raw payload to an inbox or outbox table before returning 200, so a crash between acknowledgement and processing does not silently drop the event.
  • Design webhook processors as idempotent consumers and record the platform's event identifier in the same transaction as the business effect, so duplicate delivery is safe to retry.
  • Bound request bodies, headers, queue capacity, attempts, processing time, and retained payload age.
  • Validate the event against current local business state even after source authentication succeeds.
  • Track acknowledgement latency, oldest pending age, duplicate rate, failures, and last successful receipt per provider.
  • Rotate provider secrets through a controlled overlap and remove the old value promptly.

Production checklist

  • Each provider has an isolated endpoint, secret, signature procedure, request limits, and owner.
  • HMAC covers exact raw bytes and decoded digests are compared in fixed time.
  • Timestamp or replay protection is applied when the provider supports it.
  • A durable unique inbox record exists before any 2xx acknowledgement.
  • Business processing is idempotent and completion is atomic with its effects.
  • Queue and worker concurrency are bounded and pending records recover after restart.
  • Duplicate, invalid, out-of-order, delayed, unknown, and failed events have tested policy.
  • Secret rotation, replay, retention, reconciliation, alerting, and compromise have runbooks.

Common interview questions

Why should business logic not run inside the webhook receiving endpoint?

Most platforms have a short response timeout — often five to thirty seconds — after which they mark the delivery as failed and retry. Business logic involving database writes, external calls, or message publishing can easily exceed that window. Acknowledging immediately and handing off to a background processor decouples reception from processing and prevents unnecessary retries.

What is a timing attack and why does it matter for HMAC verification?

A timing attack measures how long a comparison takes to infer whether the guess is partially correct. Standard string equality returns early on the first mismatch, leaking information through response time variance. CryptographicOperations.FixedTimeEquals always takes the same time regardless of where strings differ, making the comparison safe.

How do you handle webhook events that arrive out of order?

Most webhook events carry a timestamp and event type. The processor should check whether the event represents a state that the current aggregate state can transition to. If an older event arrives after a newer one has already been applied, the processor can detect and skip it using the recorded event sequence or a status field on the aggregate.

Why must a webhook signature use the raw request body?

The sender signs bytes, not a parsed object. Whitespace, escaping, character encoding, or property-order changes can produce a different digest for equivalent JSON.

When is it safe to acknowledge a webhook?

After authenticity and basic bounds are checked and the delivery is durably recorded so a crash cannot erase accepted work.

Does a valid signature make payload data trustworthy?

It proves possession of the provider secret for those bytes. The receiver must still validate schemas and authorize business effects against its own current state.

Dedicated GitHub sample

Clone, run, test, and modify the focused implementation created for this guide.

Verified sample

Webhook Durable Inbox

A .NET 10 receiver demonstrating exact-byte HMAC verification, fixed-time digest comparison, durable-before-ack acceptance, duplicate protection, bounded background processing, recovery, and HTTP tests.

ASP.NET Core 10HMAC SHA-256Hosted ServicesxUnit
dedicated-samplewebhooksdurable-inboxidempotencyintegration-testing
Run
dotnet run --project src/WebhookDurableInbox
Test
dotnet test WebhookDurableInbox.slnx