FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Webhook Delivery & HMAC Signatures

Asynchronous webhook delivery, exponential backoff retries, and HMAC SHA-256 signature verification.

Freshness: current•15 min read•Software and Web Engineering

Key Learning Outcomes

  • ✓Implement secure webhook delivery pipelines with HMAC signatures
  • ✓Manage delivery retries with exponential backoff and jitter
Full Technical Reference Document

Mental model

Webhooks invert synchronous API polling by pushing event notifications over HTTP POST whenever domain state changes (invoice.paid, eval.completed). Because webhooks cross untrusted public networks into customer endpoints with unpredictable uptime, reliable systems enforce two independent contracts: authenticity & freshness on the receiver side (constant-time HMAC-SHA256 verification over the raw byte payload + signed timestamp to block spoofing and replay), and at-least-once resilient delivery on the producer side (outbox-backed async dispatch queues, exponential backoff with jitter, SSRF egress protection, and endpoint circuit breakers so one broken customer server never starves healthy tenants).

Event Committed to Outbox Queue
Sign Timestamp + Raw Bytes (HMAC-SHA256)
Async Worker POST with Delivery-ID
Receiver Constant-Time Verify & Dedupe
Exponential Backoff + Jitter on 5xx
Conceptual teaching model synthesized from:owasp-api-security,mdn-http-headers

Theory

Both producer (sender) and consumer (receiver) engineering decisions determine whether webhook pipelines scale cleanly or turn into self-inflicted outages:

ComponentFailure Mode Without SafeguardProduction Implementation Standard
Signature Payload & TimingKey-spacing/Unicode re-serialization alters json.dumps() hashSign exact f"{timestamp}.{raw_body}" bytes (X-Signature: t=...,v1=...) and compare via hmac.compare_digest()
Replay WindowAttacker re-POSTs captured legitimate payload hours laterReject timestamps older than 300 seconds (5 min) + store X-Webhook-ID in Redis idempotency cache
Producer Queue IsolationSlow/dead customer endpoint ties up shared delivery workersStrict connect/read timeouts (2 s / 5 s), per-endpoint queues or circuit breakers, and exponential backoff + full jitter
SSRF Attack VectorUser registers http://169.254.169.254/latest/meta-data as webhook URLBlock private/loopback/link-local CIDRs post-DNS resolution, re-pin resolved IP, disable HTTP redirects

Dual-Secret Rotation, Async Verification, and Receiver Fast-Ack

Supporting zero-downtime secret rotation requires signing with an active primary secret (or temporarily dual-signing v1=<new>,v1=<old>) while receivers validate any v1 signature matching current or grace-period keys. Critically on the receiver side, read raw request await request.body() bytes before Pydantic/JSON parsing—re-encoding a parsed Python dict back into JSON frequently mutates whitespace or key ordering, breaking valid signatures! Once verified and deduplicated via X-Webhook-ID, enqueue heavy database/email workflows asynchronously and return HTTP 202 Accepted within 1–2 seconds; slow inline processing triggers producer timeouts and duplicate retry storms.

python
import hashlib
import hmac
import time
from fastapi import FastAPI, Header, HTTPException, Request, status
​
app = FastAPI()
MAX_SKEW_SECONDS = 300
ACTIVE_SECRETS = ["whsec_current_9f8e7d", "whsec_previous_grace"] # Enables zero-downtime key rotation
​
def verify_webhook_signature(raw_body: bytes, sig_header: str, secrets: list[str]) -> bool:
parts = dict(item.split("=", 1) for item in sig_header.split(",") if "=" in item)
ts_str, provided_sig = parts.get("t"), parts.get("v1")
if not ts_str or not provided_sig or not ts_str.isdigit():
return False
​
if abs(int(time.time()) - int(ts_str)) > MAX_SKEW_SECONDS:
return False # Defends against delayed replay attacks
​
signed_payload = f"{ts_str}.".encode("utf-8") + raw_body
for secret in secrets:
expected = hmac.new(secret.encode("utf-8"), signed_payload, hashlib.sha256).hexdigest()
if hmac.compare_digest(expected, provided_sig):
return True
return False
​
@app.post("/webhooks/billing", status_code=status.HTTP_202_ACCEPTED)
async def receive_webhook(
request: Request,
x_webhook_signature: str = Header(...),
x_webhook_id: str = Header(...),
) -> dict[str, str]:
raw_body = await request.body()
if not verify_webhook_signature(raw_body, x_webhook_signature, ACTIVE_SECRETS):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid webhook signature")
​
# Fast-ack after atomic idempotency check (SET idemp:{x_webhook_id} 1 NX EX 86400) -> enqueue async job
return {"accepted": x_webhook_id}

