Skip to content
Suriyaprakash.
Engineering

Field note / Engineering+

Idempotency in Depth: Retries, Idempotency Keys, and Safe Replays for APIs

How to make retried POST requests safe with idempotency keys, payload fingerprints, in-flight locks, and a clear rule for what to store after a failure, with tested results.

Published
Reading time17 min read
Filed underEngineering

A client sends POST /payments. The server charges the card, writes the row, and starts sending the response. The connection drops halfway. From the client's side, nothing came back. It has no idea whether the charge happened.

It can retry and risk charging twice. Or it can give up and leave the customer in a state nobody intended. Idempotency is the property that removes that choice. If the same logical request can be sent more than once and produces one effect, the client can retry without fear.

This article covers how to get that property for an HTTP API with a POST endpoint. It is a standalone topic rather than a part of the backend series. It assumes you know what an HTTP request and a database transaction are. The examples use Node.js, but the ideas apply anywhere.

Quick answer

  • An operation is idempotent when repeating it has the same effect as doing it once. HTTP defines this for methods, and POST is not in the list.
  • An idempotency key lets the client name one logical operation. The client sends the same key on every retry of that operation. The server remembers the key and replays the first outcome.
  • The server must do three things atomically. Claim the key, run the side effect, and record the outcome. Checking for the key and then acting on it is a race.
  • Store a fingerprint of the request body. Reusing a key with a different payload is a client bug, and the server should reject it rather than replay the wrong response.
  • Decide deliberately what happens after a failure. If the side effect may have happened, releasing the key so the retry runs again is the double-charge bug.
client                              server
  | POST /payments                    |
  | Idempotency-Key: 8e03...          |
  |---------------------------------->|  claim key (in_progress)
  |                                   |  charge card
  |        (response lost)           |  record outcome (completed)
  |<-  ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ |
  | retry: same key, same body       |
  |---------------------------------->|  key completed -> replay stored response
  |<----------------------------------|  200, Idempotent-Replayed: true

Why POST needs help

RFC 9110 defines idempotency for request methods like this: "A request method is considered 'idempotent' if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request." It then lists which methods have that property: "Of the request methods defined by this specification, PUT, DELETE, and safe request methods are idempotent." POST is not on that list.

The same section explains why the distinction matters for clients. Idempotent methods "can be repeated automatically if a communication failure occurs before the client is able to read the server's response." It then says a client "SHOULD NOT automatically retry a request with a non-idempotent method unless it has some means to know that the request semantics are actually idempotent, regardless of the method, or some means to detect that the original request was never applied." RFC 9110, section 9.2.2

An idempotency key is one of those "some means". It is the mechanism that lets a POST be retried safely. Without one, the client has to choose between retrying blindly and not retrying at all.

Where the retries come from

These are the common sources. They are general categories, not incidents I have observed.

  • A lost response. The server finished the work, and the network or a proxy dropped the reply.
  • A client timeout that is shorter than the server's work. A proxy might give up after 30 seconds while the handler keeps running and finishes at 40.
  • A double submit. A user clicks "Pay" twice, or a mobile app resumes a form after it was backgrounded.
  • Retries from infrastructure. A load balancer, a service mesh, or your own HTTP client may retry on a 502 or a reset connection.
  • Redelivery from a queue or webhook sender. Most queues and webhook systems deliver at least once. The same message can arrive twice.

Once any of these can occur, the handler is called more than once for the same intent. The question is whether the second call repeats the side effect.

The idempotency key

The client generates a unique value for each logical operation and sends it in a header. The header name is conventionally Idempotency-Key. The IETF has an Internet-Draft for it, draft-ietf-httpapi-idempotency-key-header. At the time I checked, the datatracker showed revision 09 as an active Internet-Draft, not an RFC, with an expiry of 25 May 2027. Treat it as a draft, and don't assume every client or framework follows it exactly. The draft defines the value as a Structured Fields string, so a valid header looks like this:

POST /payments HTTP/1.1
Host: api.example.com
Content-Type: application/json
Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324"

