How to Make REST API Endpoints Idempotent in Java Safely
Make POST endpoints safe to retry with an Idempotency-Key header, a unique constraint and a stored response, and know which methods are idempotent already.

A mobile app sends POST /payments, the connection drops before the response arrives, and the app does what any reliable client does: it sends the request again. If your endpoint treats the second request as new, the customer pays twice. Making an endpoint idempotent means that repeating a request has the same effect as sending it once, and it is a property you build, not one HTTP gives you for POST. The earlier posts on this site cover the theory of retries and the shape of an idempotency key. This one is the implementation view: which methods are safe already, a complete table-backed handler in Spring Boot, how to make the work and the key atomic, how to prove it holds under concurrent duplicates with a test, how long to keep keys, what to return and why a message consumer needs the same treatment. Examples use Spring Boot 4, Java 25 and PostgreSQL 17.
What is idempotent already
HTTP defines which methods should be idempotent (RFC 9110, idempotent methods): GET, HEAD, OPTIONS, PUT and DELETE. The definition is about server state after the request, not the response. Whether your code honors it is your job, and a few common patterns quietly break it.
// Idempotent: the same body sets the same state, however often it arrives
@PutMapping("/customers/{id}/email")
void setEmail(@PathVariable long id, @RequestBody EmailChange body) {
customers.updateEmail(id, body.email());
}
// Not idempotent despite being a PUT: it adds
@PutMapping("/accounts/{id}/credit")
void credit(@PathVariable long id, @RequestBody Amount body) {
accounts.addBalance(id, body.cents()); // every retry adds again
}The second endpoint is named like an assignment and behaves like an increment. Fix it either by changing the contract to "set the balance to X" (idempotent, but loses concurrent updates) or by treating the credit as a new resource with its own identity: PUT /accounts/7/credits/{creditId} where the client chooses the creditId, so the second delivery overwrites the same row. That last pattern, client-chosen ids, is the cheapest way to make creation idempotent when you can use it. DELETE is idempotent if a second delete leaves the same state (the item is gone), even though the status code may differ, 204 then 404.
POST is the remaining problem: it creates or triggers, and the server chooses the outcome. The tool for it is the idempotency key. The design of the header is described in the IETF draft for the Idempotency-Key header, and the surrounding theory in idempotency, retries and at-least-once delivery.
The idempotency key
The client generates a unique value (a UUID) once per logical operation, and sends the same value on every retry:
curl -X POST localhost:8080/payments \
-H 'Idempotency-Key: 3f1c2a6e-8d0b-4a5e-9c7f-2b1d4e6a7c90' \
-H 'Content-Type: application/json' \
-d '{"orderId": 42, "amountCents": 4999}'The server remembers the first outcome under that key and returns it for any repeat. The two properties it must guarantee are exactly-one execution of the side effect for a key, and a response for the repeat that matches the original. Both depend on the key store being atomic, which is the subject of the next sections.
The table
A unique constraint in the database is the only arbiter that is correct under concurrency, because two requests can arrive in the same millisecond on two different servers. Store the key, a hash of the request, the status and the saved response:
CREATE TABLE idempotency_key (
key varchar(64) PRIMARY KEY,
request_hash char(64) NOT NULL,
state varchar(12) NOT NULL CHECK (state IN ('IN_PROGRESS', 'DONE')),
http_status int,
response_body text,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX idx_idempotency_created ON idempotency_key (created_at);The request_hash is the SHA-256 of the body. When a key is reused with a different body, the client has a bug, and replaying the first response would hide it; the server should reject with 422. The index on created_at supports expiry (below).
The handler
Keep the idempotency logic out of every controller by putting it in one component that wraps the operation:
@Component
class IdempotentExecutor {
private final JdbcClient jdbc;
private final TransactionTemplate tx;
IdempotentExecutor(JdbcClient jdbc, TransactionTemplate tx) {
this.jdbc = jdbc;
this.tx = tx;
}
record Outcome(int status, String body) { }
Outcome execute(String key, String requestHash, Supplier<Outcome> operation) {
return tx.execute(status -> {
int claimed = jdbc.sql("""
insert into idempotency_key (key, request_hash, state)
values (:k, :h, 'IN_PROGRESS')
on conflict (key) do nothing
""").param("k", key).param("h", requestHash).update();
if (claimed == 0) {
return replay(key, requestHash);
}
Outcome result = operation.get(); // the real work, same transaction
jdbc.sql("""
update idempotency_key
set state = 'DONE', http_status = :s, response_body = :b
where key = :k
""").param("s", result.status()).param("b", result.body()).param("k", key).update();
return result;
});
}
private Outcome replay(String key, String requestHash) {
var row = jdbc.sql("select request_hash, state, http_status, response_body from idempotency_key where key = :k for share")
.param("k", key)
.query((rs, n) -> new Object[]{rs.getString(1), rs.getString(2), rs.getInt(3), rs.getString(4)})
.single();
if (!requestHash.equals(row[0])) {
return new Outcome(422, "{\"title\":\"Idempotency-Key reused with a different request\"}");
}
if ("IN_PROGRESS".equals(row[1])) {
return new Outcome(409, "{\"title\":\"A request with this key is still being processed\"}");
}
return new Outcome((Integer) row[2], (String) row[3]);
}
}The on conflict do nothing insert is the atomic claim: exactly one caller gets claimed == 1. A concurrent duplicate blocks on the unique index until the first transaction commits, then sees the finished row and replays it. The controller becomes small:
@PostMapping("/payments")
ResponseEntity<String> pay(@RequestHeader("Idempotency-Key") String key, @RequestBody String body) {
var outcome = executor.execute(key, sha256(body), () -> payments.charge(body));
return ResponseEntity.status(outcome.status()).body(outcome.body());
}A related failure to know: the unique-key violation surfaces as a different exception when you use a plain insert without on conflict, described in SQLIntegrityConstraintViolationException on insert.
Make the work and the key atomic
The design above puts the claim, the business write and the saved response in one database transaction. If the process dies half-way, the transaction rolls back, the key row disappears with it and a retry starts fresh. That is the cleanest property and it holds only when the side effect is a write to the same database.
When the side effect is outside the transaction, such as a call to a payment provider, atomicity is impossible, and you must choose which failure to accept:
- Claim, call, record. If the process dies after the call and before the record, the retry finds
IN_PROGRESSforever or re-executes. Mitigate by passing the same key to the provider, so it deduplicates on its side too. Most payment APIs accept an idempotency key for exactly this reason. - Time out stale claims. Treat an
IN_PROGRESSrow older than the operation's maximum duration as abandoned, and let a retry take it over by updating the row in a compare-and-set.
State this limit in the documentation of the endpoint. Idempotency across two systems is only as strong as the weaker one.
Prove it under concurrency
The failure you are guarding against only appears when two requests overlap, so test with overlap. Fire many identical requests at once and assert that the side effect ran once:
@SpringBootTest
@AutoConfigureMockMvc
@Testcontainers
class PaymentIdempotencyTest {
@Autowired MockMvc mvc;
@Autowired JdbcClient jdbc;
@Test
void twentyConcurrentDuplicatesChargeOnce() throws Exception {
String key = UUID.randomUUID().toString();
String body = "{\"orderId\":42,\"amountCents\":4999}";
try (var pool = Executors.newVirtualThreadPerTaskExecutor()) {
var futures = IntStream.range(0, 20).mapToObj(i -> pool.submit(() ->
mvc.perform(post("/payments")
.header("Idempotency-Key", key)
.contentType(MediaType.APPLICATION_JSON)
.content(body)).andReturn().getResponse().getStatus())).toList();
var statuses = new ArrayList<Integer>();
for (var f : futures) statuses.add(f.get());
assertThat(statuses).allMatch(s -> s == 201 || s == 409);
assertThat(statuses).contains(201);
}
Integer charges = jdbc.sql("select count(*) from payment where order_id = 42").query(Integer.class).single();
assertThat(charges).isEqualTo(1);
}
}The decisive assertion is the last one: one row, whatever the interleaving. The statuses show the mix: one 201 for the winner, and duplicates answered 201 (replay after commit) or 409 (arrived while in progress). A client retrying on 409 after a short delay gets the stored 201. Run this test against the real database engine, as in-memory substitutes may not block on the unique index the same way.
Expire keys
Keys cannot live forever. They must outlive the longest period during which a client might retry the same operation, which for mobile apps with queued retries can be a day, and no longer. A scheduled job removes the old ones:
@Scheduled(cron = "0 15 * * * *")
void purge() {
int n = jdbc.sql("delete from idempotency_key where created_at < now() - interval '48 hours'").update();
log.info("purged {} idempotency keys", n);
}Choose 24 to 72 hours, and document it: a key reused after expiry is treated as a new operation. Use the created_at index so the delete does not scan the table, and delete in batches if the table is large.
What to return on a duplicate
Return the same status and body as the first success, so the client cannot tell a replay from the original and does not need special handling. If you want it visible, add a response header such as Idempotent-Replayed: true. Return 409 while the first request is in progress, and 422 for a reused key with a different payload. Never answer 500 to a duplicate, because that makes the client retry again. Use the standard error body for failures, per the project's REST API design rules.
Messages are the same problem
A Kafka consumer sees the same event twice after a rebalance or a crash before commit. The same table pattern applies: the message id plays the role of the key, and the handler inserts it in the same transaction as the work. A message already in the table is acknowledged and skipped. The consumer-specific details, offsets and commit order, are in writing a reliable Kafka consumer in Java.
Where this does not apply
A read-only endpoint needs no key. An operation that is naturally idempotent, setting a value or deleting a row, is already safe, and adding a key store makes it slower for nothing. Where a duplicate is harmless, such as recording a page view, accept the duplicate. And when the side effect cannot be repeated or looked up (a physical shipment), the deduplication has to live in the system that performs it; your table can only record what it was told.


