Why the webhook handler must not call the LLM
Webhook senders want a fast 2xx. An LLM call can take seconds, hit a timeout, and trigger redelivery. If you call the model inside the handler, a slow provider becomes a webhook outage, and retries become duplicate work or duplicate charges.
Treat the webhook as a notification, not a job. Verify it, write it down, acknowledge it, and let a worker do the model call. The cost is eventual consistency: results appear later, so your UI or downstream system needs a pending state. The benefit is that you can retry, replay, and inspect every event.
The durable handoff: verify, persist, ack, process
Verify the signature against the raw body with a constant-time compare before parsing JSON.
Persist the raw payload and a stable event_id with a unique constraint. Use the provider event id when present; otherwise hash the body.
Insert the job in the same transaction as the event record. This is the outbox pattern: no event is acknowledged unless the job exists.
Return 200 or 202 immediately. Do not wait for the model.
Let a worker claim one job at a time with a lease, call the model, store the result, and mark the job done.
On failure, requeue with backoff. After a bounded number of attempts, move the job to a dead-letter state for inspection.
The receiver below uses SQLite so it runs locally with no extra services. Swap SQLite for Postgres in production; the pattern is the same. Save it as receiver.py, set WEBHOOK_SECRET, and run uvicorn receiver:app --reload.
import hashlib
import hmac
import json
import os
import sqlite3
import time
from contextlib import closing
from fastapi import FastAPI, Header, HTTPException, Request
DB = os.environ.get('EVENTS_DB', 'events.db')
SECRET = os.environ['WEBHOOK_SECRET'].encode()
app = FastAPI()
def db():
conn = sqlite3.connect(DB, timeout=30)
conn.execute('PRAGMA journal_mode=WAL')
conn.execute('''CREATE TABLE IF NOT EXISTS jobs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
event_id TEXT UNIQUE NOT NULL,
payload TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'queued',
attempts INTEGER NOT NULL DEFAULT 0,
next_at REAL NOT NULL DEFAULT 0,
lease_until REAL NOT NULL DEFAULT 0,
result TEXT
)''')
conn.commit()
return conn
@app.post('/webhooks/events')
async def receive(request: Request, x_signature: str = Header(default='')):
body = await request.body()
expected = hmac.new(SECRET, body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, x_signature):
raise HTTPException(status_code=401, detail='bad signature')
try:
event = json.loads(body)
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail='bad json')
event_id = str(event.get('id')) if isinstance(event, dict) and event.get('id') else hashlib.sha256(body).hexdigest()
with closing(db()) as conn, conn:
conn.execute(
'INSERT OR IGNORE INTO jobs (event_id, payload, next_at) VALUES (?, ?, ?)',
(event_id, body.decode(), time.time()),
)
return {'accepted': True, 'event_id': event_id}
A worker that claims jobs safely
The worker must be safe to run more than once and safe to run in parallel. The claim query uses BEGIN IMMEDIATE so two workers cannot take the same row, and it requeues jobs whose lease expired because a worker crashed.
Set the lease longer than your normal model call, and make the retry count visible. The example stores the last error in result so you can debug without opening a separate log store.
import json
import os
import sqlite3
import time
from contextlib import closing
from openai import OpenAI
DB = os.environ.get('EVENTS_DB', 'events.db')
client = OpenAI(
api_key=os.environ['AICREDITS_API_KEY'],
base_url='https://api.aicreditsapi.com/v1',
timeout=30.0,
max_retries=0,
)
def db():
conn = sqlite3.connect(DB, timeout=30)
conn.execute('PRAGMA journal_mode=WAL')
conn.execute('''CREATE TABLE IF NOT EXISTS jobs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
event_id TEXT UNIQUE NOT NULL,
payload TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'queued',
attempts INTEGER NOT NULL DEFAULT 0,
next_at REAL NOT NULL DEFAULT 0,
lease_until REAL NOT NULL DEFAULT 0,
result TEXT
)''')
conn.commit()
return conn
def claim():
with closing(db()) as conn:
conn.execute('BEGIN IMMEDIATE')
now = time.time()
conn.execute(
'UPDATE jobs SET status = ?, next_at = ? WHERE status = ? AND lease_until < ?',
('queued', now, 'processing', now),
)
row = conn.execute(
'SELECT id, payload, attempts FROM jobs WHERE status = ? AND next_at <= ? ORDER BY id LIMIT 1',
('queued', now),
).fetchone()
if not row:
conn.execute('COMMIT')
return None
job_id, payload, attempts = row
conn.execute(
'UPDATE jobs SET status = ?, attempts = attempts + 1, lease_until = ? WHERE id = ?',
('processing', now + 120, job_id),
)
conn.execute('COMMIT')
return job_id, payload, attempts + 1
def finish(job_id, result=None, error=None):
with closing(db()) as conn, conn:
if error is None:
conn.execute(
'UPDATE jobs SET status = ?, result = ? WHERE id = ?',
('done', result, job_id),
)
return
row = conn.execute('SELECT attempts FROM jobs WHERE id = ?', (job_id,)).fetchone()
attempts = row[0] if row else 1
if attempts >= 5:
conn.execute(
'UPDATE jobs SET status = ?, result = ? WHERE id = ?',
('dead', error, job_id),
)
else:
conn.execute(
'UPDATE jobs SET status = ?, next_at = ?, result = ? WHERE id = ?',
('queued', time.time() + min(300, 2 ** attempts), error, job_id),
)
def process(payload):
event = json.loads(payload)
prompt = f'Summarize this event for an on-call engineer in 3 bullets. Event: {json.dumps(event)[:6000]}'
response = client.chat.completions.create(
model='deepseek-v4-flash',
messages=[
{'role': 'system', 'content': 'You are a concise incident assistant. Return only actionable bullets.'},
{'role': 'user', 'content': prompt},
],
temperature=0.2,
)
return response.choices[0].message.content
def main():
while True:
job = claim()
if job is None:
time.sleep(2)
continue
job_id, payload, _ = job
try:
finish(job_id, result=process(payload))
except Exception as exc:
finish(job_id, error=f'{type(exc).__name__}: {exc}')
if __name__ == '__main__':
main()
Run it with AICREDITS_API_KEY set: python worker.py. The client uses max_retries=0 because the worker already owns retries; layering SDK retries on top of job retries makes duplicate calls harder to reason about.
What to put in the prompt (and what to keep out)
Event payloads are often large and noisy. Truncate the payload before it reaches the prompt, keep stable fields such as event_id, type, severity, and source, and put the raw payload in object storage if you need full fidelity. Do not ask the model to decide routing if deterministic rules can do it; use the model for summarization, classification with a closed label set, or drafting a customer-facing note.
Use deepseek-v4-flash as the default worker model. It is the fast, lower-cost option and is a good fit for triage, summaries, and extraction. Use deepseek-v4-pro when the output is customer-facing or the event is ambiguous and the extra reasoning is worth the higher cost. Route by job type, not by guesswork: a separate queue for pro jobs keeps flash throughput predictable.
Pricing is qualitative here: cache hits are cheaper, off-peak usage costs less, and pro costs more than flash. Check aicreditsapi.com/deepseek-prices for current rates before you size a queue.
| Failure mode | Symptom | Fix |
|---|---|---|
| Inline LLM call | Webhook timeouts and sender retries | Acknowledge first; process in a worker |
| Duplicate delivery | Repeated model calls or side effects | Unique event_id plus stored result |
| Worker crash | Jobs stuck in processing | Lease timestamp and expired-lease requeue |
| Oversized payload | Prompt truncation or failed jobs | Cap input size; store raw payload separately |
| Provider outage | Retry storm and deep backlog | Exponential backoff plus dead-letter state |
| Unverified webhook | Spoofed events and wasted model calls | HMAC compare_digest before parsing |
Operational guardrails that save money and sanity
Store an idempotency key per event and reuse the stored result on replay. A redelivered webhook should not produce a second model call.
Log event_id, job_id, model, attempt number, token usage, and outcome. Token usage is the signal that catches prompt bloat.
Cap input size before the API call. A truncated summary is better than a failed job and a retry storm.
Separate queues by priority: interactive events, batch enrichment, and pro-model work. A single stuck batch job should not block password-reset summaries.
Monitor queue depth and oldest job age, not just worker CPU. Backpressure is a product decision: shed low-priority events or pause intake.
Keep a replay tool. When you change a prompt, you will want to rerun a day of events against a sample and compare outputs.
A practical rule for model choice
Start every new event type on deepseek-v4-flash with a tight prompt and a small output limit. Measure whether the output is good enough for the decision it supports. Move only the jobs that fail review to deepseek-v4-pro, and keep the flash path as the fallback for volume spikes.
If you are outside China and need DeepSeek API credits without a Chinese phone number or bank account, AiCredits sells credits payable by card or PayPal. The endpoint in the code above is the one you use; the OpenAI SDK works unchanged. AiCredits also offers linting tools if you want a second pass on the worker code before it handles production events.
FAQ
You can, but you should not for anything that matters. A slow model call can exceed the sender timeout and trigger redelivery. Acknowledge fast, persist the event, and process it in a worker.
Use a unique event_id with a database constraint, claim jobs atomically, and store the result keyed by event_id. On replay, return the stored result instead of calling the model again.
No. A database table with a unique constraint and a lease is enough for many teams. A broker helps when you need fan-out, very high throughput, or multiple consumers with different priorities. The outbox pattern still applies.
Default to deepseek-v4-flash for high-volume event processing. Use deepseek-v4-pro for ambiguous or customer-facing jobs where the extra reasoning is worth the higher cost. Keep separate queues so pro jobs do not slow down flash jobs.
Longer than your observed model call time with margin for retries. If a worker dies, the lease expires and the job is requeued. Do not set it so short that a healthy slow call gets duplicated.
See aicreditsapi.com/deepseek-prices for current rates. Pricing is qualitative in this guide because rates change; cache hits and off-peak usage are cheaper, and pro costs more than flash.