{"amount": 4200, "currency": "USD", "order_id": "ord_1841"}

Three rules matter more than the exact header format.

1. The key identifies the operation, not the attempt. The client generates the key once, when the user decides to pay. Every retry of that payment sends the same key. A common mistake is generating a fresh key inside the retry loop, which turns a retry into a new operation and brings the double charge back.

2. The key is scoped. Two users can send the same string. Store the key with the account or tenant, and usually the route, so one customer's key cannot collide with another's.

3. The key has a lifetime. Stripe documents that for its v1 API, keys "can be removed automatically after they're at least 24 hours old", and that a reused key after pruning generates a new request. Stripe's idempotent requests reference describes the same idea. Pick a retention window longer than your longest realistic retry, and document what a client should do if it retries after the window closes. For example, an order id in the body can be checked against the database, which is a different guard from the key.

Stripe's documentation also notes that keys apply to POST requests in v1. Keys sent with GET and DELETE have no effect there. Your own API can choose differently, but the key is only meaningful for operations that are not already idempotent.

Fingerprint the payload

A key without a payload check is a trap. Suppose a client sends {"amount": 4200} with key k-1, then later sends {"amount": 99900} with the same key. A server that only checks the key will replay the first response, and the second request silently gets the wrong result.

Store a fingerprint of the request body next to the key. On a repeat, compare fingerprints. If they differ, reject the request. The IETF draft says the key "MUST NOT be reused with another request with a different request payload", and recommends an error status such as 422 for this case. Stripe's docs say the idempotency layer compares incoming parameters with the original and returns an error if they differ.

A detail that bites: hash a canonical form, not raw bytes. {"amount":1,"currency":"USD"} and {"currency":"USD", "amount":1} are the same request to a JSON parser, but a raw byte hash will treat them as different. Parse the body, sort or normalize the fields the way your schema defines them, and hash that.

The concurrency race

The simplest implementation looks like this:

const existing = await store.get(key)
if (existing) return replay(existing)

const result = await chargeCard(body)      // the side effect
await store.set(key, result)
return result

It is correct when requests arrive one after another. It fails when two arrive together. Both requests see no record, both charge the card, and both write a result. The second write overwrites the first.

I tested this with a small Node HTTP server. Each request sleeps for 50 milliseconds to stand in for the provider call. Two identical POSTs with no key handling at all ran the side effect twice. The check-then-act version is the same as having no key:

naive: concurrent duplicates both execute   charges=2  statuses=200,200

The fix is to claim the key before the side effect, in a single step that only one request can win. Here is the core of the handler I tested:

const fp = createHash('sha256').update(canonicalBody).digest('hex')
const existing = store.get(key)
if (existing) {
  if (existing.fp !== fp) return send(422, 'key reused with different payload')
  if (existing.status === 'in_progress') return send(409, 'request with this key is in progress')
  return replay(existing)
}
// Claim the key synchronously, before any await.
store.set(key, { fp, status: 'in_progress' })
await chargeCard(body)
store.set(key, { fp, status: 'done', code: 200, body: payload })

The result of the concurrent test with that handler was:

keyed: concurrent duplicate executes once   charges=1  statuses=200,409

The check and the claim happen in the same synchronous block. In a single Node process, nothing else can run between them, so the claim is atomic. That reasoning does not carry over to several servers. Once there is more than one process, the claim must be an atomic operation on shared storage. Section "Where the record lives" covers that.

The second request got 409. Returning 409 with a Retry-After header is a choice, not a requirement. The alternative is to hold the second request until the first finishes. Holding is nicer for the client but harder to implement well: you need timeouts, and you need to handle a first request that never finishes.

What to store when the request fails

This is the part most implementations get wrong.

Suppose the first attempt charges the card, and then a later step, such as writing a receipt row, throws a 500. The side effect happened. If the server releases the key on failure, the client's retry sees no record and charges again. I tested this exact sequence:

release-on-failure: 500 then 200, charges=2

