Webhooks Explained: Signed Payloads and Retries
Why Webhooks Are Hard to Get Right
You've built an API, and now you need to notify other services when events happen. Webhooks seem simple: send an HTTP POST to a URL. But in production, webhooks fail in subtle ways. Receivers go down, networks hiccup, and attackers try to forge requests. Without proper safeguards, your integration becomes unreliable and insecure.
This guide covers two critical aspects of webhooks: securing payloads with signatures and implementing robust retry logic. You'll learn practical patterns to build webhooks that other developers trust.
How Webhooks Work (Briefly)
A webhook is a user-defined HTTP callback. When an event occurs in your system, you send an HTTP request to a URL provided by the consumer. The consumer processes the payload and returns a 2xx status code to acknowledge receipt.
Common examples include payment notifications, CI/CD triggers, and chat messages. The challenge is ensuring the request is authentic and handling delivery failures gracefully.
Securing Webhooks with Signed Payloads
Without verification, anyone can send fake requests to your webhook endpoint. Signing payloads with a shared secret allows the receiver to verify authenticity and integrity.
HMAC Signatures: The Standard Approach
HMAC (Hash-based Message Authentication Code) is the de facto standard. The sender computes a signature using a secret key and the request body, then includes it in a header. The receiver recomputes the signature and compares.
Here's a typical flow:
- Both parties share a secret key (e.g., generated during webhook registration).
- Sender creates the request body (JSON).
- Sender computes HMAC-SHA256 of the body using the secret.
- Sender includes the signature in a header like
X-Signature. - Receiver computes HMAC of the received body and compares using a constant-time function.
Always use a constant-time comparison to prevent timing attacks. In Node.js, use crypto.timingSafeEqual; in Python, hmac.compare_digest.
Example: Signing and Verifying in Node.js
const crypto = require('crypto');
// Sender side
function signPayload(payload, secret) {
return crypto.createHmac('sha256', secret).update(payload).digest('hex');
}
// Receiver side
function verifySignature(payload, signature, secret) {
const expected = signPayload(payload, secret);
return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
}
Include a timestamp in the signed payload to prevent replay attacks. The receiver should reject requests older than a few minutes.
What About Asymmetric Signatures?
HMAC requires sharing a secret. For third-party webhooks where you don't want to share secrets, consider asymmetric signatures (e.g., RSA or ECDSA). The sender signs with a private key, and receivers verify with a public key. This is common in platforms like GitHub (though GitHub uses HMAC for webhooks).
Implementing Reliable Retries
Webhooks are fire-and-forget from the sender's perspective, but networks and receivers are unreliable. You need a retry mechanism to ensure delivery.
Retry Strategy Basics
- Exponential backoff: Wait longer between each retry (e.g., 1s, 5s, 30s, 5m).
- Maximum attempts: Limit retries to avoid infinite loops (e.g., 5 attempts over 24 hours).
- Idempotency: Receivers should handle duplicate deliveries gracefully using an idempotency key.
Most importantly, only retry on transient failures: network errors, timeouts, or 5xx responses. Do not retry on 4xx client errors (except 429 Too Many Requests).
Example: Retry Logic with Exponential Backoff
import time
import requests
def deliver_webhook(url, payload, max_retries=5):
for attempt in range(max_retries):
try:
response = requests.post(url, json=payload, timeout=10)
if response.status_code < 500 and response.status_code != 429:
return True # success or non-retryable error
except requests.RequestException:
pass
time.sleep(2 ** attempt) # exponential backoff
return False
In production, use a queue system (e.g., RabbitMQ, Redis, or a database-backed job queue) to handle retries asynchronously. This decouples delivery from your main application flow.
Handling Duplicates and Ordering
Retries can cause duplicate deliveries. Include a unique event ID in the payload and document that receivers must be idempotent. For ordering, webhooks are generally not ordered; if order matters, include a sequence number or timestamp and let the receiver sort.
Comparison: HMAC vs Asymmetric Signatures
| Aspect | HMAC | Asymmetric (RSA/ECDSA) |
|---|---|---|
| Key management | Shared secret | Public/private key pair |
| Performance | Fast | Slower |
| Use case | First-party integrations | Third-party or public webhooks |
| Replay protection | Requires timestamp | Requires timestamp |
Choose HMAC for simplicity and speed when you control both ends. Use asymmetric signatures when you need to verify without sharing secrets.
Best Practices for Webhook Security and Reliability
- Use HTTPS: Always deliver webhooks over TLS to prevent eavesdropping.
- Validate URLs: When registering webhooks, validate the URL to prevent SSRF attacks.
- Include a user-agent: Identify your service in the User-Agent header.
- Log deliveries: Keep logs of webhook attempts for debugging and auditing.
- Provide a dashboard: Let consumers view and replay failed deliveries.
Testing your webhook endpoint is easier with tools like JSON Formatter to inspect payloads, but always verify signatures in code.
FAQ
What is a signed webhook payload?
A signed payload includes a cryptographic signature (usually HMAC) that allows the receiver to verify the request came from a trusted source and wasn't tampered with.
How many times should I retry a failed webhook?
Common practice is 3–5 retries with exponential backoff over 24 hours. Adjust based on your reliability needs and receiver capabilities.
Can I use webhooks without signatures?
You can, but it's insecure. Without signatures, attackers can forge requests. Always sign webhooks in production.
Ready to build more reliable integrations? Start by formatting and validating your JSON payloads with our JSON Formatter to ensure they're well-formed before signing.