Webhooks look like the simplest possible integration pattern. You make an HTTP POST. The end. What could go wrong?
Everything. Everything goes wrong. I've spent more on-call hours debugging webhook issues than any other class of integration problem. Duplicates because retries fired before the original completed. Lost events because the receiver returned 500 and the sender gave up. Replay attacks because the signature used a shared secret with no timestamp. Webhook bugs are the integration equivalent of timezone bugs-deceptively simple, surprisingly nasty, and they only show up in production.
This article is what I've learned shipping webhook systems on both sides: receiving them from Stripe, GitHub, and Slack, and sending them to customers who sometimes have very strange server setups. We'll cover the receiver side, the sender side, and the production patterns that decide whether your webhooks are a reliable feature or a 3am phone call.
A webhook is just an HTTP POST that one server sends to another when something happens. The simplicity is the trap. HTTP is unreliable, networks are unreliable, receivers are unreliable, and your definition of "delivered" is probably wrong. Let's fix that.
Webhooks vs Polling
| Aspect | Webhooks | Polling |
|---|---|---|
| Latency | Sub-second to seconds | Interval-bound (e.g., 60s) |
| Receiver load | Per-event | Constant regardless of activity |
| Sender load | Per-event | Constant |
| Complexity | Higher (signing, retries, idempotency) | Lower (just call the API) |
| Failure modes | Lost events, duplicates | Missed windows, rate limits |
| Best for | Real-time updates, event-driven architectures | Infrequent checks, simple clients |
Webhooks win when you need low-latency notifications and have many events. Polling wins when events are rare or the receiver can't expose a public endpoint. There's no shame in polling-Stripe's API is fully pollable, and many integrations do exactly that.
The mistake I see most often: teams default to webhooks because they sound more "modern." Then they spend weeks building retry logic, signature verification, and an admin UI for customers to redeliver events. If you'd just polled GET /events every 30 seconds, you'd have shipped in an afternoon. Use the right tool.
The Two Halves: Receiving and Sending
You can be a webhook receiver (Stripe sends you events), a webhook sender (you send events to your customers), or both. The patterns are different. We'll cover both.
CodeCopy RECEIVING SENDING
┌──────────────┐ ┌──────────────┐
│ External │ │ Your app │
│ service │ │ (event │
│ (Stripe, │ │ producer) │
│ GitHub) │ └──────┬───────┘
└──────┬───────┘ │
│ POST /webhooks │ publish event
│ + signature ▼
▼ ┌──────────────┐
┌──────────────┐ │ Queue │
│ Your │ │ (Redis/ │
│ endpoint │ │ SQS/PG) │
└──────┬───────┘ └──────┬───────┘
│ │ consume
│ verify + acknowledge ▼
▼ ┌──────────────┐
┌──────────────┐ │ Worker │
│ Queue │ │ - signs │
│ (async │ │ - POSTs │
│ processing)│ │ - retries │
└──────────────┘ └──────┬───────┘
│
▼
┌──────────────┐
│ Customer's │
│ endpoint │
└──────────────┘
Two key principles apply to both halves:
- Acknowledge fast. The receiver should return 200 within seconds, then process asynchronously. The sender should enqueue and process asynchronously, never blocking the request that triggered the event.
- Idempotency everywhere. Assume every event will be delivered at least once. Sometimes more. Your handlers must be idempotent.
Prerequisites
- Python 3.11+. The code is Python; the patterns translate to any language.
- A queue: Redis, SQS, or Postgres (yes, Postgres works as a queue with
FOR UPDATE SKIP LOCKED). - A way to receive webhooks locally:
ngrok,stripe listen, orwebhook.site. -
fastapifor the receiver endpoint,httpxfor the sender HTTP client.
BashCopy
shell
pip install "fastapi==0.115.0" "uvicorn[standard]==0.30.6" "httpx==0.27.2"
pip install "redis==5.0.8" "sqlalchemy[asyncio]==2.0.35" "asyncpg==0.29.0"
pip install "pydantic==2.9.2" "structlog==24.4.0"
markdown
Receiver Side: Signature Verification
This is the most important part of receiving webhooks. If you don't verify the signature, anyone can send fake events to your endpoint. I've seen this happen-a misconfigured webhook endpoint got spammed with fake "payment succeeded" events. Don't be that team.
Each sender has a slightly different signature scheme, but they all share the same shape: a secret shared between sender and receiver, a signature computed over the request body (and sometimes a timestamp), and the signature sent in a header.
Stripe's scheme: t=<timestamp>,v1=<signature>. The signature is HMAC-SHA256(secret, "<timestamp>.<body>"). Let's implement that.
PythonCopy
python
app/webhooks/stripe_receiver.py
import hashlib
import hmac
import time
from typing import Annotated
from fastapi import APIRouter, Header, HTTPException, Request, status
import structlog
from app.config import settings
from app.queue import enqueue_event
router = APIRouter()
logger = structlog.get_logger()
Reject webhooks older than this (replay attack protection).
MAX_AGE_SECONDS = 5 * 60
def verify_stripe_signature(
body: bytes, signature_header: str, secret: str, tolerance: int = MAX_AGE_SECONDS
) -> None:
'''Raise HTTPException 401 if the signature is invalid or stale.'''
try:
# Header looks like: t=1614858005,v1=abc123,v1=def456
parts = dict(p.split("=", 1) for p in signature_header.split(","))
timestamp_str = parts.get("t")
signatures = [v for k, v in parts.items() if k == "v1"]
if not timestamp_str or not signatures:
raise HTTPException(status_code=401, detail="Malformed signature header")
timestamp = int(timestamp_str)
except (ValueError, KeyError):
raise HTTPException(status_code=401, detail="Malformed signature header")
# Replay protection
now = int(time.time())
if abs(now - timestamp) > tolerance:
raise HTTPException(status_code=401, detail="Timestamp outside tolerance")
# Compute expected signature
signed_payload = f"{timestamp}.".encode() + body
expected = hmac.new(
secret.encode(), signed_payload, hashlib.sha256
).hexdigest()
# Constant-time comparison to prevent timing attacks
if not any(hmac.compare_digest(expected, s) for s in signatures):
raise HTTPException(status_code=401, detail="Invalid signature")
@router.post("/webhooks/stripe", status_code=status.HTTP_200_OK)
async def stripe_webhook(
request: Request,
stripe_signature: Annotated[str, Header()],
) -> dict[str, str]:
# Read the raw body BEFORE any JSON parsing. The signature is over bytes.
body = await request.body()
verify_stripe_signature(body, stripe_signature, settings.stripe_webhook_secret)
# Only now parse JSON
import json
try:
event = json.loads(body)
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail="Invalid JSON")
# Enqueue for async processing. Never do real work inline.
await enqueue_event(
queue="stripe_events",
payload={
"id": event["id"], # Stripe's event ID, use as idempotency key
"type": event["type"],
"data": event["data"]["object"],
"created": event["created"],
},
)
logger.info("webhook.received", event_id=event["id"], type=event["type"])
return {"status": "received"}
markdown
Three things that matter:
- Read the raw body first. If you let FastAPI parse the JSON, the body bytes might be slightly different (whitespace, key order) than what was signed. Verification fails. Always verify against the exact bytes received.
- Constant-time comparison.
hmac.compare_digestprevents timing attacks where an attacker reconstructs the signature by measuring response times. Don't use==. - Replay protection. Without checking the timestamp, an attacker who captured a valid webhook can replay it indefinitely. The 5-minute tolerance handles clock drift between you and the sender.
The Idempotency Problem
Stripe, like most webhook senders, retries on any non-2xx response. They also retry if they don't get a response within their timeout (Stripe's is ~20 seconds). This means your endpoint will receive duplicate events. Not "might"-will.
If your handler does create_order(event.data.id), the second delivery creates a duplicate order. The fix: use the event ID as an idempotency key.
PythonCopy
python
app/webhooks/handlers/stripe_handlers.py
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models import ProcessedEvent, Order
async def handle_checkout_completed(
event_id: str, data: dict, db: AsyncSession
) -> None:
# Idempotency check: have we processed this event before?
existing = await db.execute(
select(ProcessedEvent).where(ProcessedEvent.event_id == event_id)
)
if existing.scalar_one_or_none() is not None:
# Already processed. Acknowledge silently.
return
# Do the actual work
order = Order(
id=data["id"],
customer_email=data["customer_details"]["email"],
amount_total=data["amount_total"],
currency=data["currency"],
status="paid",
)
db.add(order)
# Record that we've processed this event
db.add(ProcessedEvent(event_id=event_id, event_type="checkout.session.completed"))
await db.commit()
markdown
The processed_events table is your dedupe layer. It's cheap-just a unique index on event_id. The cost of not having this is much higher.
There's a subtle race here: two deliveries of the same event could both check the table simultaneously, both miss, both insert. The unique index on event_id saves you-the second insert fails, and you catch the IntegrityError and treat it as "already processed." Always have the DB enforce uniqueness, not just application logic.
Processing Webhooks Asynchronously
The receiver endpoint should do the absolute minimum: verify signature, enqueue, return 200. Real processing happens in a worker.
Why? Because Stripe (and most senders) have a strict timeout. If you don't respond within ~20 seconds, they retry. If your handler does something slow-calls a third-party API, sends an email, generates a PDF-you'll time out. Stripe retries, you process again, you time out again. Eventually Stripe gives up.
PythonCopy
python
app/queue.py
import json
import redis.asyncio as redis
from app.config import settings
_redis = redis.from_url(settings.redis_url)
async def enqueue_event(queue: str, payload: dict) -> None:
'''Push an event onto a Redis list. Workers pop and process.'''
await _redis.rpush(queue, json.dumps(payload))
async def dequeue_event(queue: str, timeout: int = 5) -> dict | None:
'''Blocking pop with timeout. Returns None if no event within timeout.'''
result = await _redis.blpop(queue, timeout=timeout)
if result is None:
return None
_, raw = result
return json.loads(raw)
plaintext
PythonCopy
python
app/worker.py
import asyncio
import structlog
from app.queue import dequeue_event
from app.webhooks.handlers.stripe_handlers import handle_checkout_completed
from app.database import SessionLocal
logger = structlog.get_logger()
HANDLERS = {
"checkout.session.completed": handle_checkout_completed,
# ... other event types
}
async def process_event(event: dict) -> None:
handler = HANDLERS.get(event["type"])
if handler is None:
logger.warning("worker.no_handler", event_type=event["type"])
return
async with SessionLocal() as db:
try:
await handler(event["id"], event["data"], db)
except Exception:
logger.exception("worker.handler_failed", event_id=event["id"])
raise
async def run_worker(queue: str = "stripe_events") -> None:
logger.info("worker.starting", queue=queue)
while True:
event = await dequeue_event(queue)
if event is None:
continue
try:
await process_event(event)
except Exception:
# Don't crash the worker on a bad event.
# In a real system, push to a dead-letter queue.
continue
if name == "main":
asyncio.run(run_worker())
markdown
Run the worker separately from the API: python -m app.worker. In prod, run multiple workers-Redis BLPOP ensures each event is consumed by exactly one worker.
Sender Side: The Queue-Based Pattern
When you're the one sending webhooks, the rules change. Your job is to deliver reliably, handle slow/broken customer endpoints, retry sensibly, and not lose events when your own servers restart.
The anti-pattern: send the webhook inline in the request handler that triggered the event. If the customer's endpoint is slow, your request is slow. If the customer's endpoint is down, your request fails. You've coupled your user's experience to someone else's server.
The right pattern: write events to a queue, have a separate worker deliver them.
PythonCopy
python
app/sender/event_store.py
import uuid
from datetime import datetime
from typing import Optional
from sqlalchemy import String, DateTime, Integer, Text, select
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import Base
class WebhookEvent(Base):
tablename = "webhook_events"
id: Mapped[str] = mapped_column(String(64), primary_key=True, default=lambda: str(uuid.uuid4()))
event_type: Mapped[str] = mapped_column(String(100), index=True)
payload: Mapped[str] = mapped_column(Text) # JSON
target_url: Mapped[str] = mapped_column(String(500))
secret: Mapped[str] = mapped_column(String(100)) # per-subscription secret
status: Mapped[str] = mapped_column(String(20), default="pending", index=True)
# pending | in_flight | delivered | failed | dead_letter
attempts: Mapped[int] = mapped_column(Integer, default=0)
max_attempts: Mapped[int] = mapped_column(Integer, default=8)
next_attempt_at: Mapped[datetime] = mapped_column(DateTime, index=True)
last_error: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
async def enqueue_webhook(
db: AsyncSession,
event_type: str,
payload: dict,
target_url: str,
secret: str,
) -> WebhookEvent:
'''Called by application code when an event happens.'''
event = WebhookEvent(
event_type=event_type,
payload=json.dumps(payload),
target_url=target_url,
secret=secret,
next_attempt_at=datetime.utcnow(),
)
db.add(event)
await db.commit()
return event
import json # noqa: E402
plaintext
PythonCopy
python
app/sender/delivery.py
import hashlib
import hmac
import time
from datetime import datetime, timedelta
import httpx
import structlog
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.sender.event_store import WebhookEvent
logger = structlog.get_logger()
Exponential backoff: 1s, 2s, 4s, 8s, ..., capped at 1 hour
BACKOFF_SECONDS = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 3600]
DELIVERY_TIMEOUT_SECONDS = 10
def sign_payload(body: bytes, secret: str) -> str:
'''Stripe-style signature: t=,v1='''
ts = int(time.time())
signed = f"{ts}.".encode() + body
sig = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
return f"t={ts},v1={sig}"
async def deliver_event(db: AsyncSession, event: WebhookEvent) -> bool:
'''Attempt to deliver one event. Returns True on success.'''
body = event.payload.encode()
signature = sign_payload(body, event.secret)
headers = {
"Content-Type": "application/json",
"X-Webhook-Signature": signature,
"X-Webhook-Event-ID": event.id,
"X-Webhook-Event-Type": event.event_type,
"User-Agent": "MyApp-Webhooks/1.0",
}
async with httpx.AsyncClient(timeout=DELIVERY_TIMEOUT_SECONDS) as client:
try:
resp = await client.post(event.target_url, content=body, headers=headers)
except (httpx.TimeoutException, httpx.NetworkError) as e:
await _handle_failure(db, event, str(e))
return False
if 200 <= resp.status_code < 300:
event.status = "delivered"
event.last_error = None
await db.commit()
logger.info("webhook.delivered", event_id=event.id, status=resp.status_code)
return True
# Non-2xx: treat as failure, schedule retry
await _handle_failure(
db, event, f"HTTP {resp.status_code}: {resp.text[:200]}"
)
return False
async def _handle_failure(db: AsyncSession, event: WebhookEvent, error: str) -> None:
event.attempts += 1
event.last_error = error
if event.attempts >= event.max_attempts:
event.status = "dead_letter"
logger.warning(
"webhook.dead_lettered",
event_id=event.id,
attempts=event.attempts,
error=error,
)
else:
delay = BACKOFF_SECONDS[min(event.attempts - 1, len(BACKOFF_SECONDS) - 1)]
event.next_attempt_at = datetime.utcnow() + timedelta(seconds=delay)
logger.info(
"webhook.scheduled_retry",
event_id=event.id,
attempt=event.attempts,
delay=delay,
error=error,
)
await db.commit()
plaintext
Key choices:
- Stripe-style signature. It's a well-understood pattern; customers can verify it with the same code they use for Stripe.
- Exponential backoff with jitter (would add jitter in prod; omitted here for clarity). Without backoff, you hammer a struggling endpoint and make it worse.
-
DELIVERY_TIMEOUT_SECONDS = 10. Tight. If the customer can't respond in 10s, they're broken or their handler is too slow. Don't let one slow customer block your workers. - Dead-letter after N attempts. Stop trying. Surface it in a dashboard so the customer can see "we couldn't deliver these events" and trigger a manual retry.
The Sender Worker Loop
PythonCopy
python
app/sender/worker.py
import asyncio
from datetime import datetime
from sqlalchemy import select, and_
from app.database import SessionLocal
from app.sender.event_store import WebhookEvent
from app.sender.delivery import deliver_event
async def run_sender_worker(batch_size: int = 20, sleep_seconds: float = 1.0) -> None:
'''Continuously pick up due webhook events and deliver them.'''
while True:
async with SessionLocal() as db:
now = datetime.utcnow()
stmt = (
select(WebhookEvent)
.where(
and_(
WebhookEvent.status.in_(["pending", "in_flight"]),
WebhookEvent.next_attempt_at <= now,
)
)
.order_by(WebhookEvent.next_attempt_at.asc())
.limit(batch_size)
.with_for_update(skip_locked=True) # multiple workers safe
)
result = await db.execute(stmt)
events = result.scalars().all()
for event in events:
event.status = "in_flight"
await db.commit()
for event in events:
try:
await deliver_event(db, event)
except Exception as e:
# Unexpected error; mark for retry
event.last_error = f"Worker error: {e}"
event.status = "pending"
event.next_attempt_at = datetime.utcnow()
await db.commit()
if not events:
await asyncio.sleep(sleep_seconds)
markdown
The with_for_update(skip_locked=True) is the magic. It lets multiple workers pull from the same table without picking up the same rows. Postgres skips rows that are already locked by another worker. This is the pattern that turns a regular table into a queue.
Production Considerations
Observability. Webhooks are invisible when they fail. You need:
- Per-endpoint delivery success rate
- Per-event-type delivery latency
- Dead-letter queue with manual retry UI
- Customer-facing delivery logs (so they can debug their own endpoints)
Retries vs redelivery. Automatic retries (exponential backoff) handle transient failures. Manual redelivery (admin clicks "resend" in a dashboard) handles the case where the customer's endpoint was down for a week. Both are necessary.
Idempotency on the receiver side is not your job. But document it loudly. Tell your customers: "We will deliver this event at least once. Sometimes more. Make your handler idempotent." Provide a unique event ID in a header (X-Webhook-Event-ID) so they can dedupe.
Signature secret rotation. Eventually you'll need to rotate secrets. Support two active secrets at once (old and new), accept signatures from either, log which one was used. After all customers have migrated to the new secret, drop the old one. Stripe does this and the pattern works.
Rate limiting per endpoint. Some customers' endpoints can't handle high throughput. Add per-target rate limiting (e.g., max 10 events/sec per URL). Without it, one customer's bulk operation can starve others.
Connection pooling for outbound HTTP. Don't create a new httpx.AsyncClient per delivery. Reuse a single client (or a small pool) across the worker. Connection setup is a significant fraction of delivery latency.
Dead-letter queue review. Have a dashboard. Have an alert when the DLQ grows past a threshold. Someone should look at dead-lettered events daily.
Common Mistakes
Mistake: Processing inline in the receiver. Stripe sends an event, you do real work, you take 30 seconds, Stripe times out and retries. You process again. Fix: enqueue and acknowledge fast. Process in a worker.
Mistake: No idempotency key. Duplicate deliveries create duplicate side effects. Customer gets charged twice. Fix: persist a record of processed event IDs, check before processing.
Mistake: Comparing signatures with ==. Timing attacks reconstruct the signature byte by byte. Fix: hmac.compare_digest.
Mistake: No replay protection. Valid webhook captured by an attacker, replayed months later. Fix: include a timestamp in the signed payload, reject old timestamps.
Mistake: Inline webhook sending. Customer's endpoint is slow, your user's request is slow. Fix: write events to a queue, deliver asynchronously.
Mistake: Retrying without backoff. Customer's endpoint is down, you retry every second for an hour, you DoS them harder. Fix: exponential backoff with jitter.
Mistake: No dead-letter queue. Failed events disappear. Customer never knows. Fix: after N retries, move to DLQ, surface in a dashboard, allow manual retry.
Mistake: Not testing the failure modes. Happy-path testing passes. Production breaks because the customer's endpoint returned 500 and you had no retry. Fix: test with a deliberately broken endpoint.
Troubleshooting: Real Issues I've Hit
"Stripe keeps resending the same event." Your endpoint is timing out. Stripe's timeout is ~20s. If you're processing synchronously, you're too slow. Move work to a background queue. Acknowledge within 2s.
"Customer says they didn't receive the webhook." Three places to check: (1) did you enqueue it? Check the webhook_events table. (2) did the worker deliver it? Check the delivery log. (3) did their server return 2xx? Often they returned 200 but their handler crashed. Ask them to check their logs for the event ID.
"Webhooks work in dev but not prod." SSL. Your dev environment accepted self-signed certs; prod rejects them. Or: dev was on the same network as the customer's test endpoint; prod isn't. Check httpx SSL configuration.
"Duplicates in production despite idempotency check." Race condition: two deliveries arrive simultaneously, both check the processed_events table, both miss, both insert. The unique index saves you if you have one. If you don't, fix that first.
"Worker dies after one bad event." Missing try/except in the worker loop. One bad event kills the worker, no more events get processed. Always catch exceptions per-event.
"Signature verification fails intermittently." You're parsing the body before verifying. The parsed JSON, when re-serialized, doesn't match the original bytes. Verify against raw bytes.
"Customer can't verify signature." They're using the wrong secret. Or they're computing HMAC over the JSON-parsed body, not the raw bytes. Or their clock is off (replay protection triggering). Send them a test event with a known body and signature.
Testing Webhooks Locally
You need a way to receive webhooks on your dev machine. Three options:
-
ngrok. Tunnels a public URL to localhost. Stripe/GitHub/Slack can send to the ngrok URL. Free tier works. - Sender's CLI. Stripe has
stripe listen --forward-to localhost:8000/webhooks/stripe. Generates test events withstripe trigger checkout.session.completed. -
webhook.site. A public endpoint that captures and displays webhooks. Great for debugging what a sender is sending.
For the sender side, test with webhook.site or a local server that always returns 500, to verify your retry logic.
PythonCopy
python
tests/test_delivery.py
import pytest
from unittest.mock import AsyncMock, patch
from app.sender.delivery import deliver_event
from app.sender.event_store import WebhookEvent
@pytest.mark.asyncio
async def test_delivery_success(db_session):
event = WebhookEvent(
id="evt_test_1",
event_type="test.event",
payload='{"hello": "world"}',
target_url="https://example.com/webhook",
secret="whsec_test",
status="pending",
attempts=0,
max_attempts=8,
next_attempt_at=datetime.utcnow(),
)
db_session.add(event)
await db_session.commit()
mock_response = AsyncMock()
mock_response.status_code = 200
with patch("app.sender.delivery.httpx.AsyncClient") as mock_client_cls:
mock_client = mock_client_cls.return_value.aenter.return_value
mock_client.post = AsyncMock(return_value=mock_response)
result = await deliver_event(db_session, event)
assert result is True
assert event.status == "delivered"
@pytest.mark.asyncio
async def test_delivery_retries_on_500(db_session):
event = WebhookEvent(
id="evt_test_2",
event_type="test.event",
payload='{"hello": "world"}',
target_url="https://example.com/webhook",
secret="whsec_test",
status="pending",
attempts=0,
max_attempts=8,
next_attempt_at=datetime.utcnow(),
)
db_session.add(event)
await db_session.commit()
mock_response = AsyncMock()
mock_response.status_code = 500
mock_response.text = "Internal Server Error"
with patch("app.sender.delivery.httpx.AsyncClient") as mock_client_cls:
mock_client = mock_client_cls.return_value.aenter.return_value
mock_client.post = AsyncMock(return_value=mock_response)
result = await deliver_event(db_session, event)
assert result is False
assert event.status == "pending"
assert event.attempts == 1
assert event.next_attempt_at > datetime.utcnow() # scheduled for future
The 500 test is the important one. If your code doesn't have tests for the failure paths, it doesn't have working failure paths.
Cost Considerations
Webhooks are cheap to operate but expensive to get right.
- Receiving: minimal cost. A small FastAPI instance + Redis handles thousands of webhooks per minute.
- Sending: scales with your customer count and event volume. Each delivery is an HTTP request. At 1M events/day to 1K endpoints, that's 1M HTTP requests/day. Use connection pooling, keep payloads small.
- Database: the
webhook_eventstable grows fast. Archive delivered events after 30 days; keep failed/dead-lettered indefinitely (or until manually resolved). - DLQ review time: non-trivial. Someone has to look at failed deliveries. Budget 1-2 hours/week per 100 active webhook subscribers.
The biggest hidden cost is customer support. Customers will swear they didn't receive a webhook. You'll need delivery logs, searchable by event ID, that you can show them. Build that dashboard early.
Alternatives
- Long polling. Client opens a request, server holds it open until an event arrives. Simpler than webhooks for the client, but resource-heavy at scale.
- Server-Sent Events (SSE). Client opens a persistent connection, server pushes events. Great for browser-based clients, awkward for server-to-server.
- Message queues (SQS, NATS, Kafka). For internal event-driven systems, a real message broker is better than webhooks. Webhooks are for crossing trust boundaries (your server → customer's server).
- Polling the API. Sometimes the right answer. If events are rare and receivers can't expose endpoints, polling is simpler and more reliable.
The webhook sweet spot is: server-to-server, event-driven, crossing an organizational boundary, with moderate latency requirements.
Real-World Use Cases I've Shipped
- Payment processor integration. Receiving Stripe webhooks. Idempotency on event ID saved us from double-charging customers at least twice. The replay-protection timestamp caught a misconfigured customer who was re-sending old events.
- CI/CD notifications. Sending webhooks to customers when their builds finish. The dead-letter queue caught a customer whose endpoint was down for a week-they could see all missed events and replay them after they fixed it.
- Data sync. Customer configures a webhook URL; we send
record.updatedevents. Used Postgres as the queue (SKIP LOCKED) because the team didn't want to add Redis. Worked fine at moderate scale. - Multi-tenant notification fan-out. One event triggers N webhooks (one per subscribed tenant). Added per-tenant rate limiting after one tenant's slow endpoint backed up the whole queue.
Wrapping Up
Webhooks are deceptively simple. The protocol is trivial-a POST request. The implementation is full of edge cases, failure modes, and production reality. The patterns in this article-signature verification with replay protection, idempotency via event IDs, async processing, queue-based sending, exponential backoff, dead-letter queues-are not optional. They are the difference between a webhook system that works and one that generates 3am phone calls.
If you take one thing from this: idempotency is the whole game. Not signature verification (though that's critical too). Idempotency. Because every other failure mode-retries, duplicates, slow workers, crashed servers-funnels into "your handler must be safe to call twice with the same event." Get that right, and the rest is engineering. Get it wrong, and you'll be writing reconciliation scripts at 4am.
Webhooks aren't going away. They're still the lingua franca of server-to-server event delivery. Build them right, and they're invisible infrastructure. Build them wrong, and they're the most visible bug in your product.
Originally published on Mango Developer.
