Definition
Imagine you are waiting for a package. You could check the tracking page every hour (polling), or you could sign up for delivery notifications that text you when the package arrives. Webhooks are that notification system for APIs - instead of your application constantly asking “did anything happen yet?”, the other service proactively tells you when something interesting occurs.
In technical terms, a webhook is an HTTP callback: when an event happens in one system, that system makes an HTTP POST request to a URL you specified, delivering data about the event. You register your URL (“call this endpoint when someone makes a payment”), and the provider calls it automatically when the event occurs. It is the inverse of the normal API pattern where you call them.
This approach is dramatically more efficient than polling. Instead of making thousands of requests that mostly return “nope, nothing new,” you only process events when they actually happen. For integrations with payment processors, notification services, CI/CD pipelines, and countless other systems, webhooks are the standard pattern. They enable real-time reactions to events without the overhead of constant checking.
Example
Payment notifications: When a customer completes a payment on Stripe, Stripe sends a webhook to your server with all the payment details. You use this to fulfill orders, send confirmation emails, and update your database - all triggered automatically the moment payment succeeds.
GitHub CI/CD: When you push code to GitHub, a webhook notifies your CI system (Jenkins, CircleCI, etc.) to start building and testing. The build starts immediately without the CI system needing to constantly poll GitHub.
Slack integrations: When something happens in your app (new signup, error alert, sale completed), you can send a webhook to Slack to post a message automatically. This powers all those “New sale: $99 from Alice!” notifications in company Slack channels.
E-commerce shipping updates: Shipping carriers like FedEx and UPS offer webhooks. When a package status changes (shipped, in transit, delivered), they notify your system, which can then notify your customers.
Analogy
The Doorbell Notification: Instead of constantly checking your front door for visitors (polling), a doorbell rings when someone arrives (webhook). You only respond when there is actually someone there. Webhooks are doorbells for your applications.
The Emergency Alert System: Your phone does not check for emergency alerts every second. Instead, the alert system pushes notifications when emergencies happen. Webhooks follow this push model - you receive information when it is available.
The Newspaper Subscription: Instead of going to the newsstand every morning to check if the paper arrived (polling), you have it delivered to your door (webhook). The delivery happens automatically when there is something new.
The Fire Alarm: A fire alarm does not require you to periodically check for fires. It monitors continuously and alerts you immediately when smoke is detected. Webhooks create similar instant alerting for digital events.
Code Example
// Registering a webhook
POST /api/webhooks
{
"url": "https://myapp.com/webhooks/payment",
"events": ["payment.completed", "payment.failed"]
}
// Receiving webhook (Express.js)
app.post('/webhooks/payment', (req, res) => {
const event = req.body;
// Verify signature for security
const signature = req.headers['x-webhook-signature'];
if (!verifySignature(event, signature, secret)) {
return res.status(401).send('Invalid signature');
}
// Process event
if (event.type === 'payment.completed') {
processPayment(event.data);
}
// Acknowledge receipt
res.status(200).send('OK');
});
// Webhook payload example
{
"id": "evt_123",
"type": "payment.completed",
"created": 1609459200,
"data": {
"amount": 1000,
"currency": "usd",
"customer": "cus_123"
}
}
Diagram
sequenceDiagram participant Client participant Provider Client->>Provider: POST /webhooks Provider->>Client: 201 Created + secret Provider->>Provider: Event occurs Provider->>Client: POST callback + signature Client->>Client: Verify signature Client->>Provider: 200 OK Provider--xClient: Delivery fails Provider->>Client: Retry with backoff
Security Notes
CRITICAL: Webhooks are HTTP callbacks. Implement secure delivery and verification.
Webhook Fundamentals:
- HTTP callback: Server calls client via HTTP
- Event-driven: Triggered by events on server
- Asynchronous: Client doesn’t wait for response
- Real-time: Near-real-time notification
- Push model: Server pushes to client (vs pulling)
Security:
- HTTPS mandatory: Always use HTTPS for webhooks
- Signature verification: Sign webhook payload
- Token validation: Include authorization token
- Rate limiting: Limit webhook requests
- Timeout: Timeout slow webhook handlers
- Retry logic: Implement exponential backoff
Signature Verification:
- Shared secret: Server and client share secret
- HMAC signature: Sign payload with shared secret
- Verify signature: Client verifies signature before processing
- Timestamp: Include timestamp to prevent replay
- Request body: Sign entire request body
Reliability:
- Delivery guarantees: At-least-once or exactly-once
- Retry logic: Retry failed deliveries
- Exponential backoff: Increase delay between retries
- Dead letter queue: Queue failed deliveries
- Monitoring: Monitor delivery failures
Scaling & Performance:
- Async processing: Don’t block webhook handling
- Queue system: Queue webhooks for processing
- Batch webhooks: Batch multiple events
- Circuit breaker: Stop delivering if endpoint down
- Health checks: Monitor webhook endpoint health
Best Practices:
- Document format: Clear webhook payload format
- Version webhooks: Version webhook format
- Event types: Clear event type documentation
- Retry policy: Document retry behavior
- Timeout: Implement appropriate timeouts
- Logging: Log all webhook activity
Best Practices
- Always verify webhook signatures using HMAC-SHA256 or similar
- Use HTTPS endpoints only - never accept webhooks over HTTP
- Implement idempotency using event IDs to handle duplicate deliveries
- Return 200 OK immediately, process payload asynchronously via queue
- Store webhook secrets securely (environment variables, secrets manager)
- Implement proper retry handling with exponential backoff
Common Mistakes
Not validating webhook signatures (security risk), processing webhooks synchronously causing timeouts, not handling duplicate deliveries (no idempotency), exposing HTTP endpoints, returning non-2xx before processing completion, not logging failed webhooks for debugging, hardcoding webhook secrets in code.