Skip to main content

Idempotency: The Most Important Pattern in Payment Engineering

· 9 min read
Payments Mastery
Payment Systems Learning Platform

Every distributed system needs idempotency. But in payments, getting it wrong doesn't mean a duplicated notification or an extra log entry — it means charging someone's credit card twice. That's a support ticket, a chargeback, and a customer who never comes back.

I've seen this happen in production more than once. A network timeout during authorization, an aggressive retry policy, and suddenly a customer has two $847 charges on their statement. The fix took five minutes. The cleanup took a week.

In anything that touches money movement, idempotency isn't a nice-to-have pattern. It's the foundation everything else rests on.

The Problem: Networks Are Unreliable​

Here's the scenario that causes the most trouble. The platform sends a payment request to its gateway or processor. The request makes it through. The issuer approves it. But the response gets lost — maybe a load balancer times out, maybe a TCP connection drops.

From the platform's perspective, the request failed. From the issuer's perspective, it succeeded. Now what?

Without that idempotency key (abc-123), the gateway has no way to tell a retry from a new purchase. It sends a second authorization, and the customer gets a second $50 hold. With the key, the gateway recognises the retry and replays the stored result. The network never sees a second request.

Where Idempotency Keys Stop​

A common misconception is that the idempotency key travels all the way to the issuer. It doesn't. Idempotency keys are an API-layer concept. They live in your platform and in your gateway or processor's API (Stripe, Adyen, Braintree and most modern processor APIs accept one). The card network speaks ISO 8583, and ISO 8583 has no idempotency key field.

Below the API layer, messages carry their own identifiers, and those identifiers do a different job:

LayerIdentifierWhat happens when something is uncertain
Platform APIClient-supplied idempotency keyReplay the stored response; don't reprocess
Gateway / processor APIIdempotency key (if the API supports one)Replay the stored result; never send a second authorization for the same key
Processor ↔ networkSTAN (DE 11), Retrieval Reference Number (DE 37)Match each response to its request; on a timeout, send a reversal (0400) for the original message
Network ↔ issuerNetwork transaction ID (e.g. Visa Transaction ID, Mastercard Trace ID)Link the authorization to its reversal, clearing record and any dispute. Issuers may decline an apparent duplicate through their own velocity rules, but they don't replay earlier decisions

The STAN (System Trace Audit Number) is assigned by whoever sends the message and is not globally unique. Systems combine it with other fields to match responses and reversals.

So what happens when the timeout is below your gateway, between the processor and the network? The protocol's answer is reversal, not replay:

ISO 8583 does have the idea of a repeat message: the last digit of the message type marks a retransmission, as in 0401 for a repeated reversal. That lets a receiver recognise "the same message, sent again". In practice it's used for reversals and advices, not for retrying an authorization and getting the original answer back.

The critical insight: above the network, idempotency is your job and your gateway's job. Below it, uncertainty is resolved with reversals and transaction identifiers. If you connect to a processor directly at the ISO 8583 level, a retry without a reversal is exactly how double holds happen.

The State Machine Perspective​

A payment isn't a single event — it's a state machine. Idempotency behaves differently depending on which state the payment is in when the retry arrives.

The Unknown state is where things get interesting. When an authorization times out, there's genuinely no way to know whether money moved. There are three options:

  1. Retry with the same idempotency key. This is safe only if the API you're calling honours idempotency keys. It returns the original result if the first request went through.
  2. Query the transaction status. Many gateways support lookup by your reference or by the key.
  3. Reverse, then start again. If you're the one talking ISO 8583 (or your provider offers no key or status lookup), send a reversal for the original attempt first. Only then is a new authorization safe.

One nuance worth keeping in mind: an idempotent retry returning "approved" still carries the original timestamp. Authorizations are only valid for a limited time, which depends on the network and the authorization type (often around a week for a standard purchase). An approval from last month isn't actionable for capture, even though the idempotency layer says "approved". The status matters, but so does the age.

