Skip to content

Idempotency in APIs: idempotency keys, duplicate payments and how payment gateways handle them

Why a timeout can turn into a double charge, which HTTP methods are already idempotent, how an idempotency key works, what Stripe, Pix and the IETF do and how to implement it in your back end.

Ramon Gomes 13 min read Level: Intermediate

Also available in: Español, Français, Português

Someone taps "Pay R$ 120" in the app. The elevator goes down to the parking garage, the signal drops, the screen spins for 30 seconds and shows "Something went wrong. Try again?". They tap. The next day, the statement has two R$ 120 charges.

Nobody did anything wrong on purpose. The first request reached the server and was processed; what got lost was the response. The second request looked the same, and the server had no way of knowing it was a repeat.

That's the problem idempotency solves. In the queues article it already showed up on the consumer side, with a message delivered twice. Here I cover it from start to finish, using a payment app as the example. Everything was checked against official sources on November 21, 2026.

Person in an elevator looking at their phone with the payment screen loading and a weak signal indicator, under the elevator's cold light
Almost every duplicate payment starts like this: the request got there, the response didn't.

What Idempotent Means

The official definition is in RFC 9110, which describes HTTP semantics: a method is idempotent when "the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request".

Two words matter there. Effect, not response: deleting a resource twice leaves the system the same, but the second response may be a 404. And intended: the server can write a log line on every call without breaking idempotency.

An easy way to remember it:

  • Setting a value is idempotent: status = PAID ten times gives PAID.
  • Adding or creating isn't: balance += 10 ten times adds 100, and "create charge" ten times creates ten charges.

The elevator call button is idempotent. Pressing it ten times calls the elevator once. A coffee machine that pours a cup on every tap isn't.

Which HTTP Methods Are Already Idempotent

Method Safe? Idempotent? Why
GET, HEAD, OPTIONS, TRACE Yes Yes They only read
PUT No Yes Replaces the resource with what was sent
DELETE No Yes Deleting twice leaves it deleted
POST No No Each call can create something new
PATCH No No (it can be, if well designed) Depends on the operation (RFC 5789)

Safe means the client didn't ask for any change. That's why the RFC warns against links like GET /order?action=delete: search crawlers and browser prefetching follow every GET link.

And the golden rule from the RFC itself: a client shouldn't automatically retry a non-idempotent method unless it has some way of knowing that retrying is safe. The idempotency key is that way.

The Duplicate Payment, Step by Step

Animation of the phone sending the R$ 120 payment request; the server creates the charge, but the response gets lost on the way; the app retries and the server creates a second charge, adding up to R$ 240 on the statement
Without a key, the server can't tell a repeat from a new request.

The point that trips almost everyone up: the server did everything right. It received a charge request and charged. It received another one and charged again. The one who knows both are the same request is the client, and that's why the client has to send that information.

The Asaas documentation describes this exact mistake, under the name "duplicate charge after a retry without idempotency", and sums it up in one sentence: don't assume an operation failed just because your application didn't get the response. Stripe treats a 500 as an indeterminate result: it may or may not have worked.

In 2023, Mercado Pago made the key mandatory on its payment and refund APIsContract that defines how one program asks another for data or actions: which endpoints to call, what to send and what comes back. On the web, usually HTTP with JSON. and explained why in the official announcement: it had seen an increase in duplicate payments and refunds.

The Idempotency Key

The correct flow has three rules:

  1. The client generates the key before the first attempt (a UUID, for example).
  2. It stores the key together with the order, so it survives a closed app or a restarted server.
  3. It repeats the same key on every attempt for that payment.
sh
curl https://api.stripe.com/v1/payment_intents \
  -u sk_test_...: \
  -H "Idempotency-Key: 7f3c2a90-5d1e-4b8a-9c11-2f6e8d4a0b37" \
  -d amount=12000 \
  -d currency=brl

On the server side, the first call with that key is processed normally, and the result is stored. The following ones return the same result without running anything again. Stripe also marks the replayed response with the Idempotent-Replayed: true header.

Animation of the same scenario with the key abc: the first call creates the charge and records abc as completed in a table; the response gets lost; the second call with the same key checks the table, finds abc completed and returns the stored receipt, with a replayed response badge
With a key, the second attempt becomes a lookup, not a charge.

The most common mistake, and the one that cancels everything out: generating a new key on every attempt. Stripe itself warns that a new key can start a second operation.

How Each Gateway Does It

