Lesson 7 of 9 · 23m
Safe Receivers: Fast Acknowledgement and Asynchronous Processing
Build webhook receivers that verify, persist, acknowledge quickly, and process asynchronously so slow business logic does not turn into delivery failure.
The healthiest webhook receiver does almost nothing in the HTTP request path. It authenticates the delivery, validates the envelope enough to store it, writes it durably, acknowledges, and lets asynchronous workers do the risky business logic. The moment you call three internal services, render a PDF, email a customer, and update a CRM before responding, your endpoint latency becomes the producer's retry problem.
The receiver contract
A good request path looks like this:
@app.post("/webhooks/acme")
async def receive(request: Request):
body = await request.body()
verify_signature(request.headers, body, settings.acme_secret)
envelope = parse_envelope(body)
await db.execute(
"INSERT INTO inbound_webhook_events (provider, event_id, body, received_at) "
"VALUES ('acme', $1, $2, now()) "
"ON CONFLICT (provider, event_id) DO NOTHING",
envelope.id,
body.decode(),
)
return Response(status_code=202)202 Accepted is honest when processing is queued. Return 200 if processing is already complete and the semantic distinction matters. Either way, the producer only needs acknowledgement that responsibility transferred. Do not expose internal processing failures after durable acceptance unless the contract says a retry is desired.
Acknowledge fast, but not before durability
There is a dangerous shortcut: acknowledge before writing the event because the database is slow. That converts your receiver into a lossy proxy. Durability means the event is recoverable after process crash — a database insert, transactional queue write, or similarly strong storage operation. Memory is not durability.
Idempotent processing is mandatory
The inbox insert uses ON CONFLICT DO NOTHING, but that only deduplicates the receipt. The worker also needs an idempotent effect:
async def process_inbox(row):
event = json.loads(row.body)
async with db.transaction():
claimed = await mark_processing_if_new(row.id, event["id"])
if not claimed:
return
await apply_business_effect(event)
await mark_processed(row.id)Exactly how you claim depends on the effect. Sometimes the event ID is written into the same transaction as the business update. Sometimes a state transition is naturally idempotent: setting status='active' twice is harmless, while incrementing balance twice is not.
Timeouts create duplicates by design
If your receiver normally responds in 100 ms but occasionally does 8 seconds of work, a producer with a 5-second timeout will retry while the first worker continues. This is not rare. Decouple receiving and applying. Then tune worker concurrency so backlog drain is predictable.
Validate structure after trust, before use
Signature verification proves origin, not schema correctness. A provider can deploy a bug. Validate id, type, created, and required object fields before applying effects. For unknown event types, store and ignore deliberately; throwing exceptions into retry loops because a provider launched a new event type is self-inflicted fragility.
Backpressure and isolation
Use separate queues for inbound processing and customer-triggered interactive work. Apply per-provider concurrency caps. If one provider sends a million-event backfill, it must not starve payment webhooks from another provider. Monitor inbox age and processing error rate independently.
Field notes
- A
202does not mean "we verified all business preconditions." It means "we accepted the message for processing." - Store the raw body for reconciliation and schema debugging, but redact secrets or regulated data according to retention policy.
- Do not use the webhook handler as a general-purpose synchronous RPC endpoint; retries will multiply expensive effects.
- Distinguish poison-message failure from transient dependency failure. One malformed event should not block an entire partition forever.
- Test deploy safety by killing a worker mid-processing. Recovery behavior is part of the receiver design, not an afterthought.
Was this lesson helpful?