Webhooks Explained: Signed Payloads and Reliable Retries
You've built an API and now need to notify external services when events happen—like a payment succeeding or a user signing up. Polling is inefficient, so you turn to webhooks. But soon you face two critical questions: How do you ensure the payload hasn't been tampered with? and What happens if the receiver is down? This article answers both with practical, production-ready patterns for signed payloads and reliable retries.
What Are Webhooks and Why Sign Them?
Webhooks are user-defined HTTP callbacks triggered by events. Your server sends a POST request to a URL provided by the receiver, containing event data. Unlike APIs where the client initiates requests, webhooks push data in near real-time.
However, because webhooks are publicly accessible endpoints, they are vulnerable to spoofing. An attacker could send fake payloads to your receiver, triggering unintended actions. Signing payloads with a shared secret ensures authenticity and integrity.
How to Sign Webhook Payloads
The standard approach is HMAC (Hash-based Message Authentication Code) with SHA-256. The sender and receiver share a secret key. For each request, the sender computes a signature over the raw request body and includes it in a header (e.g., X-Signature). The receiver recomputes the signature and compares it.
Step-by-Step Implementation
- Generate a secret (e.g., 32 random bytes) and share it securely with the receiver.
- On send, compute
HMAC-SHA256(secret, raw_body)and hex-encode it. - Include the signature in a header, optionally with a timestamp to prevent replay attacks.
- On receive, read the raw body (before JSON parsing), recompute the HMAC, and compare using a constant-time function.
// Node.js example: signing on send
const crypto = require('crypto');
const secret = 'your_shared_secret';
const payload = JSON.stringify({ event: 'payment.success', amount: 100 });
const signature = crypto.createHmac('sha256', secret).update(payload).digest('hex');
// Send POST with header X-Signature: signature
// Verifying on receive (Express middleware)
app.use('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
const signature = req.headers['x-signature'];
const expected = crypto.createHmac('sha256', secret).update(req.body).digest('hex');
if (!crypto.timingSafeEqual(Buffer.from(signature, 'hex'), Buffer.from(expected, 'hex'))) {
return res.status(401).send('Invalid signature');
}
// Process payload
});
Important: Use constant-time comparison to avoid timing attacks. Also, include a timestamp in the signed data to prevent replay attacks—reject requests older than a few minutes.
Designing Reliable Retries
Networks fail, servers restart, and receivers may be temporarily unavailable. A robust webhook system must retry failed deliveries without causing duplicate side effects.
Retry Strategy
- Exponential backoff: Wait longer between each retry (e.g., 1s, 5s, 30s, 5m, 30m).
- Max attempts: Set a limit (e.g., 5 retries) to avoid infinite loops.
- Dead-letter queue: After max attempts, store the event for manual inspection.
- Idempotency: Include a unique event ID in the payload. The receiver should track processed IDs and ignore duplicates.
Example Retry Logic (Pseudocode)
function sendWebhook(url, payload, attempt = 1) {
const maxAttempts = 5;
const delay = Math.min(1000 * 2 ** attempt, 30000); // up to 30s
fetch(url, { method: 'POST', body: payload, headers: { 'X-Signature': sign(payload) } })
.then(res => {
if (!res.ok && attempt < maxAttempts) {
setTimeout(() => sendWebhook(url, payload, attempt + 1), delay);
}
})
.catch(() => {
if (attempt < maxAttempts) {
setTimeout(() => sendWebhook(url, payload, attempt + 1), delay);
}
});
}
In production, use a job queue (like Redis-based Bull or RabbitMQ) to manage retries asynchronously and avoid blocking your main process.
Best Practices for Webhook Security and Reliability
| Practice | Why It Matters |
|---|---|
| Sign payloads with HMAC | Prevents tampering and spoofing |
| Use HTTPS | Encrypts data in transit |
| Include timestamp | Mitigates replay attacks |
| Idempotent receivers | Avoids duplicate processing |
| Retry with backoff | Handles transient failures gracefully |
| Log all attempts | Aids debugging and auditing |
FAQ
How do I verify a webhook signature?
Compute the HMAC of the raw request body using the shared secret and compare it to the signature header using a constant-time comparison function. Reject if they don't match.
What should I do if a webhook fails after multiple retries?
Move the event to a dead-letter queue for manual review. Alert your team and provide a way to manually re-trigger the webhook.
Can I use webhooks without signing payloads?
It's risky. Without signatures, anyone can send fake requests to your endpoint. Always sign payloads in production to ensure authenticity.
When debugging webhook payloads, you'll often work with JSON data. Use our JSON formatter to pretty-print and validate payloads quickly.