Header Max length How long it's kept
Stripe Idempotency-Key 255 characters At least 24 hours (API v1)
Adyen idempotency-key 64 characters 7 to 14 days
PayPal PayPal-Request-Id 38 characters Varies by API
Mercado Pago X-Idempotency-Key 128 characters (Orders) Not stated in the documentation
Asaas No documented header Uses externalReference and checks before creating
Pix (Central Bank API) txid in the URL, with PUT 26 to 35 characters Unique per receiver

Three details that make a difference:

  • Stripe stores even the error. If the first call started running and returned a 500, retrying with the same key returns the same 500. Retrying doesn't fix it; you have to reconcile (look up the object or wait for the webhook).
  • PayPal returns the current state, not the original response. If the payment changed status between one call and the next, you get the new one.
  • Pix was born idempotent. The charge is created with PUT /cob/{txid}, and the txid is generated by the receiver. Since PUT is idempotent by definition, repeating the same call doesn't create another charge. Refunds follow the same design, with PUT /pix/{e2eid}/devolucao/{id}.

Asaas deserves a paragraph. The documentation doesn't mention a key header, but it describes the flow that solves the problem: record the attempt before calling, use externalReference to link the charge to your order and, after a timeout, check whether the charge exists before creating another one.

The Standard the IETF Is Writing

The draft "The Idempotency-Key HTTP Header Field", from the IETF httpapi working group, reached version 09 on November 21, 2026. It isn't an RFC yet, but it already describes what the gateways do and suggests clear error codes:

Situation Suggested code
Key missing on an operation that requires it 400 Bad Request
Same key with a different body 422 Unprocessable Content
Same key while the first one is still running 409 Conflict

The 409 is the only one where the client can just wait and retry without changing anything.

The draft also carries a security warning: a predictable key lets someone guess another client's key and read their stored response. So, on the server, combine the key you received with the account ID of whoever sent it.

Two Calls at the Same Time

There's a trickier case: the app sends the second attempt while the first one is still being processed. If the server only checks "has this key already been completed?", both pass the check and both charge.

Animation of two requests with the same key arriving almost together: the first records the key as processing and moves on to the gateway; the second hits the lock and comes back with a 409; a moment later, the second retries and gets the completed receipt
Recording 'processing' before charging is what shuts the door on the race.

The way out is to record the key as processing before any side effect, atomically, with a UNIQUE constraint in the database. Whoever arrives later finds the lock and gets a conflict. Everyone does this, each with their own code: 409 at Stripe and in the IETF draft, 422 or 409 with code 704 at Adyen, 423 resource_locked at Mercado Pago.

Implementing It in Your Back End

One table is enough. In Postgres:

sql
CREATE TABLE idempotency_keys (
  account_id   BIGINT      NOT NULL,
  key          TEXT        NOT NULL,
  fingerprint  TEXT        NOT NULL,          -- hash of the request body
  status       TEXT        NOT NULL CHECK (status IN ('PROCESSING', 'COMPLETED')),
  response     JSONB,
  created_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (account_id, key)
);

And the flow, in simplified TypeScript:

ts
async function pay(req: Request) {
  const key = req.headers['idempotency-key'];
  if (!key) return error(400, 'Idempotency-Key is required');
  const fingerprint = sha256(JSON.stringify(req.body));

  // 1. Try to reserve the key. Only one process can.
  const reserved = await db.query(
    `INSERT INTO idempotency_keys (account_id, key, fingerprint, status)
     VALUES ($1, $2, $3, 'PROCESSING')
     ON CONFLICT (account_id, key) DO NOTHING
     RETURNING key`,
    [req.accountId, key, fingerprint],
  );

  if (reserved.rowCount === 0) {
    const current = await find(req.accountId, key);
    if (current.fingerprint !== fingerprint) return error(422, 'Key used with a different body');
    if (current.status === 'PROCESSING') return error(409, 'Still processing');
    return replay(current.response); // returns the stored result
  }

  // 2. First time: run it and store the result.
  const result = await gateway.charge(req.body, { key });
  await complete(req.accountId, key, result);
  return result;
}

Notice that the key also goes to the gateway. That way, if your server crashes between charging and storing the result, the next attempt reaches the gateway with the same key, and the gateway is the one that blocks the duplicate.

A few precautions the sources reinforce:

  • Expiration. The key doesn't need to live forever. Stripe keeps it for at least 24 hours, Adyen for 7 to 14 days, AWS Powertools for 1 hour by default. Pick yours, document it and delete the old ones.
  • Body fingerprint. Without it, a key reused with a different amount would return the old response without warning anyone.
  • Failure before running. If validation fails or an error happens before any side effect, delete the reservation to allow a new attempt. That's what Stripe and Powertools do.

If you use AWS Lambda, Powertools (version 3.41 for Python, 2.36 for TypeScript) already gives you all of this in a decorator, backed by DynamoDB or Redis.

