Webhooks Explained: Signed Payloads and Retries
You've built an API and now need to notify other services when events happen. You could have them poll your API, but that's inefficient. Webhooks solve this by pushing events to subscribers in real-time. However, naive webhook implementations often suffer from security vulnerabilities and unreliable delivery. This guide explains how to implement webhooks correctly using signed payloads and retries.
What Are Webhooks?
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 subscriber. The request body typically contains event data in JSON format. This allows subscribers to react immediately without polling.
But webhooks introduce challenges: how do you ensure the request came from you? How do you handle failures? Let's tackle these with signed payloads and retries.
Why Sign Webhook Payloads?
Without signatures, anyone can send fake events to your subscribers. They might trigger unintended actions, corrupt data, or cause security incidents. Signing payloads with a shared secret allows subscribers to verify authenticity and integrity.
We use HMAC (Hash-based Message Authentication Code) with SHA-256. The sender and receiver share a secret key. The sender computes a signature over the payload and includes it in a header. The receiver recomputes the signature and compares.
Generating the Signature
Here's how to generate an HMAC signature in Python:
import hmac
import hashlib
import json
def sign_payload(payload, secret):
body = json.dumps(payload, separators=(',', ':')).encode('utf-8')
signature = hmac.new(secret.encode('utf-8'), body, hashlib.sha256).hexdigest()
return signature
Include the signature in a header like X-Signature. Also include a timestamp to prevent replay attacks.
Verifying the Signature
On the receiving end, verify the signature before processing:
def verify_signature(request_body, secret, received_signature):
expected = hmac.new(secret.encode('utf-8'), request_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, received_signature)
Use hmac.compare_digest to prevent timing attacks. Always verify the timestamp to reject old requests.
Implementing Retries for Failed Deliveries
Webhook endpoints can fail: network issues, server downtime, or bugs. A robust system must retry failed deliveries. But retries need careful design to avoid overwhelming the receiver.
Retry Strategy
- Exponential backoff: Wait longer between each retry (e.g., 1s, 5s, 30s, 5m, 30m).
- Maximum attempts: Limit retries (e.g., 5 attempts) to avoid infinite loops.
- Dead-letter queue: After max attempts, store the event for manual inspection.
- Idempotency: Include a unique event ID so receivers can deduplicate.
Example Retry Logic
Use a background job system like Celery or Sidekiq. Here's a simplified Python example using requests and tenacity:
import requests
from tenacity import retry, stop_after_attempt, wait_exponential
@retry(stop=stop_after_attempt(5), wait=wait_exponential(multiplier=1, min=1, max=60))
def deliver_webhook(url, payload, signature):
headers = {'X-Signature': signature, 'Content-Type': 'application/json'}
response = requests.post(url, json=payload, headers=headers, timeout=10)
response.raise_for_status()
return response
This retries on failure with exponential backoff. In production, use a persistent queue to avoid losing events on crash.
Best Practices for Webhook Security
- Use HTTPS: Always deliver webhooks over TLS to prevent eavesdropping.
- Rotate secrets: Allow subscribers to rotate secrets periodically.
- Validate timestamp: Reject requests older than a few minutes to prevent replay attacks.
- Log deliveries: Keep logs for debugging and auditing.
Comparison: Signed vs Unsigned Webhooks
| Aspect | Unsigned | Signed |
|---|---|---|
| Security | Anyone can spoof | Only holder of secret can sign |
| Integrity | Payload can be tampered | Tampering breaks signature |
| Implementation | Simple | Requires HMAC logic |
FAQ
How do I handle duplicate webhook deliveries?
Include a unique event ID in the payload and have receivers track processed IDs to ignore duplicates.
What should I do if my webhook endpoint is down?
The sender should retry with exponential backoff. Ensure your endpoint returns a 2xx status quickly to acknowledge receipt.
Can I use JWT instead of HMAC for webhook signatures?
Yes, but HMAC is simpler and sufficient for most cases. JWT adds structure but requires more complex verification.
When debugging webhook payloads, use the JSON formatter to pretty-print and inspect the data.