# Retry-safe webhook receiver A working reference implementation of the pattern I use for webhook → target-API integrations. Written for a real integration shape: an inbound event must create-or-update a record in a separate system, exactly once, even when the sender retries. ```python #!/usr/bin/env python3 """ webhook_receiver.py — retry-safe webhook listener with idempotent fan-out. Design notes (why it looks like this): 1. Verify before parsing. The signature check runs on raw bytes, before any JSON decode, because a re-serialised body is not the body the sender signed. 2. Idempotency is keyed on the sender's event id, not on our own request id. Retries from the sender must collapse to one downstream effect. 3. The downstream call is guarded by a claim row written *before* the call. Claim -> call -> commit. A crash between claim and commit is recoverable; a crash after the call but before commit re-reads the claim and reconciles. 4. Nothing raises out of the handler unless we intend a non-2xx. Senders retry on 5xx, so an unhandled exception turns one event into a storm. """ from __future__ import annotations import hashlib import hmac import json import logging import os import sqlite3 import time from contextlib import closing from dataclasses import dataclass from typing import Any import requests from flask import Flask, request, jsonify log = logging.getLogger("webhook") app = Flask(__name__) SIGNING_SECRET = os.environ["WEBHOOK_SIGNING_SECRET"].encode() TARGET_BASE = os.environ["TARGET_API_BASE"].rstrip("/") TARGET_TOKEN = os.environ["TARGET_API_TOKEN"] DB_PATH = os.environ.get("WEBHOOK_DB", "webhook.sqlite3") # Tolerate clock skew, but not replay of an old capture. MAX_SKEW_SECONDS = 300 @dataclass(frozen=True) class Event: event_id: str kind: str payload: dict[str, Any] def init_db() -> None: with closing(sqlite3.connect(DB_PATH)) as db: db.execute( """ CREATE TABLE IF NOT EXISTS processed ( event_id TEXT PRIMARY KEY, status TEXT NOT NULL, -- claimed | done | failed attempts INTEGER NOT NULL DEFAULT 0, updated_at REAL NOT NULL, detail TEXT ) """ ) db.commit() def verify(raw: bytes, signature: str | None, timestamp: str | None) -> bool: """Constant-time HMAC over f'{timestamp}.{raw}'. Rejects stale timestamps.""" if not signature or not timestamp: return False try: ts = int(timestamp) except ValueError: return False if abs(time.time() - ts) > MAX_SKEW_SECONDS: log.warning("stale webhook timestamp %s", timestamp) return False expected = hmac.new( SIGNING_SECRET, f"{timestamp}.".encode() + raw, hashlib.sha256 ).hexdigest() return hmac.compare_digest(expected, signature) def claim(event_id: str) -> str: """Return 'new' | 'done' | 'retry'. Writes the claim before any side effect.""" now = time.time() with closing(sqlite3.connect(DB_PATH)) as db: db.execute("BEGIN IMMEDIATE") row = db.execute( "SELECT status FROM processed WHERE event_id = ?", (event_id,) ).fetchone() if row is None: db.execute( "INSERT INTO processed(event_id, status, attempts, updated_at) " "VALUES (?, 'claimed', 1, ?)", (event_id, now), ) db.commit() return "new" status = row[0] if status == "done": db.commit() return "done" db.execute( "UPDATE processed SET status='claimed', attempts=attempts+1, updated_at=? " "WHERE event_id=?", (now, event_id), ) db.commit() return "retry" def finish(event_id: str, status: str, detail: str = "") -> None: with closing(sqlite3.connect(DB_PATH)) as db: db.execute( "UPDATE processed SET status=?, updated_at=?, detail=? WHERE event_id=?", (status, time.time(), detail[:500], event_id), ) db.commit() def map_fields(payload: dict[str, Any]) -> dict[str, Any]: """Explicit field map. Anything unmapped is dropped on purpose, logged at debug.""" customer = payload.get("customer") or {} order = payload.get("order") or {} mapped = { "external_id": str(order.get("id") or ""), "customer_email": (customer.get("email") or "").strip().lower(), "customer_name": (customer.get("name") or "").strip(), "amount_cents": int(order.get("amount_cents") or 0), "currency": (order.get("currency") or "EUR").upper(), "placed_at": order.get("created_at"), } required = ("external_id", "customer_email", "amount_cents") missing = [k for k in required if not mapped[k]] if missing: raise ValueError(f"missing required fields: {', '.join(missing)}") unmapped = set(order) - { "id", "amount_cents", "currency", "created_at" } | set(customer) - {"email", "name"} if unmapped: log.debug("dropped unmapped keys: %s", sorted(unmapped)) return mapped def upsert(mapped: dict[str, Any]) -> dict[str, Any]: """Create-or-update against the target API, keyed on external_id.""" headers = { "Authorization": f"Bearer {TARGET_TOKEN}", "Content-Type": "application/json", "Idempotency-Key": mapped["external_id"], } resp = requests.put( f"{TARGET_BASE}/orders/{mapped['external_id']}", headers=headers, json=mapped, timeout=15, ) if resp.status_code >= 500: # Let the sender retry; our claim row makes the retry safe. raise RuntimeError(f"target 5xx: {resp.status_code}") if resp.status_code >= 400: # 4xx will not improve on retry. Record it, return 200, alert. finish(mapped["external_id"], "failed", resp.text) log.error("target rejected payload: %s %s", resp.status_code, resp.text[:300]) return {"ok": False, "reason": "rejected"} return {"ok": True, "target_id": resp.json().get("id")} @app.post("/webhook") def webhook(): raw = request.get_data(cache=True) if not verify(raw, request.headers.get("X-Signature"), request.headers.get("X-Timestamp")): return jsonify(error="bad signature"), 401 try: body = json.loads(raw) except json.JSONDecodeError: return jsonify(error="malformed json"), 400 event_id = request.headers.get("X-Event-Id") or body.get("id") if not event_id: return jsonify(error="no event id"), 400 state = claim(event_id) if state == "done": log.info("duplicate %s ignored", event_id) return jsonify(ok=True, duplicate=True), 200 try: mapped = map_fields(body) result = upsert(mapped) if result["ok"]: finish(event_id, "done") return jsonify(ok=True), 200 except ValueError as exc: finish(event_id, "failed", str(exc)) return jsonify(error=str(exc)), 422 except Exception as exc: # noqa: BLE001 - deliberate: 5xx makes the sender retry log.exception("processing failed for %s", event_id) return jsonify(error="retry later"), 503 if __name__ == "__main__": init_db() logging.basicConfig(level=logging.INFO) app.run(port=int(os.environ.get("PORT", "8080"))) ``` ## The four decisions that matter **1. Verify the signature before parsing.** The HMAC runs over the raw request body. Decode JSON first and you are verifying a re-serialised object, not the bytes the sender signed — that is a signature check that passes on payloads that were never signed. **2. Idempotency keyed on the sender's event id.** Not on our own request id, not on a hash of the body. Senders retry the same event id; the claim row collapses those retries into one downstream effect. **3. Claim → call → commit.** A row is written *before* the outbound call. A crash between claim and commit is recoverable on retry. A crash after the call but before commit re-reads the claim and reconciles instead of double-creating. **4. 4xx does not retry, 5xx does.** A target API rejecting the payload will reject it identically on attempt two. Returning 200 after recording the failure stops the retry storm and lets an alert fire once. Returning 503 on genuine transient failure lets the sender retry safely, because of decision 3. ## What a first milestone would look like One endpoint, one event type, proven end to end: - Sender → our endpoint → target API, create-or-update confirmed - Duplicate delivery test: same event id twice, exactly one record on the target - Failure test: target returns 500, sender retries, no duplicate created - Signature test: tampered body rejected with 401, never reaching the handler - Field map documented as a table, with unmapped keys logged rather than silently dropped Additional events after that reuse the same claim/finish skeleton — only the field map and the target call change. That is why the mapping is isolated in one function.