Webhooks are how most platforms push state changes across service boundaries in near real time. They tell a merchant a payment succeeded, tell a CI system a commit landed, or tell a data warehouse an export is ready. The outbound delivery workers that send them sit between your internal message queue and networks and servers you don’t control.
When an external endpoint degrades, naive retry logic and rigid queue settings can turn a slow customer server into a platform-wide incident. A resilient pipeline needs four things:
- It distinguishes transport-layer failures from application-layer timeouts.
- It isolates latency-sensitive traffic from bulk traffic.
- It applies backpressure when consumer capacity drops.
- It keeps queue leases consistent with HTTP timeouts.
The numeric values below (timeouts, tier weights, latency targets) are starting points to tune against your own traffic, not universal constants. Where a figure comes from vendor documentation, the article says so.
1. Handling 504 Gateway Timeout vs. Connection Reset on Outbound Webhook Workers
Many webhook workers treat every non-2xx outcome identically: catch the error, increment an attempt counter, and requeue. That is a common source of retry storms. A 504 Gateway Timeout and a TCP reset (ECONNRESET) say very different things about what the receiver has already done.
For context, real senders retry for a long time. Stripe, for example, documents that in live mode it retries delivery of an event for up to three days with exponential backoff, and in test mode retries three times over a few hours. Your worker’s behavior over those hours and days matters more than its behavior in the first few seconds.
Transport-Layer Drops vs. Upstream Origin Timeouts
What happened on the wire determines whether an immediate retry is safe and how likely a duplicate side effect is at the receiver.
-
TCP connection reset (
ECONNRESET/RST): The peer, a firewall, or a load balancer aborted an established connection instead of closing it cleanly. A common cause is connection reuse. The worker picks an idle keep-alive connection from its pool just as the server or proxy has closed it. This is well documented on AWS Application Load Balancers (ALB), whose idle timeout defaults to 60 seconds. AWS advises setting the target’s keep-alive timeout higher than the load balancer’s idle timeout so the target never closes a connection the balancer is about to reuse. Resets also happen when a pod is killed mid-request. If the reset arrives before the request was written, the origin usually never saw it. If it arrives after, you can’t tell. -
Half-open connections: A network partition, NAT table eviction, or silent peer crash can break the path without any
RSTorFINreaching the sender. The worker’s socket still looksESTABLISHEDand its read blocks. TCP keep-alive probes are off by default on most systems and, where enabled, often wait hours before the first probe (Linux defaults to 7,200 seconds). In practice only your application-level read and response timeouts will end the wait. -
504 Gateway Timeout: An intermediary such as a CDN, API gateway, or reverse proxy (NGINX, Envoy, an ALB) did not get a timely response from the upstream server. HTTP defines it as an upstream-timeout signal, not a statement about whether the origin received the request. Typically the origin did receive it and may still be working on it. The default idle timeout on an ALB is 60 seconds, and NGINX’sproxy_read_timeoutalso defaults to 60 seconds.
A caveat on diagnosis: a stale pooled connection often surfaces as a 502 from the load balancer rather than a reset on your side. Treat 502 as ambiguous too, and don’t assume resets and 504s are the only shapes this takes.
| Failure mode | Layer | Upstream processing state | Retry amplification risk | Recommended action |
|---|---|---|---|---|
| Reset on a pooled socket before the request was written | TCP | Likely not started | Low | Evict the connection and retry once on a fresh connection, then back off. |
| Reset after the request was written | TCP | Unknown | Moderate | Retry with exponential backoff and jitter; rely on idempotency keys or event IDs. |
| Read or response-header timeout (including half-open sockets) | Transport / client timeout | Unknown; may be hung or processing | High | Abort the socket; apply a moderate initial delay before retrying. |
504 Gateway Timeout |
HTTP 5xx from a proxy |
Probably received; possibly still processing | Critical | Use an elevated base delay with full jitter and a per-destination circuit breaker. |
Because any of these can occur after the receiver has acted, delivery is at-least-once. Include a stable event ID in every delivery (and keep it constant across retries) so receivers can deduplicate.
Preventing Origin Amplification During Slowdowns
When a receiver’s database locks up or its worker pool saturates, requests outlast its gateway timeout and its proxy starts returning 504s. If your worker retries within a second or two, the receiver now processes the original slow request and the retry at the same time. Across thousands of queued events, this positive feedback loop can keep the receiver from ever recovering.
To avoid amplification, give each phase its own timeout and use failure-specific backoff.
-
Granular timeout budgets. Don’t use one monolithic client timeout. Typical starting points:
- Connect (dial) timeout, 2–3 seconds: fail fast if the host is unreachable.
- TLS handshake timeout, 3–5 seconds: avoid hanging on stalled negotiations.
-
Response header timeout, about 10–15 seconds: how long to wait for the receiver to acknowledge. Receivers should acknowledge before doing heavy work. Stripe asks endpoints to return a
2xxquickly, before complex logic that could time out. GitHub.com states that it expects a2xxwithin 10 seconds and otherwise terminates the connection and counts the delivery as failed. Many receivers are stricter, so don’t assume your sender-side timeout matches theirs.
- Align the worker lease with the HTTP timeout. The queue’s visibility timeout (or lease) must exceed the full HTTP timeout budget plus local post-processing. If the response header timeout is 15 seconds and post-processing takes 2 seconds, a lease of 25–30 seconds leaves headroom. If the HTTP timeout equals or exceeds the lease, a slow response lets the broker hand the message to a second worker while the first is still waiting on the socket, which guarantees concurrent duplicate deliveries.
-
Use jittered backoff and per-destination circuit breakers. For
504s (and read timeouts), skip fast retries and start from an elevated base delay, for example 15–30 seconds instead of 1 second. Add jitter so retries from many events don’t synchronize. The AWS Architecture Blog’s “Full Jitter” formula is:
sleep = random_between(0, min(cap, base * 2^attempt))
The same post describes “Decorrelated Jitter”, a different variant that grows from the previous sleep:
sleep = min(cap, random_between(base, previous_sleep * 3))
In AWS’s simulations, both cut client work and server load substantially compared with un-jittered backoff. Full Jitter did less total work but took slightly longer to complete. Pick one deliberately rather than mixing the names.
Alongside backoff, keep lightweight per-destination health state (a sliding window or token bucket in Redis or process memory). When a host’s rate of 504, 502, or 429 responses crosses a threshold, open a circuit breaker or sharply lower dispatch concurrency to that host. Probe with occasional requests until 2xx responses resume.
2. Priority Queuing for Interactive vs. Batch Webhook Events
Outbound webhooks are not equally urgent. A customer waiting on a checkout page for a payment_intent.succeeded event (Stripe’s event name for a successful payment) is hurt by a few seconds of delay. A nightly catalog sync or an export-completion notification can usually wait much longer.
When both kinds share one FIFO queue and one worker pool, a single tenant triggering a bulk operation that emits hundreds of thousands of events can cause head-of-line (HoL) blocking and starve real-time events across the platform.
Architectural Patterns for Priority Isolation
1. Dedicated Queues by Traffic Class
Many brokers don’t offer per-message priority. Apache Kafka has no message priority, and neither Amazon SQS standard queues nor FIFO queues have a priority attribute. Some brokers do, notably RabbitMQ with priority queues, but its own guidance is to keep the number of priority levels small. A portable approach is to split traffic into separate queues (or topics) by service-level objective (SLO) tier. The latency targets below are illustrative examples, not benchmarks:
- Tier 0, interactive: payment results, one-time-passcode and session events. Example target: P99 dispatch latency under 250 ms.
- Tier 1, standard transactional: order updates, subscription renewals, ticket changes. Example target: under 2 s.
- Tier 2, batch and bulk: nightly syncs, backfills, export completions, high-volume telemetry. Example target: under 60 s.
- Tier 3, retry or penalty box: events that already failed and are waiting out a backoff. Keeping retries out of the first-attempt queues stops flaky endpoints from tying up workers that healthy traffic needs.
Scheduling retries has a practical constraint on SQS. Per-message delay is limited, so longer backoffs generally need a scheduler or datastore that holds events until they are due. Alternatively, you can extend visibility on a received message, which is capped at 12 hours from receipt.
2. Weighted Fair Queuing vs. Strict Priority
Once traffic is tiered, consumption needs to avoid both starvation and wasted capacity.
- Strict priority polling (anti-pattern): Always draining Tier 0 before looking at lower tiers means a sustained burst of interactive traffic, or a misbehaving client flooding Tier 0, can starve everything else indefinitely.
- Weighted fair queuing: Workers pull from tiers in proportion to configured weights, for example 70% of capacity to Tier 0, 20% to Tier 1, and 10% to Tier 2. When a tier is idle, its share spills over to the others. When Tier 2 spikes, Tier 0 keeps its guaranteed share.
Weights are policy decisions. Start from observed traffic mix and your SLO targets, then adjust.
3. Tenant-Level Fair Dispatch (Noisy-Neighbor Protection)
Even inside one tier, a single high-volume tenant can monopolize workers, for example during a flash sale. A two-level scheduling approach helps:
- Ingest classification. The ingestion API inspects the event type and tenant plan, routes the event to the right tier, and stamps an enqueue timestamp so you can measure end-to-end latency per tier.
- Per-destination concurrency limits. Before sending to a tenant’s endpoint, the worker acquires a slot from a distributed semaphore keyed by destination host or tenant ID. If a tenant has 50,000 queued events and a limit of 25 in-flight requests, workers defer that tenant’s extra messages (for example with a delayed requeue) and move on to other tenants’ events.
Handling Priority Inversion
Priority inversion can also happen on the receiver’s side. An interactive event sent to a customer endpoint that is saturated by your own batch traffic will queue behind it if the customer ingests everything with one thread pool. Mitigations:
- Let tenants register separate destination URLs per event category, such as one for payments and one for bulk analytics.
- Optionally add a custom priority header (for example
X-Webhook-Priority: interactive | batch; this is a convention you define, not a standard) so sophisticated receivers can route traffic at their gateway. - Reserve a small share of each destination’s concurrency (for example 10–15%) for Tier 0 so a tenant’s own batch export can’t consume its entire connection allowance.
3. Managing Queue Backpressure When Downstream Consumer Concurrency Drops
Slowdowns come from inside the pipeline as well as from customer endpoints. Signature-signing services, enrichment databases, and audit-log writers can all degrade through connection pool exhaustion, garbage collection pauses, slow autoscaling, or endpoint rate limiting (429 Too Many Requests). Without coordinated backpressure the system can enter queue thrashing, where messages repeatedly expire, redeliver, and pile load onto the component that is trying to recover.
The Mechanics of Queue Thrashing
Consider a pull-based queue, such as a database-backed or Redis-backed job queue where workers claim batches of jobs under a 30-second lease. (Amazon SQS caps a single ReceiveMessage call at 10 messages, so the numbers below assume a queue that allows larger claims.)
- Downstream latency climbs from 50 ms to 4 seconds per message during a database replica failover.
- A worker claims 50 jobs and processes them sequentially. At 4 seconds each, the batch needs 200 seconds.
- At 30 seconds, roughly 7 jobs have completed and an 8th is in flight. The leases on the remaining 43 jobs expire.
- The queue makes those 43 jobs available again and other workers claim them, while the original worker keeps working through its local list.
- Each job may now be processed two, three, or more times concurrently. That multiplies load on the degraded database and slows recovery further.
Designing Adaptive Lease Renewal
The fix is to separate lease duration from total batch processing time.
1. Lease Heartbeating (Auto-Extension)
A very long static timeout delays recovery when a worker dies. If a worker is killed or runs out of memory, its messages stay hidden for the full duration. A better pattern is a short initial lease plus a background loop that extends the lease while work is actually progressing. AWS recommends this heartbeat approach for SQS.
- When a worker takes a message, it registers the receipt handle in an in-memory registry of active leases.
- A background timer runs at a fraction of the lease, such as every
lease / 3(every 10 seconds for a 30-second lease). - For each message still being processed, it extends the lease. On SQS this is
ChangeMessageVisibility, or the batch variant, which accepts up to 10 entries per call. The new timeout counts from the moment of the call. -
Maximum lease lifetime: Cap total extension (for example at 5 minutes) so a stuck worker can’t hold a message forever. When the cap is reached, the heartbeater stops extending, the worker cancels its local context (in Go, via
context.WithTimeout), and the message returns to the queue. On SQS there is also a hard platform limit: a message’s visibility can’t exceed 12 hours from when it was first received, and extending doesn’t reset that limit.
2. Latency- and Error-Aware Retry Delays
When an endpoint returns 429 Too Many Requests or 503 Service Unavailable, it may include a Retry-After header, which HTTP allows either as a number of seconds or as an HTTP date. Honor it when computing the next delay:
next_delay = max(calculated_backoff, retry_after_seconds) // capped at a sane maximum, e.g. 1 hour
For internal dependencies that are degrading, raise base delays in proportion to observed processing latency so workers aren’t renewing leases every few seconds under broker load.
Consumer Pull Pacing and Adaptive Concurrency Control
Leases prevent duplicates after a message is claimed. Pull pacing prevents workers from claiming more than they can process.
1. Bounded Local Concurrency Instead of Unbounded Prefetch
Don’t let a queue client prefetch into an unbounded buffer. Tie polling to available capacity:
available_slots = max_concurrency - in_flight_tasks - buffered_tasks
Poll only when available_slots > 0, and request at most min(max_batch_size, available_slots) messages. If downstream stalls and in-flight tasks stop completing, available_slots reaches zero and polling pauses. Messages stay safely in the broker instead of timing out in a worker’s memory.
2. Adaptive Concurrency Limits (AIMD)
A fixed limit such as MAX_CONCURRENCY = 100 is either too low in normal times or too high during degradation. Adaptive limiters adjust the ceiling from feedback. Netflix’s open-source concurrency-limits library borrows ideas from TCP congestion control and treats a service’s concurrency limit like a congestion window. It includes several algorithms, including AIMD (a loss-based approach), and delay-based ones such as Vegas and Gradient2.
A simple AIMD scheme for a webhook worker looks like this:
- Additive increase: While latency stays under target (for example P95 below 200 ms) and errors are near zero, raise the limit slowly, for example by one slot per 50 successful requests.
-
Multiplicative decrease: When latency exceeds the target or timeouts and throttling errors spike, cut the limit sharply, for example
limit = max(min_limit, floor(limit * 0.7)).
Lowering the ceiling immediately reduces available_slots, which halts new pulls and relieves pressure on the struggling dependency until latency recovers. Use a latency window or smoothing so a brief garbage-collection pause doesn’t collapse your limit.
3. Backpressure at the Ingestion Edge
A queue is a buffer, not an infinite sink. When batch queues or specific tenant partitions pass safe depth thresholds:
- Pause non-critical producers. Internal batch schedulers should check queue depth or lag before enqueuing more work and pause above a threshold.
-
Shed load. For synchronous ingestion APIs, return
429 Too Many Requestswith aRetry-Afterheader once capacity limits are reached. This pushes pressure upstream before memory or broker storage is exhausted and Tier 0 delivery is affected.
Summary Checklist for Production Webhook Queues
-
Classify failures by what you know about the wire: Distinguish resets before the request was written from resets after it, read timeouts, and
504s. Treat all of them as possibly processed, and make deliveries idempotent with stable event IDs. - Keep lease longer than timeout: The queue lease must exceed the total HTTP timeout budget plus processing overhead. Heartbeat long work, with a hard maximum lease lifetime.
-
Use jittered backoff: Apply Full or Decorrelated Jitter with a cap, honor
Retry-After, and add per-destination circuit breakers. - Isolate traffic tiers: Separate interactive, standard, batch, and retry queues. Use weighted fair consumption and per-destination concurrency limits to prevent head-of-line blocking and noisy-neighbor starvation.
- Couple polling to capacity: Use bounded prefetch and adaptive concurrency limits so pulling slows automatically when downstream throughput drops.
-
Push back at the edge: Pause internal batch producers and return
429withRetry-Afterto external producers when queues run deep.
References
- Stripe documentation, “Receive Stripe events in your webhook endpoint” (retry behavior, quick
2xxresponses): https://stripe.com/docs/webhooks - GitHub documentation, “Best practices for using webhooks” (10-second response expectation on GitHub.com): https://docs.github.com/webhooks/using-webhooks/best-practices-for-using-webhooks
- Amazon SQS Developer Guide, visibility timeout and
ChangeMessageVisibility(30-second default, 12-hour maximum, heartbeat guidance): https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html - AWS Architecture Blog, “Exponential Backoff And Jitter”: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
- AWS Knowledge Center, ALB 504 errors and idle timeout defaults: https://www.repost.aws/knowledge-center/504-error-alb
- AWS Knowledge Center, troubleshooting ELB/ALB 502 errors (keep-alive vs. idle timeout): https://www.repost.aws/knowledge-center/elb-alb-troubleshoot-502-errors
- Netflix,
concurrency-limits(adaptive concurrency based on TCP congestion control): https://github.com/Netflix/concurrency-limits
Originally published at https://instawebhook.com/blog/engineering-resilient-webhook-delivery-retries-backoff-and-queue-mechanics-at-sc
Top comments (0)