Skip to content
Engineering

Idempotency Keys for APIs: Stripe's Rules, the IETF Draft and a Storage Design

AIDToolStack EditorialNovember 7, 20269 min read
API DesignIdempotencyStripeHTTP
Share:Twitter

A checkout page sends POST /orders. The server writes the order, commits, and starts sending 201 Created. Somewhere between the load balancer and a phone on a train, the connection dies. The client has a timeout and nothing else. Retry, and you might create a second order. Don't retry, and you might have lost the first one.

Brandur Leach laid out the three ways a request fails in Stripe's 2017 post on idempotency: the connection never gets established, the server fails partway through, or the server finishes and the response is lost. Only the first is safe to retry blindly. An idempotency key turns the other two into the same easy case. The client attaches a unique key to the operation, and the server promises to do the work at most once per key and to give back the original result when it sees the key again.

The HTTP methods post covers why POST needs this and PUT doesn't. This one is about the contract and the storage behind it.

Sequence diagram: the client sends POST /orders with key k1, the server commits the order and replies 201, but the connection drops; the client retries with the same body and key, the server finds k1 marked done and replays the saved 201 with the same order id
Sequence diagram: the client sends POST /orders with key k1, the server commits the order and replies 201, but the connection drops; the client retries with the same body and key, the server finds k1 marked done and replays the saved 201 with the same order id

What Stripe actually promises

Stripe's implementation is the one most people copy, so it's worth reading the rules precisely rather than from memory. From the API reference as of November 2026, for API v1:

  • All POST requests accept an Idempotency-Key header. Sending one on GET or DELETE has no effect, since those are idempotent already.
  • Keys are up to 255 characters. Stripe suggests V4 UUIDs or another random string with enough entropy, and says not to use sensitive data such as email addresses as keys.
  • Stripe saves the status code and body of the first request "after endpoint execution begins". Retries get that saved response back, including 500s.
  • If the parameters fail validation, or the request collides with a concurrent request using the same key, nothing is saved and you can retry.
  • Keys can be pruned once they're at least 24 hours old. Reuse a key after that and you get a new request.
  • Reusing a key with different parameters is an error.

The error-handling guide fills in the client side. A 409 means another request with the same key is still running: wait and retry with the same key and the same parameters, because a new key "can start a second operation". Retry an unresolved operation only within the first 24 hours; after that, stop and reconcile by fetching the object, checking the Dashboard and reading webhook events. Replayed responses carry Idempotent-Replayed: true, which is handy in logs.

API v2 is different, and the v2 overview is explicit about it. The replay window is 30 days, keys are scoped to the same API and the same account or sandbox, POST and DELETE both accept keys, and if you send none Stripe generates a UUID for you. The bigger change is that v2 doesn't just replay a stored failure: if the first attempt failed or partially failed, a retry re-executes the failed work without repeating side effects. So "Stripe returns the cached 500" is true for v1 and false for v2. Check which namespace you're calling before you write retry logic.

The IETF draft

The header is being standardised as draft-ietf-httpapi-idempotency-key-header. As of November 2026 it's at revision -08, dated 22 October 2026, still an Internet-Draft in the HTTPAPI working group, not an RFC. The parts worth building against:

  • The value is a Structured Field String (RFC 9651), so on the wire it's quoted: Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324".
  • The key "MUST be unique and MUST NOT be reused with another request with a different request payload."
  • A server MAY combine the key with a fingerprint of the payload, such as a checksum or digest.
  • Expiry is up to the server, but it SHOULD be published in your docs. The draft doesn't define a header for it.
  • Error codes: 400 when a required key is missing, 422 when a key is reused with a different payload, 409 when a retry arrives while the original is still in flight. Problem details (RFC 9457) are suggested for the bodies.

Stripe's v1 example sends the key unquoted, and its docs describe a parameter mismatch only as "an error" rather than promising a 422. That's allowed: the draft also says each API MUST publish its own idempotency specification. Write yours down.

Designing the server side

Here's the flow I'd implement. The important property is that claiming a key is a single atomic insert, so two racing retries can't both run the side effect.

