HomeBlogHow to Build a Reliable Webhook...

Engineering Guide · 9 min read · August 1, 2026

How to Build a Reliable Webhook Delivery and Retry System

Outbound webhooks seem simple until one customer's slow endpoint stalls your worker pool or an attacker supplies a cloud metadata URL. Here is the production blueprint for event capture, HMAC signing with secret rotation, SSRF-safe HTTP dispatch, jittered retries, and per-endpoint circuit breakers.

Author
Smit Desai
Published
August 1, 2026
Read time
9 min read
Topic
APIs & Integrations
Services
Custom Web · Mobile Apps · All Services

Shipping outbound webhooks turns your application from a passive database into an event-driven platform. The first version usually takes an afternoon: loop over subscribed endpoints and fire an HTTP POST whenever an order completes or a ticket updates.

Then reality arrives. One enterprise subscriber's staging server hangs for 45 seconds before returning a 504. Your worker threads fill up, and healthy customers stop receiving real-time events. Another user enters http://169.254.169.254/latest/meta-data/ as their webhook URL. A third rotates their signing secret and loses three hours of events because you didn't support dual-key overlap.

Production webhook delivery requires strict isolation between tenants, defensive networking, and predictable retry semantics.

Outbound webhook delivery, signing, and retry architecture


1. Guarantee Event Capture with an Outbox and Attempt Log

Never fire webhooks directly inside your business logic, and never assume queue insertion after a database commit always succeeds. Persist the event inside the same transaction as the state change, then fan out per active subscription into a dedicated delivery log.

