The duplicate charge
A customer pays 49.90 for an order from a train. The request leaves the phone, the train enters a tunnel, and the app waits. After ten seconds it gives up and tries again, as it was built to do. The second attempt succeeds and the app shows a receipt.
The bank statement shows two charges.
Neither request handler reported a failure. The API received two valid requests and handled both correctly, so both charged the card. The first one succeeded too; only its answer never arrived.
Catullus asked for a thousand kisses, then a hundred, then another thousand, and proposed to muddle the total so that nobody could know it. A client that retries is in the same position, except it never wanted to lose count. Your API has to keep count for it.
This article shows why retries lead to duplicate charges unless the operation deduplicates them, how an idempotency key does that, and why the key has to travel all the way to the payment provider. Examples use ASP.NET Core, EF Core and PostgreSQL, but the reasoning holds for any stack.
The whole argument in 40 seconds.
The version everyone writes first
Charge the card, save the payment, return 201:
app.MapPost("/payments", async (PaymentRequest request, PaymentProvider provider, AppDb db, CancellationToken ct) =>
{
var chargeId = await provider.ChargeAsync(request.OrderId, request.Amount, ct);
var payment = new Payment { OrderId = request.OrderId, Amount = request.Amount, ProviderChargeId = chargeId };
db.Payments.Add(payment);
await db.SaveChangesAsync(ct);
return Results.Created($"/payments/{payment.Id}", payment);
});
It is correct for every request it receives. The problem is that it can't tell a second payment from a second attempt at the first one.
Why it fails
A timeout tells the client nothing about what happened. Three different stories look identical from its side:
| What happened | Charged? | What the client sees |
|---|---|---|
| The request never reached the API | No | Timeout |
| The API failed before charging | No | Timeout or 500 |
| The charge succeeded and the response was lost | Yes | Timeout |
The client can't tell these apart, so it has two choices: give up and maybe lose a sale, or retry and maybe charge twice. Almost everything in a modern system chooses to retry:
- People. A spinner that lasts too long gets a second tap.
- HTTP clients. The standard resilience handler for
HttpClientin .NET retries failed requests, POST included, unless you turn that off withDisableForUnsafeHttpMethods(). - Infrastructure. Gateways and load balancers can replay a request to another instance.
- Message consumers. Brokers deliver at least once, so a handler that calls your API will sometimes call it twice.
Retrying is the right reaction to a timeout only when repeating the request is safe. HTTP says which methods are meant to be repeatable: GET, PUT and DELETE are defined as idempotent. POST is not, and "create a payment" is a POST. RFC 9110 tells clients not to retry such a request automatically unless they know it is safe, and many of the retriers above do it anyway.
Three common fixes don't close the gap:
- Disable the Pay button after the first click. That stops one of the four retriers above.
- Check for an existing payment for this order before charging. This is the check-then-act race from A database constraint beats an async validator: two attempts can both find nothing. It also blocks orders that are legitimately paid in two parts.
- Treat the same amount within a minute as a duplicate. A guess blocks real payments and misses slow retries.
The server can't work out whether two identical requests are one intention or two. Only the client knows that, so the client has to say it.
The fix: let the client name the payment
Roman law barred a second action on the same matter, a principle later compressed into the maxim ne bis in idem, not twice for the same thing. A court can only apply it if it can recognise the same matter when it comes back. An idempotency key gives a payment that identity.
The client generates a unique value for each payment it intends to make, usually a UUID, and sends it in an Idempotency-Key header. Every retry of that payment carries the same key. A new payment gets a new key.
POST /payments
Content-Type: application/json
Idempotency-Key: 0f2b6c1e-8d4a-4f0b-9a57-3c1d2e4f5a6b
{"orderId":"order-2001","amount":49.90}
The header is not a standard yet. The IETF draft that defines it writes the value as a quoted string, Idempotency-Key: "0f2b6c1e-..."; Stripe and many other APIs take it bare, as above. Pick one convention and document it. The sample accepts both forms as the same key and rejects a request that carries more than one.
The Greeks had an object for this, the symbolon: a token broken in two when an agreement was made, each party keeping a half. Whoever arrived later with the matching half was speaking about the same agreement. The key is the client's half, and the server keeps the other.
The server side has three steps.
1. Claim the key
The API keeps one row per key: the key, a fingerprint of the request, a status and, once the work is done, the response.
The fingerprint defines what "the same request" means, so choose it deliberately. A hash of the raw body treats 49.9 and 49.90 as two different payments and turns a harmless retry into an error. The sample validates the request first and then hashes the order id and the amount in cents.
A lookup followed by an insert would be the same race again. One statement does both, and the primary key decides which request owns the key:
var claimed = await db.Database.ExecuteSqlInterpolatedAsync($"""
INSERT INTO idempotency_keys (key, request_hash, status, locked_at)
VALUES ({key}, {hash}, 'in_progress', now())
ON CONFLICT (key) DO UPDATE SET locked_at = now()
WHERE idempotency_keys.status = 'in_progress'
AND idempotency_keys.request_hash = {hash}
AND idempotency_keys.locked_at < {staleBefore}
""", ct);
If the statement changes one row, this request owns the key and does the work. If it changes none, the key belongs to someone else, and the stored row says what to answer:
| The key is | Answer | Why |
|---|---|---|
| Missing from the request | 400 | The contract requires it |
| New | Do the work | This is the first attempt |
| Completed, same request | The stored response | This is a retry; the work is done |
| In progress | 409 | The first attempt is still running; try again shortly |
| Known, different request | 422 | A key names one payment; this is a client bug |
The three status codes are the ones the IETF draft for the Idempotency-Key header recommends. Treat them as that draft's conventions. They don't all follow from the three questions in 400 or 422?: a key reused with a different request breaks the documented contract and conflicts with stored state at the same time, and the draft still answers it with 422.
The ON CONFLICT ... WHERE part handles one more case: a request that claimed the key and then died. Its row stays in_progress forever unless someone may take it over, so a retry of the same request can do that once the lock is older than a timeout.
2. Pass the key to the payment provider
This is the step that is easiest to skip and the one the article's title depends on.
The API can crash after the provider charged the card and before the payment is saved. The key row is still in_progress, the retry takes it over after the timeout, and the work runs again. If the second run calls the provider without the key, the card is charged twice, and all the bookkeeping above only made the bug rarer.
So the key goes downstream:
var providerKey = $"payments/{key}";
var chargeId = await provider.ChargeAsync(request.OrderId, request.Amount, providerKey, ct);
The provider applies the same rule you do: it has seen this key, so it returns the result of the first attempt and doesn't charge again. Stripe accepts an Idempotency-Key header for exactly this purpose, and most payment providers have an equivalent.
The result of the first attempt is not always a successful charge. Three outcomes need different handling:
- The charge succeeded and the response was lost. The retry gets the original charge back. This is the case the sample shows.
- The card was declined. That answer is final. Store it and replay it, as you would a success.
- The outcome is unknown, because the provider timed out or answered with an error. Stripe, for example, replays a stored 500 for the same key. Retry with the same key, and if that doesn't settle it, ask the provider what happened before you do anything else.
Derive the downstream key from the caller's scope, the operation and the client's key, for example {tenant}/payments/{key}. If two tenants both send the key abc and you pass it on unchanged to one shared provider account, the provider sees a single operation.
The general rule: every call with a side effect that sits behind your endpoint needs the key, or a value derived from it, and has to deduplicate on it. A system that ignores the key gains nothing from receiving it. Idempotency doesn't pass through a call chain by itself.
3. Save the payment and the response together
db.Payments.Add(payment);
var record = await db.IdempotencyKeys.SingleAsync(r => r.Key == key, ct);
record.Status = IdempotencyRecord.Completed;
record.ResponseStatus = StatusCodes.Status201Created;
record.ResponseBody = body;
await db.SaveChangesAsync(ct); // one transaction
The payment row and the completed key row are written in one transaction, so the API can never hold a payment without a stored response or a stored response without a payment.
A unique index on payments.idempotency_key is the final guard. If a slow request and a retry that took over its key both reach this point, the index lets one of them save and the other replays the winner's response.
A retry now gets the first answer back, marked as a replay:
HTTP/1.1 201 Created
Content-Type: application/json
Idempotent-Replayed: true
{"paymentId":"01a1c9df-a519-7943-a6ba-243902b58d7d","orderId":"order-2001","amount":49.90,"providerChargeId":"ch_9"}
What the key table asks of you
The table is small, but it comes with decisions:
- The lock timeout. Make it longer than the processing time you expect. There may be no true worst case, so one day a retry will take over a request that is still running. That is still safe here, because the provider deduplicates on the key and the unique index allows one payment, but you pay for the work twice.
- Retention. Keys can't be kept forever. Pick a period, delete older rows, and tell clients not to retry after it. Stripe, for example, may remove keys once they are at least 24 hours old.
- The provider's window. The provider forgets keys too, and afterwards it treats the same key as a new request. Suppose the API failed after a charge, and a retry takes the key over after the provider has pruned it: the card is charged again. No local index can stop that, because no payment was ever saved. So end automatic recovery well inside the provider's retention period. After it, reconcile: look the payment up at the provider by a reference you saved with the key before calling it, such as the order id, and only then decide whether to charge.
- Scope. A key is unique per caller. In a multi-tenant API the primary key is the tenant and the key together, so one customer's key can never collide with another's.
- Validation comes first. Reject a malformed request before claiming the key, so a 400 never uses one up.
- No database transaction across the provider call. Claim the key in its own statement, call the provider, then save. Holding a transaction open while a remote system thinks ties up a connection for as long as that system takes.
When you don't need a key table
The table is the general answer. Often a smaller one is enough:
| Situation | Smaller answer |
|---|---|
| The resource has a natural unique identity, such as one payment per order | That identity can name the operation: claim it as you would a key and derive the provider's key from it. A unique index alone is not enough, because the second request charges the card before its insert fails |
| The client can choose the identifier | PUT /payments/{id} with a client-generated id, which then plays the role of the key. PUT only promises idempotency; the implementation still has to claim the id and pass it to the provider |
| The work only touches your own database | Insert the key and do the work in one transaction; no in_progress state is needed |
| The operation is naturally repeatable, such as "set status to shipped" | Nothing; write it as an upsert |
Reach for the key table when a POST has a side effect outside your database that must not happen twice. Payments are the clearest case; sending an email or creating a shipment are others.
The rule
- A timeout is not a "no". Clients will retry, whether or not it is safe. Every write that must not happen twice needs a name the client chooses.
- Let one unique key decide who does the work. Claim it in one statement, store the response, and replay it to every retry.
- Pass the key to everything behind the endpoint that can deduplicate on it. Your API is only as idempotent as the last system it calls.
Roman law did have a remedy for the payment made twice. Gaius records in his Institutes that whoever receives what was not owed, from someone who paid by mistake, is bound to return it. A refund process is still worth having. It is a poor substitute for charging once.
Run it yourself
The companion sample is a minimal ASP.NET Core API that runs entirely in Docker, next to PostgreSQL. It takes the same payment in two ways: POST /naive/payments, with no key, and POST /payments, with the key table. The payment provider is faked inside the sample and keeps its own record of charges. A small client plays the customer on the train.
docker compose up -d --build
docker compose run --rm demo
The output on my machine:
1. No key: the client retries a payment of 49.90 five times at once
POST /naive/payments 5 x 201
2. Same retries, with one Idempotency-Key
POST /payments 1 x 201, 4 x 409
retry after it finished: 201 (replayed)
same amount sent as 49.9: 201 (replayed)
3. The same key with a different amount
POST /payments 422
4. The request fails after the card is charged, before the payment is saved
first attempt: 500
immediate retry: 409
retry after 2.5 s: 201
What the API saved and what the provider charged (GET /stats):
order-1001: 5 payment row(s), 5 charge(s), 249.50 charged
order-1002: 1 payment row(s), 1 charge(s), 49.90 charged
order-1003: 1 payment row(s), 1 charge(s), 49.90 charged
Five charges and 249.50 taken for one 49.90 order without the key; one charge with it. Step 4 is the one to study: the request fails after the card is charged, the retry is refused while the first attempt still holds the key, and the next retry finishes the payment without a second charge, because the provider recognised the key.
The demo has limits. Step 4 fails one request; it doesn't kill the process. The fake provider always charges successfully and never forgets a key, so declines, unknown outcomes and the provider's retention window are described above but not simulated.
The sample's lock timeout is 2 seconds so that step 4 is quick to watch. The README explains the other switches.
Further reading
- IETF draft: The Idempotency-Key HTTP Header Field
- Stripe API: idempotent requests
- RFC 9110: idempotent methods
- PostgreSQL: INSERT ... ON CONFLICT
- .NET: build resilient HTTP apps
This article is part of Justified Complexity: Building Backends One Decision at a Time.
Updated 2026-11-11: the classical references now link to their sources, and the Roman rule behind ne bis in idem is described more exactly as barring a second action on the same matter.
Updated 2026-11-11, after a review: two shortcuts in "When you don't need a key table" were wrong, since a unique index or a PUT alone doesn't stop the second charge, and are corrected. Added the provider's key retention window, the provider's other outcomes (declines and unknown results), the definition of the request fingerprint, the header's syntax, and the scope of the downstream key. The status codes are presented as the IETF draft's conventions, and "the API crashes" in the demo is now "the request fails".