Stripe webhooks look straightforward during local development with the Stripe CLI. You verify the signature, parse event.type, update a row in PostgreSQL, and return 200 OK.
That approach breaks in production. Stripe guarantees at-least-once delivery, not exactly-once delivery. Under network retries, bursty checkout traffic, or overlapping events (checkout.session.completed arriving milliseconds before or after invoice.paid), a naive handler will double-credit user balances, create duplicate subscriptions, or trigger deadlocks.
Here is how to build an idempotent, concurrency-safe webhook handler in Node.js and PostgreSQL.
1. Track Processed Events with a Unique Constraint
In-memory deduplication (Set or Redis with a short TTL) fails as soon as you run multiple Node.js instances or restart a container. Your source of truth for idempotency belongs in PostgreSQL, inside the same transaction as your business state mutation.
Create a stripe_events table and a sample wallets table:
CREATE TABLE stripe_events (
event_id TEXT PRIMARY KEY,
event_type TEXT NOT NULL,
processed_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE wallets (
user_id UUID PRIMARY KEY,
balance_cents INTEGER NOT NULL DEFAULT 0 CHECK (balance_cents >= 0),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
Using event_id TEXT PRIMARY KEY delegates concurrency control to PostgreSQL. If two identical webhooks hit two different Node.js workers at the exact same millisecond, PostgreSQL lets one insert proceed and forces the second to wait until the first transaction commits or rolls back.
2. Combine Signature Verification with Atomic Transactions
Never parse the JSON body before verifying the Stripe signature Express's express.json() mutates the raw buffer and breaks stripe.webhooks.constructEvent. Mount express.raw({ type: 'application/json' }) strictly on the webhook route.
Here is the complete Express handler using pg:
import express, { Request, Response } from 'express';
import Stripe from 'stripe';
import { Pool } from 'pg';
const app = express();
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: '2025-02-24.acacia',
});
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: 20,
});
app.post(
'/webhooks/stripe',
express.raw({ type: 'application/json' }),
async (req: Request, res: Response): Promise<void> => {
const signature = req.headers['stripe-signature'];
if (typeof signature !== 'string') {
res.status(400).send('Missing stripe-signature header');
return;
}
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(
req.body,
signature,
process.env.STRIPE_WEBHOOK_SECRET!
);
} catch (err) {
const message = err instanceof Error ? err.message : 'Invalid signature';
res.status(400).send(`Webhook Error: ${message}`);
return;
}
const client = await pool.connect();
try {
await client.query('BEGIN');
const insertResult = await client.query(
`INSERT INTO stripe_events (event_id, event_type)
VALUES ($1, $2)
ON CONFLICT (event_id) DO NOTHING
RETURNING event_id`,
[event.id, event.type]
);
if (insertResult.rowCount === 0) {
await client.query('COMMIT');
res.status(200).json({ received: true, duplicate: true });
return;
}
if (event.type === 'checkout.session.completed') {
const session = event.data.object as Stripe.Checkout.Session;
const userId = session.metadata?.user_id;
const amountTotal = session.amount_total;
if (!userId || typeof amountTotal !== 'number') {
throw new Error(`Incomplete session payload for event ${event.id}`);
}
await client.query(
`INSERT INTO wallets (user_id, balance_cents)
VALUES ($1, $2)
ON CONFLICT (user_id)
DO UPDATE SET
balance_cents = wallets.balance_cents + EXCLUDED.balance_cents,
updated_at = NOW()`,
[userId, amountTotal]
);
}
await client.query('COMMIT');
res.status(200).json({ received: true });
} catch (err) {
await client.query('ROLLBACK');
console.error(`Failed to process Stripe event ${event.id}:`, err);
res.status(500).send('Internal Server Error');
} finally {
client.release();
}
}
);
app.listen(3000, () => {
console.log('Webhook server listening on port 3000');
});
3. Why ON CONFLICT DO NOTHING Beats Read-Then-Write
A common mistake is running SELECT 1 FROM stripe_events WHERE event_id = $1 before inserting. Under concurrent load, two requests can both execute the SELECT, both get zero rows back, and both attempt to credit the wallet.
With INSERT ... ON CONFLICT (event_id) DO NOTHING RETURNING event_id, PostgreSQL acquires a row-level index lock on the conflict key:
- Worker A inserts
evt_123and begins updatingwallets. - Worker B tries to insert
evt_123and blocks until Worker A finishes. - If Worker A commits, Worker B's
INSERTreturnsrowCount === 0and exits cleanly with200 OK. - If Worker A rolls back (for instance, due to a transient DB timeout), Worker B immediately acquires the lock and processes
evt_123instead of dropping it.
4. Stress-Testing Concurrency Locally
Before deploying, verify the lock behavior by firing parallel requests with identical event IDs against your local endpoint. You can write a quick script using Node's native fetch:
import crypto from 'node:crypto';
const WEBHOOK_SECRET = process.env.STRIPE_WEBHOOK_SECRET!;
const ENDPOINT = 'http://localhost:3000/webhooks/stripe';
function signPayload(payload: string, secret: string): string {
const timestamp = Math.floor(Date.now() / 1000);
const signedPayload = `${timestamp}.${payload}`; const signature = crypto .createHmac('sha256', secret) .update(signedPayload, 'utf8') .digest('hex'); return `t=${timestamp},v1=${signature}`; } async function runConcurrencyTest() { const payload = JSON.stringify({ id: `evt_test_${Date.now()}`,
object: 'event',
type: 'checkout.session.completed',
data: {
object: {
amount_total: 2500,
metadata: { user_id: '11111111-1111-1111-1111-111111111111' },
},
},
});
const sigHeader = signPayload(payload, WEBHOOK_SECRET);
const requests = Array.from({ length: 15 }, () =>
fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'stripe-signature': sigHeader,
},
body: payload,
}).then((r) => r.json())
);
const results = await Promise.all(requests);
console.log(results);
}
runConcurrencyTest();
If everything is wired correctly, exactly one response returns { received: true }, fourteen return { received: true, duplicate: true }, and the wallet balance increases by 2500 not 37500.
Key Takeaways
- Keep event deduplication inside the same SQL transaction as your state update so partial failures never poison the idempotency table.
- Return
500on transient database errors so Stripe retries with exponential backoff; return200on duplicates so Stripe stops retrying. - Keep webhook handlers fast. If an event triggers slow side effects like sending emails or generating PDFs, write a job row inside the same transaction and let a background worker handle it asynchronously.
Top comments (0)