How do you rotate a webhook HMAC secret with zero downtime?
Question
Your payment webhook receiver checks X-Signature against one WEBHOOK_SECRET. Last quarter, swapping that secret in a single deploy dropped 400 valid in-flight webhooks with HTTP 401 while senders still signed with the old key.
- Update
check_sigto accept an ordered key list ([current, previous]) using constant-time comparison. - Give the exact rollout order to rotate from
test-key-v1totest-key-v2without dropping valid requests.
import hashlib import hmac def check_sig(payload, sig_hex, secret): expected = hmac.new(secret, payload, hashlib.sha256).hexdigest() return expected == sig_hex
Show hints (3)
- "TWO ACTIVE KEYS"
Let the receiver accept signatures produced by either
currentorpreviousduring the overlap window. - "AVOID TIMING LEAKS"
Replace
==on HMAC digests withhmac.compare_digestso comparison time does not leak matching prefix bytes. - "RECEIVER BEFORE SENDER"
Which side must know
test-key-v2first so no in-flight webhook hits a receiver that rejects it?
Show checked explanation
Accept an ordered key list [current, previous] on the receiver and compare each digest with hmac.compare_digest. Roll out in four steps: add test-key-v2 to all receivers, switch senders to sign with test-key-v2, wait until metrics show zero traffic on test-key-v1, then remove test-key-v1.
import hashlib import hmac def sign(payload, secret): return hmac.new(secret, payload, hashlib.sha256).hexdigest() def check_sig(payload, sig_hex, secrets): matched = False for key in secrets: matched |= hmac.compare_digest(sign(payload, key), sig_hex) return matched body = b'{"invoice":"invoice_9001"}' ring = [b"test-key-v2", b"test-key-v1"] cases = [("v2", b"test-key-v2"), ("v1", b"test-key-v1"), ("bad", b"wrong")] for label, key in cases: print(label, "->", check_sig(body, sign(body, key), ring))
v2 -> True v1 -> True bad -> False
Code run on CPython 3.12.10 against synthetic HMAC-SHA256 signatures across all four rotation stages; official Python, OWASP, AWS, and NIST links checked. Checked by an editor other than the author.
Walkthrough
A single-key swap fails because rolling deploys, worker queues, and webhook retries mean senders and receivers never cut over at the same instant. Zero-downtime rotation separates adding the new secret from retiring the old secret with a dual-key accept window.
| stage | senders sign with | receivers accept | exit check |
|---|---|---|---|
| 1. Add new key | test-key-v1 | [test-key-v2, test-key-v1] | Every receiver pod loaded v2 |
| 2. Switch signer | test-key-v2 | [test-key-v2, test-key-v1] | New events sign with v2; retries still pass on v1 |
| 3. Drain old traffic | test-key-v2 | [test-key-v2, test-key-v1] | Metrics show 0 accepted calls on v1 past retry TTL |
| 4. Retire old key | test-key-v2 | [test-key-v2] | Delete v1 from config and secret manager |
Use constant-time digest comparison. Python's == stops at the first mismatching character, which leaks timing signals across repeated requests. hmac.compare_digest checks the full digest in constant time. Combining loop results with |= also inspects every key in the tiny ring instead of stopping early when the first key matches.
Track key drain safely. Tag each key with a non-secret key ID (v1, v2) and increment a counter (webhook_sig_match{key_id="v1"}) whenever a signature matches. Never log raw secrets or full digests. Once v1 hits zero for longer than your maximum webhook retry window, stage 4 can retire v1 cleanly.
Common mistakes
- Switching senders to
test-key-v2before every receiver instance accepts it. Lagging pods and rolling deploys reject valid webhooks with 401. - Comparing HMAC hex strings with
==instead ofhmac.compare_digest. Early exit on the first wrong character creates a timing side channel. - Leaving
test-key-v1in the accept list forever "just in case". Rotation limits exposure only after the old key is actually removed. - Logging the raw secret or signature header to debug a 401 spike. Emit only the non-secret
key_idand pass/fail count.
Follow-up questions
- "What changes during an emergency rotation after
test-key-v1is confirmed leaked?" Trade zero downtime for fast containment. Deploytest-key-v2to receivers, switch senders right away, and revoketest-key-v1immediately rather than waiting out the retry window, then replay any dropped events later. - "How do you stop someone from replaying a valid signed webhook hours later?" Include a Unix timestamp header (and event ID) inside the signed payload, such as
f"{ts}.{body}". Reject requests outside a short clock skew window like 5 minutes, and deduplicate event IDs. - "How does zero-downtime rotation work for asymmetric JWT signing keys (RS256 or EdDSA)?" Use the same overlap order. Publish the new public key under a new
kidin your JWKS endpoint and wait past cache TTL. Then switch issuers to the new private key, wait past token expiry, and drop the old public key.
What a strong answer covers
Implements a [current, previous] accept window using hmac.compare_digest, gives the exact four-stage rollout order, tracks old-key drain with non-secret key IDs, and distinguishes routine rotation from emergency revocation.
Open in interactive practice deck →