Releasing the key is the right move only when you know the side effect did not happen. A validation error that rejects the body before any charge is one example. A conflicting concurrent request that was refused is another. Stripe's documentation draws the same line: it saves the status code and body of the first request once execution begins, including 500 errors, so retries return the saved response. It says it does not save results when a request fails validation or conflicts with a concurrent request, so those can be retried.

There is no universal rule that you should replay a 500 forever. The decision depends on what the failure means. Two options work:

  • Store the outcome of any attempt that reached the side effect. A retry replays the stored failure. The client must then make a new key if it wants to try the operation again after fixing the underlying problem.
  • Move the record to a state the system can resolve. If the outcome is unknown, for example after a timeout to a provider, the record stays in_progress, and a reconciliation job checks with the provider before deciding.

The thing to avoid is releasing the key while the side effect's outcome is unknown.

A hypothetical example of the unknown outcome

Say your handler calls a payment provider and the call times out after 10 seconds. The provider might have charged the card or not. You do not know. Your record should not say failed, because the client's retry would then charge again if the provider had succeeded. It should stay in_progress until something resolves it, usually a lookup of the provider's record by your own reference.

That means in_progress needs its own timeout. If the process crashes while holding a key, the key can stick forever. Store a lease or a claimed_at time, and let a stale claim be taken over only after the reconciliation step has checked the outcome. The details depend on your provider. The principle is that a stale lock must not turn into a duplicate charge.

Where the record lives

The claim has to be atomic across every server that can receive the request. Two common options.

In the same database as the business write. Insert the key row and the business row in one transaction, with a unique constraint on the key. The second insert fails, and the transaction rolls back. This gives the strongest consistency between the record and the effect, because they commit together. The cost is that the provider call, if any, must happen outside the transaction, which brings back the unknown-outcome problem above.

Here is a sketch of the table. I did not run this against Postgres, because Docker was not running in my environment when I tested, so treat it as untested:

create table idempotency_keys (
  scope           text        not null,   -- account id plus route
  key             text        not null,
  fingerprint     text        not null,
  status          text        not null,   -- 'in_progress' or 'completed'
  response_code   integer,
  response_body   jsonb,
  claimed_at      timestamptz not null default now(),
  primary key (scope, key)
);

-- Claim: exactly one concurrent insert returns a row.
insert into idempotency_keys (scope, key, fingerprint, status)
values ($1, $2, $3, 'in_progress')
on conflict (scope, key) do nothing
returning key;

If the insert returns no row, a record exists. Read it, compare the fingerprint, and branch as in the handler above.

In a fast shared store such as Redis. A SET key value NX EX ttl gives an atomic claim with an expiry. It is quick, and the expiry handles cleanup. The weakness is that the claim and the business write are two separate systems. If the process dies between them, the claim and the effect can disagree. Use it when the side effect is idempotent on its own side, or when you can tolerate the reconciliation work.

Neither option is free. The database approach puts load on the primary. The Redis approach needs a plan for Redis losing its data.

Tests I ran and what they do not show

The experiment is a single Node file with no dependencies. It runs seven checks against in-memory handlers on 127.0.0.1. I used Node.js v24.22.1.

CheckResult
Naive handler, concurrent duplicatesBoth execute, charges=2 (PASS)
Keyed handler, concurrent duplicatesOne executes, 200 and 409 (PASS)
Keyed handler, sequential retry after successReplayed, charges=1, header Idempotent-Replayed: true (PASS)
Same key, different body422, nothing executed (PASS)
Release key on failure, then retrySecond attempt executes, charges=2 (PASS)
Missing key400 (PASS)

Seven checks, seven passes. That shows the logic works in one process with an in-memory map. It does not show:

  • behaviour across several server instances,
  • what a database unique constraint does under load,
  • recovery after a crash in the middle of a request,
  • how a real payment provider behaves when retried,
  • the Postgres and Redis sketches above, which I did not run.

Tradeoffs and when this does not apply

