How Do You Prevent Double Charges When a Payment Succeeds but Your Database Fails?
Everyone knows to stop a double charge. Far fewer teams handle the nastier case: the payment gateway says yes, and then your own database write fails.
In short: A payment operation touches two systems, the payment gateway (Stripe, Chargebee or any other) and your database. If the gateway call succeeds and your database commit fails, the customer has paid but your system has no record of it, and a retry may charge them again. Gateway idempotency keys don’t fully solve this. We use a small application-level guard: after the gateway succeeds, we store the invoice ID and the exact amounts in Redis; a retry reuses them instead of charging again; a different pending operation is rejected with a 409; the key is deleted after a successful commit and expires on its own as a safety net. We cover it with 45 dedicated test cases across three billing operations, including one known gap we document openly.
The failure nobody plans for
Picture a subscription system. A staff member switches a patient’s package mid-cycle. The system works out the proration, creates an invoice at the payment gateway, charges the card, and then writes the invoice, the new package and the wallet transactions to the database.
Now the database commit fails. A lock timeout, a dropped connection, a deploy at the wrong moment.
What’s the state of the world?
- At the gateway: the customer has been charged.
- In your database: nothing happened. The old package is still active, and there’s no invoice record.
- On the staff member’s screen: an error. So they click again.
Without protection, the retry calculates the proration again and charges the card a second time. That’s the double charge everyone worries about, but its root cause isn’t the double click. It’s the gap between two systems that can’t be updated in one transaction.
Why gateway idempotency keys aren’t enough
Payment gateways offer idempotency keys, and you should use them. Send the same key twice and the gateway returns the original result instead of creating a second charge. We use them too, for example in scheduled renewal jobs.
But for user-initiated operations they leave real gaps:
- The key must be exactly the same on the retry. If it’s generated per request, it protects nothing. That’s one of the most common idempotency bugs.
- Your inputs may change between attempts. Proration depends on today’s date. If the retry happens tomorrow, the recalculated amounts differ, so you’d be sending a different request, and your wallet records wouldn’t match the original invoice.
- They don’t tell your database what happened. The gateway knows the charge succeeded. Your database still needs the invoice ID and amounts to record it correctly.
- They don’t stop a different operation. If the first switch is half-finished and the user tries to switch to another package, the gateway sees a brand-new request.
So we added a guard at the application level, around the gateway call.
The pattern: guard, charge, record, clear
The guard is a single Redis key per subscription and operation. Its value holds everything needed to finish the operation without calling the gateway again:
- the gateway invoice ID;
- the target of the operation (for example, the new package);
- the exact amounts that were charged and refunded.
Step by step:
- Lock the record. The subscription row is locked for the duration of the request, so two simultaneous requests can’t both proceed.
- Check for a pending key.
- No key: this is a fresh operation. Proceed.
- Key for the same target: a previous attempt charged the customer but didn’t record it. Reuse the stored invoice ID and amounts, and skip the gateway entirely.
- Key for a different target: a different operation is half-finished. Return 409 Conflict and ask the user to retry the original operation first. This prevents orphaned invoices.
- Call the gateway, only when there’s no pending key.
- Write the key immediately after the gateway succeeds, before touching the database.
- Write the database records using the amounts from step 2 or step 4.
- Commit. On success, delete the key. On failure, keep it, so the retry can recover.
Here’s a simplified sketch of the idea. It isn’t production code, just the shape of it:
def switch_package(subscription, new_package_id):
pending = guard.get(subscription.id)
if pending and pending.target != new_package_id:
raise Conflict("Finish the pending switch before starting another.")
if pending:
invoice_id, amounts = pending.invoice_id, pending.amounts # recover
else:
amounts = calculate_proration(subscription, new_package_id)
invoice_id = gateway.charge(subscription.customer, amounts)
guard.set(subscription.id, target=new_package_id,
invoice_id=invoice_id, amounts=amounts, ttl_days=30)
record_invoice(subscription, invoice_id, amounts)
apply_new_package(subscription, new_package_id)
record_wallet_transactions(subscription, amounts)
return subscription
# In the request handler, after a successful commit:
# guard.delete(subscription.id)
Note on the supplied sketch: Its database-recording lines are indented inside the fresh-operation branch. A recovery must also execute those lines using the stored invoice ID and amounts, as the workflow above describes. The sketch is retained as supplied, not offered as production code.
The details that make it work
Store the amounts, don’t recalculate them. If a retry happens on a different day, recalculating the proration would produce different numbers. Storing the original amounts guarantees that the wallet records match the invoice the customer actually received.
Delete the key only after the commit. The key is removed by the request handler, after the transaction commits, not inside the business logic. That keeps the guard’s lifetime tied to the one moment that matters.
Make the key specific enough. For cancellations with a refund, the key includes the refund amount. A subscription can be cancelled, restarted and cancelled again later, and each cancellation must not collide with the previous one.
Use an expiry as a safety net. Keys expire after 30 days. If an operation is abandoned and never retried, the key can’t block the subscription forever.
Don’t let the guard become a single point of failure. If Redis is unavailable when the check runs, the request proceeds as if there’s no key and logs a warning. If deleting the key fails after a successful commit, the response still succeeds and the expiry cleans up later. The guard protects payments; it must not stop them.
Never write the key when the gateway fails. If invoice creation or the charge fails, no key is written, so the retry makes a fresh, clean attempt.
The gap we chose to document, not hide
No pattern built on two separate systems can be perfect, and this one has a known gap.
If the gateway succeeds, and writing the Redis key fails, and the database commit also fails, all in the same request, then there’s no record anywhere that the charge happened. The next retry will call the gateway again, which could double-charge.
Each of those three things is unlikely. All three together are rare. We decided the extra complexity of closing the gap completely wasn’t worth it, but we didn’t pretend it doesn’t exist:
- it’s written down in the code as a known, accepted risk;
- it has its own test cases, labelled as a known gap, in all three operations;
- it’s the case to watch for in reconciliation between gateway records and our own.
We think writing down known gaps is a sign of a healthy system, not a weak one.
How we test it
We wrote 45 idempotency test cases across the three billing operations that move money:
| Operation | Idempotency test cases |
|---|---|
| Switching a subscription package | 16 |
| Cancelling with a refund | 16 |
| Changing the billing cycle | 13 |
They cover, among others:
- the first-ever call with no key;
- a retry after the gateway succeeded but the commit failed;
- a retry for a different target, which must return 409;
- Redis unavailable during the check;
- Redis failing to write after the gateway succeeds;
- the documented gap: Redis write and commit both fail;
- a retry on a different day, which must use the stored amounts;
- key deletion after commit, and deletion failing after commit;
- no key written when the gateway call fails;
- the 30-day expiry;
- two simultaneous requests for the same subscription;
- an accidental retry after a successful operation;
- stored amounts and invoice IDs matching what’s recorded in the database.
Where AI fits in
This series is about building with AI agents, so it’s fair to ask what role AI played here.
The coding agent wrote much of the implementation. But the important decisions were made by people: that the dual-write gap needed handling, that amounts must be stored rather than recalculated, that a conflicting operation should get a 409, and that one rare gap was acceptable if documented. Those decisions went into the specification and the test cases first. The agent then built against them, and the tests checked the result.
That’s the pattern we keep coming back to: AI is fast at implementing a well-specified design. Deciding what the design should be, especially around money, is still engineering.
The forward deployed angle
Forward deployed engineers often inherit payment integrations that work on the happy path and fail on retries. Knowing where the dual-write gap is, and how to close it, is the kind of production detail that makes a deployment trustworthy, and it’s exactly what a client can’t specify on their own.
Explore our forward deployed engineering approach.
Key takeaways
- The dangerous payment failure isn’t the double click; it’s the gateway succeeding while your database commit fails.
- Gateway idempotency keys help, but they don’t record the outcome in your database or stop conflicting operations.
- Store the gateway invoice ID and the exact amounts immediately after the gateway call, and reuse them on retry.
- Reject a different operation while one is pending, with a 409.
- Delete the guard only after the commit, and give it an expiry as a safety net.
- Don’t let the guard block payments when Redis is down.
- Document the gaps you accept, and test them.
Related articles
- How Do You Verify That AI-Generated Code Follows Every Business Rule?
- How Do You Teach an AI Coding Agent Your Engineering Standards?
- Why Is Specification, Not Coding, the Bottleneck in AI Software Development?
Frequently asked questions
What is payment idempotency?
Payment idempotency means that repeating the same payment request has the same effect as making it once. A retry, double click or network timeout must never charge the customer twice.
Are Stripe idempotency keys enough to prevent double charges?
They prevent the gateway from processing the same request twice, if the key is identical on every retry. They don’t record the outcome in your database, don’t help when your inputs change between attempts, and don’t stop a different operation from starting while one is half-finished.
What should happen if the payment succeeds but the database commit fails?
The retry should recognize that the payment already happened and record it using the original invoice ID and amounts, without calling the gateway again. That requires storing those details somewhere durable immediately after the gateway call succeeds.
Why return 409 for a different operation?
Because a half-finished operation already charged or refunded the customer. Starting a different one would leave an orphaned invoice. The user should complete the original operation first.
What happens if Redis is down?
In our design the request proceeds as if no key exists, and a warning is logged. The guard protects payments but must never prevent them.
Does this apply to gateways other than Stripe?
Yes. The pattern is gateway-neutral. Any operation that updates an external payment system and your own database in separate steps has the same dual-write problem.