On the Other Side: Webhooks and Queues

When the gateway tells your system the payment was approved, it can also tell you twice. Asaas documents webhook delivery as "at least once", and the same goes for SQS Standard. The queues article shows why.

The defense is the same idea, with the event ID in place of the key:

sql
INSERT INTO received_events (event_id, payload)
VALUES ($1, $2)
ON CONFLICT (event_id) DO NOTHING;

If it inserted, process it. If it didn't, it was already processed. And reply 200 to the webhook only after saving, never before.

Animation of a payment approved webhook arriving twice; the first copy is saved to the table and releases the order; the second hits the unique constraint, is discarded and the order stays released just once
A UNIQUE constraint on the event ID turns a double delivery into a non-event.
Cartoon of a bakery clerk looking at the paper ticket a customer is showing for the second time and pointing to an already served sign, while the customer holds the bread they've already taken
The number has already been called. The bread has already been wrapped.

Quick check

1. The app got no response from the server when creating a payment. What does that mean?
Show answer

Answer: That the outcome is unknown: the payment may have been created

The response may have been lost after the server processed the request. That's why you retry with the same key or check first.

2. Which of these HTTP methods is not idempotent according to RFC 9110?
Show answer

Answer: POST

PUT and DELETE are idempotent by definition. POST can create something new on every call.

3. Two requests with the same key arrive together. What does the IETF draft suggest returning for the second one?
Show answer

Answer: 409 Conflict, and the client can try again later

422 is for the same key with a different body. 409 is for when the original is still in progress.

Frequently Asked Questions

Is idempotency the same as deduplication?

They're cousins. Deduplication means discarding the repeated copy. Idempotency means making sure a repeat doesn't change the outcome, either by discarding the copy or because the operation doesn't accumulate by nature (like status = PAID).

How long should I keep the key?

Long enough to cover the client's automatic retries. Gateways range from 24 hours to 14 days. For your own app, 24 hours is usually enough, as long as it's documented.

Do I need a key on GET, PUT and DELETE?

According to the RFC, no: they're already idempotent. Stripe says a key on GET and DELETE has no effect. The care goes to POST and PATCH.

Does an idempotency key protect against the user double clicking the button?

Yes, if the front end generates the key when the payment screen opens, and not on every click. Disabling the button helps, but it doesn't protect against network failures.

What if I use the cart ID as the key?

It works, and Stripe mentions this strategy, because it prevents paying for the same cart twice. Just make sure a legitimate new payment for the same cart (after a refund, for example) uses a different key.

References

Checked on November 21, 2026:

Source: https://ramongomessilva.com.br/blog/idempotency-in-apis · Accessed on December 03, 2026

Share Share on LinkedIn Share on X
Cite this article

Ready-made reference, with today as the access date.

ABNT

Brazilian standard (NBR 6023). Use it in theses and academic papers submitted in Brazil.

GOMES, Ramon. Idempotency in APIs: idempotency keys, duplicate payments and how payment gateways handle them. Ramon Gomes, 27 nov. 2026. Disponível em: https://ramongomessilva.com.br/blog/idempotency-in-apis. Acesso em: 3 dez. 2026.

APA

American Psychological Association style. Common in scientific papers and journals, especially in the social, behavioral and health sciences.

Gomes, R. (2026, November 27). Idempotency in APIs: idempotency keys, duplicate payments and how payment gateways handle them. Ramon Gomes. https://ramongomessilva.com.br/blog/idempotency-in-apis

BibTeX

Format for LaTeX users (Overleaf, for example). Paste it into your .bib file or import it into Zotero or Mendeley.

@online{gomes2026idempotencyinapis,
  author = {Gomes, Ramon},
  title = {{Idempotency in APIs: idempotency keys, duplicate payments and how payment gateways handle them}},
  organization = {Ramon Gomes},
  year = {2026},
  month = nov,
  date = {2026-11-27},
  url = {https://ramongomessilva.com.br/blog/idempotency-in-apis},
  urldate = {2026-12-03}
}
Found a mistake?

Wrong fact, broken link, outdated information: tell me and I will fix it.

10 to 2,000 characters. If you can, point to the right source.

Only so I can reply. It never shows on any page of the site.

Written by

Ramon Gomes

Software Engineer

Full stack software engineer. I like taking a messy problem, listening to the people who live with it and shipping something that holds up day to day. These days I split my time between my own products, applied AI and client work.

Available for projects

Need Something Like This Built?

I build websites, systems, apps and AI automations, from design to deploy. Tell me what you need or see what I offer.

Related Articles