DEV Community

Pablo Ian Laurino
Pablo Ian Laurino

Posted on

Stop Losing Leads to Silent Webhook Failures: A Zero-Loss FastAPI + SQLite WAL Architecture

The Problem You Didn't Know You Had

Last quarter, a client's GoHighLevel funnel showed 847 form submissions. Their CRM had 791 contacts. Fifty-six leads — roughly $14K in pipeline — vanished between the webhook and the database. No errors. No alerts. Just... gone.

This isn't rare. It's the default state of webhook integrations.

The failure modes are boring but brutal:

  • Target endpoint returns 5xx → webhook provider retries 3x, then gives up
  • Network blip between your VPS and the CRM → request never arrives
  • n8n workflow crashes mid-execution → event processed but never persisted
  • Rate limit hit → webhook dropped with no dead-letter visibility
  • Idempotency key missing → duplicate leads created, or worse, the first one lost

Most teams discover this weeks later during a pipeline review. By then, the leads are cold.

What a Real Solution Looks Like

I built Webhook DLQ Shield — a FastAPI service that sits between your webhook producers (Typeform, Stripe, GHL forms, n8n, custom apps) and your automation/CRM endpoints. It guarantees at-least-once delivery with full auditability.

Core guarantees:

  1. Persist before forward — Every event hits SQLite WAL before the first delivery attempt
  2. Deduplication by (source, idempotency_key) — SHA-256 of raw body as fallback; zero duplicate forwards
  3. Exponential backoff replay worker — Configurable retries, lease-based recovery if the process dies mid-delivery
  4. Dead-letter transition with alerting — Slack/Telegram notification when an event exhausts retries
  5. Admin API for inspection & manual replay — /dlq, /dlq/replay, /stats, /health

Stack: FastAPI + SQLite WAL (full synchronous) + Uvicorn single-worker + Docker. ~400 lines. Zero external queue dependency.

Producer → POST /webhooks/{source} → SQLite WAL (atomic insert + dedupe)
                ↓
         Immediate delivery attempt → Target (CRM, n8n, HubSpot, etc.)
                ↓
         Success? → mark delivered
         Fail?    → schedule retry with exponential backoff
                ↓
         Max retries exceeded → dead_letter + alert (Slack/Telegram)
                ↓
         Operator → GET /dlq → POST /dlq/{event_id}/replay
Enter fullscreen mode Exit fullscreen mode

