Webhook delivery sits at the boundary between decoupled distributed systems. Basic queue-and-retry tutorials cover exponential backoff and dead-letter queues. Production webhook infrastructure fails at the edges: system clocks that disagree across containerized workers, batched payloads that fail partially, and retry schedules that outlive the business windows they exist to serve.

Provider practice varies widely. GitHub does not automatically redeliver failed webhook deliveries and leaves redelivery to manual action or your own scripts. Stripe retries live-mode events with exponential backoff for up to three days. Svix publishes a fixed schedule of immediate, 5 seconds, 5 minutes, 30 minutes, 2 hours, 5 hours, then 10 hours twice, with each period starting after the previous failure. That schedule spans roughly 27.5 hours. If you build a sender, you have to choose where on this spectrum to sit, and the choice has consequences beyond the backoff formula.

1. Clock Skew and Drift in Delayed Webhook Schedulers

Delayed webhook retries rely on time-ordered data structures. The most common are Redis sorted sets (ZSET), relational scheduled_at indexes, and broker-side delays or visibility timeouts such as those in Amazon SQS. Any design that mixes timestamps produced by different machines assumes those machines agree on the time.

How Wall-Clock Assumptions Break Distributed Schedulers

Linux exposes several clocks, and two matter here. The clock_gettime(3) manual page describes them:

  • Wall-clock time (CLOCK_REALTIME): Calendar time that can be set by an administrator or adjusted by NTP. It is affected by discontinuous jumps and by incremental adjtime/NTP adjustments, so it can step backward.
  • Monotonic time (CLOCK_MONOTONIC): Not affected by discontinuous jumps such as a manual clock change, but still affected by incremental adjtime/NTP slewing. On Linux it does not count time the system is suspended. CLOCK_BOOTTIME is identical except that it includes suspended time, and CLOCK_MONOTONIC_RAW is not subject to NTP frequency adjustments.

When a webhook worker computes a retry timestamp as now() + backoff and writes it into shared state, several failure modes appear:

  1. Premature retries (enqueuer clock behind the poller): If the enqueuing worker’s clock lags the polling scheduler’s by 45 seconds, a retry scheduled at worker_now + 30s is already in the past from the scheduler’s point of view. The backoff collapses into an immediate retry, which is the opposite of what you want during a downstream outage.
  2. Stalled retries (enqueuer clock ahead of the poller): If the enqueuer runs ahead, retries stay invisible for longer than intended. The same happens when a scheduler node’s clock steps backward after an NTP correction, because tasks are not due until the local clock catches up.
  3. Premature lease expiry in homegrown lease queues: If one process writes lease_expires_at using its own clock and a separate reaper compares it with a different clock, a few seconds of skew can make a live lease look expired. Two workers then dispatch the same webhook concurrently.

Managed brokers largely avoid the third problem by judging expiry on the broker side. In Amazon SQS, the visibility timeout starts when a message is returned to a consumer, and the broker enforces it. The remaining risk is that your worker’s belief about how much lease time is left diverges from the broker’s, for example during a long pause. SQS also does not guarantee that a message won’t be delivered more than once within the visibility timeout, so duplicate-safe processing is required regardless.

Architectural Mitigations

The fix is to stop using uncoordinated node wall clocks as the source of truth for retry scheduling.

Scheduling Primitive Wall-Clock Vulnerability Clock-Skew-Resilient Alternative
Redis sorted set (ZADD) Workers compute score = local_now + delay, mixing clocks across nodes. Compute the score inside a Lua script from Redis server time (TIME) plus a relative delay.
SQL polling (WHERE retry_at <= now()) Application servers pass client-generated timestamps into INSERT/UPDATE statements. Let the database compute both sides: now() + interval '30 seconds' on write and now() on read. In PostgreSQL, now() returns the transaction start time, so use clock_timestamp() when you need the actual current time.
Broker visibility timeouts (SQS) The worker’s local timer drifts from the broker’s lease timer during CPU throttling or pauses. Extend leases with relative durations (ChangeMessageVisibility), and heartbeat well before expiry. SQS’s own guidance gives the example of extending by 2 minutes every minute.
Native delayed delivery (SQS DelaySeconds) Per-message delay is limited to 15 minutes in standard queues. Use it for short backoffs only, and keep longer delays in a durable scheduler.
In-process delay wheels System.currentTimeMillis() and CLOCK_REALTIME shift during NTP steps. Anchor durations to a monotonic source (System.nanoTime(), clock_gettime(CLOCK_MONOTONIC)). Use CLOCK_BOOTTIME if the process can be suspended and elapsed time must include the suspension.

