Webhooks Others Can Trust: Sign, Retry, Verify
Send webhooks from a job queue with Standard Webhooks signatures, stable event IDs, retries with backoff and jitter and a per-attempt delivery log, and build a receiver that checks signature and timestamp and processes each event once.
Contentsand lesson path
On this page
- Why it matters
- The signature scheme: Standard Webhooks
- The sender: a queue, a retry policy and a delivery log
- The receiver: verify first, then process each event once
- Run it: a delivery log and the attack tests
- Common mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of Real-Time APIs & Webhooks
- Polling, Push or Callback? Choosing a Delivery Channel Concept · 20 min
- Streaming Responses and Server-Sent Events Worked example · 25 min
- Lab: An Authenticated WebSocket Feed Across Workers Lab · 30 min
- Webhooks Others Can Trust: Sign, Retry, Verify Worked example · 25 min
- Long-Lived Connections in Production: Proxies, Limits and Deploys Concept · 15 min
- Check: Choose and Defend a Real-Time Design Knowledge check · 8 questions
What you will learn
- Deliver outgoing webhooks from a job queue with signed payloads, event IDs for deduplication, retries with backoff and a delivery log, and verify an incoming webhook's signature and timestamp before acting on it.
Prerequisites: Async I/O in Python
01. Why it matters
A webhook turns the usual API around: instead of a client asking "has anything changed?", your service sends an HTTP POST to a URL the customer registered as soon as an event happens, such as invoice.paid. The receiver only sees a request from the internet, so four things can go wrong:
- Forgery. Anyone who knows the URL can post a fake event. The receiver needs proof that you sent it and nobody changed it.
- Replay. An attacker who captures one genuine request can send it again later. A valid signature alone does not stop that.
- Loss. The receiver may be down. If you send once from inside your request handler, the event is gone, and your handler waits on someone else's server.
- Duplicates. If the receiver processed the event but its
200got lost, you cannot tell that from a failure, so you send again. Delivery is at least once.
This worked example builds both sides for a billing service: a sender that signs, queues, retries with backoff and logs every attempt, and a receiver that verifies each request and acts on each event once.
02. The signature scheme: Standard Webhooks
This lesson follows the Standard Webhooks specification, an open, community-maintained specification (version 1.0.0; not an IETF or W3C standard) with reference libraries for senders and receivers. Every delivery carries three headers:
webhook-id: the event ID, such asmsg_2KWPBgLlAfxdpx2AI54pPJ85f4W. It stays the same on every retry, so the receiver can use it as an idempotency key (a key that marks "already done").webhook-timestamp: the time of this attempt in Unix seconds. A retry gets a new one.webhook-signature:v1,plus the base64 HMAC-SHA256 ofid.timestamp.body, made with a secret shared with this one endpoint.
Because the ID and timestamp are inside the signed string, nobody can change either without breaking the signature. The secret is shown as whsec_ plus base64 of 24 to 64 random bytes; the HMAC key is the decoded bytes. The signature header is a space-separated list, so during a secret rotation you sign with both keys and the receiver accepts any match. The specification also defines an asymmetric scheme, v2a (Ed25519), which receivers check with a public key (whpk_…), so they hold no secret that could forge events; its signed string adds an endpoint ID, so a webhook signed for one endpoint fails at another. The older v1a identifier is deprecated in favour of v2a. Other providers vary: Stripe signs timestamp.body, and GitHub's X-Hub-Signature-256 covers only the body, so GitHub receivers rely on the X-GitHub-Delivery ID to spot repeats.
import base64
import hashlib
import hmac
def secret_bytes(secret: str) -> bytes:
# Standard Webhooks secrets look like whsec_<base64 of 24 to 64 random bytes>
return base64.b64decode(secret.removeprefix("whsec_"))
def sign(secret: str, msg_id: str, timestamp: int, body: bytes) -> str:
"""Signature for the webhook-signature header: v1,<base64 HMAC-SHA256>."""
content = f"{msg_id}.{timestamp}.".encode() + body # id, timestamp, raw body
mac = hmac.new(secret_bytes(secret), content, hashlib.sha256).digest()
return "v1," + base64.b64encode(mac).decode()03. The sender: a queue, a retry policy and a delivery log
The sender never posts from the request that created the event. enqueue only writes rows: one job per event and endpoint in webhook_jobs, the queue, with the body serialised once so every attempt sends the same bytes. Write these rows in the same transaction as the change that caused the event (the outbox pattern), so no event is lost between the two. The deliveries table is the delivery log: one row per attempt, with the status code or network error and the next retry time, which is what support staff check when a customer asks "did you send it?". SQLite keeps the example self-contained; with several workers on PostgreSQL, claim jobs with SELECT … FOR UPDATE SKIP LOCKED.
import json
import socket
import uuid
import httpx
from signing import sign
from ssrf_guard import SecurityError, resolve_and_vet # from the SSRF lesson
SCHEMA = """
CREATE TABLE IF NOT EXISTS endpoints (
id TEXT PRIMARY KEY, url TEXT, secret TEXT, enabled INTEGER DEFAULT 1);
CREATE TABLE IF NOT EXISTS webhook_jobs ( -- the queue: one job per event and endpoint
event_id TEXT, endpoint_id TEXT, body BLOB, attempt INTEGER DEFAULT 0,
run_at REAL, state TEXT DEFAULT 'pending', -- pending, delivered, failed
PRIMARY KEY (event_id, endpoint_id));
CREATE TABLE IF NOT EXISTS deliveries ( -- the delivery log: one row per attempt
id INTEGER PRIMARY KEY, event_id TEXT, endpoint_id TEXT, attempt INTEGER,
sent_at REAL, status_code INTEGER, error TEXT, next_retry_at REAL);
"""
# Seconds to wait after attempt 1, 2, ...: the example schedule in the spec
DELAYS = [5, 300, 1800, 7200, 18000, 36000, 50400, 72000, 86400]
def enqueue(db, event_type: str, data: dict, now: float, event_id=None) -> str:
"""Record the event once. Its id stays the same on every retry."""
event_id = event_id or f"msg_{uuid.uuid4().hex}"
body = json.dumps({"type": event_type, "data": data}, separators=(",", ":"))
endpoints = db.execute("SELECT id FROM endpoints WHERE enabled = 1").fetchall()
db.executemany(
"INSERT INTO webhook_jobs (event_id, endpoint_id, body, run_at)"
" VALUES (?, ?, ?, ?)",
[(event_id, ep, body.encode(), now) for (ep,) in endpoints])
db.commit()
return event_idNext, decide which failures deserve another try. A retry helps only when the same request can succeed later:
- A network error (DNS failure, refused connection, timeout), a
5xxor a429 Too Many Requestsusually means "not now": retry after a delay, and honour aRetry-Afterheader. 410 Gonemeans the receiver wants no more events: disable the endpoint.- A redirect or another
4xxwill most likely repeat, because the request itself is the problem (wrong secret, bad URL, rejected payload). The job becomesfailedand the log row stays, so someone can fix the endpoint and replay it. The specification counts every non-2xxas a failure and some providers retry them all; stopping here is this lesson's choice.
The delays follow the specification's example schedule (5 seconds, 5 minutes, 30 minutes, then hours: about three days in total), each multiplied by a random factor between 0.8 and 1.2. Without this jitter, every event that failed during an outage would be retried at the same second.
def classify(status: int | None, error: str | None) -> str:
if error is not None:
return "retry" # DNS failure, refused connection, reset, timeout
if 200 <= status < 300:
return "delivered"
if status == 410:
return "disable" # the receiver asks us to stop sending
if status == 429 or status >= 500:
return "retry" # overloaded or broken right now: may work later
return "failed" # 3xx and other 4xx: the same request gets the same answer
async def run_due(db, client, now, rng, resolver=socket.getaddrinfo) -> list:
"""One worker tick: try every job whose time has come."""
jobs = db.execute("SELECT event_id, endpoint_id, body, attempt FROM webhook_jobs"
" WHERE state = 'pending' AND run_at <= ? ORDER BY run_at",
(now,)).fetchall()
return [await attempt_delivery(db, client, j, now, rng, resolver) for j in jobs]One attempt signs the stored body with a fresh timestamp and the same webhook-id, posts it with a 15-second timeout (the specification suggests 15 to 30 seconds), and records the result. The subscriber's URL is untrusted input, so resolve_and_vet from the SSRF lesson runs before every attempt, not only at registration: DNS can change in between and point the name at an internal address. httpx does not follow redirects unless asked, which matters for the same reason. To close the gap between that check and the connection itself, send through the SSRF lesson's pinned connection or an egress proxy with the same rules.
async def attempt_delivery(db, client, job, now, rng, resolver=socket.getaddrinfo):
event_id, endpoint_id, body, attempt = job[0], job[1], job[2], job[3] + 1
url, secret = db.execute("SELECT url, secret FROM endpoints WHERE id = ?",
(endpoint_id,)).fetchone()
status = error = retry_after = outcome = None
try:
resolve_and_vet(url, resolver) # DNS may have changed since registration
ts = int(now) # a new timestamp for each attempt, the same webhook-id
headers = {"content-type": "application/json", "webhook-id": event_id,
"webhook-timestamp": str(ts),
"webhook-signature": sign(secret, event_id, ts, body)}
r = await client.post(url, content=body, headers=headers, timeout=15)
status = r.status_code # httpx does not follow redirects by default
if r.headers.get("retry-after", "").isdigit():
retry_after = int(r.headers["retry-after"])
except SecurityError as exc:
outcome, error = "failed", f"refused: {exc}"
except httpx.TransportError as exc:
error = type(exc).__name__
outcome = outcome or classify(status, error)
if outcome == "retry" and attempt > len(DELAYS):
outcome = "failed" # schedule used up: alert the owner of the endpoint
next_at = None
if outcome == "retry": # jitter spreads retries so they do not arrive together
delay = DELAYS[attempt - 1] * rng.uniform(0.8, 1.2)
next_at = round(now + max(delay, retry_after or 0))
db.execute("INSERT INTO deliveries (event_id, endpoint_id, attempt, sent_at,"
" status_code, error, next_retry_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
(event_id, endpoint_id, attempt, now, status, error, next_at))
state = {"retry": "pending", "disable": "failed"}.get(outcome, outcome)
db.execute("UPDATE webhook_jobs SET attempt = ?, state = ?, run_at = ?"
" WHERE event_id = ? AND endpoint_id = ?",
(attempt, state, next_at, event_id, endpoint_id))
if outcome == "disable":
db.execute("UPDATE endpoints SET enabled = 0 WHERE id = ?", (endpoint_id,))
db.commit()
return outcome04. The receiver: verify first, then process each event once
The receiver works on the raw body bytes, because those are what was signed. verify rejects missing headers and a timestamp more than 300 seconds from its own clock, then recomputes the signature and compares it with hmac.compare_digest, which does not stop at the first differing byte, so timing does not reveal how much of a forged signature was right. Comparing bytes also turns a header full of odd characters into a 401, not a crash.
Only a verified request reaches deduplication. INSERT … ON CONFLICT (webhook_id) DO NOTHING inserts a new ID and does nothing for a known one; rowcount tells you which. A repeat gets 200, because any other answer brings more retries. The dedupe row and the work share one transaction: if the work fails, both roll back, the sender sees a 500, and its retry is processed. In PostgreSQL the same statement also handles two copies arriving together: the second insert waits for the first to commit, then does nothing.
How long to keep IDs? The timestamp window stops replays older than 5 minutes, but a sender retry has a fresh timestamp and can come days later. Keep IDs at least as long as the retry schedule, here about three days.
import hmac
import json
import sqlite3
import time
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from signing import sign
TOLERANCE = 300 # seconds; also bounds how long a captured request can be replayed
def verify(secret: str, headers, body: bytes, now: float):
"""Return None if the request is genuine, else (status code, reason)."""
msg_id = headers.get("webhook-id", "")
ts = headers.get("webhook-timestamp", "")
if not msg_id or not (ts.isascii() and ts.isdigit()):
return 400, "missing or malformed webhook headers"
if abs(now - int(ts)) > TOLERANCE:
return 400, "timestamp outside the tolerance window"
expected = sign(secret, msg_id, int(ts), body).encode()
# Space-separated list: during a secret rotation the sender signs twice
for candidate in headers.get("webhook-signature", "").split(" "):
if hmac.compare_digest(expected, candidate.encode()): # constant time
return None
return 401, "no valid signature"def create_app(db_path: str, secret: str, clock=time.time) -> FastAPI:
app = FastAPI()
db = sqlite3.connect(db_path, check_same_thread=False)
db.executescript(
"CREATE TABLE IF NOT EXISTS processed_webhooks ("
" webhook_id TEXT PRIMARY KEY, received_at REAL);"
"CREATE TABLE IF NOT EXISTS paid_invoices (invoice_id TEXT);")
@app.post("/webhooks")
async def receive(request: Request):
body = await request.body() # the raw bytes that were signed
problem = verify(secret, request.headers, body, clock())
if problem:
return JSONResponse({"detail": problem[1]}, status_code=problem[0])
event = json.loads(body)
with db: # one transaction: the dedupe row and the work commit together
cur = db.execute(
"INSERT INTO processed_webhooks VALUES (?, ?)"
" ON CONFLICT (webhook_id) DO NOTHING",
(request.headers["webhook-id"], clock()))
if cur.rowcount == 0:
return {"status": "duplicate"} # 2xx, so the sender stops retrying
if event["type"] == "invoice.paid":
db.execute("INSERT INTO paid_invoices VALUES (?)",
(event["data"]["invoice_id"],))
return {"status": "processed"}
app.state.db = db
return app05. Run it: a delivery log and the attack tests
Put the five files in one folder with ssrf_guard.py (both parts, from the SSRF lesson). No network or open port is needed: httpx.ASGITransport delivers each request to a FastAPI app in the same process, Router picks the app by host or raises a connection error, and a fake resolver gives the demo hosts public addresses. The shop runs the real receiver but is down for the first tick, the CRM answers 429 and then 400, an old endpoint answers 410, and one URL points at the cloud metadata address. Clock and jitter are seeded, so your output should match.
import asyncio
import random
import sqlite3
import httpx
from fastapi import FastAPI, Response
import outbox
from receiver import create_app
SECRET = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw" # demo only: real ones from a vault
NOW = 1_800_000_000 # fixed clock so the log below is reproducible
PUBLIC = {"shop.example.com": "93.184.215.14", "crm.example.com": "93.184.215.15",
"old.example.com": "93.184.215.16"}
def resolver(host, port, type=0): # fake DNS: public addresses for the demo hosts
return [(2, 1, 6, "", (PUBLIC.get(host, host), port))]
def stub(*answers): # a receiver that replies with these status codes in turn
app, replies = FastAPI(), iter(answers)
@app.post("/hooks")
async def hook():
code, headers = next(replies)
return Response(status_code=code, headers=headers)
return app
class Router(httpx.AsyncBaseTransport):
"""Sends each request to the in-process app for its host, or fails."""
def __init__(self, apps):
self.apps, self.down = apps, set()
async def handle_async_request(self, request):
host = request.url.host
if host in self.down or host not in self.apps:
raise httpx.ConnectError("connection refused", request=request)
return await self.apps[host].handle_async_request(request)async def main():
db = sqlite3.connect(":memory:")
db.executescript(outbox.SCHEMA)
# Demo only: one SECRET for all four. Real senders generate a separate
# secret for each endpoint, so one leaked secret cannot sign for others.
db.executemany("INSERT INTO endpoints (id, url, secret) VALUES (?, ?, ?)", [
("shop", "https://shop.example.com/webhooks", SECRET),
("crm", "https://crm.example.com/hooks", SECRET),
("old", "https://old.example.com/hooks", SECRET),
("meta", "http://169.254.169.254/latest/meta-data/", SECRET)])
clock = [NOW] # the receiver reads the same fake clock
shop = create_app(":memory:", SECRET, clock=lambda: clock[0])
router = Router({
"shop.example.com": httpx.ASGITransport(app=shop),
"crm.example.com": httpx.ASGITransport(
app=stub((429, {"retry-after": "600"}), (400, {}))),
"old.example.com": httpx.ASGITransport(app=stub((410, {})))})
rng = random.Random(7) # seeded jitter, for a reproducible demo
outbox.enqueue(db, "invoice.paid", {"invoice_id": "inv_42"}, NOW,
event_id="msg_01") # fixed id for the demo; normally random
router.down.add("shop.example.com") # the shop's server is down at first
async with httpx.AsyncClient(transport=router) as client:
for tick in (0, 10, 700): # three worker ticks, seconds after the event
clock[0] = NOW + tick
if tick:
router.down.clear() # the shop is back up
print(f"t={tick}:", await outbox.run_due(db, client, NOW + tick, rng,
resolver))
print("endpoint try status next_retry error")
for ep, n, code, nxt, err in db.execute(
"SELECT endpoint_id, attempt, status_code, next_retry_at, error"
" FROM deliveries ORDER BY id"):
retry = "-" if nxt is None else f"t+{int(nxt - NOW)}"
print(f"{ep:<8} {n:<3} {str(code):<6} {retry:<10} {err or ''}")
print("shop processed:", shop.state.db.execute(
"SELECT invoice_id FROM paid_invoices").fetchall())
print("enabled:", db.execute("SELECT id, enabled FROM endpoints").fetchall())
asyncio.run(main())python -m venv .venv && . .venv/bin/activate
pip install "fastapi==0.165.0" "httpx==0.28.1" "pytest==9.2.0"
python demo.pyt=0: ['retry', 'retry', 'disable', 'failed']
t=10: ['delivered']
t=700: ['failed']
endpoint try status next_retry error
shop 1 None t+5 ConnectError
crm 1 429 t+600
old 1 410 -
meta 1 None - refused: non-public ['169.254.169.254']
shop 2 200 -
crm 2 400 -
shop processed: [('inv_42',)]
enabled: [('shop', 1), ('crm', 1), ('old', 0), ('meta', 1)]The shop's first attempt hit ConnectError and was rescheduled 5 seconds later (5 × jitter, rounded); at t=10 it got 200, and the receiver stored inv_42 once. The CRM's 429 asked for 600 seconds, so its retry waited until t+600, and its 400 then ended the job. The 410 disabled the old endpoint, and the metadata URL was refused before any request left.
The tests attack the receiver. To check that they have teeth, they were also run against copies of receiver.py without deduplication or without the timestamp check; the replay test and the stale-timestamp test then failed.
import asyncio
import json
import httpx
import pytest
from outbox import classify
from receiver import create_app
from signing import sign
SECRET = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw"
NOW = 1_800_000_000
BODY = json.dumps({"type": "invoice.paid", "data": {"invoice_id": "inv_42"}},
separators=(",", ":")).encode()
def signed(msg_id="msg_01", ts=NOW, body=BODY, secret=SECRET):
return {"webhook-id": msg_id, "webhook-timestamp": str(ts),
"webhook-signature": sign(secret, msg_id, ts, body)}
@pytest.fixture
def receiver(tmp_path):
app = create_app(str(tmp_path / "rx.db"), SECRET, clock=lambda: NOW)
def post(headers, body=BODY): # a real HTTP request into the app, in process
async def go():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app),
base_url="https://rx.test") as client:
return await client.post("/webhooks", content=body, headers=headers)
return asyncio.run(go())
def paid():
return app.state.db.execute("SELECT count(*) FROM paid_invoices").fetchone()[0]
return post, paid
def test_replayed_request_is_acknowledged_but_not_processed_twice(receiver):
post, paid = receiver
first = post(signed())
again = post(signed()) # same bytes
assert first.json() == {"status": "processed"}
assert (again.status_code, again.json()) == (200, {"status": "duplicate"})
assert paid() == 1def test_tampered_body_is_rejected(receiver):
post, paid = receiver
forged = BODY.replace(b"inv_42", b"inv_99")
r = post(signed(), body=forged)
assert (r.status_code, paid()) == (401, 0)
def test_stale_timestamp_is_rejected_even_with_a_valid_signature(receiver):
post, paid = receiver
r = post(signed(ts=NOW - 301))
assert (r.status_code, r.json()["detail"]) == (400, "timestamp outside the "
"tolerance window")
def test_fresh_timestamp_on_an_old_signature_is_rejected(receiver):
post, _ = receiver
headers = signed(ts=NOW - 3600) | {"webhook-timestamp": str(NOW)}
assert post(headers).status_code == 401
def test_new_id_on_a_captured_request_is_rejected(receiver):
post, _ = receiver
headers = signed() | {"webhook-id": "msg_02"} # the id is signed too
assert post(headers).status_code == 401
def test_rotation_second_signature_is_accepted(receiver):
post, _ = receiver
old = signed(secret="whsec_" + "A" * 32)["webhook-signature"]
new = signed()["webhook-signature"]
headers = signed() | {"webhook-signature": f"{old} {new}"}
assert post(headers).status_code == 200
def test_junk_signature_gets_401_not_500(receiver):
post, _ = receiver
headers = signed() | {"webhook-signature": "v1,é" * 3}
r = post({k: v.encode() for k, v in headers.items()})
assert r.status_code == 401
@pytest.mark.parametrize("status, error, outcome", [
(200, None, "delivered"), (None, "ConnectTimeout", "retry"), (503, None, "retry"),
(429, None, "retry"), (410, None, "disable"), (400, None, "failed"),
(301, None, "failed")])
def test_retry_only_what_can_succeed_later(status, error, outcome):
assert classify(status, error) == outcome$ python -m pytest -q test_webhooks.py
.............. [100%]
14 passed in 0.77s06. Common mistakes
07. Check your understanding
08. Apply it
Add signed outgoing webhooks to your practice service:
- Create the
endpoints,webhook_jobsanddeliveriestables, and enqueue atask.updatedevent in the same transaction as the task change. - Run the delivery worker from your job queue (claim jobs with
FOR UPDATE SKIP LOCKEDon PostgreSQL) and add an admin endpoint that lists the delivery log of one event. - Write tests proving that a tampered body, a stale timestamp, a changed
webhook-idand a replayed request are rejected or not processed twice, and that a500from the receiver produces a retry row withnext_retry_at.
The next lesson covers long-lived connections in production: proxies, limits and deploys.
09. Review prompt
Without looking back, explain what the webhook-id, webhook-timestamp and webhook-signature headers are for and why the ID and timestamp are part of the signed string. Then describe how the sender decides whether to retry an attempt, what it writes to the delivery log, and why the delays have jitter. Finally, explain why the receiver answers a duplicate with 200 and why the dedupe row and the work must commit in one transaction.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.