Idempotency Key Spring Boot Implementation for Safe Retries
Implement an Idempotency-Key header in Spring Boot so a retried POST returns the first result: key storage, request hashing, concurrency and expiry.

Networks fail between "request sent" and "response received". When a payment request times out, the client cannot tell whether the charge happened, so it retries, and without protection the customer is charged twice. An idempotency key makes the retry safe: the client sends a unique value, and the server promises to run the operation at most once for that value. The general idea is in idempotent endpoints. This guide builds the mechanism on Spring Boot 4 and PostgreSQL, from the table to the controller, and spends equal time on the failure cases, because those are where most implementations are wrong.
The contract
The client generates a unique value, such as a UUID, and sends it in a header:
POST /payments
Idempotency-Key: 2f0f6c3e-5b7c-4a39-9c1f-0f3f5a2f7a10
Content-Type: application/json
{"orderId": 42, "amount": "25.00"}The server promises that the same key with the same body gives the same result, and that the work runs once. A retry with the same key returns the stored response. A retry with the same key and a different body is an error, because it means the client has a bug. The header name matches the IETF draft of the same name, so clients familiar with other payment APIs will recognise it.
The table
create table idempotency_key (
key varchar(64) primary key,
request_hash char(64) not null,
status varchar(12) not null, -- IN_PROGRESS, DONE
response_code int,
response_body text,
created_at timestamptz not null default now()
);The primary key is the mutual exclusion. Two requests with the same key cannot both insert it, and the database enforces that even across several application instances, which an in-memory set could not. The request hash stores a fingerprint of the first request so that a later one with the same key can be compared. Scope keys by client or account in a real system, so one customer cannot replay another's key.
The flow
@Service
class IdempotencyService {
private final JdbcClient jdbc;
IdempotencyService(JdbcClient jdbc) { this.jdbc = jdbc; }
enum Start { NEW, REPLAY, IN_PROGRESS, MISMATCH }
record Stored(Start start, int code, String body) { }
@Transactional
Stored begin(String key, String hash) {
int inserted = jdbc.sql("""
insert into idempotency_key (key, request_hash, status)
values (:key, :hash, 'IN_PROGRESS') on conflict (key) do nothing
""").param("key", key).param("hash", hash).update();
if (inserted == 1) return new Stored(Start.NEW, 0, null);
var row = jdbc.sql("select request_hash, status, response_code, response_body from idempotency_key where key = :key")
.param("key", key).query().singleRow();
if (!hash.equals(row.get("request_hash"))) return new Stored(Start.MISMATCH, 0, null);
if ("IN_PROGRESS".equals(row.get("status"))) return new Stored(Start.IN_PROGRESS, 0, null);
return new Stored(Start.REPLAY, (Integer) row.get("response_code"), (String) row.get("response_body"));
}
void complete(String key, int code, String body) {
jdbc.sql("update idempotency_key set status = 'DONE', response_code = :c, response_body = :b where key = :k")
.param("c", code).param("b", body).param("k", key).update();
}
}The statement insert ... on conflict do nothing decides, in one atomic step, whether this request is the first one with the key: it returns 1 for the first and 0 for every later one. That is the whole trick, and it avoids the check-then-insert race that a separate select would have. The hash is a SHA-256 of the method, path and body, so two different requests cannot share a key without being noticed.
The controller
@PostMapping("/payments")
ResponseEntity<String> pay(@RequestHeader("Idempotency-Key") String key, @RequestBody String body) {
var started = idempotency.begin(key, Hashing.sha256(body));
return switch (started.start()) {
case REPLAY -> ResponseEntity.status(started.code()).body(started.body());
case IN_PROGRESS -> ResponseEntity.status(HttpStatus.CONFLICT).body("request in progress");
case MISMATCH -> ResponseEntity.unprocessableEntity().body("key reused with a different request");
case NEW -> {
Payment payment = payments.charge(parse(body));
String response = toJson(payment);
idempotency.complete(key, 201, response);
yield ResponseEntity.status(HttpStatus.CREATED).body(response);
}
};
}The begin call must commit before the charge happens, so a concurrent duplicate sees IN_PROGRESS instead of waiting on a lock. When the payment is local to your database, do the business work and the complete call in one transaction, so the stored response and the charge succeed or fail together. When the work calls an external provider, pass the key on to the provider as well, because the provider's own idempotency completes the chain. Without it, a crash after the provider charged and before your complete leaves you unable to know.
Failure cases
A crash after the charge but before complete leaves the key IN_PROGRESS forever. Add a timeout: treat an old in-progress key as retryable after a few minutes, and make the downstream call idempotent, so that the repeat is safe. This is the case that separates a toy implementation from a real one.
A server error should not be stored as the final response. A 500 caused by a database blip would then be replayed to every retry, and the client could never succeed with that key. Delete the key, or mark it failed, so the client can retry the same key and get a fresh attempt.
Validation errors are a judgement call. Most APIs do not store them, so the client can fix the request and retry with the same key. If you do store them, the client must use a new key after the fix.
Testing it
Write a test that sends the same request twice and asserts that the second response equals the first and that the charge was made once. Write one that sends the same key with different bodies and expects 422. And write a concurrency test: fire two identical requests at the same time from two threads and assert that exactly one charges and the other receives 409 or the replay. The last test is the one that proves the atomic insert works.
Housekeeping
delete from idempotency_key where created_at < now() - interval '24 hours';Run it as a scheduled job. Keep keys long enough to cover the client's longest retry window, and longer than any queue that might redeliver. Twenty-four hours is a common choice, and the table stays small because each row holds one response.
Scope and security of keys
A key is a client-chosen value, so treat it as untrusted input. Limit its length, accept only a safe character set and reject the request if the header is missing for an operation that requires it. Scope the table's primary key by the authenticated account, for example (account_id, key), so one customer cannot learn the stored response of another by guessing a value. Never put the key in a URL or a log line at a level that other teams can read, since the replayed response may contain personal data.
What to store in the response
Store enough to replay: the status code, the body and the headers that matter, such as Location. Do not store a response that contains a one-time secret unless the replay is meant to repeat it. For large responses, store a reference to the resource and rebuild the body on replay, which keeps the table small. Whatever you store, replay it byte for byte, because a client that compares the retry with the first answer should see no difference.
Observability
Count the outcomes of begin as a metric: new, replay, in-progress and mismatch. A rising replay rate means clients are timing out and retrying, which tells you about latency before users complain. A mismatch is always a client bug and worth a log line with the account.
When keys are unnecessary
PUT and DELETE are idempotent by definition and do not need keys, and the status codes used here are explained in returning the right status codes. For message consumers the equivalent is the idempotent consumer, described in duplicate messages. The reference is the IETF Idempotency-Key header draft, and Stripe's idempotent requests document a mature design.