Decision flow for an incoming POST with an Idempotency-Key: if the key is new for the account, insert a row marked in_progress, run the side effect, save the status code and body and mark it done, then return 201; if the key exists with a different fingerprint, return 422; if it exists and is still in progress, return 409; if it exists and is done, replay the saved response
Decision flow for an incoming POST with an Idempotency-Key: if the key is new for the account, insert a row marked in_progress, run the side effect, save the status code and body and mark it done, then return 201; if the key exists with a different fingerprint, return 422; if it exists and is still in progress, return 409; if it exists and is done, replay the saved response

And here it is as runnable code, using Node's built-in node:sqlite so there's nothing to install (Node 24.4; it prints an ExperimentalWarning for the SQLite module). In production the table lives in your main Postgres or MySQL database.

import { DatabaseSync } from 'node:sqlite';
import { createHash } from 'node:crypto';

const db = new DatabaseSync(':memory:');
db.exec(`CREATE TABLE idempotency_keys (
  account_id    TEXT NOT NULL,
  key           TEXT NOT NULL,
  fingerprint   TEXT NOT NULL,
  status        TEXT NOT NULL,          -- 'in_progress' | 'done'
  response_code INTEGER,
  response_body TEXT,
  created_at    INTEGER NOT NULL,
  PRIMARY KEY (account_id, key)
)`);

const fingerprint = (method, path, body) =>
  createHash('sha256').update(`${method} ${path}\n${JSON.stringify(body)}`).digest('hex');

const claim = db.prepare(`INSERT INTO idempotency_keys
  (account_id, key, fingerprint, status, created_at)
  VALUES (?, ?, ?, 'in_progress', ?) ON CONFLICT DO NOTHING`);
const find = db.prepare(`SELECT * FROM idempotency_keys WHERE account_id = ? AND key = ?`);
const finish = db.prepare(`UPDATE idempotency_keys SET status='done', response_code=?, response_body=?
  WHERE account_id = ? AND key = ?`);

let charges = 0;
function handle(account, key, body, { crashBeforeFinish = false } = {}) {
  const fp = fingerprint('POST', '/v1/charges', body);
  const { changes } = claim.run(account, key, fp, Date.now());
  if (changes === 0) {
    const row = find.get(account, key);
    if (row.fingerprint !== fp) return [422, 'Idempotency-Key reused with a different payload'];
    if (row.status === 'in_progress') return [409, 'A request with this key is still in progress'];
    return [row.response_code, row.response_body + ' (replayed)'];
  }
  charges++;                                   // the side effect
  if (crashBeforeFinish) return [504, 'gateway timeout'];
  const res = JSON.stringify({ id: `ch_${charges}`, amount: body.amount });
  finish.run(201, res, account, key);
  return [201, res];
}

Calling it with the same key twice, then with a changed amount, then from a second account, then simulating a crash between the side effect and the save:

[ 201, '{"id":"ch_1","amount":500}' ]
[ 201, '{"id":"ch_1","amount":500} (replayed)' ]
[ 422, 'Idempotency-Key reused with a different payload' ]
[ 201, '{"id":"ch_2","amount":500}' ]
[ 504, 'gateway timeout' ]
[ 409, 'A request with this key is still in progress' ]
charges created: 3

The first four lines are the happy paths. The last two are the hard part, and they're why a toy version isn't enough.

The stuck "in progress" row

If the process dies after the side effect but before saving the response, the row sits at in_progress forever and every retry gets a 409. You need a way out, and there are two honest options.

Lock with a timeout. Store a locked_at timestamp and let a retry take over a row whose lock is older than some limit. That's what Brandur's Postgres implementation does, and the write-up is the best long-form treatment of this problem I know of. His table keys on (user_id, idempotency_key), tracks locked_at and a recovery_point, and splits the request into "atomic phases": local database work in a transaction, with each call to a foreign system (a card charge, an email) in its own phase. A retry resumes from the last recorded recovery point instead of starting over.

Make the side effect itself idempotent. If the external call accepts its own idempotency key, pass a key derived from yours. Then taking over a stale lock and re-running is safe, because the downstream system dedupes. This is the main reason to prefer providers that support keys.

Brandur also describes a "completer" process that pushes abandoned requests to completion and a "reaper" that deletes old keys, suggesting about 72 hours so a bug shipped on Friday can still be fixed and replayed on Monday. That's a design suggestion, not a standard. Pick a window, publish it as the draft asks, and make it longer than your clients' retry horizon.

Choices you'll have to make