Alternatives and trade-offs

  • Signed HTTPS Webhooks (HMAC-SHA256 + Backoff Queue): Push-based real-time latency, works cleanly behind standard firewalls via customer HTTPS endpoints, ubiquitous developer expectation (Stripe/GitHub standard); requires outbox queueing, SSRF defense, retry budgets, and dead-endpoint disabling logic.
  • Event Streams / Pull Polling (Kafka / GET /events?cursor=...): Zero client NAT/firewall/SSRF headaches and natural receiver backpressure (clients pull only at their own pace), at the cost of either higher idle polling traffic or stateful SSE/broker access.
  • Mutual TLS (mTLS) or Asymmetric Ed25519 Signatures (Standard Webhooks): Eliminates shared symmetric secrets across customer systems, simplifying public verification via JWKS/public keys at slightly higher key-management complexity.

Failure modes and misconceptions

  1. String Equality (==) Instead of Constant-Time hmac.compare_digest: Using == leaks signature prefix timing differences byte-by-byte to remote statistical timing attacks. Always use hmac.compare_digest().
  2. Hashing Parsed & Re-Serialized JSON Instead of Raw HTTP Bytes: Signing or verifying json.dumps(parsed_json) fails unpredictably whenever float formatting (10.0 vs 10), UTF-8 escaping, or whitespace differs between producer and receiver. Always hash exact raw HTTP wire bytes.
  3. Producer Following HTTP 301/302 Redirects or Skipping SSRF CIDR Filtering: Following blind redirects on customer-supplied webhook URLs lets attackers bounce outbound requests from https://attacker.com/hook into http://169.254.169.254/latest/meta-data (AWS IAM credentials) or internal VPC Redis ports (6379) (OWASP API7:2023 SSRF). Resolve DNS safely in an egress proxy, reject private/loopback/link-local ranges, disable auto-redirects, and enforce HTTPS only.
  4. Blocking Shared Producer Worker Pools on One Unresponsive Receiver: Retrying a tenant whose webhook server returns 504 after 30 s inside a single shared worker pool starves all healthy tenants ("noisy neighbor head-of-line blocking"). Isolate endpoints with per-destination concurrency caps, tight 5 s timeouts, and automated webhook suspension after N consecutive days of failures.
Reflect before revealing the guide

Decision scenario

Your AI developer platform emits billing and async evaluation completion webhooks to thousands of customer-configured URLs while also ingesting inbound Stripe/GitHub webhooks securely. For outbound delivery, store events in a PostgreSQL Transactional Outbox, validate resolved DNS IPs via an SSRF-hardened egress proxy (blocking RFC1918/link-local/loopback ranges and redirects), sign exact UTF-8 payload bytes alongside Unix timestamps (t=...,v1=...) using active + grace-period rotating secrets, dispatch via per-tenant rate-limited workers (5 s timeout, exponential backoff + full jitter, dead-endpoint pause after 72 h failures); for inbound ingestion, compute hmac.compare_digest over raw request.body() within a 300 s timestamp window, deduplicate on X-Webhook-ID in Redis, enqueue internal work, and reply 202 Accepted immediately.

Learning outcomes

  • Compute and validate HMAC-SHA256 webhook signatures cleanly over raw UTF-8 HTTP request bytes with hmac.compare_digest().
  • Stop replay and duplicate-processing bugs using signed timestamp windows (<= 300 s) and X-Webhook-ID idempotency keys.
  • Harden outbound webhook workers against SSRF, noisy-neighbor queue starvation, and retry storms.
  • Support zero-downtime webhook secret rotation and receiver fast-ack queuing (202 Accepted).

Trade-offs

HMAC-signed push webhooks deliver sub-second cross-company event integration without shared message brokers, yet require substantial producer infrastructure (outboxes, SSRF egress isolation, jittered backoff, circuit breaking) and careful receiver idempotency engineering.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next