Graceful Secret Rotation Mid-Retry: Avoiding Signature Mismatches on Delayed Webhook Attempts
Prevent webhook signature failures during secret rotation when events sit in backoff retries or replay queues. Learn dual-secret validation and safe re-signing.

Graceful Secret Rotation Mid-Retry: Avoiding Signature Mismatches on Delayed Webhook Attempts
Rotating signing secrets is routine hygiene. In an asynchronous webhook pipeline, though, a rotation at the wrong moment can cause a quiet, self-inflicted outage. Events waiting in backoff queues, or in a dead-letter queue (DLQ) for manual replay, start failing receiver authentication. The receiver typically answers 400, 401 or 403, depending on how its framework handles a failed signature check.
The cause is that an event often outlives a rotation window. Suppose a consumer outage stalls delivery for six hours, and an engineer or compliance job rotates the endpoint secret during hour three, invalidating the old one immediately. Every retry signed with the old key then fails, as does every replay that reuses an old signature. Unless the delivery pipeline was designed for mid-retry key transitions, those failures continue until someone intervenes.
This article covers how mid-retry mismatches arise, how the Standard Webhooks specification and major providers handle rotation, and a runbook for rotating without dropping events.
The Mechanics of Mid-Retry Signature Mismatches
A webhook event passes through two phases:
- Ingestion and enqueueing: The producer emits a domain event (for example
invoice.paid), persists the payload, and enqueues a delivery job. - Egress and signing: A worker dequeues the job, builds the HTTP request, computes the signature, and sends it.
A mismatch occurs when the producer’s active signing key and the consumer’s active verification key are out of sync on a given attempt. This happens in two common patterns.
Pattern A: Pre-Signed Payloads in the Queue
Some systems compute the signature once at ingestion and store the signed headers in the queue message.
- Key mismatch: If the consumer rotates and drops the old secret, any pre-signed message still in a backoff queue or DLQ carries a signature from the retired key, and the consumer rejects it.
- Stale timestamps: Even if the consumer keeps the old secret, a pre-signed message keeps its original timestamp. The Standard Webhooks specification says the timestamp is that of the attempt, and that it is updated on every retry. This is a security measure against replay attacks. Receivers are expected to reject timestamps outside a tolerance window. The widely used default is five minutes: Stripe’s libraries reject events older than that by default, and the Standard Webhooks libraries and Svix-based verifiers also default to 300 seconds. A message delayed by fifteen minutes fails replay protection even when the signature is mathematically valid.
Pattern B: Sign-at-Dispatch with Uncoordinated Cutover
The Standard Webhooks model is to sign at dispatch. Each attempt gets a fresh timestamp, while webhook-id stays constant across retries. This removes the stale-timestamp problem but introduces a race during rotation.
- If the producer switches to a new secret K₂ and drops K₁ immediately, retries dispatched before the consumer deploys K₂ are signed only with K₂, and consumers still running K₁ reject them.
- If the consumer swaps to K₂ and drops K₁ before the producer switches, in-flight retries signed with K₁ fail.
Dual signing closes both gaps, as covered below.
Architectural Comparison: Pre-Signing vs. Sign-at-Dispatch
| Dimension | Pre-signed at ingestion | Sign-at-dispatch |
|---|---|---|
| Timestamp freshness | Stale on retry; fails tolerance checks unless the receiver disables them. | Fresh on every attempt, as the Standard Webhooks spec expects. |
| Secret rotation impact | Queued messages are bound to the old key; requires re-signing or very long dual-key periods. | The next attempt uses whichever keys are currently active. |
| Payload handling | Must store exact serialized bytes plus headers. | Must store exact serialized bytes, signed fresh each time. |
| DLQ replay | Fails unless the replay worker strips old signature headers and re-signs. | Works as long as the original bytes are preserved. |
| Compute cost | Once per event. | Once per attempt. Negligible for HMAC-SHA256; asymmetric signing is more CPU-intensive, and a KMS or HSM adds latency. |
For these reasons, sign-at-dispatch is the better default.
How Providers Handle Rotation Today
The pattern of signing with both the old and new secret for a limited time is standard across providers. The 24-hour window is typical, though details vary.
| Provider | Documented rotation behavior |
|---|---|
| Svix | Rotating an endpoint secret signs messages with both the new and old secret for 24 hours. |
| Stripe | When you roll an endpoint secret you can delay the old secret’s expiry by up to 24 hours. During that time Stripe generates one signature per active secret. |
| Bird | Signs with the old and new secrets for 24 hours, and allows up to five concurrently valid secrets. |
| Hookdeck Event Gateway | Signs every delivery attempt with Standard Webhooks and verifies incoming Standard Webhooks signatures. A source accepts the request if any v1 signature in the header matches. Per its changelog, a destination signs with only one secret and rotation was not yet available for signing, so check the current docs before relying on it. |
Stripe’s retry behavior also shows why rotation windows matter. In live mode it retries failed deliveries with exponential backoff for up to three days. A delayed retry can therefore be dispatched after a 24-hour rotation window has closed. The Dashboard also lets you resend events for up to 15 days after creation.
Designing Zero-Downtime Secret Rotation
Safe rotation depends on three things: dual-signature emission, tolerant consumer verification, and preservation of the exact original payload bytes.
1. Dual-Signature Emission (Producer Side)
The Standard Webhooks webhook-signature header is a space-delimited list of signatures. The spec says the list exists to support zero-downtime rotation. During a rotation, the producer signs with both the current and old key, and consumers can try each signature until one matches.
POST /webhooks/payments HTTP/1.1
Host: api.consumer.example.com
Content-Type: application/json
webhook-id: msg_2KWPBgLlAfxdpx2AI54pPJ85f4W
webhook-timestamp: 1674087231
webhook-signature: v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4= v1,bm9ldHUjKzFob2VudXRob2VodWUzMjRvdWVvdW9ldQo=
For symmetric signatures, the signed content is msg_id.timestamp.payload, with the three parts joined by full stops. The signature is base64(HMAC-SHA256(key, signed_content)), using the base64-decoded portion of the whsec_ secret as the key. The spec recommends symmetric secrets between 24 and 64 bytes, unique per endpoint.
During a rotation window, the producer holds two secrets for the endpoint:
- Primary: the newly generated secret.
- Secondary: the expiring secret, with an explicit expiry timestamp.
Every worker that handles a first attempt, a backoff retry, or a DLQ replay during the window signs with both secrets, using a fresh timestamp and the stored raw payload.
Producer Dual-Signing Implementation (TypeScript / Node.js)
import crypto from 'node:crypto';
interface EndpointSecret {
id: string;
keyMaterial: Buffer; // base64-decoded bytes after the "whsec_" prefix
expiresAt: Date | null; // null for the primary secret
}
export function generateWebhookHeaders(
webhookId: string,
rawPayload: string, // the exact string that will be sent as the HTTP body
secrets: EndpointSecret[]
): Record<string, string> {
// The spec requires the ID and timestamp not to contain "." characters.
if (webhookId.includes('.')) {
throw new Error('webhook-id must not contain "."');
}
const timestamp = Math.floor(Date.now() / 1000).toString();
const signedContent = `${webhookId}.${timestamp}.${rawPayload}`;
const now = new Date();
const signatures = secrets
.filter((s) => !s.expiresAt || s.expiresAt > now)
.map((s) => {
const sig = crypto
.createHmac('sha256', s.keyMaterial)
.update(signedContent, 'utf8')
.digest('base64');
return `v1,${sig}`;
});
if (signatures.length === 0) {
throw new Error(`No valid signing secrets for webhook ${webhookId}`);
}
return {
'webhook-id': webhookId,
'webhook-timestamp': timestamp,
'webhook-signature': signatures.join(' '),
};
}
2. Multi-Key Constant-Time Verification (Consumer Side)
The consumer must parse every space-delimited signature in the header, and accept the request if any signature verifies against any configured secret. The OWASP Webhook Security Cheat Sheet says this “accept any match” rule is what makes rotation safe in either order.
Several verification rules matter here:
- Use constant-time comparison. The Standard Webhooks spec warns that a non-constant-time comparison can expose consumers to timing attacks and turn them into signing oracles. Use
crypto.timingSafeEqualin Node.js orhmac.compare_digestin Python, never==. - Check the timestamp tolerance. Reject timestamps too far from the current time, typically ±300 seconds, to limit replay of captured requests.
- Deduplicate on
webhook-id. The spec recommends using it as an idempotency key, since it stays the same across retries. - Verify the raw body. Verify against the exact bytes received, not a parsed and re-serialized object.
Consumer Verification Middleware (Python)
import base64
import hashlib
import hmac
import time
from typing import Sequence
TOLERANCE_SECONDS = 300 # common default replay-protection window
class WebhookVerificationError(Exception):
pass
def verify_webhook_signature(
webhook_id: str,
timestamp_header: str,
signature_header: str,
raw_body: bytes,
active_secrets: Sequence[bytes], # decoded key bytes, e.g. [K_new, K_old]
) -> bool:
# 1. Validate timestamp freshness first
try:
timestamp = int(timestamp_header)
except ValueError as exc:
raise WebhookVerificationError("Malformed webhook-timestamp") from exc
if abs(int(time.time()) - timestamp) > TOLERANCE_SECONDS:
raise WebhookVerificationError("Timestamp outside tolerance window")
# 2. Parse space-delimited v1 signatures (split on whitespace, not commas)
candidates = [
part[3:] for part in signature_header.split() if part.startswith("v1,")
]
if not candidates:
raise WebhookVerificationError("No v1 signatures in header")
# 3. Rebuild the signed content: msg_id.timestamp.payload
signed_bytes = f"{webhook_id}.{timestamp_header}.".encode("utf-8") + raw_body
# 4. Compare against every active secret and every candidate signature
for secret in active_secrets:
digest = hmac.new(secret, signed_bytes, hashlib.sha256).digest()
expected = base64.b64encode(digest).decode("utf-8")
for candidate in candidates:
if hmac.compare_digest(expected, candidate):
return True
raise WebhookVerificationError("Signature verification failed")
3. Asymmetric Keys and Key Identifiers
Symmetric secrets are fast and simple, but the spec recommends asymmetric signatures when you don’t control the security of both sides. With asymmetric keys only the producer holds the private key, and consumers verify with a public key. The private key can live in a KMS or HSM.
In the Standard Webhooks spec, asymmetric signatures use Ed25519 over the SHA-256 hash of endpoint_id.msg_id.timestamp.payload, identified by the v2a prefix. The endpoint ID in the signed content stops a webhook sent to one endpoint from being replayed to another that trusts the same public key. The older v1a scheme has been deprecated in favor of v2a.
Rotation works differently here. The spec notes that asymmetric key pairs are rotated by the producer, and a consumer may not know which public key signed a given webhook. Consumers should therefore keep a list of trusted public keys and accept the webhook if any signature in the header verifies against any of them.
Outside Standard Webhooks, RFC 9421 (HTTP Message Signatures, February 2024) defines Signature-Input and Signature fields. Its signature parameters include keyid, created and alg, which lets a receiver look up the right key directly instead of trying each one. The RFC also allows multiple signatures on one message. A body digest is typically included via Content-Digest (RFC 9530). A representative example, with a placeholder instead of a real signature value:
Content-Digest: sha-256=:<base64-sha256-of-body>:
Signature-Input: sig1=("@method" "@target-uri" "content-digest");created=1795831500;keyid="ep_key_2026_11_v2";alg="ed25519"
Signature: sig1=:<base64-ed25519-signature>:
During a rotation, a delayed retry is re-signed at dispatch time with the currently active keyid. The consumer’s key store keeps both the previous and the new public key until the old one is retired.
Re-Signing Strategies for Dead-Letter Queues and Manual Replays
Backoff schedules usually span hours to days. The Standard Webhooks spec’s example runs through ten attempts over roughly 75 hours, and it recommends schedules that span multiple days. Events that land in a DLQ can sit for much longer, so by the time someone triggers a replay, the old key’s grace period has almost certainly expired. The spec stresses that consumers need a way to manually replay specific webhooks, or failures within a range, to recover from long outages.
A replay that retransmits archived HTTP requests verbatim will fail, because the signature and timestamp are stale. A safe replay follows three rules.
Rule 1: Store the Exact Original Bytes
The spec notes that a common failure mode is parsing the body as JSON and serializing it again. Serialization is not necessarily identical across implementations, or even across invocations of the same one. Key order, whitespace, Unicode escaping and number formatting can all change. Store the exact serialized payload (as a BYTEA or blob) at event creation, alongside the original webhook-id, and sign those same bytes on every attempt and replay.
Rule 2: Strip Old Signature Metadata and Re-Sign
When a replay worker pulls an event from the DLQ:
- Keep the original
webhook-id, so the consumer’s deduplication layer can recognize the event. - Discard the old
webhook-timestampandwebhook-signatureheaders. - Generate a fresh timestamp for the replay attempt.
- Sign with the endpoint’s currently active secret or secrets.
Consumers should record an event ID as processed only after successful handling. Otherwise a retry of an event whose first attempt failed partway could be dropped as a duplicate.
Rule 3: Log Key Lineage per Attempt
Record the ID of the secret (never the secret itself) used to sign each attempt. When a delayed retry returns an authentication error, seeing that the attempt was signed with a secret different from the endpoint’s current one points straight at a rotation problem.
Step-by-Step Zero-Downtime Rotation Runbook
Whether you are doing a routine rotation or responding to a suspected leak, use four phases.
Phase 1: Provision the New Secret
- Generate a new cryptographically random secret, for example 32 bytes (the Standard Webhooks spec allows 24 to 64), and encode it as
whsec_<base64>. - Store it as the endpoint’s primary secret on the producer. Keep the old secret active with an expiry timestamp.
Emergency exception: If the old secret was leaked, dual signing keeps a compromised key in play. Revoke the old secret immediately on both sides. Expect 401 responses on in-flight retries, and recover those events with a re-signed replay once the new secret is deployed. Stripe, for example, lets you expire a compromised secret immediately instead of waiting out the full window.
Phase 2: Dual-Sign and Roll Out to Consumers
- The producer signs every attempt, including retries and replays, with both secrets.
- The consumer deploys the new secret to every receiver instance and gateway, accepting both old and new during the transition.
- Confirm through metrics that incoming webhooks are verifying against the new secret.
Phase 3: Drain the Old Key
Set the old secret’s expiry based on how your pipeline signs:
- Sign-at-dispatch: retries are signed with whatever keys are active when they are sent, so the backoff window doesn’t constrain the old key’s lifetime. Consumer deployment time does. The old key must stay valid until every consumer instance trusts the new key, plus a safety buffer. Providers commonly use 24 hours.
- Pre-signed queues: the old key must remain valid, and not be revoked on the consumer, for as long as the longest-lived queued message could still be sent. Better still, re-sign queued messages at dispatch.
The remaining risk is a retry dispatched after the old key expires, to a consumer that has not yet deployed the new key. If your retry schedule is long and your consumers deploy slowly, extend the window or confirm adoption before expiring the key.
Phase 4: Retire the Old Secret
- Once the window ends and consumers have adopted the new key, remove the old secret from the producer’s signing list and the consumer’s verification list.
- Events remaining in a DLQ will be signed with the new secret when replayed.
Common Pitfalls That Break Mid-Retry Verification
- Parsing the body before verifying. Frameworks that parse JSON into
req.bodyand re-serialize it before the HMAC check will alter whitespace or key order. Verify against the raw bytes. - Single-signature header parsing. Some consumers assume
webhook-signaturehas one value. If the parser splits on,first, a header containingv1,sig1 v1,sig2is mangled and every valid webhook fails during rotation. Split on whitespace first. - Clock drift. Fresh timestamps only work if worker clocks are synchronized. A clock skewed beyond the receiver’s tolerance, commonly five minutes, makes every retry fail the freshness check.
- Out-of-band replay tools. Support scripts that read secrets from stale environment variables, or that bypass the signing service, will break after a rotation. Route all manual replays through the same signing pipeline as automated retries.
- Reusing secrets across endpoints. The Standard Webhooks spec requires symmetric keys to be unique per endpoint. Stripe likewise generates a separate secret per endpoint, and a different one for test and live mode on the same endpoint. Shared secrets turn one rotation into a fleet-wide event.
- Letting
.into IDs. Because the signed content is delimited by full stops, the spec requires that the message ID and timestamp not be user-controlled, or at least not contain.. Hookdeck’s changelog, for example, notes that it fails the attempt if awebhook-idcontains a period.
Key Takeaways
- Sign at dispatch with a fresh timestamp, and keep
webhook-idconstant across retries. - During rotation, sign with both the old and new secret. Consumers should accept any matching signature.
- Size the old key’s lifetime by consumer deployment time for sign-at-dispatch pipelines, and by queue residence time for pre-signed ones.
- Preserve the exact payload bytes so replays re-sign cleanly.
- Log the secret ID used for each attempt, never the secret itself.