Why SQLite WAL Works Here (And When It Doesn't)

SQLite WAL + PRAGMA synchronous=FULL + transactional claims gives you:

  • Single-file durability across container restarts (Docker volume)
  • No separate Redis/PostgreSQL operational burden
  • Sub-millisecond write latency on local NVMe
  • Perfect for single-host, single-worker deployments

The boundary: One container, one Uvicorn worker, one SQLite file. If you need multi-host HA or >500 req/s sustained, swap the storage layer — the API contract stays identical. REDIS_URL is reserved in config for that migration.

The Deduplication Logic That Matters

# In app/services/intake.py
async def persist_event(source: str, body: bytes, idempotency_key: str | None) -> Event:
    key = idempotency_key or hashlib.sha256(body).hexdigest()

    async with db.execute(
        """INSERT INTO events (source, idempotency_key, payload, status)
           VALUES (?, ?, ?, 'pending_retry')
           ON CONFLICT(source, idempotency_key) DO UPDATE SET
             payload=excluded.payload,
             status='pending_retry',
             attempts=0,
             next_retry_at=datetime('now'),
             updated_at=datetime('now')
           RETURNING id, source, idempotency_key, status, attempts"""
    ) as cursor:
        row = await cursor.fetchone()
        return Event(*row)
Enter fullscreen mode Exit fullscreen mode

The ON CONFLICT clause handles both new events and replays atomically. A repeated webhook returns the original event_id and does not forward again. Your target still needs to deduplicate by X-Webhook-Event-Id header (at-least-once boundary), but you've eliminated the producer-side duplicate problem.

Replay Worker: Lease-Based Recovery

The worker claims events with a delivery lease — if the process crashes during HTTP delivery, the lease expires and another worker (or the same one on restart) picks it up.

# In app/services/worker.py
async def claim_due_events(limit: int) -> list[Event]:
    lease_expires = datetime.utcnow() + timedelta(seconds=DELIVERY_LEASE_SECONDS)

    await db.execute(
        """UPDATE events
           SET status='delivering',
               delivery_lease_expires=?,
               attempts=attempts+1,
               updated_at=datetime('now')
           WHERE id IN (
             SELECT id FROM events
             WHERE status IN ('pending_retry','delivering')
               AND (delivery_lease_expires IS NULL OR delivery_lease_expires < datetime('now'))
               AND next_retry_at <= datetime('now')
             ORDER BY next_retry_at
             LIMIT ?
           )""",
        (lease_expires.isoformat(), limit)
    )
Enter fullscreen mode Exit fullscreen mode

Backoff: RETRY_BASE_SECONDS * (2 ** attempt), capped at RETRY_MAX_SECONDS. Default config: base=30s, max=3600s, max_retries=5 (6 total attempts).

Alerting That Actually Gets Seen

When an event hits dead_letter, the service posts to ALERT_WEBHOOK_URL (Slack-compatible) and/or sends a Telegram message via TELEGRAM_BOT_TOKEN + TELEGRAM_CHAT_ID. Alert failures are logged — never discard the dead-lettered event.

{
  "text": "🚨 *Webhook DLQ Alert*\nEvent `evt_abc123` (source: `forms`) moved to dead_letter after 6 attempts.\nLast error: `Connection refused`\nReplay: `POST /dlq/evt_abc123/replay`"
}
Enter fullscreen mode Exit fullscreen mode

Deploy in 3 Commands

git clone https://github.com/PabloIan92/webhook-dlq-shield
cd webhook-dlq-shield
cp .env.example .env  # Set TARGET_WEBHOOK_URL, WEBHOOK_SECRET, ADMIN_API_KEY
docker compose up --build
Enter fullscreen mode Exit fullscreen mode

API docs at http://localhost:8000/docs. Health check at /health (unauthenticated for container probes).

Production checklist:

  • [ ] Serve behind TLS (Caddy/Traefik/Cloudflare Tunnel)
  • [ ] Set WEBHOOK_SECRET for HMAC-SHA256 verification
  • [ ] Set ADMIN_API_KEY for /dlq and /stats protection
  • [ ] Configure ALERT_WEBHOOK_URL or Telegram credentials
  • [ ] Point your webhook producers to https://your-domain/webhooks/{source}

Real-World Usage

GoHighLevel form → Webhook DLQ Shield → n8n workflow → HubSpot

  • GHL webhook sends to /webhooks/ghl-forms
  • Shield persists, forwards to n8n webhook endpoint
  • n8n enriches, creates HubSpot contact
  • If n8n is down: event queues, retries, alerts on Slack
  • Operator replays from /dlq after n8n recovers

Stripe webhook → Shield → internal billing service

  • Stripe sends checkout.session.completed to /webhooks/stripe
  • Stripe-Signature verified by your app (Shield passes raw body + headers)
  • Billing service processes; if it 500s, Shield retries automatically

The Blueprint & Done-For-You Option

The repo is MIT-licensed. Fork it, adapt it, run it yourself.

If you'd rather not spend a day wiring it into GHL/n8n/HubSpot/Stripe with alerting tuned — there's a packaged blueprint ($99) and a 72-hour done-for-you VPS install ($499) on Gumroad:

👉 Get Webhook DLQ Shield on Gumroad

Includes:

  • Webhook_DLQ_Shield_v1.zip (source + Docker + systemd + Caddy configs)
  • Environment templates for GHL, n8n, HubSpot, Stripe
  • Telegram/Slack alert wiring guide
  • 7-day email support for the DFY tier

Repository

GitHub: https://github.com/PabloIan92/webhook-dlq-shield

Issues/PRs welcome. 7/7 tests passing (pytest -q).


Built this after losing leads to silent webhook failures one too many times. If you've ever had a pipeline review reveal "missing" contacts — this is the fix.

Top comments (0)