DEV Community

Sangmin Lee
Sangmin Lee

Posted on • Originally published at claudeguide.io

Claude API Webhook Integration: Async Patterns and Event-Driven AI

Originally published at claudeguide.io/claude-api-webhook-integration

Claude API Webhook Integration: Async Patterns and Event-Driven AI

To use Claude API with webhooks, your server receives an inbound HTTP POST from an external service, queues or immediately calls the Claude API with the extracted payload, then posts the result to a callback URL or stores it for the requester to poll. The pattern has two variants: synchronous (respond within the webhook's timeout window, typically 5–30 seconds) and asynchronous (acknowledge the webhook instantly with HTTP 200, process Claude in the background, push results later). For anything beyond simple one-line completions, the async pattern is more robust and avoids webhook timeout failures.

This guide covers both patterns with production-ready code in Python (FastAPI) and Node.js (Express), plus error handling, retries, rate-limit awareness, and payload security.


Why Webhooks for Claude API?

Most Claude API tutorials show synchronous request-response: send a prompt, wait for the reply. That works for user-facing chat. It breaks for event-driven architectures.

Consider these real scenarios:

  • GitHub event → label a pull request using Claude → post comment
  • Stripe payment → generate a personalized onboarding email body via Claude → send via Loops
  • Typeform submission → Claude scores a lead and writes a CRM note → update HubSpot
  • Slack message → route to Claude for classification → trigger downstream automation

In each case, an external service calls your endpoint when something happens. You do not control the timing. The upstream service typically expects an HTTP 200 within 5–10 seconds or it retries. Claude API calls can take 1–15 seconds depending on model and output length. The mismatch creates timeout failures at scale.

The solution is an async webhook architecture: acknowledge fast, process separately.

For how webhooks fit into broader production designs, see Claude API Production Architecture.


Pattern 1: Inbound Webhook → Claude Processing → Outbound Response

The simplest viable pattern for latency-tolerant webhooks:

External Service  →  Your Webhook Endpoint
                           ↓ (async, background task)
                      Claude API Call
                           ↓
                      Outbound POST to callback_url
                      (or write to DB / queue)
Enter fullscreen mode Exit fullscreen mode

When to use: The webhook sender either (a) supports a callback_url for async results, (b) does not require a meaningful response body, or (c) your Claude call reliably completes within the sender's timeout window.

Key properties:

  • Return HTTP 200/202 immediately to acknowledge receipt
  • Move Claude processing off the request thread
  • Write results to persistent storage or push to a callback URL
  • Idempotency key (usually the webhook's event ID) prevents double-processing on retries

Pattern 2: Async Job Queue with Claude

For high-throughput or mission-critical pipelines, add a proper queue between the webhook receiver and the Claude API call:

Webhook Endpoint  →  Enqueue job (Redis / SQS / database)  →  HTTP 202
                           ↓ (worker process, separate)
                      Dequeue + Call Claude API
                           ↓
                      Store result + notify (callback / webhook / polling)
Enter fullscreen mode Exit fullscreen mode

When to use:

  • Bursts of webhooks could overwhelm your Claude rate limits
  • Jobs must survive server restarts
  • You need retry logic with backoff on Claude API errors
  • Multiple workers process the queue in parallel

For a full breakdown of rate limit strategies in production, see Claude API Production Architecture.


FastAPI Example: Receive Webhook, Call Claude, Respond

This example handles a GitHub PR event webhook, asks Claude to summarize the diff, and posts a comment back.


python
import os
import hmac
import hashlib
import httpx
from fastapi import FastAPI, BackgroundTasks, HTTPException, Request
from anthropic import Anthropic

app = FastAPI()
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

GITHUB_WEBHOOK_SECRET = os.environ["GITHUB_WEBHOOK_SECRET"].encode()


def verify_github_signature(payload: bytes, signature_header: str) -

---

## FAQ

### How do I prevent duplicate processing when a webhook is retried?

Webhook providers retry on non-2xx responses or timeouts. Use the provider's event ID as an idempotency key: before processing, check a database or Redis set for the event ID. If it exists, return 200 immediately without re-processing. If not, insert the ID and proceed. Most providers include a stable event ID in the headers or body (e.g., GitHub's `X-GitHub-Delivery`, Stripe's `id` field).

### What happens if Claude API is slow and the webhook times out?

Return HTTP 202 Accepted immediately and process asynchronously. Never block the HTTP response on the Claude API call. If the webhook sender marks your endpoint as failed after a timeout and retries, idempotency key checks will prevent duplicate Claude calls on the retry. For webhook senders that require synchronous results (rare), use claude-haiku-4-5 with a strict `max_tokens` cap to minimize latency, and set an explicit timeout on your Claude API call so a slow response does not hang the request thread indefinitely.

### Should I use FastAPI BackgroundTasks or Celery for Claude webhook processing?

Use `BackgroundTasks` for simple, low-volume use cases where jobs can be lost on server restart (e.g., internal tooling, low-stakes notifications). Use Celery, Redis Queue (RQ), or a database-backed queue for production workloads where job durability, visibility, retry logic, and horizontal scaling matter. The rule: if losing a job would be a business problem, use a persistent queue. If it is acceptable to skip a job on deploy, `BackgroundTasks` is fine.

### Can I use Claude's streaming API with webhooks?

Yes, but only for the outbound Claude-to-your-server direction. Webhooks are standard HTTP POST — the webhook sender does not receive a streaming response from you. You can stream Claude's output internally (writing chunks to a database or SSE channel) while the webhook endpoint has already responded with 202. This is useful for real-time UI updates while a background job processes a webhook event.

### What model should I use for webhook-triggered Claude calls?

Default to `claude-haiku-4-5` for classification, routing, summarization, and short-form generation tasks triggered by webhooks. Haiku has the highest throughput (lowest latency, lowest cost), which matters when processing queues of hundreds of jobs. Use `claude-sonnet-4-5` for tasks requiring multi-step reasoning, code generation, or nuanced analysis. Reserve `claude-opus-4-5` for edge cases that genuinely need it — keeping Opus usage below 5% of total calls is a practical cost discipline. Full guidance at [Haiku vs Sonnet vs Opus: Which Model?](/claude-haiku-sonnet-opus-which-model).

---

## Summary

The core webhook + Claude API integration has three rules:

1. **Acknowledge fast** — return 2xx before calling Claude
2. **Verify signatures** — reject unverified payloads before any processing
3. **Handle retries** — idempotency keys prevent double-processing on webhook retries

The async background task pattern works for most use cases. Add a persistent queue (Redis, SQS, or database) when job durability, rate-limit management, or horizontal scaling become requirements. Prompt caching on shared system prompts dramatically increases effective throughput within your rate limits.

For the full production architecture picture, including request queuing, cost monitoring, and fallback chains, see [Claude API Production Architecture](/claude-api-production-architecture).

---

[→ P5 Cost Optimization Masterclass — $59](https://shoutfirst.gumroad.com/l/msjkda?utm_source=claudeguide&utm_medium=article&utm_campaign=claude-api-webhook-integration)

Prompt caching, model routing, batch API, and a full cost calculator. Everything needed to run Claude API at production scale without burning your budget.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)