Introduction to Webhooks
In this tutorial, you will learn about Introduction to Webhooks. We cover key concepts, practical examples, and best practices to help you master this topic.
Webhooks are user-defined HTTP callbacks that enable real-time event-driven communication by having servers send HTTP POST requests to registered URLs when specific events occur, replacing polling.
What You Learn
You will learn what webhooks are, how they differ from traditional APIs and polling, their architecture and lifecycle, common use cases, and when to choose webhooks over other real-time communication patterns.
Why It Matters
Webhooks power modern event-driven systems. Payment providers use them for Transaction updates, CI/CD tools for build notifications, and messaging platforms for real-time delivery. Understanding webhooks is essential for building integrations in todays API ecosystem.
Real-World Use
DodaTech's Durga Antivirus Pro uses webhooks to notify enterprise dashboards when threats are detected. Instead of the dashboard polling every 5 seconds, the antivirus sends a Webhook instantly when a new signature matches, reducing detection-to-notification latency from 5 seconds to under 100ms.
What Is a Webhook?
A webhook is an HTTP callback triggered by an event. You register a URL with a provider. When the provider detects an event, it sends an HTTP POST request to your URL with a payload describing the event.
graph LR
Provider[Provider/Server] -->|Event occurs| Trigger{Trigger webhook}
Trigger -->|POST /your-url| Consumer[Your Server]
Consumer -->|200 OK| Provider
The provider sends data. Your server receives it. You Process it. You respond with 200 OK to acknowledge receipt.
Webhooks vs APIs
// Polling: client asks repeatedly
async function checkPayments() {
while (true) {
const payments = await fetch('/api/payments?status=pending');
const data = await payments.json();
if (data.length > 0) processPayments(data);
await sleep(5000); // Wait 5 seconds
}
}
// Webhook: server notifies you
// Step 1: Register your webhook URL with the provider
const webhookUrl = 'https://myserver.com/webhooks/payments';
// Step 2: Provider sends POST when a payment is created
// POST /webhooks/payments
// Body: { event: "payment.completed", data: { id: 123, amount: 50 } }
// Step 3: You process the webhook
app.post('/webhooks/payments', (req, res) => {
const { event, data } = req.body;
if (event === 'payment.completed') {
updateOrderStatus(data.id, 'paid');
}
res.status(200).send('OK');
});
Expected output: Polling checks every 5 seconds and may miss delays. Webhooks notify instantly. The provider sends the webhook within 100ms of the event. Your server processes it immediately.
Webhook Lifecycle
graph TD
Register[Register webhook URL] --> Event[Event occurs]
Event --> Build[Build payload]
Build --> Sign[Sign payload with HMAC]
Sign --> POST[POST to consumer URL]
POST --> Response{Response?}
Response -->|200 OK| Done[Done - acknowledged]
Response -->|4xx/5xx| Retry[Retry with backoff]
Retry --> Max{Max retries?}
Max -->|No| POST
Max -->|Yes| Dead[Dead letter queue]
Each step matters. Registration tells the provider where to send. Signing verifies authenticity. Retries handle temporary failures. Dead letter queues capture permanent failures.
Common Webhook Events
// Payment provider webhooks
const paymentEvents = {
'payment.intent.created': { /* ... */ },
'payment.intent.succeeded': { /* ... */ },
'payment.intent.failed': { /* ... */ },
'charge.refunded': { /* ... */ },
'subscription.renewed': { /* ... */ },
};
// GitHub webhooks
const githubEvents = {
'push': { /* commit pushed to repo */ },
'pull_request': { /* PR opened/closed/merged */ },
'issues': { /* issue created/updated */ },
'release': { /* release published */ },
};
// Stripe webhooks
const stripeEvents = {
'checkout.session.completed': { /* payment done */ },
'customer.subscription.updated': { /* plan change */ },
'invoice.paid': { /* invoice settled */ },
'charge.dispute.created': { /* customer disputed */ },
};
Expected output: Each provider defines its own event types. The webhook payload includes the event type, timestamp, and relevant data. Your handler uses the event type to decide processing logic.
When to Use Webhooks
Use webhooks when: you need real-time notification, you want to avoid polling costs, the event frequency is unpredictable, the provider supports it, and you can expose a public endpoint.
Avoid webhooks when: you need guaranteed delivery in order, you cannot expose a public endpoint, the consumer is offline, or you need bidirectional streaming.
Common Mistakes
1. Not Returning 200 Quickly
If your webhook handler does database queries or external API calls before responding, the provider times out and retries unnecessarily. Acknowledge immediately, process later.
2. No Payload Verification
Without signature verification, anyone can send fake webhooks to your endpoint. Always verify HMAC signatures before processing the payload.
3. Assuming Ordered Delivery
Most providers do not guarantee webhook order. Network issues or retries can deliver event 2 before event 1. Handle out-of-order delivery with idempotency keys.
4. Blocking on Downstream Services
If your webhook handler calls an external API that is slow, all webhooks queue behind it. Use async processing: acknowledge immediately, queue the work, process in the background.
5. No Logging
Without logging, debugging webhook failures is impossible. Log every incoming webhook: headers, payload, processing result, and response time.
Practice Questions
1. What is the main difference between webhooks and polling?
Polling requires the client to repeatedly check for new data. Webhooks have the server push data when an event occurs. Webhooks are more efficient and real-time.
2. Why must webhook handlers return 200 quickly?
Providers have timeouts (usually 5-30 seconds). Slow responses trigger retries. Return 200 immediately after validating the payload. Process the event asynchronously.
3. What is a webhook payload?
The data body sent in the POST request. It typically contains the event type, timestamp, and event-specific data. Format varies by provider: JSON, XML, or form-encoded.
4. Can webhooks guarantee delivery order?
Rarely. Network delays, retries, and multi-server architectures mean events may arrive out of order. Design your system to reorder events or tolerate out-of-order delivery.
Challenge
Design a webhook system for a file upload service. Define the events (file.uploaded, file.processed, file.error), payload structure for each, retry policy (3 retries with exponential backoff), and signature scheme (HMAC-SHA256). Document the registration API endpoint.
FAQ
Mini Project: Webhook Echo Server
Build a webhook echo server that: accepts POST requests at /webhook, logs the request headers and body, returns 200 OK immediately, stores the last 100 webhooks in memory, provides GET /webhooks to view received webhooks, and GET /webhooks/:id for a single webhook detail.
What's Next
Now that you understand webhook basics, compare Webhooks vs Polling to choose the right pattern for your use case, then explore the complete webhook flow.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro