A customer clicks Pay. The request times out. They click again. Now they've been charged twice, and you've got a support ticket and a refund to process.
That's not a rare edge case. It's what happens to every API that takes money, creates orders, or sends messages the moment the network gets flaky. Retries are how clients survive timeouts, and a retry of a POST is a duplicate unless you do something about it. Idempotency keys are that something.
I've shipped this pattern into payment flows and order systems, and the mechanics are always the same: a key, a store, and a few rules about what to do when the same key shows up twice. Get those rules right and a retried request is free. Get them wrong and you either double-charge people or hand back stale responses. This guide is the full implementation, not just the concept: storage, response replay, concurrency, request fingerprinting, and key expiry. The code is Spring Boot and Postgres, but the logic ports to any stack.
What are idempotency keys, and why do REST APIs need them?
An idempotency key is a unique, client-generated value that lets a server detect a retried request and return the original result instead of performing the operation a second time.
The reason you need one comes down to HTTP method semantics. GET, PUT, and DELETE are idempotent by definition: calling them twice lands you in the same state as calling them once. POST is not. A POST that creates a charge, an order, or a message changes state every time it runs. And POST is exactly the method clients retry most, because a timeout is ambiguous. When a request times out, the client has no idea whether the request was lost on the way to the server or the response was lost on the way back. So it retries. Without a key, your server sees that retry as a brand-new request and does the work again.
The key rides along in a header named Idempotency-Key. There's an active IETF draft defining it (draft-ietf-httpapi-idempotency-key-header), though it isn't a ratified standard yet, so treat it as a well-established convention rather than a spec you can hold a vendor to. Stripe popularized the approach, and most payment and infrastructure APIs now follow the same shape. The client generates a unique value (a version 4 UUID is the usual choice) for each logical operation and sends the same value on every retry of that operation. A new operation gets a new key.
How does an idempotency key flow through a request?
The server checks the key against a store before doing any work, then branches into one of three paths: first-time, replay, or in-flight.
Here's the lifecycle. A request arrives with a key. The server looks it up:
- No record exists. This is the first time. The server reserves the key (writes a row marked
IN_FLIGHT), runs the operation, saves the response, and marks the recordCOMPLETED. - A
COMPLETEDrecord exists. This is a retry of a finished request. The server skips the work entirely and replays the stored response. - An
IN_FLIGHTrecord exists. The first request is still running. The server rejects this one with409 Conflictso the client backs off and tries again later.
Those three branches are the whole pattern. Everything else is detail about how you store the record, how you make the reservation atomic, and how you guard against misuse.
The client's job is small but strict: generate one key per logical operation, reuse it on every retry, and never reuse it for a different operation. If you let the client be sloppy here, the server-side guards in the sections below are what save you.
How do you store and replay idempotent responses?
You persist the key, the response status, and the response body, then return that saved response verbatim on any retry that matches a completed key.
Start with the table. The key is the primary key, which matters a lot for the concurrency story later:
CREATE TABLE idempotency_record (
idempotency_key TEXT PRIMARY KEY,
request_fingerprint TEXT NOT NULL,
status TEXT NOT NULL, -- IN_FLIGHT | COMPLETED
response_status INT,
response_body JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);The cleanest place to wrap the logic is the service layer, where you control the transaction around the real side effect. The flow reads top to bottom: reserve the key, do the work, save the response.
public PaymentResult charge(String key, String fingerprint, ChargeRequest request) {
try {
store.reserve(key, fingerprint); // INSERT ... status = 'IN_FLIGHT'
} catch (DuplicateKeyException e) {
return resolveExisting(key, fingerprint); // replay, 409, or 422
}
PaymentResult result = paymentGateway.charge(request); // the real, non-idempotent side effect
store.complete(key, 200, toJson(result)); // status = 'COMPLETED', save response
return result;
}The reserve call is a plain insert, and the complete call writes the response back:
-- reserve
INSERT INTO idempotency_record (idempotency_key, request_fingerprint, status)
VALUES (?, ?, 'IN_FLIGHT');
-- complete
UPDATE idempotency_record
SET status = 'COMPLETED', response_status = ?, response_body = ?::jsonb
WHERE idempotency_key = ?;On a retry of a completed request, reserve throws a duplicate-key error, resolveExisting finds the COMPLETED row, and you deserialize and return the stored response_body without ever touching the payment gateway. That's the replay. The caller gets the exact same result object the original request produced.
How do you handle concurrent requests with the same key?
You let the database's unique constraint pick a single winner, and you return 409 Conflict to everyone who arrives while the first request is still in flight.
This is the part most homegrown implementations get wrong. Picture two retries landing in the same millisecond. If your code does "check if the key exists, and if not, proceed," both requests check, both see nothing, and both proceed. Double charge. A read-then-write check has a race in the gap between the read and the write, and no amount of application-level locking fully closes it across multiple instances.
The fix is to make the reservation itself atomic. Because idempotency_key is the primary key, only one INSERT can win. Every concurrent caller trying to reserve the same key gets a DuplicateKeyException, and they all fall into resolveExisting:
private PaymentResult resolveExisting(String key, String fingerprint) {
IdempotencyRecord record = store.find(key).orElseThrow();
if (!record.fingerprint().equals(fingerprint)) {
throw new IdempotencyException(422, "Key reused with a different request body");
}
if (record.status() == Status.IN_FLIGHT) {
throw new IdempotencyException(409, "A request with this key is still in progress");
}
return fromJson(record.responseBody(), PaymentResult.class); // COMPLETED -> replay
}The database is the source of truth for who got there first, so this holds even when your API runs behind a load balancer across a dozen pods. If you'd rather keep the reservation out of your primary database, Redis works too: SET key value NX EX 86400 succeeds for exactly one caller and fails for the rest, which gives you the same single-winner guarantee. I lean on the Postgres unique constraint when I'm already persisting the response there, because it's one fewer moving part. Either way, prove the concurrent path returns 409 with a real database in your tests rather than a mock, which is exactly the kind of thing Testcontainers makes easy.
How do you stop a client from reusing a key with a different payload?
You hash the request into a fingerprint, store it next to the key, and reject any later request that presents the same key with a different fingerprint.
A key is a promise that says "this is the same operation." If a client accidentally reuses a key for a different charge, say the same key for a $10 payment and then a $400 one, neither answer is acceptable. Replaying the first response would tell the client the $400 charge succeeded when it never ran. Running the operation would break the promise the key made. So you detect the mismatch and refuse it with 422 Unprocessable Entity, which is what Stripe does.
The fingerprint is a hash over the parts of the request that define the operation: method, path, and body.
static String fingerprint(String method, String path, byte[] body) throws NoSuchAlgorithmException {
MessageDigest sha = MessageDigest.getInstance("SHA-256");
sha.update(method.getBytes(UTF_8));
sha.update((byte) ' ');
sha.update(path.getBytes(UTF_8));
sha.update((byte) '\n');
sha.update(body);
return HexFormat.of().formatHex(sha.digest());
}You compute this once when the request arrives, pass it into reserve, and compare it inside resolveExisting. A matching fingerprint means it's a genuine retry, so you replay. A different fingerprint with the same key means the client made a mistake, and a clear 422 tells them so instead of silently doing the wrong thing.
When should you expire idempotency keys?
Twenty-four hours is the standard window, matching Stripe, and a TTL or scheduled cleanup keeps the store from growing forever.
Keys only matter for the retry window. A client that's going to retry a failed payment will do it within seconds or minutes, not days. After a day, a repeated key almost always means a new logical operation or a bug, not a legitimate retry. So you set an expiry that comfortably covers your worst-case retry and backoff schedule, then drop anything older.
How you expire depends on the store. Redis gives you this for free with EX 86400 on the reservation. In Postgres, index created_at and run a scheduled delete, or partition the table by day and drop old partitions:
DELETE FROM idempotency_record
WHERE created_at < now() - INTERVAL '24 hours';One detail worth holding in your head: expiry and replay interact. If a key expires and the same client retries afterward, they get a fresh execution, because the record that would have triggered a replay is gone. That's almost always fine, since real retries happen fast, but it's the reason you set the window longer than your maximum retry schedule rather than shorter. Don't keep keys forever either. The store grows without bound and you're holding request bodies you no longer need.
Where do idempotency keys end and the outbox begin?
Idempotency is a contract between client and server, and the key is just how you write it down. The client promises "same key means same operation," and the server promises "I'll run it at most once and tell you the same answer every time you ask."
Here's the part that's easy to miss: idempotency keys protect the entry point, but the work behind them often spans more than one system. A single charge might hit a payment gateway, write a row, and publish an event. The key stops the duplicate request from running the handler twice. It does nothing about a duplicate event leaking into your message stream if the publish and the database write aren't atomic. For exactly-once across those boundaries, pair this with the outbox pattern so the response you replay and the events you emit stay consistent.
Build it once as a small store plus a service wrapper, and every unsafe endpoint you have gets safe retries for free. That's a good trade for a few dozen lines and one table.
For the canonical reference, read Stripe's engineering write-up on idempotency and their API docs on idempotent requests. The header itself is specified in the IETF Idempotency-Key draft.
Keep Reading
- How to Implement the Debezium Outbox Pattern in Spring Boot. Idempotency stops duplicate requests; the outbox stops duplicate events downstream. They're the two halves of exactly-once.
- The One System Design Question That Failed 80% of Candidates in 2025. Rate limiting and idempotency are the two guardrails almost every write endpoint needs.
- Integration Testing with TestContainers in Spring Boot. Spin up real Postgres in your tests to prove the concurrent-key path actually returns 409.