Reliable Webhooks documentation
The README, architecture and security documents shipped in v1.0.1 of the package, published so you can judge the API before you buy. Markdown version.
Get Reliable Webhooks · $49Source, tests and examples · v1.0.1 · one-time
Reliable Webhooks (@softreuse/webhook-kit) v1.0.1
Receive webhooks without losing, duplicating or double-processing them. Signature verification, idempotency, persistence, retries with backoff and dead letters in ~780 lines of TypeScript with zero runtime dependencies.
- Node >= 20 (also runs on Bun, Deno and edge runtimes: Web Crypto +
Request/Responseonly) - TypeScript strict · ESM · PostgreSQL store included (any DB via the
WebhookStoreinterface) - Providers: Stripe, GitHub, and a generic HMAC provider for everything else
Contents of this package
src/ the library (read it: it is short)
receiver.ts verify → persist → acknowledge → process, retries, replay
providers/ stripe.ts, github.ts, hmac.ts
stores/ postgres.ts, memory.ts
retry.ts, errors.ts, logger.ts, crypto.ts, adapters/node.ts
migrations/001_webhook_events.sql
tests/ 60 tests: providers, receiver, retry, Node adapter, store contract (Memory + Postgres)
examples/
stripe-fulfillment/ runnable offline demo (`npm run demo`)
next-app-router/ route handler + cron worker + Postgres wiring
node-http/ node:http / Express
docs/ARCHITECTURE.md how it works and why
docs/SECURITY.md threat model and deployment checklist
CHANGELOG.md · LICENSE.md
1. See it work (30 seconds)
npm install
npm run demo
The demo starts a real HTTP server and walks through: a forged request (rejected), a valid event while your database is down (stored, retried), a duplicate delivery (ignored) and recovery (fulfilled exactly once).
Run the tests: npm test. To also run the Postgres store tests against a real database: DATABASE_URL=postgres://... npm test (it creates and drops its own temporary table).
2. Install into your project
Option A — copy the source (recommended). Copy src/ to e.g. src/lib/webhook-kit/ and migrations/001_webhook_events.sql into your migrations. You own the code; adjust freely.
Option B — local package. npm run build, then npm install ../path/to/this/folder. Import from @softreuse/webhook-kit.
The examples import from ../../src/index.js; in your app import from wherever you placed it.
3. Quick start (Next.js App Router + Postgres + Stripe)
- Run
migrations/001_webhook_events.sqlon your database. - Create the receiver once (
examples/next-app-router/webhooks.ts):
import { Pool } from "pg";
import { createWebhookReceiver, PostgresStore, stripeProvider } from "@softreuse/webhook-kit";
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
export const receiver = createWebhookReceiver({
provider: stripeProvider({ secret: process.env.STRIPE_WEBHOOK_SECRET! }),
store: new PostgresStore(pool),
handlers: {
"checkout.session.completed": async ({ event, idempotencyKey }) => {
// your business logic: make it idempotent using idempotencyKey
},
},
});
- Mount it (
app/api/webhooks/stripe/route.ts):
export async function POST(request: Request) {
return receiver.handle(request);
}
- Schedule the retry worker every minute (
app/api/cron/webhooks/route.ts, seeexamples/next-app-router/cron-route.ts) so failed events are retried:
await receiver.processDue({ limit: 25 });
- Point Stripe at
https://your-app/api/webhooks/stripeand copy the signing secret intoSTRIPE_WEBHOOK_SECRET.
That is the whole integration. Everything below is reference.
4. How a request is handled
| Situation | Response | Stored? |
|---|---|---|
| Not POST | 405 |
no |
Body larger than maxBodyBytes |
413 |
no |
| Missing/invalid/old signature | 401 |
no |
| Verified but no id/type | 400 |
no |
| Could not write to the store | 500 (provider will retry) |
no |
| New event | 200 {"status":"accepted"} |
yes, then processed (inline) |
| Duplicate event id | 200 {"status":"duplicate"} |
already was |
| Handler throws | 200 {"status":"accepted"}: it is stored and we retry |
yes, pending + backoff |
Details and reasoning: docs/ARCHITECTURE.md.
5. Handlers
handlers: {
"invoice.paid": async (ctx) => {
ctx.event.payload; // parsed JSON body (unknown: validate it, e.g. with zod)
ctx.event.rawBody; // exact bytes as received
ctx.event.attempt; // 1 on the first try, 2 on the first retry, ...
ctx.idempotencyKey; // "stripe:evt_123" — use it for your own idempotent writes
ctx.logger.info("...");
},
"*": (ctx) => { /* fallback for unlisted types */ },
}
- Events with no matching handler (and no
"*") are acknowledged and recorded asprocessed. - Throw to fail the attempt: it is retried with backoff.
- Throw
NonRetryableErrorwhen retrying cannot help (unknown customer, invalid payload): the event goes straight todead. - Handlers run at least once. Make side effects idempotent (
INSERT ... ON CONFLICT DO NOTHINGkeyed byidempotencyKey, or check-then-write inside a transaction).
6. Providers
stripeProvider({ secret: "whsec_...", toleranceSeconds: 300 })
githubProvider({ secret: "..." })
hmacProvider({
name: "acme",
secret: "...", // or ["new", "old"] while rotating
signatureHeader: "x-acme-signature",
signaturePrefix: "sha256=", // optional
encoding: "hex", // or "base64"
timestampHeader: "x-acme-timestamp", // optional: enables replay protection (signed as `${ts}.${body}`)
toleranceSeconds: 300,
signedMessage: (rawBody, timestamp) => `${timestamp}.${rawBody}`, // optional override
identify: ({ rawBody, headers }) => ({ id: headers.get("x-acme-id")!, type: JSON.parse(rawBody).type }),
})
Pass an array as secret to rotate secrets without downtime. Need a provider with a different scheme? Implement WebhookProvider (name, verify, identify).
7. Configuration
| Option | Default | Meaning |
|---|---|---|
provider |
required | Verifies and identifies requests |
store |
required | PostgresStore, MemoryStore or your own WebhookStore |
handlers |
required | Map of event type → handler ("*" fallback) |
mode |
"inline" |
"deferred" = only store; a worker calls processDue() |
retry.maxAttempts |
8 |
Total attempts including the first |
retry.baseDelayMs |
30000 |
Delay ceiling before the 1st retry; doubles each attempt |
retry.maxDelayMs |
3600000 |
Cap for any delay. Delays use full jitter: uniform in [0, ceiling] |
maxBodyBytes |
1048576 |
Request size limit |
handlerTimeoutMs |
30000 |
A handler running longer counts as a failed attempt |
leaseMs |
handlerTimeoutMs + 30000 |
How long a claimed event is reserved before another worker may take it |
logger |
JSON to console | { info, warn, error }(msg, fields); use silentLogger in tests |
now, random |
system | Injectable for deterministic tests |
With the defaults an event is attempted at most 8 times over roughly 1–2 hours before it is dead-lettered.
8. Operating it
await receiver.processDue({ limit: 25 }); // run due retries; also recovers crashed workers
await receiver.store.list({ status: "dead" }); // inspect dead letters
await receiver.replay({ provider: "stripe", id: "evt_123" }); // give a dead event a fresh set of attempts
Alert when dead letters exist. Prune old rows with the DELETE at the bottom of the migration. Structured logs (webhook.processed, webhook.retry_scheduled, webhook.dead, webhook.duplicate, webhook.signature_rejected, webhook.persist_failed) contain ids, types and attempt numbers only.
9. Express / node:http
import { toNodeHandler } from "@softreuse/webhook-kit";
app.post("/webhooks/github", toNodeHandler(receiver)); // NO express.json() on this route
10. Other databases
Implement the WebhookStore interface (8 small methods; see src/types.ts) and add it to the impls list in tests/store.contract.test.ts. The contract tests check idempotency under concurrency, lease semantics, retry scheduling, dead letters and replay. PostgresStore accepts anything with a node-postgres-style query(text, values) method.
11. Troubleshooting
| Symptom | Cause / fix |
|---|---|
Always 401 invalid signature |
The body was parsed and re-serialised before reaching the receiver (remove express.json()/body parsers on this route), or you copied the wrong secret (each Stripe endpoint has its own whsec_), or you are using a CLI-forwarded secret against a dashboard endpoint. |
401 ... timestamp outside tolerance |
Server clock drift, or you are replaying an old captured request. Check NTP; widen toleranceSeconds only if the clock cannot be fixed. |
Events stay pending |
Nothing calls processDue(). Schedule it. In deferred mode it is the only thing that processes events. |
Events stuck in processing |
A worker died mid-handler. They are re-claimed automatically after leaseMs. |
| Handler ran twice | Expected under at-least-once delivery (e.g. crash after the side effect). Use ctx.idempotencyKey. |
dead events after an outage |
Fix the cause, then replay() them. Raise retry.maxAttempts/maxDelayMs if your outages are long. |
| Handler "timed out" but its side effect still happened | handlerTimeoutMs stops waiting; JavaScript cannot cancel a running handler. The event is retried while the first run may still finish, which is why handlers must be idempotent. Pass an AbortSignal.timeout() into your own I/O if you want real cancellation. |
| Function killed mid-handler on serverless | Your platform's max duration is shorter than handlerTimeoutMs. Raise it (e.g. Vercel export const maxDuration = 60), lower handlerTimeoutMs, or use mode: "deferred" and let the cron worker process events. The lease recovers the event either way. |
500 could not persist event |
The store is unreachable. The provider will retry; check database connectivity/credentials. |
Invalid table name |
PostgresStore({ table }) only accepts name or schema.name made of letters, digits and underscores. |
12. Compatibility
Test suite (60 tests, 10 of them against a real database) passes on Node 20, 22, 24 and 26, against PostgreSQL 17 (Supabase). The library needs only crypto.subtle, Request, Response, Headers and TextEncoder (Node >= 20, Bun, Deno, Cloudflare Workers; the Postgres store needs a Postgres client, the memory store needs nothing). The Node adapter needs node:http.
13. Updates and license
Purchase includes all v1.x releases (see CHANGELOG.md). Licensed under the Softreuse Commercial License (LICENSE.md): unlimited own projects, no redistribution as a standalone product. Support: support@softreuse.com
Architecture
The one rule
Persist first, then process. A webhook is acknowledged with 2xx only after it is durably stored. From that moment you own delivery (retries, ordering decisions, dead letters) and the provider no longer has to.
provider ──POST──▶ handle(request)
│ 1. read body (size-capped, raw bytes)
│ 2. provider.verify ── fail ─▶ 401 (nothing stored)
│ 3. provider.identify ─ fail ─▶ 400
│ 4. store.insert ───── error ─▶ 500 (provider will retry; this is the ONLY 5xx path)
│ │ duplicate ────────────▶ 200 {status:"duplicate"}
│ 5. inline mode: claim + run handler
▼
200 {status:"accepted"} (even if the handler failed: it is stored, we retry)
worker / cron ──▶ processDue() ──▶ claimDue (lease) ──▶ handler ──▶ processed | pending(+backoff) | dead
Event lifecycle
| Status | Meaning |
|---|---|
pending |
Stored and waiting. next_attempt_at says when it is due (now for new events, later after a failure). |
processing |
Leased by a worker until locked_until. If the worker dies, the lease expires and the event is claimable again. |
processed |
Handler finished without throwing. Terminal. |
dead |
Attempt budget spent, or the handler threw NonRetryableError. Terminal until you replay it. |
Transitions: pending → processing → processed, processing → pending (retry, with backoff), processing → dead, dead → pending (replay).
Why each mechanism exists
- Idempotency key =
(provider, event_id)primary key. Providers deliver at least once: network timeouts, your own 5xx, and manual re-sends all produce duplicates. The database, not application code, decides who wins, so concurrent duplicates are safe. - Lease (
locked_until) instead of a lock. A process that crashes or is killed mid-handler (common on serverless) cannot release a lock. A lease expires by itself.attemptscounts every claim, so an event that crashes its worker every time is dead-lettered instead of looping forever. FOR UPDATE SKIP LOCKED. Many workers can poll the same table without blocking each other or processing the same row twice.- Backoff with full jitter. After an outage, thousands of failed events would otherwise retry at the same instant and knock the recovering system over again.
- Handlers run at-least-once. A handler can succeed and the process die before
markProcessed. The only correct answer is an idempotent handler; that is why every handler receivesidempotencyKey("<provider>:<event id>") for you to use in your own writes. - Ack after persist, not after processing. Answering
2xxonly after a slow handler finishes makes the provider time out and re-send. Answering after the durable insert keeps the provider's retry logic out of your failure path.
Ordering
Webhooks may arrive out of order and retries make that worse. The kit does not serialise events. If you need ordering, make handlers order-independent: compare an object's updated_at/version in the payload with what you have stored, or re-fetch the object from the provider API inside the handler instead of trusting the payload.
Modes
inline(default): processing happens inside the request after the insert. Simple, works on serverless. Keep handlers fast (the default timeout is 30 s).deferred: the request only stores the event; a worker/cron callsprocessDue(). Use for slow handlers or when your platform caps request time.
In both modes failed events are retried by processDue(), so schedule it (every minute is a good default).
Extending
- Another provider: use
hmacProvider({ ... })for any shared-secret HMAC scheme, or implement the two-methodWebhookProviderinterface (verify,identify). - Another database: implement
WebhookStore(8 methods).tests/store.contract.test.tsruns a behavioural contract against any implementation; add yours to theimplslist.
Security notes
Reviewed against the Softreuse Product Standard. This documents what the module defends against, what it does not, and what you must do in your deployment.
Threat model
| Threat | Mitigation in the kit |
|---|---|
| Forged requests | HMAC-SHA256 verification over the raw body, using crypto.subtle.verify (constant-time). Unauthenticated requests get 401 and are never stored. |
| Replay of a captured request | Timestamp tolerance (Stripe: default 300 s, configurable; generic provider with timestampHeader). For providers without timestamps (GitHub), replay is neutralised by idempotency on the delivery id. |
| Duplicate delivery | Primary-key idempotency enforced by the database; concurrent duplicates tested. |
| Timing attacks on the signature | No string/array equality on secrets or signatures; all candidate secrets are checked without early exit. |
| Oversized body (memory DoS) | maxBodyBytes (default 1 MiB) checked against Content-Length and again while streaming. |
| Malformed signature headers | Parsed defensively; every failure path throws SignatureError (→ 401), never an unhandled exception. |
| SQL injection | Every value is a bound parameter. The only interpolated identifier (table name) is validated against a strict pattern at construction. Test included. |
| Poison events / crash loops | Lease expiry + attempt counter: an event that repeatedly kills its worker is dead-lettered. |
| Secret leakage via logs | The kit logs ids, types, attempt numbers and error messages only: never bodies, headers or secrets. Test included. |
| Secret rotation downtime | secret: [new, old] accepts both during the rotation window. |
What it does NOT do
- No IP allow-listing. Signatures are the trust boundary. If your provider publishes IP ranges and you want a second layer, enforce it at your edge/WAF.
- No ordering guarantees (see ARCHITECTURE.md).
- No exactly-once processing. Delivery to your handler is at-least-once; make side effects idempotent (use
ctx.idempotencyKey). - No rate limiting. Put your platform's rate limiter in front of the route if you expect abuse. Forged requests are cheap (one HMAC) but not free.
- No encryption at rest.
raw_bodyis stored as received and may contain personal data. Apply your database's encryption, restrict access, and prune old rows.
Your deployment checklist
- Store secrets in environment variables / a secrets manager; never commit them. Use a distinct secret per environment.
- Mount the route without a JSON body parser. Parsing and re-serialising changes bytes and breaks (or, worse, weakens) verification.
- Serve over HTTPS only.
- Run the migration and restrict the table to your application's database role.
- Schedule
processDue()and alert whendeadevents exist (store.list({ status: "dead" })). - Prune processed events (see the commented
DELETEat the bottom of the migration). - Error messages stored in
last_errorcome from your handlers: do not put personal data in exception messages.
Dependencies
Zero runtime dependencies. Development dependencies (typescript, vitest, pg, tsx) are not shipped. npm audit --omit=dev reports nothing for this package.
Reporting a vulnerability
Email support@softreuse.com with details. We acknowledge within 3 business days and ship fixes as patch releases to all customers.
Get Reliable Webhooks · $49Source, tests and examples · v1.0.1 · one-time