Skip to main content

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

  1. Client registers a webhook:
POST /api/webhooks
Content-Type: application/json

{
"event": "report.completed",
"callbackUrl": "https://client.com/webhook/reports"
}
  1. Server processes the task asynchronously.

  2. 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"
}
  1. 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

  1. Client requests report generation
POST /api/reports
Content-Type: application/json

{
"reportType": "monthly_sales",
"format": "pdf",
"webhookUrl": "https://client.com/webhook/reports"
}
  1. Server responds immediately
HTTP/1.1 202 Accepted
Content-Type: application/json

{
"taskId": "1010",
"status": "pending"
}
  1. Server processes task in background

  2. Server sends webhook when done

POST https://client.com/webhook/reports
Content-Type: application/json

{
"taskId": "1010",
"status": "completed",
"resultUrl": "/api/reports/1010/download"
}
  1. Client downloads report
GET /api/reports/1010/download

Best Practices for Async & Webhooks

  1. Idempotency: Webhooks may be delivered multiple times. Clients should handle duplicates.
  2. Retries: Servers should retry webhooks if the client endpoint fails.
  3. Security: Validate webhook payloads using signatures or tokens.
  4. Status endpoints: Always provide a /status URL even if webhooks are used.
  5. Queue management: Use scalable queue systems to handle spikes in async tasks.