Webhooks
Webhooks are a way for a server to notify a client automatically when an event occurs or an asynchronous task completes. Instead of polling, the server calls a client-provided URL.
How Webhooks Work
- Client registers a webhook:
POST /api/webhooks
Content-Type: application/json
{
"event": "report.completed",
"callbackUrl": "https://client.com/webhook/reports"
}
-
Server processes the task asynchronously.
-
When task completes, server sends a POST request to the client’s callback URL:
POST https://client.com/webhook/reports
Content-Type: application/json
{
"taskId": "789",
"status": "completed",
"resultUrl": "/api/reports/789/download"
}
- Client processes the webhook and fetches the result if needed.
Advantages of Webhooks
- No need for polling → reduces network traffic.
- Real-time notifications → better user experience.
- Scales better → server pushes updates only when needed.
Combining Async Processing & Webhooks
- Async processing handles long-running tasks.
- Webhooks notify clients when tasks are complete.
Flow Example:
Client -> POST /api/reports -> Server returns 202 + taskId
Server queues task -> background worker processes task
Task completes -> Server calls client webhook
Client receives webhook -> Downloads result
Generating a Report
- Client requests report generation
POST /api/reports
Content-Type: application/json
{
"reportType": "monthly_sales",
"format": "pdf",
"webhookUrl": "https://client.com/webhook/reports"
}
- Server responds immediately
HTTP/1.1 202 Accepted
Content-Type: application/json
{
"taskId": "1010",
"status": "pending"
}
-
Server processes task in background
-
Server sends webhook when done
POST https://client.com/webhook/reports
Content-Type: application/json
{
"taskId": "1010",
"status": "completed",
"resultUrl": "/api/reports/1010/download"
}
- Client downloads report
GET /api/reports/1010/download
Best Practices for Async & Webhooks
- Idempotency: Webhooks may be delivered multiple times. Clients should handle duplicates.
- Retries: Servers should retry webhooks if the client endpoint fails.
- Security: Validate webhook payloads using signatures or tokens.
- Status endpoints: Always provide a /status URL even if webhooks are used.
- Queue management: Use scalable queue systems to handle spikes in async tasks.