Cluster 14 · Python Backend · Depends + hmac.compare_digest

FastAPI Raw-Body HMAC Verification, RateLimit-* Headers & Async Worker Pattern

Implement zero-bug FastAPI webhook endpoints using `await request.body()`, `hmac.compare_digest`, replay-window checks, RFC `RateLimit-*` / `Retry-After` responses, and background queues.

100% Browser-Side · WebCrypto crypto.subtle · Strict CSP

2. RFC RateLimit-* & Retry-After Header Builder

IETF RateLimit + RFC 9110
Cloudflare Workers / Edge Middleware Helper (ratelimit.ts)
// Cloudflare Workers RFC RateLimit-* + Retry-After Response Helper
export function rateLimitResponse(remaining: number, resetSec: number, throttled: boolean): Response {
  const headers: Record<string, string> = {
    "Content-Type": "application/json",
    "RateLimit-Policy": '"webhook-ingest";q=100;w=60',
    "RateLimit": `"webhook-ingest";r=${Math.max(0, remaining)};t=${Math.max(0, resetSec)}`,
    "X-RateLimit-Limit": "100",
    "X-RateLimit-Remaining": String(Math.max(0, remaining)),
    "X-RateLimit-Reset": String(Math.floor(Date.now() / 1000) + Math.max(0, resetSec)),
  };
  if (throttled) {
    headers["Retry-After"] = String(Math.max(1, resetSec));
    headers["Cache-Control"] = "no-store";
    return new Response(JSON.stringify({ error: "rate_limited", retryAfterSec: resetSec }), { status: 429, headers });
  }
  return new Response(JSON.stringify({ ok: true }), { status: 200, headers });
}
RateLimit-* & Retry-After Compliance Score
100 / 100
PASS
RL-001: RFC 9110 §10.2.3 Retry-After present on HTTP 429 PASS
Communicates deterministic cooldown window so upstream webhook dispatchers pause safely.
RL-002: Quota math consistent (0/100 remaining over 60s window) PASS
Policy "webhook-ingest" matches IETF draft-ietf-httpapi-ratelimit-headers structured field syntax.
Generated HTTP Response Headers
HTTP/1.1 429 Too Many Requests
RateLimit-Policy: "webhook-ingest";q=100;w=60
RateLimit: "webhook-ingest";r=0;t=17
Retry-After: 17
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1796137217
Cache-Control: no-store
WebhookSLA Guard · Live Check $29 WebhookSLA Guard Kit

Verify Live Webhook Replay Defense, 429 Retry-After & DLQ SLA Readiness

Run a live webhook endpoint & SLA audit on WebhookSLA Guard (webhook.runglab.dev), grab the turnkey $29 WebhookSLA Guard Kit (WebCrypto HMAC verifiers, replay-window store, RFC RateLimit-* middleware & DLQ runbooks) on Creem, or audit webhook OpenAPI specs on SpecDiff (spec.runglab.dev). Need a PayPal invoice? Email [email protected].

Webhook SLA, Signature & Retry Specification Matrix

Control / Header Production Baseline Reliability & Security Rationale
Raw Body Access await request.body() Never verify HMAC against a Pydantic BaseModel `.model_dump_json()` string
Constant-Time Check hmac.compare_digest(a, b) Built-in Python stdlib constant-time comparison prevents timing side-channels
Rate-Limit Headers RateLimit-Policy + RateLimit + Retry-After Return HTTP 429 with `Retry-After` when webhook burst limits engage
Async Processing Enqueue to Celery/ARQ/Redis (avoid heavy work in request) Respond 200/202 in < 500ms; handle retries and DLQ in worker

FastAPI Dependency for HMAC + Replay Verification (Python)

fastapi_webhook.py
import hashlib
import hmac
import time
from fastapi import FastAPI, Header, HTTPException, Request

app = FastAPI()

async def verify_webhook_sig(
    request: Request,
    stripe_signature: str = Header(default=""),
    secret: str = "whsec_replace_me",
    tolerance_sec: int = 300,
) -> bytes:
    raw_body = await request.body()
    parts = dict(kv.split("=", 1) for kv in stripe_signature.split(",") if "=" in kv)
    ts = int(parts.get("t", "0") or 0)
    now = int(time.time())
    if not ts or (now - ts) > tolerance_sec or (ts - now) > 30:
        raise HTTPException(status_code=400, detail="replay_window_rejected")

    signed = f"{ts}.".encode("utf-8") + raw_body
    expected = hmac.new(secret.encode("utf-8"), signed, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(parts.get("v1", "").lower(), expected):
        raise HTTPException(status_code=401, detail="invalid_signature")
    return raw_body

FastAPI 429 RateLimit-* + Retry-After Exception Helper

fastapi_ratelimit.py
from fastapi.responses import JSONResponse

def rate_limited_response(policy: str, limit: int, window: int, retry_after: int) -> JSONResponse:
    return JSONResponse(
        status_code=429,
        content={"error": "rate_limited", "retry_after": retry_after},
        headers={
            "RateLimit-Policy": f'"{policy}";q={limit};w={window}',
            "RateLimit": f'"{policy}";r=0;t={retry_after}',
            "Retry-After": str(max(1, retry_after)),
            "Cache-Control": "no-store",
        },
    )

Implementation Steps & Key Insights

  1. Inject a FastAPI dependency that reads `await request.body()` as raw `bytes` before Pydantic JSON parsing.
  2. Validate timestamp freshness (`now - ts <= tolerance_sec`) and verify HMAC via `hmac.compare_digest`.
  3. Emit IETF `RateLimit-Policy`, `RateLimit`, and RFC 9110 `Retry-After` headers whenever rate limiting returns HTTP 429.
  4. Push verified payloads onto ARQ/Celery/RQ with exponential backoff and DLQ monitoring rather than blocking uvicorn workers.
  • FastAPI `await request.body()` caches bytes safely on `request._body`, letting downstream Pydantic validators parse JSON cleanly after verification.
  • Using `BackgroundTasks` for critical billing webhooks risks losing in-flight jobs on pod restarts; prefer a durable Redis/Postgres queue with DLQ.
  • Pair FastAPI OpenAPI contracts with `https://spec.runglab.dev` to validate webhook callback security & schema hygiene.

Common Production Pitfalls

  • Passing Pydantic `model.model_dump_json()` into `hmac.new()` — whitespace and field defaults break every signature.
  • Using Python `==` instead of `hmac.compare_digest()`.
  • Omitting `Retry-After` on custom FastAPI 429 middleware responses.
Ship Faster: Audit your live endpoint on webhook.runglab.dev or grab the $29 WebhookSLA Guard Kit.

More Enterprise Webhook SLA & Signature Guides

← Back to Webhook SLA Kit Hub · WebhookSLA Guard ($29 Kit) → · SpecDiff OpenAPI Audit → · Cluster 7B: CORS & HMAC → · Cluster 9: OpenAPI OWASP →

Frequently Asked Questions

Can FastAPI read `await request.body()` and still parse Pydantic JSON afterwards?

Yes — Starlette/FastAPI caches `request.body()` internally on the `Request` instance so subsequent `request.json()` calls succeed without re-reading the stream.

Why shouldn't I rely solely on FastAPI `BackgroundTasks` for payment webhooks?

In-process `BackgroundTasks` live in worker RAM and vanish if the container restarts or OOMs. Use a persistent queue with exponential backoff and a DLQ.

Where can I inspect my FastAPI OpenAPI & live webhook SLA headers?

Use https://spec.runglab.dev for OpenAPI OWASP checks and https://webhook.runglab.dev for live webhook SLA verification.