If you've integrated a payment provider, you've written a webhook handler. It usually looks something like this:
app.post('/webhooks/payments', async (req, res) => {
const event = req.body;
if (event.type === 'charge.succeeded') {
await db.query(
`UPDATE subscriptions SET status = 'active', paid_until = paid_until + interval '1 month'
WHERE id = $1`,
[event.subscriptionId],
);
}
res.sendStatus(200);
});
It works in development. In production it has a problem: providers deliver webhooks at least once, not exactly once. If your server is slow to respond, times out, or returns a 500, the provider retries. Sometimes it retries while your first attempt is still running. Sometimes two copies of the same event arrive within milliseconds of each other.
With the handler above, each delivery extends the subscription by another month. In a billing system where the handler also triggers a charge, each delivery can charge the customer again.
I ran into this while building the payment-recovery engine for RailSwitch, a subscription billing system on Nigerian payment rails. The requirement was simple to state: each customer is charged exactly once per billing cycle, no matter how many times, or how concurrently, an event is delivered. This article walks through the pattern that got us there.
Three ways webhooks break you
- Duplicates. The same event (same ID) arrives twice, minutes apart, because the provider didn't get your 200 in time.
- Concurrent duplicates. The same event arrives twice at the same time, so both requests pass any "have I seen this?" check before either one records it.
-
Out-of-order events. A
charge.failedfor an old attempt arrives after a newercharge.succeeded.
A fix that handles only the first case is the most common bug. Checking a table and then inserting into it is a race: two requests can both check, both see nothing, and both proceed.
The building blocks
The pattern has four parts, and they only work together:
- An idempotency key for every event.
- A processed-events table with a unique constraint on that key.
- A row lock on the thing being changed (here, the subscription).
- All of it inside one database transaction.
1. An idempotency key
Every inbound event needs a stable identifier. Most providers include an event ID. If yours doesn't, derive one from fields that uniquely identify the event (for example, the provider's transaction reference plus the event type). Don't use a timestamp or anything generated on receipt, because a retry would get a different key.
2. A processed-events table
CREATE TABLE processed_events (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
subscription_id text NOT NULL REFERENCES subscriptions(id),
idempotency_key text NOT NULL,
result jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (subscription_id, idempotency_key)
);
The UNIQUE constraint is the part that actually guarantees correctness. Application-level checks are an optimisation; the database constraint is the guarantee. If two transactions ever try to record the same key, one of them fails.
Notice the result column. Instead of just recording "seen it", store what processing produced. When a duplicate arrives, you can return the same answer the first delivery got. That keeps responses consistent for callers that retry.
3. Lock the row you're changing
SELECT id, status, version, context
FROM subscriptions
WHERE id = $1
FOR UPDATE;
FOR UPDATE takes a row-level lock that lasts until the transaction ends. A second transaction that tries to lock the same subscription waits until the first commits or rolls back. That turns "two events at the same time" into "two events one after another", which is the case we already know how to handle.
I also keep a version column and check it on write:
UPDATE subscriptions
SET status = $2, context = $3, version = version + 1
WHERE id = $1 AND version = $4;
If the update touches zero rows, something changed the subscription since we read it, and we abort instead of overwriting newer data. With the row lock in place this should never fire, but it costs almost nothing and catches mistakes, like a code path that forgot to take the lock.
4. One transaction around everything
Here's the shape of the handler (simplified from the RailSwitch wrapper):
async function processEvent(subscriptionId: string, event: PaymentEvent, key: string) {
return db.transaction(async (tx) => {
// 1. Already processed? Return the stored result.
const seen = await tx.query(
`SELECT result FROM processed_events
WHERE subscription_id = $1 AND idempotency_key = $2`,
[subscriptionId, key],
);
if (seen.rows[0]) return { ...seen.rows[0].result, cached: true };
// 2. Lock the subscription row.
const { rows } = await tx.query(
`SELECT status, version, context FROM subscriptions WHERE id = $1 FOR UPDATE`,
[subscriptionId],
);
const sub = rows[0];
// 3. Decide the new state (a state machine works well here).
const next = applyEvent(sub, event);
// 4. Persist with a version check.
const updated = await tx.query(
`UPDATE subscriptions SET status = $2, context = $3, version = version + 1
WHERE id = $1 AND version = $4`,
[subscriptionId, next.status, next.context, sub.version],
);
if (updated.rowCount !== 1) throw new Error('stale version');
// 5. Record the key in the same transaction.
await tx.query(
`INSERT INTO processed_events (subscription_id, idempotency_key, result)
VALUES ($1, $2, $3)`,
[subscriptionId, key, next],
);
return { ...next, cached: false };
});
}
Why does the order matter? The state change and the "I processed this" record commit together or not at all. If the process crashes halfway, both roll back, and the provider's retry processes the event cleanly. You never end up with "state changed but key not recorded" (which causes a double charge on retry) or "key recorded but state unchanged" (which silently drops the event).
What about the race on step 1? Two concurrent duplicates can both run the SELECT and both find nothing. The second one then blocks on FOR UPDATE until the first commits. When it continues, it would insert the same key, and the UNIQUE constraint rejects it. Catch that error and treat it as a duplicate. In practice you can make this cleaner by re-checking processed_events after acquiring the lock, so the second request finds the first request's record and returns the cached result.
Keep side effects out of the transaction
The handler above changes state. It doesn't call the payment provider. That's deliberate.
If you make an HTTP call to charge a card inside the transaction and the transaction later rolls back, the charge already happened and you can't roll it back. In RailSwitch, the state machine decides that a charge should happen, and a separate worker performs it after the transaction commits, using its own idempotency key when it calls the provider. Most payment APIs accept one, so a retried charge request is safe on their side too.
Prove it with a concurrency test
Don't trust this pattern until you've watched it hold under load. The test that convinced me fires the same event many times in parallel against a real PostgreSQL database (not a mock):
it('applies a duplicated event exactly once under concurrency', async () => {
const sub = await createSubscription({ status: 'past_due' });
const event = { type: 'charge.succeeded', id: 'evt_123' };
const results = await Promise.allSettled(
Array.from({ length: 20 }, () => processEvent(sub.id, event, event.id)),
);
const row = await getSubscription(sub.id);
expect(row.status).toBe('active');
expect(row.version).toBe(sub.version + 1); // changed exactly once
const recorded = await countProcessedEvents(sub.id, event.id);
expect(recorded).toBe(1);
expect(results.filter((r) => r.status === 'fulfilled').length).toBeGreaterThan(0);
});
Run it against a real database in CI. Mocks don't have row locks or unique constraints, so a mocked version of this test passes even when the code is broken.
Checklist
- Every event has a stable idempotency key that's the same across retries.
- A
UNIQUEconstraint enforces "processed once", not just an application check. - The row being changed is locked with
SELECT … FOR UPDATE. - State change and idempotency record commit in the same transaction.
- A version check guards the write.
- External side effects happen after commit, with their own idempotency keys.
- A concurrency test runs against a real database.
None of these steps is complicated on its own. The bugs come from doing three of them and skipping the fourth. Payment providers will eventually send you a duplicate at exactly the wrong moment, so it's worth building the handler as if that's already happened.
Abdurrahman Balogun is a backend engineer and final-year Computer Science student at the University of Lagos. The full implementation, including the state machine and tests, is in railswitch-engine on GitHub.
Top comments (0)