Scope keys per account. Two customers generating the same UUID is unlikely; a buggy client library reusing a constant is not. Stripe v2 scopes by account and API, Brandur's index is per user. Never let one tenant's key replay another tenant's response.

Fingerprint carefully. My example hashes JSON.stringify(body), which depends on key order. If clients might serialise the same object differently, canonicalise first (sort keys) or fingerprint only the fields that matter. Include the method and path so a key reused on another endpoint is caught. If you want to eyeball what a fingerprint should be while debugging, the hash generator computes SHA-256 of a pasted string in the browser.

Decide what you store for errors. Stripe v1 stores whatever happened once execution began, 500s included. A narrower policy is common: store the response once the side effect has committed, and release the key (delete the row) on failures where nothing changed, so a retry can run. Whatever you choose, write it in the docs, because clients will build retry logic around it.

Keep the key in the same database as the work where you can. Then the claim, the business write and the saved response can share transactions. A Redis SET NX in front of a Postgres write is fine for dropping duplicate clicks, but it can't tell you whether the write committed.

Don't confuse this with webhooks. Idempotency keys protect you when you retry to someone else. When a provider retries to you, dedupe on the event ID instead; the webhooks guide and the Stripe integration patterns post cover that side.

On the client

A key identifies an operation, not an attempt. Generate it once, when the user clicks "Pay" or when a job is created, persist it alongside the pending operation, and send the same value on every retry, including retries after a process restart. A fresh crypto.randomUUID() per attempt gives you no protection at all. For quick manual testing with curl, our UUID generator makes v4 values in bulk; the UUID versions post compares v4 and v7 if you're choosing between them.

Stripe's own docs list a second strategy: derive the key from something the user already has, such as a cart ID, which neatly blocks double submits. Combine that with exponential backoff and jitter (both in the 2017 post) and respect 429 and Retry-After from the server; the rate limiting post covers those headers.

Before you ship it

  • Required on every POST that creates or charges; 400 if missing.
  • Unique index on (account_id, key); claim with a single insert.
  • Fingerprint of method, path and canonicalised body; 422 on mismatch.
  • 409 while in progress, with a lock timeout so rows can't stick.
  • Replay the stored status and body, and mark replays with a header.
  • A published retention window, enforced by a cleanup job.
  • Clients generate one key per operation and persist it before the first attempt.
AE

Written by AIDToolStack Editorial

Researched from official documentation, specifications and vendor pages, listed under Sources below. Last checked November 2026.

Sources

  1. stripe.com/blog/idempotency
  2. docs.stripe.com/api/idempotent_requests
  3. docs.stripe.com/error-low-level
  4. docs.stripe.com/api-v2-overview
  5. datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/
  6. brandur.org/idempotency-keys

Related Posts

Explore on AIDToolStack

Discover tools and servers featured in our directory.

MCP Servers

Trigger.dev Jobs MCP ServerManage Trigger.dev background jobs from your AI coding assistant. Monitor job runs, trigger tasks manually, inspect execution logs, manage schedules, and debug failed runs. The server provides operational visibility into your background job infrastructure — see which tasks are running, queued, or failed, and take action. Your AI can help diagnose job failures from execution logs, retry failed tasks, and optimize concurrency configurations for better throughput.Tailscale Network MCP ServerManage your Tailscale mesh VPN network from your AI coding assistant. View connected devices, manage ACLs, configure exit nodes, check device status, and manage DNS settings. The server provides visibility into your Tailscale network — see which machines are online, troubleshoot connectivity issues, manage network access policies, and configure routes. Useful for developers managing distributed infrastructure where Tailscale provides secure networking between services.Portainer Docker MCP ServerManage Docker environments through Portainer's API from your AI coding assistant. Control containers, images, networks, and volumes across multiple Docker hosts and Kubernetes clusters. The server provides tools for container lifecycle management, image pulling and building, stack deployment, and resource monitoring. Portainer's multi-environment management makes this server particularly valuable for teams managing containers across development, staging, and production environments.

Reviews

Sign in to leave a review.

No reviews yet. Be the first!

Comments

Sign in to leave a comment.

No comments yet. Be the first!

Sponsor Our Newsletter

Reach thousands of developers who are actively evaluating AI tools, MCP servers, and dev infrastructure. Our weekly newsletter goes to engaged technical decision-makers.

Growing subscriber baseHigh open rates

All sponsored content is clearly labeled per our editorial policy.