Centralizing the Time Oracle in Redis

For Redis-backed schedulers, avoid passing a client-generated Unix timestamp as the sorted-set score. Compute it inside a Lua script from Redis’s own clock. TIME returns a two-element array of Unix seconds and microseconds.

Scripts that call TIME and then write used to be rejected because Redis replicated the whole script. Since Redis 5, scripts are replicated as their effects rather than verbatim, so this pattern works on any current version.

-- KEYS[1]: delayed_webhooks sorted set -- ARGV[1]: webhook ID -- ARGV[2]: relative backoff delay in milliseconds local t = redis.call('TIME') local now_ms = (tonumber(t[1]) * 1000) + math.floor(tonumber(t[2]) / 1000) local execute_at = now_ms + tonumber(ARGV[2]) redis.call('ZADD', KEYS[1], execute_at, ARGV[1]) return execute_at 

The claim step should use the same clock. This script moves due items into an in-flight set with a lease deadline and issues a fencing token per claim:

-- KEYS[1]: delayed_webhooks (ZSET) -- KEYS[2]: in_flight (ZSET, score = lease deadline in ms) -- KEYS[3]: fencing_tokens (HASH, webhook ID -> counter) -- ARGV[1]: max items to claim -- ARGV[2]: lease duration in milliseconds local t = redis.call('TIME') local now_ms = (tonumber(t[1]) * 1000) + math.floor(tonumber(t[2]) / 1000) local due = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', now_ms, 'LIMIT', 0, tonumber(ARGV[1])) local claimed = {} for _, id in ipairs(due) do redis.call('ZREM', KEYS[1], id) redis.call('ZADD', KEYS[2], now_ms + tonumber(ARGV[2]), id) table.insert(claimed, id) table.insert(claimed, redis.call('HINCRBY', KEYS[3], id, 1)) end return claimed 

Two caveats apply:

  • Because enqueue and claim both read TIME on the same Redis primary, skew between your worker containers no longer affects scheduling. The oracle is now that primary’s clock, so a failover to a replica whose clock differs slightly can still shift scores, and you should keep the replicas under good time synchronization.
  • In Redis Cluster, all keys a script touches must hash to the same slot, for example by sharing a hash tag such as {webhooks}.

Fencing Tokens for Paused Workers

A worker can be paused (a long garbage-collection pause, a CPU-throttled container, a frozen VM) after it has claimed a webhook and before it records the result. By then its lease may have expired and another worker may hold the webhook. Attach a monotonically increasing fencing token to every claim, as the script above does. When a worker writes a delivery result, the state store rejects any write whose token is older than the latest one issued for that webhook.

This pattern comes from the distributed-locking literature, and the enforcement point is important. A worker’s local check, such as comparing a monotonic timer against its lease duration just before sending, is a useful optimization. It is not a safety guarantee, because the pause can happen immediately after the check. Correctness comes from the store refusing stale tokens. The HTTP request itself can still go out twice in that window, which is why the receiving side also needs idempotency (see section 2).

2. Partial Batch Failures in Multi-Event Webhooks

High-throughput webhook providers frequently batch several events into a single HTTP POST to amortize TLS handshakes, connection setup, and header overhead. The tradeoff is that HTTP gives you a single status code for the whole request.

The All-or-Nothing HTTP Trap

Providers generally treat any 2xx as success and everything else as failure. The Svix documentation, for instance, says other statuses, including 3xx redirects, are treated as failures. When a batch of 50 events contains one that the consumer cannot process, the consumer is left with two bad options:

  • Return 500: The provider retries all 50 events. Unless the consumer deduplicates per event, the 49 healthy events are processed again, producing duplicate ledger entries, duplicate emails, or inflated counters.
  • Return 200 to stop the retries: The failed event is silently dropped unless the consumer has its own durable ingestion queue. That pushes reliability work onto every subscriber.

Per-Item Status Tracking and Split-Retry Logic

Handling partial failures well needs a contract between sender and receiver, plus queue-splitting mechanics on the dispatcher.

1. Structured Partial-Success Response Contracts

The pattern has precedent in queue consumers. AWS Lambda’s SQS integration lets a function return a batchItemFailures list when you enable ReportBatchItemFailures on the event source mapping, so only the listed messages are retried. This is a Lambda feature rather than an SQS protocol feature, but it shows the shape of the idea.

For webhooks, there is no universal standard. HTTP 207 Multi-Status comes from WebDAV (RFC 4918). Because most senders treat any 2xx as full success, a 207 or a custom failure envelope only works if sender and receiver have explicitly agreed to it. If you operate both sides, or publish the contract to your subscribers, a response like this is workable:

{ "batch_id": "bat_98f7a2c1", "results": [ { "event_id": "evt_001", "status": "succeeded" }, { "event_id": "evt_002", "status": "failed", "retryable": true, "reason": "downstream_timeout" }, { "event_id": "evt_003", "status": "failed", "retryable": false, "reason": "schema_validation_error" } ] } 

2. Dispatcher Split-Retry State Machine

When the dispatcher receives a partial-failure response, it transitions each event independently instead of re-enqueueing the original batch:

  1. Acknowledge healthy records (evt_001): Mark as DELIVERED in the delivery log. These events never enter a retry queue.
  2. Quarantine non-retryable failures (evt_003): Events marked "retryable": false go to a subscriber-visible dead-letter queue for inspection and replay.
  3. Isolate retryable failures (evt_002): Detach them from the batch and re-enqueue each with its own attempt counter incremented.
[Batch: evt_001, evt_002, evt_003] │ HTTP POST /webhook ▼ Partial-failure response ├── evt_001 (succeeded) ──▶ Mark DELIVERED ├── evt_002 (retryable) ──▶ Isolated retry queue (attempt + 1) └── evt_003 (terminal) ──▶ Dead-letter queue 

3. Adaptive Batch Splitting for Legacy Consumers

Many consumers cannot return per-item results and simply respond 500 or 422 when anything in the batch fails. To keep one poison-pill event from blocking its neighbors, the dispatcher can bisect:

  • Initial delivery: Send a batch of N events, for example N = 32.
  • First failure: Instead of retrying all 32 together, split the batch into two sub-batches of 16 on the next attempt.
  • Recursive isolation: Sub-batches that succeed leave the queue. The sub-batch containing the bad record keeps splitting until it reaches a single event, so one bad event is isolated in about log₂(N) rounds (five for N = 32).

Some caveats:

  • Healthy events in a failed batch may already have been processed by the consumer before it returned the error. Bisection can therefore redeliver them, so consumers must deduplicate by event ID.
  • Every bisection round is a delivery attempt that consumes the retry schedule. Budget those rounds against the event’s deadline (see section 3), or you will spend the time window just locating the bad record.
  • If a batch contains several bad records, the number of rounds and requests grows accordingly. Cap the total number of splits per batch.

4. Consumer-Side Idempotency Gates

Even with split-retry logic, a network timeout after the consumer has committed will cause a duplicate delivery. Stripe’s documentation and practitioner guides recommend recording each event ID you process and skipping repeats. For batched deliveries, wrap each item in an atomic idempotency check keyed by something like (subscription_id, event_id), enforced by a unique constraint in the same database transaction as the business state change. That way a crash between “record event as seen” and “apply side effect” cannot leave the two out of sync.

3. Retry Budget Exhaustion vs. SLA Deadlines

The standard exponential backoff formula, delay = base × 2^attempt plus jitter, is designed around infrastructure recovery: it gives overloaded servers progressively more breathing room. AWS’s widely cited Exponential Backoff and Jitter analysis shows that adding jitter spreads retries and reduces contention between clients. It does nothing to make retries respect business deadlines.

Where Unbounded Exponential Backoff Breaks Business Logic

Consider a pipeline with a 5-second base delay, a multiplier of 2, and 15 attempts. The delays and cumulative elapsed time are:

  • Delays 1–5: 5s, 10s, 20s, 40s, 80s (cumulative about 2.6 minutes)
  • Delays 6–10: 160s, 320s, 640s, 1,280s, 2,560s (cumulative about 1.4 hours)
  • Delays 11–15: 5,120s, 10,240s, 20,480s, 40,960s, 81,920s (cumulative about 45.5 hours)

A window that long suits asynchronous accounting syncs, and it is in the same range as Stripe’s three-day window. It is harmful for latency-sensitive events:

  • Reservations and holds: If your inventory reservations or checkout holds are measured in minutes, delivering an order.payment_confirmed event hours late can trigger fulfillment for stock that has already been released. The right window depends on your own reservation design, so derive it from that rather than from a generic default.
  • Real-time risk decisions: An event consumed by a fraud or risk decision with a window of seconds to minutes is worthless once the decision has been made without it. Retrying beyond that point just spends egress and worker capacity.
  • Short-lived security tokens: One-time passcodes and magic links typically expire within minutes. A webhook-triggered notification that arrives after expiry confuses users and teaches them to distrust the channel.

Designing Time-Bounded Backoff Policies

Instead of defining retry policy only by max_attempts, bind every event to an explicit deadline budget derived from its event type.

1. Deadline-Aware Backoff Clamping

