Webhooks Explained: Signed Payloads and Retries
You've just built an integration that sends real-time notifications to a third-party service. Everything works in testing, but in production, some events never arrive, and others are processed twice. Without proper security and retry mechanisms, webhooks can become a source of silent failures and data inconsistencies.
This guide explains how to secure webhooks with signed payloads and implement robust retry logic so your integrations are both trustworthy and resilient.
What Are Webhooks and Why They Need Special Handling
Webhooks are user-defined HTTP callbacks triggered by specific events. They enable real-time communication between services, but unlike API calls initiated by your application, webhooks are push-based and rely on the network. This introduces two key challenges: security (ensuring the request truly comes from the expected sender) and reliability (guaranteeing delivery even when temporary failures occur).
Securing Webhooks with Signed Payloads
A signed payload uses a secret key to generate a cryptographic signature of the request body. The receiver can then verify the signature to confirm authenticity and integrity. The most common method is HMAC (Hash-based Message Authentication Code) with SHA-256.
How HMAC Signing Works
The sender computes an HMAC digest of the raw request body using a shared secret. This digest is sent in a header, often along with a timestamp to prevent replay attacks. The receiver recalculates the HMAC using the same secret and compares it with the received signature.
// Node.js example: generating HMAC signature
const crypto = require('crypto');
function signPayload(payload, secret) {
return crypto.createHmac('sha256', secret).update(payload).digest('hex');
}
// On the sender side:
const payload = JSON.stringify({ event: 'user.created', id: 123 });
const signature = signPayload(payload, 'your-webhook-secret');
// Include in headers: X-Signature: signature
Verifying the Signature on the Receiver
When your endpoint receives a webhook, extract the signature from the header and compute the expected signature using the raw request body (not the parsed JSON, as parsing can alter the payload). Use a constant-time comparison to prevent timing attacks.
// Node.js (Express) verification example
const express = require('express');
const crypto = require('crypto');
const app = express();
app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
const signature = req.headers['x-signature'];
const expected = crypto.createHmac('sha256', 'your-webhook-secret')
.update(req.body)
.digest('hex');
if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) {
return res.status(401).send('Invalid signature');
}
// Process the event
const event = JSON.parse(req.body);
// ...
res.status(200).send('OK');
});
Best practices:
- Always use HTTPS to protect the payload in transit.
- Include a timestamp in the signed data and reject requests older than a few minutes to prevent replay attacks.
- Rotate secrets periodically and support multiple active secrets during rotation.
- Never log the secret or the raw signature.
Implementing Reliable Retries
Even with signed payloads, network issues or temporary server errors can cause webhook delivery to fail. A robust retry strategy ensures that events are eventually delivered without overwhelming the receiver.
Retry Strategy Design
Use exponential backoff with jitter to space out retries. For example, wait 1 minute, then 5 minutes, then 30 minutes, up to a maximum number of attempts (e.g., 10). After exhausting retries, move the event to a dead-letter queue for manual inspection.
Consider these factors:
- Idempotency: Receivers should handle duplicate deliveries gracefully by using an idempotency key (e.g., event ID) to deduplicate.
- Timeouts: Set a reasonable timeout for each delivery attempt (e.g., 10 seconds) to avoid hanging connections.
- Failure classification: Retry only on 5xx responses or network errors; do not retry on 4xx (except 429 Too Many Requests).
Example Retry Logic with Exponential Backoff
// Pseudocode for sender-side retry
async function deliverWebhook(event, attempt = 1) {
const maxAttempts = 10;
try {
const response = await fetch(receiverUrl, {
method: 'POST',
body: JSON.stringify(event),
headers: { 'X-Signature': signPayload(JSON.stringify(event), secret) },
timeout: 10000
});
if (response.ok) return;
if (response.status >= 500 || response.status === 429) {
throw new Error('Retryable error');
}
// Non-retryable error (4xx)
return;
} catch (error) {
if (attempt >= maxAttempts) {
// Move to dead-letter queue
return;
}
const delay = Math.min(2 ** attempt * 1000 + Math.random() * 1000, 300000);
setTimeout(() => deliverWebhook(event, attempt + 1), delay);
}
}
Comparison of Retry Patterns
| Pattern | Pros | Cons |
|---|---|---|
| Immediate retry | Simple, fast for transient glitches | Can overwhelm receiver during outages |
| Fixed interval | Predictable load | May retry too soon or too late |
| Exponential backoff | Reduces load during failures, increases chance of success | Slower recovery for short outages |
| Exponential backoff with jitter | Prevents thundering herd, spreads retries | Slightly more complex to implement |
Testing Your Webhook Implementation
Before going live, simulate failures and verify that retries work as expected. Use tools like webhook.site or request bins to inspect headers and payloads. Also, test signature verification with tampered payloads to ensure unauthorized requests are rejected.
FAQ
What is a signed webhook payload?
A signed payload includes a cryptographic signature (usually HMAC) generated with a shared secret. It allows the receiver to verify that the request came from a trusted source and that the payload hasn't been altered.
How many times should I retry a failed webhook?
There's no universal number, but a common approach is up to 10 attempts with exponential backoff. After that, move the event to a dead-letter queue for manual review. Adjust based on your tolerance for delay and the criticality of the event.
Can I use webhooks without HTTPS?
No. Webhooks should always use HTTPS to encrypt the payload in transit and prevent eavesdropping or man-in-the-middle attacks. Using HTTP exposes sensitive data and signatures.
Ready to test your webhook payloads? Use our JSON Formatter to pretty-print and validate JSON payloads before sending them.