Webhooks Explained: Signed Payloads and Reliable Retries
You've built an API, and now you need to notify other systems when events happen. You set up a webhook endpoint, but soon you face problems: how do you ensure the receiver knows the request came from you? What happens if their server is down? Without proper safeguards, webhooks can become a source of security vulnerabilities and lost data. This article explains how to design webhooks with signed payloads and reliable retries, so you can build integrations that are both secure and resilient.
What Are Webhooks and Why They Need Security
Webhooks are user-defined HTTP callbacks. When an event occurs in your system, you send an HTTP POST request to a URL provided by the receiver. This is a simple way to achieve real-time communication between services. However, because the receiver exposes a public endpoint, anyone can send requests to it. Without verification, an attacker could forge events, leading to unauthorized actions or data corruption. Additionally, network issues or receiver downtime can cause missed events. Therefore, two critical aspects must be addressed: authenticity (via signed payloads) and reliability (via retries).
Securing Webhooks with Signed Payloads
A signed payload allows the receiver to verify that the request originated from your service and that the payload hasn't been tampered with. The standard approach is to use HMAC (Hash-based Message Authentication Code) with a shared secret.
How HMAC Signing Works
You and the receiver share a secret key. For each webhook request, you compute an HMAC of the request body using the secret and include it in a header (e.g., X-Signature). The receiver recomputes the HMAC and compares it to the header value. If they match, the request is authentic.
// Node.js example: generating a signature
const crypto = require('crypto');
const secret = 'your_shared_secret';
const payload = JSON.stringify({ event: 'user.created', data: { id: 123 } });
const signature = crypto.createHmac('sha256', secret).update(payload).digest('hex');
// Send payload with header: X-Signature: signature
The receiver must use the raw request body to compute the HMAC, not a parsed version, to avoid discrepancies.
Best Practices for Signed Payloads
- Use a strong secret: Generate a random, high-entropy secret and store it securely.
- Include a timestamp: Add a timestamp to the signed payload to prevent replay attacks. The receiver should reject requests with timestamps too far from the current time.
- Use constant-time comparison: When comparing signatures, use a constant-time algorithm to prevent timing attacks.
- Rotate secrets periodically: Allow for secret rotation without downtime by supporting multiple active secrets.
Implementing Reliable Retries
Even with signed payloads, network failures or receiver errors can cause webhook delivery to fail. A robust retry mechanism ensures that events are eventually delivered.
Retry Strategy
The most common approach is exponential backoff with jitter. This means you retry after increasing delays, adding randomness to avoid thundering herds. For example: retry after 1 minute, then 5 minutes, then 30 minutes, up to a maximum number of attempts (e.g., 5). After that, you might mark the webhook as failed and alert the receiver.
Handling Responses
The receiver should return a 2xx status code to acknowledge successful processing. Any other status code (including 3xx) should be treated as a failure and trigger a retry. However, be cautious: some errors are permanent (e.g., 400 Bad Request due to malformed payload) and retrying won't help. You can define which status codes are retryable.
Idempotency
Because retries can cause duplicate deliveries, the receiver must handle events idempotently. Include a unique event ID in the payload and have the receiver track processed IDs to avoid double processing.
Example Retry Logic (Pseudo-code)
function sendWebhook(url, payload, attempt = 1) {
const maxAttempts = 5;
const delay = Math.min(60 * 1000 * Math.pow(2, attempt - 1), 3600 * 1000); // 1min, 2min, 4min...
fetch(url, { method: 'POST', body: payload, headers: { 'X-Signature': sign(payload) } })
.then(response => {
if (response.ok) return;
if (attempt < maxAttempts) {
setTimeout(() => sendWebhook(url, payload, attempt + 1), delay + Math.random() * 1000);
} else {
// log failure, notify
}
})
.catch(error => {
if (attempt < maxAttempts) {
setTimeout(() => sendWebhook(url, payload, attempt + 1), delay + Math.random() * 1000);
} else {
// log failure
}
});
}
Comparison: Signed Payloads vs. Retries
| Aspect | Signed Payloads | Retries |
|---|---|---|
| Purpose | Authenticity and integrity | Reliability and delivery guarantee |
| Key Mechanism | HMAC with shared secret | Exponential backoff with jitter |
| Receiver Responsibility | Verify signature, check timestamp | Return 2xx, handle idempotency |
| Common Pitfalls | Using parsed body, weak secrets | Infinite retries, ignoring permanent errors |
Putting It All Together
When implementing webhooks, follow these steps:
- Generate a secret for each receiver and share it securely.
- Sign each payload with HMAC-SHA256, including a timestamp.
- Send the webhook with the signature in a header.
- Implement retries with exponential backoff and jitter.
- Log delivery attempts and provide a way to manually retry or view logs.
- Document the expected behavior for receivers, including idempotency requirements.
By combining signed payloads and smart retries, you build a webhook system that is both secure and dependable.
FAQ
How do I verify a webhook signature?
Compute the HMAC of the raw request body using your shared secret and compare it to the signature header using a constant-time comparison function.
What should I do if a webhook fails after all retries?
Log the failure and notify the receiver through an alternative channel (e.g., email or dashboard). Provide a way for them to manually trigger a retry or fetch missed events via an API.
Can I use JWT instead of HMAC for webhook signatures?
Yes, JWT can be used, but it adds complexity. HMAC is simpler and sufficient for most use cases. If you need to include claims or expiration, JWT might be preferable.
Ready to test your webhook payloads? Use our JSON Formatter to validate and pretty-print JSON payloads before sending them.