CREATE TABLE webhook_events (
  id UUID PRIMARY KEY,
  tenant_id BIGINT NOT NULL,
  event_type VARCHAR(80) NOT NULL,
  payload JSONB NOT NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE webhook_deliveries (
  id UUID PRIMARY KEY,
  event_id UUID NOT NULL REFERENCES webhook_events(id),
  endpoint_id BIGINT NOT NULL,
  attempt_count INT NOT NULL DEFAULT 0,
  status VARCHAR(24) NOT NULL DEFAULT 'pending', -- pending, delivered, dead_letter
  next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  last_http_status INT,
  last_latency_ms INT,
  last_error TEXT,
  delivered_at TIMESTAMPTZ
);

CREATE INDEX idx_webhook_deliveries_due
  ON webhook_deliveries (status, next_attempt_at)
  WHERE status = 'pending';

Include the webhook_deliveries.id (or event_id) inside the JSON payload and as a header (X-Webhook-Id) so consumers can deduplicate safely if a network drop happens right after they process the body but before their 200 OK reaches you.


2. Cryptographic Signing and Zero-Downtime Secret Rotation

Every webhook payload should be signed so recipients can verify authenticity and reject replay attacks. Follow the battle-tested timestamped HMAC pattern popularized by Stripe's webhook signature specification.

Signing Header Format

Sign ${timestamp}.${rawBody} rather than just the body, and send the signature in a versioned header:

import crypto from 'node:crypto';

export function buildSignatureHeader(
  rawBody: string,
  activeSecrets: string[],
  timestampSec = Math.floor(Date.now() / 1000)
): string {
  const signedPayload = `${timestampSec}.${rawBody}`;
  const signatures = activeSecrets.map((secret) => {
    const digest = crypto
      .createHmac('sha256', secret)
      .update(signedPayload, 'utf8')
      .digest('hex');
    return `v1=${digest}`;
  });

  return `t=${timestampSec},${signatures.join(',')}`;
}

Notice activeSecrets is an array. During secret rotation, keep both the old and new secrets active for 24 hours and include both v1= signatures in the header. Subscribers upgrade their environment variable without dropping a single event, and you expire the previous secret automatically once the rotation window closes.


3. Block SSRF and Slowloris Attacks at the Dispatcher

Accepting arbitrary callback URLs from users exposes your internal network to Server-Side Request Forgery (SSRF)—one of the top risks highlighted in the OWASP API Security Top 10. Checking hostname !== 'localhost' in regex is completely insufficient because attackers can point a public DNS A record at 127.0.0.1 or 169.254.169.254, or serve an HTTP 302 redirect to an internal IP.

Mandatory Dispatcher Hardening Rules

  • Require HTTPS in production: Reject http:// schemes, embedded credentials (https://user:pass@host), and non-standard ports unless explicitly justified.
  • Pin DNS resolution at connect time: Resolve the hostname once, verify every returned IPv4/IPv6 address is outside private (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16), loopback, link-local (169.254.0.0/16), and ULA (fc00::/7) ranges, and pass that exact validated IP to the socket—preventing DNS rebinding attacks.
  • Disable automatic redirects: Treat 3xx responses as delivery failures rather than following redirects to unverified hosts.
  • Bound timeouts and response bodies: Enforce a 2-second TCP/TLS connect timeout, a 5–8 second total request timeout, and truncate response body logging at 2 KB so a malicious receiver cannot OOM your worker by streaming 500 MB back.

4. Jittered Backoff, Concurrency Caps, and Circuit Breakers

A shared queue without per-endpoint isolation lets one broken customer degrade everyone else. If endpoint A times out on 2,000 events, those retries can saturate all worker slots if left unchecked.

Exponential Backoff with Full Jitter

Compute retry delays with capped exponential backoff plus random jitter:

export function nextRetryDelayMs(attempt: number): number {
  const baseMs = 15_000;          // 15 seconds
  const maxDelayMs = 6 * 3600_000; // 6 hours cap
  const exponential = Math.min(maxDelayMs, baseMs * Math.pow(2, attempt));
  // Full jitter spreads retry storms evenly across [0.5x, 1.0x]
  return Math.floor(exponential * (0.5 + Math.random() * 0.5));
}

Per-Endpoint Concurrency and Circuit Breaking

Pair jittered retries with two isolation mechanisms inside your background job queue:

  1. Per-endpoint concurrency limit: Cap active in-flight HTTP requests per endpoint_id (e.g., max 5 concurrent requests) so one subscriber never floods your worker pool or gets overwhelmed by bursts.
  2. Automatic circuit breaker: If an endpoint fails consecutively for 24–72 hours (or returns persistent 410 Gone), transition the endpoint to disabled_auto, stop dispatching new deliveries, and notify the tenant owner via email with a one-click replay option.

5. Build In-House vs. Managed Webhook Proxy

Deciding whether to maintain your own dispatcher or adopt an open-source/managed gateway comes down to control versus operational bandwidth.

Option Throughput & Isolation Engineering Effort Trade-Off
Simple Cron + HTTP Client Poor under slow receivers 1–2 days Breaks as soon as one subscriber stalls
Outbox + Redis/SQS + Hardened Dispatcher High with per-endpoint caps 1–2 weeks Full ownership of SSRF checks, replay UI, and metrics
Dedicated Webhook Gateway (e.g. Svix / Hookdeck) High out of the box 2–4 days integration Recurring per-message cost and third-party data transit

If your product already builds high-performance APIs and runs background queues, building a clean hardened dispatcher in-house avoids vendor lock-in and keeps sensitive customer payloads inside your VPC.


6. Give Developers Observability and Self-Service Replay

Nothing generates support tickets faster than opaque webhooks. Give your customers a clean diagnostics panel inside their dashboard showing:

  • Recent deliveries with timestamp, event ID, HTTP status code, and round-trip latency
  • Request headers and truncated response body (masked for sensitive tokens)
  • A Send Test Event button and a Replay Failed Events button for recovering after they fix a bug on their receiver

Exposing those tools turns frustrated API support threads into 30-second self-service fixes.


Engineer Resilient Event Systems with SmitDev

At SmitDev, we build production APIs, hardened webhook dispatchers, and event-driven custom web applications designed to hold up under real-world traffic and messy third-party endpoints. With 170+ shipped engagements and deep operational experience, we focus on boring, observable infrastructure that doesn't wake your team up at 3 a.m.

Need senior hands to architect or harden your webhook pipeline? Work with us at $55/day (8–9 hours of dedicated engineering) or $1,999/month for ongoing delivery. Start a conversation or learn more about our services.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Custom Web & SaaS

Custom Web Application Development

Production Laravel, Next.js, API, and multi-tenant SaaS systems engineered end to end at $55/day (8–9 hrs) or $1,999/mo.

Comparison · Buyer Guide

SmitDev vs Software Agencies

See side-by-side economics, senior code ownership, and onboarding speed vs traditional dev shops and marketplaces.

01 — Frequently asked questions

apis & integrations

How long should our webhook delivery timeout be before retrying?

Enforce a tight 5 to 10 second total request timeout (with a 2 second connect timeout) and document that subscribers must acknowledge receipt with a 2xx status before running heavy processing. Long timeouts let slow consumers exhaust your worker pool.

Why do we need jitter in webhook exponential backoff?

If a downstream customer restarts their server after a 10-minute outage and 5,000 queued webhooks retry at the exact same second, your retry wave immediately knocks their server offline again. Adding random jitter spreads retries smoothly over time.

How do you prevent SSRF attacks when users configure custom webhook URLs?

Validate URLs at registration and again right before connecting: allow only HTTPS, resolve DNS in a custom lookup hook, block private RFC 1918, loopback, and cloud metadata IP ranges (169.254.169.254), and disable automatic HTTP redirects.

Can SmitDev architect or audit an outbound webhook platform?

Yes. We design and ship fault-tolerant webhook delivery pipelines, developer signature SDKs, and replay dashboards at $55/day (8-9 hours/day) or $1,999/month.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.