Webhooks Explained: Signed Payloads and Retries
You've integrated a third-party service that sends webhooks to your endpoint. Everything works in testing, but in production you notice missing events, duplicate deliveries, and occasional security concerns. Webhooks are simple in concept but tricky to get right. This guide explains how to secure webhooks with signed payloads and implement reliable retries so you can trust your integrations.
What Are Webhooks?
Webhooks are user-defined HTTP callbacks. When an event occurs in a source system (like a payment success or a new user signup), it sends an HTTP POST request to a URL you provide. This push model is more efficient than polling and enables real-time reactions.
However, webhooks introduce challenges: the source system must reach your endpoint over the public internet, and you must ensure the request is authentic and processed exactly once.
Why Secure Webhooks with Signed Payloads?
Without verification, anyone can send fake requests to your webhook endpoint, potentially triggering unauthorized actions. Signed payloads use a secret shared between you and the sender to cryptographically sign the request body. When you receive a webhook, you verify the signature to confirm it came from the expected source and wasn't tampered with.
How HMAC Signatures Work
The most common method is HMAC (Hash-based Message Authentication Code) with SHA-256. The sender computes a hash of the payload using the shared secret and includes it in a header (e.g., X-Signature). You recompute the hash on your side and compare.
// Node.js example: verifying a signature
const crypto = require('crypto');
function verifySignature(payload, signature, secret) {
const expected = crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expected)
);
}
Always use a timing-safe comparison to prevent timing attacks. Never expose the secret in client-side code.
Step-by-Step: Implementing Signature Verification
- Retrieve the raw body – Many frameworks parse JSON automatically. You need the raw body string to compute the correct hash. Configure your framework to provide it (e.g.,
express.raw()in Node.js). - Extract the signature from the header specified by the provider (e.g.,
Stripe-Signature). - Compute the expected signature using HMAC-SHA256 with your secret.
- Compare securely using a constant-time function.
- Reject if invalid with a 401 status.
Implementing Reliable Retries
Networks fail, servers restart, and endpoints time out. A robust webhook system must retry failed deliveries. But naive retries can cause duplicate processing. Here's how to do it right.
Exponential Backoff with Jitter
Instead of retrying immediately, wait longer between each attempt. Exponential backoff increases the delay exponentially (e.g., 1s, 2s, 4s, 8s). Add random jitter to avoid thundering herd problems when many webhooks fail simultaneously.
// Pseudocode for retry logic
function scheduleRetry(attempt) {
const baseDelay = 1000; // 1 second
const maxDelay = 60000; // 1 minute
const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay);
const jitter = Math.random() * 1000;
setTimeout(() => sendWebhook(), delay + jitter);
}
Limit retries to a reasonable number (e.g., 5–10) and consider a dead-letter queue for persistent failures.
Idempotency: Handling Duplicates
Even with retries, duplicates can occur (e.g., if the sender didn't receive your 200 OK). Design your webhook handler to be idempotent. Use an idempotency key provided by the sender (often in a header like Idempotency-Key) or derive one from the event ID. Store processed keys and ignore repeats.
// Example: idempotency check with Redis
async function handleWebhook(event) {
const key = `webhook:${event.id}`;
const exists = await redis.set(key, '1', 'NX', 'EX', 86400);
if (!exists) return; // already processed
// process event
}
Respond Quickly, Process Asynchronously
Webhook senders often have short timeouts (e.g., 5 seconds). If your processing takes longer, acknowledge receipt immediately (return 200) and enqueue the work for background processing. This prevents unnecessary retries due to timeouts.
Comparison: Polling vs Webhooks
| Aspect | Polling | Webhooks |
|---|---|---|
| Latency | Depends on interval | Near real-time |
| Server load | Constant requests | Only on events |
| Complexity | Simple to implement | Requires retry & security |
| Reliability | High (you control) | Depends on sender retries |
Best Practices for Webhook Security
- Use HTTPS – Always serve webhook endpoints over TLS to prevent eavesdropping.
- Validate the source IP – If the provider publishes IP ranges, restrict incoming requests to those IPs (but don't rely solely on this).
- Timestamp validation – Include a timestamp in the signed payload and reject old requests to prevent replay attacks.
- Rotate secrets – Periodically rotate your signing secret and support multiple active secrets during rotation.
- Log everything – Log webhook attempts, including headers and payloads (redact sensitive data), to debug issues.
Testing Webhooks Locally
During development, use tools like ngrok or localtunnel to expose your local server to the internet. Always test signature verification and retry logic with simulated failures.
FAQ
What is a signed webhook payload?
A signed payload includes a cryptographic signature (usually HMAC) that allows the receiver to verify the request's authenticity and integrity. It ensures the webhook came from the expected sender and wasn't altered.
How many times should I retry a failed webhook?
There's no universal number, but 5–10 retries with exponential backoff over several hours is common. After that, move the event to a dead-letter queue for manual inspection.
Can I use webhooks without HTTPS?
Technically yes, but it's insecure. HTTPS encrypts the payload in transit and protects the signature from interception. Always use HTTPS in production.
When debugging webhook payloads or analyzing server logs, having the right tools helps. For instance, if you need to inspect JSON payloads, try the JSON Formatter to pretty-print and validate. And if you're troubleshooting Nginx access logs for webhook requests, the Nginx Log Analyzer can quickly surface patterns and errors.