Operations that are already idempotent do not need a key. A PUT that replaces a resource with the same body, or a DELETE that removes it, has the right property already. Adding a key there adds storage and latency for nothing. Be careful, though: a PUT that increments a counter or appends to a list is not idempotent, whatever its method.

Keys add cost on every request. Each keyed request writes a record, and the record must be kept for the retention window. For a read-heavy API this is wasted work. Put keys on operations with external effects: money, email, inventory, provisioning, and anything a queue consumer triggers.

A key does not fix a client that regenerates it. The server can only dedupe what the client identifies as one operation. A client that generates a new key every time it renders a button will create duplicates no matter how correct the server is.

A key does not detect duplicate intent. Two different orders that happen to have the same amount and item are two operations with two keys. Keys dedupe retries, not similar purchases.

Fingerprinting can reject legitimate changes. If a client retries with a slightly different but equivalent body, such as an added whitespace field or a reordered array, your canonicalization must treat it as the same. Otherwise the retry gets a 422. Test the canonical form with the variations your clients actually produce.

Checklist

  • Every non-idempotent endpoint that causes an external effect accepts an idempotency key.
  • The client generates the key once per logical operation and reuses it on every retry.
  • Keys are scoped to the account or tenant and the route.
  • The record stores a fingerprint of the canonical body, and a mismatch is rejected.
  • The claim is atomic on shared storage: a unique constraint or a conditional insert, never check-then-set.
  • A concurrent duplicate gets a clear retryable response, not a second execution.
  • The failure rule is written down: replay the stored outcome, or hold the key until the state is resolved.
  • in_progress records have a lease or timeout, and a reconciliation path for unknown outcomes.
  • Retention is longer than your longest retry window, and the expiry behaviour is documented for clients.

FAQ

Do I need idempotency keys for every endpoint?

No. Start with the endpoints where a duplicate causes harm: charges, orders, emails, provisioning, and anything that changes state outside your database. Reads and naturally idempotent writes do not need them.

Should the key be a UUID?

A UUID v4 is a common choice because a client can generate it without coordination. What matters more is that the client generates it once per operation and stores it until the operation finishes. Random enough to be unique, and stable across retries.

What status code should a duplicate in progress return?

409 Conflict with a Retry-After header is a reasonable default, and it tells the client to try again without treating the request as wrong. Holding the second request until the first completes is also valid, but then you need timeouts for the first request.

Can I just use the order id instead of a key?

Sometimes. A unique constraint on a business identifier is a form of idempotency, and it is often the simplest correct design. The key is more general, because it works when the operation has no natural identifier yet, such as a payment that creates the order.

What happens if the key expires and the client retries?

The server treats it as a new request. That is why the retention window must be longer than your retries, and why a business-level guard, such as a unique order id, is worth having as a second layer.

Is the IETF draft a standard?

No. At the time I checked, it was an active Internet-Draft, which means a work in progress, not an RFC. Clients and servers implement it in different ways, so read the documentation of the API you call.

Does idempotency mean the operation runs exactly once?

Not in general. It means that repeating the request produces the same effect as one execution, as far as the server can tell. A side effect that happened outside the server's knowledge, such as a provider charge the server never recorded, is a case for reconciliation, not for the key.

Final mental model

request with key K and body B
          |
          v
   key K seen before? ---- no ----> claim K (atomic) -> run side effect -> record outcome
          |
         yes
          |
   fingerprint(B) same? -- no ----> reject (422)
          |
         yes
          |
   outcome recorded? ---- no ----> in progress (409, retry later)
          |
         yes
          |
          v
   replay the stored outcome, marked as replayed

An idempotency key does not make the server smarter. It makes the server's answer to "have I done this?" a single atomic fact, so the client can ask as often as it needs to.

About the author

Suriyaprakash Somu is a full-stack developer based in Erode, Tamil Nadu, building React and Node.js applications on relational databases. He works on customer-facing experiences, reusable interfaces and access-controlled backend workflows. Explore his development work or discuss a project or developer role.