Webhooks for AI Services
From the course AI Webhooks & Event-Driven Pipelines
Implementing Webhooks
Receiving Webhooks
// Edge function to receive webhook callbacks
Deno.serve(async (req) => {
// Verify webhook signature
const signature = req.headers.get("x-webhook-signature");
const body = await req.text();
if (!verifySignature(body, signature, WEBHOOK_SECRET)) {
return new Response("Unauthorized", { status: 401 });
}
const event = JSON.parse(body);
switch (event.type) {
case "transcription.completed":
await handleTranscriptionComplete(event.data);
break;
case "image.analyzed":
await handleImageAnalyzed(event.data);
break;
case "batch.finished":
await handleBatchComplete(event.data);
break;
}
return new Response("OK", { status: 200 });
});
Sending Webhooks
async function sendWebhook(url: string, payload: any) {
const body = JSON.stringify(payload);
const signature = createHmac("sha256", WEBHOOK_SECRET)
.update(body)
.digest("hex");
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Webhook-Signature": signature,
},
body,
});
if (!response.ok) {
// Queue for retry
await queueRetry(url, payload, response.status);
}
}
Security Best Practices
- Signature verification: Always verify HMAC signatures
- IP allowlisting: Restrict webhook sources when possible
- Idempotency: Handle duplicate deliveries gracefully
- Timeout handling: Respond within 5 seconds, process async
- HTTPS only: Never accept webhooks over plain HTTP
Common Pitfall: Returning 500 Errors on Business Logic Failures
If your webhook handler throws an exception while processing a valid webhook, most providers will retry the delivery. This causes the same event to be processed multiple times. Only return 5xx errors for infrastructure failures — for business logic errors (e.g., "user not found"), return 200 to acknowledge receipt and handle the error asynchronously:
Deno.serve(async (req) => {
const event = await req.json();
// Always acknowledge first — process asynchronously
processEvent(event).catch(error => {
console.error("Event processing failed:", error, event);
alertOnCall({ event, error }); // Alert, don't retry
});
return new Response("OK", { status: 200 }); // Respond immediately
});
Best Practice: Use Webhook Idempotency Keys
Most webhook providers include an event ID in the payload. Store processed event IDs to prevent duplicate processing:
async function handleWebhookEvent(event: WebhookEvent) {
const alreadyProcessed = await redis.sismember("processed_events", event.id);
if (alreadyProcessed) {
console.log(`Skipping duplicate event: ${event.id}`);
return;
}
await processEvent(event);
await redis.sadd("processed_events", event.id);
await redis.expire("processed_events", 86400); // Prune after 24h
}
Named Product Reference: Svix for Managed Webhooks
Svix is a managed webhook delivery service that handles signature generation, retry logic, rate limiting, and a developer portal where API consumers can inspect and replay webhook deliveries. If your product needs to send webhooks to your customers' applications, Svix eliminates the need to build delivery infrastructure — integrate the Svix SDK and it handles the rest.
Key Takeaways
- •Verify webhook signatures with HMAC to prevent spoofing
- •Process webhook payloads asynchronously — respond fast
- •Handle duplicate deliveries with idempotency keys
- •Queue failed webhook deliveries for retry
Progress is kept in this browser only.