Stripe Webhook Idempotency: Stopping Duplicate Fulfillment
How to build an atomic, replay-safe Stripe webhook architecture in PostgreSQL: eliminate duplicate charges, handle retries, and solve out-of-order events.
When developing billing integrations locally with the Stripe CLI, payment events arrive sequentially over clean loopback sockets, and local database transactions commit in single-digit milliseconds. Because testing flows execute without dropped packets or processing delays, engineering teams reasonably assume that production webhooks will arrive in identical chronological order with exactly-once delivery guarantees.
In production environments, this assumption breaks down under normal network variance. Stripe guarantees at-least-once delivery; when serverless cold starts, database lock contention, or network latency push response times past 3,000 milliseconds, Stripe records a timeout and dispatches automated retries. Without atomic database-level idempotency reservation and timestamp guards, concurrent delivery attempts execute in parallel, causing duplicate credit allocations, multiple invoice rows, and corrupted subscription states.
Quick Production Webhook Triage Checklist
If your application is experiencing duplicate billing events or webhook timeout storms, implement this four-point remediation sequence:
- Verify Raw Request Byte Streams: Never parse incoming request bodies as JSON before verifying HMAC signatures. Extract unparsed text using
req.text()or raw buffers to avoid byte serialization shifts that invalidate cryptographic hashes. - Enforce Atomic Event Reservation via Primary Keys: Insert the incoming
event.idinto anidempotency_keystable usingINSERT INTO ... ON CONFLICT (event_id) DO NOTHING. If zero rows are inserted, abort execution immediately and return HTTP 200. - Decouple Heavy Business Mutations from the Ingress Route: Acknowledge webhooks with HTTP 200 within 200 milliseconds. Offload external API calls, PDF invoice rendering, and email dispatch to asynchronous background queues.
- Use Upserts and Sequence Guards for Out-of-Order Events: When updating subscriptions or balances, execute
INSERT ... ON CONFLICT DO UPDATEand ensure updates only apply if the incoming event timestamp (event.created) is strictly greater than the recorded state timestamp.
The Concurrency Window: At-Least-Once Delivery vs Race Conditions
Stripe dispatches webhooks across distributed worker clusters and retries unacknowledged payloads with exponential backoff over a 72-hour window. If your endpoint fails to return an HTTP status code between 200 and 299 within 3,000 milliseconds, Stripe flags the delivery as failed and initiates a retry.
THE DUPLICATE WEBHOOK RACE CONDITION
Stripe Dispatch Worker Serverless App Engine PostgreSQL Database
┌────────────────────────────────────┐ ┌───────────────────────────┐ ┌─────────────────────────┐
│ Dispatch Event: │ ──> │ Lambda Invocation #1 │ │ │
│ evt_1P001 (checkout.completed) │ │ Cold start latency: 2.8s │ │ │
└────────────────────────────────────┘ └───────────────────────────┘ │ │
│ │ │ │
[ 3,000ms Timeout Reached ] │ │ │
│ ▼ │ │
▼ Reads: Event Not Found ─────────> │ SELECT * FROM events... │
┌────────────────────────────────────┐ │ │ │
│ Dispatch Retry #1: │ ──> ┌───────────────────────────┐ │ │
│ evt_1P001 (Identical Payload) │ │ Lambda Invocation #2 │ │ │
└────────────────────────────────────┘ │ Warm runtime: 40ms │ │ │
└───────────────────────────┘ │ │
│ │ │
▼ │ │
Reads: Event Not Found ─────────> │ SELECT * FROM events... │
│ │ │
▼ ▼ │
[ Both Invocations Execute Double Credit Provisioning ] │
A common design flaw is the non-atomic check-then-act pattern:
// ❌ CATASTROPHIC RACE CONDITION: Check-then-act pattern allows parallel execution
export async function POST(req: Request) {
const event = await parseStripeEvent(req);
// Both concurrent executions query the database before either commits!
const existing = await db.processedEvents.findUnique({ where: { id: event.id } });
if (existing) {
return new Response('Already Handled', { status: 200 });
}
// Vulnerability Window: Both threads reach this line and award double credits
await grantCustomerCredits(event.data.object.customer, 500);
await db.processedEvents.create({ data: { id: event.id } });
return new Response('Success', { status: 200 });
}
Between the instant the first thread queries findUnique and the instant it calls create, the second concurrent retry arrives, checks the same table, finds zero records, and proceeds to credit the user account a second time.
Implementing Atomic Database Idempotency Tables
To eliminate concurrency race conditions, applications must leverage atomic relational constraints. In PostgreSQL, a primary key or unique constraint collision is evaluated atomically at the database kernel level, guaranteeing that exactly one concurrent transaction succeeds.
-- Production Idempotency Ledger Table
CREATE TABLE IF NOT EXISTS stripe_processed_events (
event_id VARCHAR(255) PRIMARY KEY,
event_type VARCHAR(100) NOT NULL,
processed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
payload JSONB
);
When an incoming webhook arrives, execute an atomic reservation insert:
// src/app/api/webhooks/stripe/route.ts - Production Atomic Handler
import { NextResponse } from 'next/server';
import Stripe from 'stripe';
import { pool } from '@/lib/db';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: '2024-06-20',
});
export async function POST(req: Request) {
const rawBody = await req.text(); // Extracts raw bytes for HMAC validation
const signature = req.headers.get('stripe-signature');
if (!signature) {
return NextResponse.json({ error: 'Missing stripe-signature header' }, { status: 400 });
}
let event: Stripe.Event;
try {
// 1. Cryptographic HMAC validation against unparsed raw byte stream
event = stripe.webhooks.constructEvent(
rawBody,
signature,
process.env.STRIPE_WEBHOOK_SECRET!
);
} catch (err: any) {
return NextResponse.json({ error: `Signature verification failed: ${err.message}` }, { status: 400 });
}
const client = await pool.connect();
try {
await client.query('BEGIN');
// 2. Atomic idempotency reservation using primary key constraint
const reservation = await client.query(
`INSERT INTO stripe_processed_events (event_id, event_type, payload)
VALUES ($1, $2, $3)
ON CONFLICT (event_id) DO NOTHING
RETURNING event_id`,
[event.id, event.type, JSON.stringify(event.data.object)]
);
// If rowCount is 0, another concurrent invocation already claimed this event
if (reservation.rowCount === 0) {
await client.query('ROLLBACK');
// Crucial: Return HTTP 200 so Stripe acknowledges delivery and halts retries
return NextResponse.json({ received: true, duplicate: true }, { status: 200 });
}
// 3. Execute business logic within the same atomic transaction
switch (event.type) {
case 'checkout.session.completed': {
const session = event.data.object as Stripe.Checkout.Session;
await fulfillCheckout(client, session);
break;
}
case 'invoice.payment_succeeded': {
const invoice = event.data.object as Stripe.Invoice;
await processInvoicePayment(client, invoice);
break;
}
case 'customer.subscription.deleted': {
const sub = event.data.object as Stripe.Subscription;
await terminateSubscriptionAccess(client, sub);
break;
}
default:
break;
}
await client.query('COMMIT');
return NextResponse.json({ received: true });
} catch (error) {
await client.query('ROLLBACK');
// Returning 500 signals to Stripe to schedule a retry after internal failure
return NextResponse.json({ error: 'Internal processing failure' }, { status: 500 });
} finally {
client.release();
}
}
Important: If
reservation.rowCount === 0, immediately rollback the transaction and return HTTP 200. Returning an error code (such as 400 or 500) indicates to Stripe that delivery failed, perpetuating the retry loop for up to 72 hours. Returning HTTP 200 confirms that the payload has been recorded and safely processed.
Solving the Out-of-Order Webhook Dilemma
Stripe webhooks are dispatched asynchronously across multi-region infrastructure, meaning event arrival order cannot be guaranteed.
Consider this standard subscription creation sequence:
- Stripe emits
customer.subscription.created. - Stripe immediately emits
invoice.payment_succeeded.
Due to variable network routing or cold start latencies, your application endpoint may receive invoice.payment_succeeded two seconds before customer.subscription.created. If the invoice handler executes a standard update query:
UPDATE subscriptions
SET status = 'active', current_period_end = $1
WHERE stripe_subscription_id = $2;
Because the preceding subscription creation event is still in flight, the record does not yet exist in your database. The UPDATE query silently updates zero rows (rowCount: 0). When the subscription creation handler finally executes moments later, it overwrites the subscription record with default un-invoiced parameters, leaving the customer account in an inactive state despite successful payment.
Strategy 1: Natural Key Upserts
Never assume an entity already exists when handling downstream billing events. Use PostgreSQL INSERT ... ON CONFLICT DO UPDATE:
INSERT INTO user_subscriptions (
user_id,
stripe_customer_id,
stripe_subscription_id,
status,
current_period_end,
updated_at
) VALUES ($1, $2, $3, $4, $5, NOW())
ON CONFLICT (stripe_subscription_id) DO UPDATE SET
status = EXCLUDED.status,
current_period_end = EXCLUDED.current_period_end,
updated_at = NOW();
Strategy 2: Event Timestamp Sequence Guards
Stripe payloads include a canonical unix timestamp: event.created. When updating customer records based on mutating events (such as customer.subscription.updated), verify that the incoming event is strictly newer than the last applied event timestamp:
UPDATE user_subscriptions
SET
status = $1,
last_stripe_event_timestamp = $2,
updated_at = NOW()
WHERE stripe_subscription_id = $3
AND last_stripe_event_timestamp < $2;
If an older event arrives delayed after a newer update has already committed, the WHERE condition safely fails to match, preserving the newer state without manual intervention.
Webhook Failure Modes vs Architectural Mitigations
The following benchmark table categorizes the most common webhook failure modes, their root causes, and verified engineering mitigations:
| Failure Mode | Root Cause | Observable Symptom | Required Mitigation Pattern |
|---|---|---|---|
| Duplicate Delivery | Network dropped packet or response latency > 3,000ms | Customer billed once but credited twice in database | PostgreSQL INSERT ... ON CONFLICT (event_id) DO NOTHING |
| Out-of-Order Events | Multi-worker concurrent dispatch across distributed queues | invoice.payment_succeeded fails because subscription record does not exist yet | State machine verification & payload upserts using Stripe Object IDs |
| Payload Deserialization Bug | Parsing body via req.json() before signature verification | Cryptographic validation failure (stripe-signature verification failed) | Extract raw body as string or buffer using req.text() before passing to SDK |
| Worker Timeout | Synchronous heavy tasks (PDF generation, third-party emails) | HTTP 504 Gateway Timeout followed by a 72-hour retry storm | Decouple webhook ingress: acknowledge with HTTP 200 in under 200ms, queue tasks to BullMQ/SQS |
| Stale Webhook Secrets | Production deployment rotation without dual-secret grace period | All production payments suddenly report 400 signature errors | Multi-secret signature verification array during credential rollover |
Cryptographic Security and Secret Rollover
Processing financial webhooks requires strict cryptographic validation. Accepting unverified JSON payloads exposes your database to forged events and arbitrary balance grants.
1. Verification from Raw Byte Streams
Always pass the exact incoming text stream to stripe.webhooks.constructEvent(). If a web middleware parses the body into an object and re-stringifies it with JSON.stringify(), key ordering and whitespace shifts will corrupt the cryptographic HMAC-SHA256 signature hash.
2. Zero-Downtime Secret Rotation
When rolling over webhook secrets in production, do not replace the secret environment variable instantaneously. In-flight requests signed with the previous secret will immediately fail. Provide dual-secret validation support during maintenance windows:
function verifyWithFallback(rawBody: string, signature: string, secrets: string[]): Stripe.Event {
for (const secret of secrets) {
try {
return stripe.webhooks.constructEvent(rawBody, signature, secret);
} catch {
// Secret did not match; try fallback secret
}
}
throw new Error('All signature verification candidates failed.');
}
Pre-Launch Webhook Verification Checklist
Before onboarding paying enterprise customers, execute these five verification checks:
- Verify Raw Body Extraction: Confirm that your API route handler accesses
req.text()or raw buffers before any parsing middleware executes. - Validate Atomic Idempotency Table: Ensure your database schema defines a primary key constraint on
stripe_processed_events.event_id. - Confirm Fast Ingress Acknowledgement: Verify that endpoints return HTTP 200 within 200ms, queueing asynchronous tasks like PDF generation to background workers.
- Inspect Connection Pooling Limits: Ensure high-volume webhook retries do not exhaust database connections by utilizing connection pooling on port 6543, as outlined in our guide on Why Supabase and Neon Freeze at Scale.
- Enforce Multi-Tenant Boundaries: Verify that webhook mutations cannot alter records belonging to outside tenants by establishing explicit database boundaries, as detailed in 5 Critical Security Boundaries in Rapid MVPs.
You can benchmark your edge endpoints and application latency using our Free GEO Checker & AI Readiness Scanner or review developer utilities in Diagnostic Tools.
If your application is managing escalating payment volume, concurrency deadlocks, or complex subscription state machines, our engineering practice provides comprehensive architecture hardening. Explore our Architecture Hardening & Scale Sprint or contact our engineering desk to schedule an architecture review.
Marcus Vance
Principal Systems ArchitectSystems engineer focusing on distributed backends, database concurrency, and application security. Specializes in high-throughput PostgreSQL concurrency, serverless connection pooling, and infrastructure hardening.
Why does Stripe send duplicate webhook events for the same transaction?
How do you prevent duplicate fulfillment when concurrent retries arrive?
Why do Stripe webhooks frequently arrive out of order?
What HTTP status code should be returned when a duplicate webhook is detected?
Have our team inspect your AI-generated codebase.
48-hour turnaround with direct pull requests fixing security and scale bottlenecks.