Prompt
How do I build an API with webhook support and retries?
Latest observation
To build an API with webhook support and retries, you need two main pieces:
- Your API publishes events
- Your system delivers those events reliably to subscribers’ webhook URLs
A good design treats webhooks as an asynchronous delivery system, not a direct part of the request that triggered the event.
1) Basic architecture
Flow
- A user action happens in your API, like
order.created - Your system stores the event in a database
- A background worker reads pending events
- The worker sends an HTTP POST to each subscriber’s webhook URL
- If delivery fails, retry with backoff
- Mark delivery as succeeded or permanently failed after max attempts
Core components
- Event store: records what happened
- Subscription store: stores webhook endpoints and event filters
- Delivery queue/worker: sends webhook requests asynchronously
- Retry logic: handles transient failures
- Signing/authentication: lets receivers verify requests
- Delivery logs: help debugging and support
2) Data model
A simple schema might include:
webhook_subscriptions
idcustomer_idurlevents(list of event types subscribed to)secretactivecreated_atupdated_at
webhook_events
idevent_typepayloadcreated_at
webhook_deliveries
idevent_idsubscription_idattempt_countstatus(pending,delivered,failed)next_retry_atlast_response_codelast_errorcreated_atupdated_at
This lets you track each event delivery independently.
3) Webhook request format
Use a consistent JSON body:
{
"id": "evt_123",
"type": "order.created",
"created_at": "2026-10-22T10:00:00Z",
"data": {
"order_id": "ord_456",
"amount": 1999,
"currency": "USD"
}
}
Include:
- unique event ID
- event type
- timestamp
- payload data
4) Send webhooks asynchronously
Never make webhook delivery part of the main user request path. If you do, your API becomes slow and unreliable.
Recommended pattern
- API request completes quickly
- Emit event to DB/queue
- Worker sends webhook in the background
Common tools:
- Queue: RabbitMQ, SQS, Redis Queue, Kafka, Sidekiq, Celery, BullMQ
- Worker: any background job runner
5) Retry strategy
Retries should happen for transient failures only.
Retry on:
- network timeouts
- DNS failures
- connection errors
- HTTP 408
- HTTP 429
- HTTP 500, 502, 503, 504
Do not retry on:
- HTTP 400, 401, 403, 404, 422
- invalid URL
- permanently rejected requests
Retry policy example
- attempt 1 immediately
- attempt 2 after 1 minute
- attempt 3 after 5 minutes
- attempt 4 after 30 minutes
- attempt 5 after 2 hours
- then mark as failed
Use exponential backoff with jitter to avoid retry storms.
Example formula:
delay = min(base * 2^attempt, max_delay) + random_jitter
6) Make deliveries idempotent
Webhooks can be delivered more than once due to retries, so receivers must be able to safely handle duplicates.
Include an idempotency key
Add headers like:
Webhook-Event-Id: evt_123Webhook-Attempt: 3
The receiver should store processed event IDs and ignore duplicates.
7) Sign webhook requests
To prevent spoofing, sign each request body with a shared secret.
Example approach
- Concatenate timestamp + raw body
- Compute HMAC SHA-256 using the subscriber secret
- Send signature in a header
Example headers:
X-Webhook-TimestampX-Webhook-Signature
The receiver verifies the signature before processing.
Pseudocode
signature = HMAC_SHA256(secret, timestamp + "." + raw_body)
This protects against tampering and replay attacks.
8) Handle timeouts
Webhook endpoints should respond quickly.
Recommendations
- connect timeout: 3–5 seconds
- read timeout: 5–10 seconds
- total timeout: 10–15 seconds max
If the receiver doesn’t respond in time, treat it as a failure and retry.
9) Delivery worker logic
Pseudo-flow:
for each pending delivery:
send POST request with event payload
if response 2xx:
mark delivered
else if retryable:
schedule retry with backoff
else:
mark failed
Important details
- limit concurrent requests per subscriber
- use circuit breakers for failing endpoints
- stop after max retries
- preserve response details for debugging
10) Rate limiting and backpressure
Some webhook endpoints may be slow or overloaded.
To protect your system:
- rate limit deliveries per customer or endpoint
- queue events instead of sending synchronously
- cap worker concurrency
- pause endpoints that consistently fail
You may also want to implement a dead-letter queue for permanently failed deliveries.
11) Observability
Expose delivery status in your dashboard or API:
- event ID
- webhook ID
- last attempt time
- response code
- error message
- next retry time
- total attempts
This makes support and debugging much easier.
12) Minimal API endpoints
A simple webhook management API might include:
Create subscription
POST /webhooks/subscriptions
List subscriptions
GET /webhooks/subscriptions
Update subscription
PATCH /webhooks/subscriptions/{id}
Delete subscription
DELETE /webhooks/subscriptions/{id}
View delivery attempts
GET /webhooks/deliveries?subscription_id=...
Test webhook
POST /webhooks/subscriptions/{id}/test
13) Example implementation outline
On event creation
def create_order(order_data):
order = save_order(order_data)
event = save_event("order.created", {"order_id": order.id})
subscriptions = get_matching_subscriptions("order.created")
for sub in subscriptions:
create_delivery(event.id, sub.id)
enqueue_delivery_job(event.id, sub.id)
return order
Delivery worker
def deliver_webhook(event_id, subscription_id):
event = load_event(event_id)
sub = load_subscription(subscription_id)
body = json.dumps({
"id": event.id,
"type": event.type,
"created_at": event.created_at,
"data": event.payload
})
timestamp = now_iso8601()
signature = sign(sub.secret, timestamp + "." + body)
response = http_post(
url=sub.url,
headers={
"Content-Type": "application/json",
"X-Webhook-Timestamp": timestamp,
"X-Webhook-Signature": signature,
"Webhook-Event-Id": event.id
},
body=body,
timeout=10
)
if 200 <= response.status_code < 300:
mark_delivered()
elif is_retryable(response.status_code):
schedule_retry()
else:
mark_failed()
14) Best practices checklist
- Deliver webhooks asynchronously
- Store events and delivery attempts
- Retry only retryable failures
- Use exponential backoff with jitter
- Sign requests with HMAC
- Include event IDs for idempotency
- Set strict timeouts
- Provide delivery logs and status
- Support manual redelivery
- Rate limit and isolate bad endpoints
15) If you want a quick tech stack recommendation
A common setup:
- API: Node.js/Express, FastAPI, Django, Go, or Rails
- Queue: SQS or RabbitMQ
- Worker: Celery / Sidekiq / BullMQ / custom worker
- DB: PostgreSQL
- HTTP client: axios / requests / net/http / faraday
- Signing: HMAC SHA-256
If you want, I can also provide:
- a full example in Node.js, Python, or Go
- a database schema
- a retry algorithm with code
- a webhook receiver example