Every event carries an immutable created_at and a policy-defined ttl, which together define deadline = created_at + ttl. Before scheduling a retry, the dispatcher computes:

next_attempt_at = now + min(cap, base × 2^attempt) + jitter 

If next_attempt_at is later than the deadline, decide whether a final attempt is still worthwhile:

  • If at least min_viable_window remains before the deadline (for example, a couple of seconds, tuned to your consumers’ response times), clamp next_attempt_at = deadline - min_viable_window so there is one last delivery attempt before the window closes.
  • Otherwise, stop retrying, mark the event EXPIRED_SLA, and emit a compensating event (such as payment.authorization_expired) so upstream workflows can release holds cleanly.

Compute now and deadline from a single time authority, as described in section 1, so that deadline checks are not subject to the same clock-skew problems.

Also honor server hints. Svix, for example, honors a Retry-After header and waits at least 60 seconds after a 429, and the IxIFlow webhook library treats an HTTP 410 as a signal to disable the endpoint. A Retry-After that points past the deadline is a reason to expire the event early rather than burn an attempt.

2. Multi-Tier Decay Schedules by Event Urgency

A single global retry configuration rarely fits all event types. The tiers below are illustrative starting points, not industry standards, and you should calibrate them against your own consumers and business rules.

Event Tier Example Use Cases Deadline Budget Backoff Strategy Max Delay Cap
Tier 0: Real-time critical Fraud checks, live cart locks Seconds to ~2 minutes Short linear or polynomial steps plus jitter ~5 seconds
Tier 1: Operational transactional Order confirmations, shipping labels, subscription renewals ~15–60 minutes Truncated exponential (base=2s, mult=2) plus jitter ~2 minutes
Tier 2: Eventual consistency Invoice PDFs, CRM profile updates, warehouse syncs 24–72 hours Exponential (base=10s, mult=2) plus jitter ~1 hour

Tier 2 roughly mirrors what established providers do. Stripe’s live-mode window is three days, and Svix’s default schedule runs about 27.5 hours before the message is marked failed.

3. Endpoint-Level Retry Budgets (Preventing Storm Amplification)

Per-event deadlines protect individual events but not the dispatcher. If a subscriber endpoint that normally receives thousands of events per second goes down, every event retrying aggressively inside a short window can overwhelm your worker pool and starve healthy tenants.

Google’s Site Reliability Engineering guidance describes two complementary controls: a per-request limit of three attempts, and a per-client retry budget that permits retries only while they stay under about 10% of request traffic. In the book’s example, adding the per-client budget reduces worst-case traffic growth from almost 3x to about 1.1x. The same book suggests a server-wide limit as an alternative form, for example capping the number of retries per minute in a process.

For a webhook dispatcher, where each destination endpoint is effectively a “server” you call, this translates to a per-endpoint retry budget:

  • Track the ratio of retries to first-attempt deliveries per endpoint over a rolling window, or use a token bucket. gRPC’s retry throttling is a well-known example: each failure removes a token, each success adds a fraction (for instance, tokenRatio: 0.1), and retries are suppressed while the token count is at or below half of maxTokens.
  • Start from the roughly 10% ratio in the SRE guidance and tune it to your traffic. Add a small baseline allowance so very low-volume endpoints can still retry at all.
  • When an endpoint has exhausted its budget during a sustained outage, move excess events to a parked queue or an open circuit-breaker state with a slow probe schedule, rather than burning worker threads on timeouts that are almost certain to fail. Parked events still obey their deadlines and expire on schedule.
  • Disable or pause chronically failing endpoints and notify the owner, as providers do. Stripe disables endpoints after about three days of continuous failures, and Svix disables endpoints that fail for five days.

Summary of Implementation Principles

  • Anchor timers to one clock authority. Don’t mix wall-clock timestamps from different worker nodes when computing sorted-set scores or lease expirations. Use server-side time (such as Redis TIME or database clock_timestamp()), relative durations, and monotonic clocks for local timers. Enforce fencing tokens at the state store, not in the worker.
  • Isolate partial batch failures at the item level. Use a per-item response contract where both sides support one, and adaptive bisection where they don’t. Pair either approach with transactional, per-event idempotency on the consumer so one bad payload neither duplicates nor drops its healthy siblings.
  • Bound retry curves to business deadlines. Replace bare attempt counts with per-event-type TTL budgets, clamped final attempts, compensating events on expiry, and per-endpoint retry budgets so that expired work fails fast and outages in one subscriber don’t spread to others.

Sources

Originally published at https://instawebhook.com/blog/engineering-resilient-webhook-systems-retries-backoff-and-queue-mechanics