What absolutely cannot happen is creating a new payment and trying again while the first one is still unresolved. That's how double-charges happen.

The Danger Zone

The window between "request sent" and "response received" is where every payment idempotency bug lives. The system must treat this as an explicit state — not as an error to retry blindly.

Where Keys Are Generated (And Where They Shouldn't Be)​

A common mistake: generating idempotency keys server-side on each request. If the client retries because it didn't get a response, the server generates a new key and processes it as a brand new payment.

The key must be generated by the caller — the entity that initiates the request and might need to retry it.

ScenarioWho Generates the KeyExample Format
Customer checkoutFrontend or API gatewaycheckout_{sessionId}_{cartHash}
Recurring billingBilling servicesub_{subscriptionId}_{billingPeriod}
Payout to merchantPayout servicepayout_{merchantId}_{date}_{sequence}
Design Hint

Tie idempotency keys to business intent, not to technical request IDs. checkout_sess_abc_cart_def means "this specific checkout attempt" — retrying with the same key is always safe. A random UUID generated per-request defeats the entire purpose.

The Race Condition Nobody Talks About​

There's a subtle failure mode even with idempotency keys in place. Two identical requests arrive at the server at nearly the same time — maybe a user double-clicked, maybe the retry fired before the first request timed out.

Both requests check the database for the idempotency key. Neither finds it (it hasn't been written yet). Both proceed to create the payment. Now you have two charges.

The fix is straightforward: use a unique constraint on the idempotency key in your database, and handle the conflict.

The first request inserts successfully. The second hits the unique constraint violation. On that conflict, you look up the existing result and return it. No double-charge.

This is one of those problems that never shows up in testing but appears immediately under production traffic. If a payment service's idempotency store doesn't have a unique index on the key — that's a ticking time bomb.

Practical Decisions​

A few architectural decisions that come up when implementing this:

How long to keep idempotency records? Most payment platforms retain them for 24-48 hours. Stripe uses 24 hours. If a client retries after that window, it's treated as a new request. For recurring billing, longer retention makes sense — keyed to the billing period.

What to store? The key, the request hash (to detect mismatched retries), the response, and a timestamp. Storing the full response means returning it instantly on a cache hit without touching any downstream systems.

What if the same key arrives with different parameters? That's a client bug. Return a 409 Conflict or 422 Unprocessable Entity — don't silently process it as a new payment, and don't return the cached result for different input. Both options are dangerous.

It's Not Just Authorization​

Most idempotency discussions focus on the authorization leg, but every money-moving operation has the same problem. A capture that gets retried can settle the same authorization twice. A refund that times out and retries can double-refund a customer just as easily as a double-auth can double-charge them. Each operation — capture, refund, payout — is its own idempotency surface with its own key strategy.

And it goes the other direction too. PayFac platforms don't just send requests to processors — they receive webhooks from them. A processor might retry a webhook notification if it doesn't get a timely acknowledgment. If the platform processes that webhook twice (say, crediting a merchant's balance on each delivery), the result is just as bad as a double-charge. Being idempotent as a receiver is just as important as being idempotent as a sender.

Key Takeaways​

  1. Idempotency is not optional — it's as fundamental as authentication. It belongs in every money-moving endpoint from day one.
  2. Keys stop at the API boundary. Your platform and your gateway deduplicate with idempotency keys. Below that, the card network resolves uncertainty with reversals and transaction identifiers, not replays.
  3. Model the unknown state explicitly — a timeout is not an error. It's a state that requires specific handling.
  4. Protect against race conditions — unique constraints in the datastore, not just application-level checks.
  5. Tie keys to intent — business-meaningful keys catch duplicates that random UUIDs miss.

For a broader look at how transactions flow through the card ecosystem, see the transaction lifecycle guide. The idempotency patterns described here apply at every stage — from authorization through settlement.


Next time, I'll dig into what happens after authorization: the surprisingly complex world of clearing and settlement, and why that $50 charge takes two days to actually move money.

Share: