Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Implement idempotent handling for a POST /payments endpoint in Spring Boot that accepts an Idempotency-Key header, so that a client retry after a timeout does not charge twice. Describe the table and the code flow.

We store each Idempotency-Key in a table with a unique constraint on client id plus key, together with a hash of the request, a status and the stored response. A request first inserts a row in status IN_PROGRESS; a unique violation means a duplicate, which gets the stored response if the hashes match, 409 if it is still in progress, and 422 if the same key comes with a different request. The charge runs only for the request that won the insert, the row is updated with its response in a controlled order, and old keys expire after a retention period.

Why this question is asked

Payments are where retries hurt most. A mobile client times out after 10 seconds, the user taps Pay again, and if the server treats both requests as new, the customer is charged twice. The Idempotency-Key header is the common contract for avoiding this: the client sends a unique key per logical payment and reuses it on retries. Interviewers ask us to implement it because the details, races, mismatched requests, crashes in the middle, separate a working design from a naive one. In this answer, we will design the table, walk through the request flow, write the Spring Boot code, handle the in-progress and mismatch cases, and finish with crashes and expiry.

1A Quick Recap of the Idempotency-Key Contract

The client generates a unique value, usually a UUID, for each payment it intends to make, and sends it as the Idempotency-Key header on POST /payments. If it does not get a response, it retries with the same key. The server promises that all requests with the same key from the same client have the effect of one request, and that a retry returns the same response the first request produced.

So the server needs to remember three things per key: that it has seen the key, what the original request was, so it can detect misuse, and what it answered, so it can answer the same way again.

2Designing the Table

The table holds one row per client and key. The unique constraint is what makes the whole design safe under concurrency, because the database, not our code, decides which of two simultaneous requests is first.

SQL
CREATE TABLE idempotency_key (
client_id text NOT NULL,
idem_key text NOT NULL,
request_hash text NOT NULL, -- SHA-256 of method, path and body
status text NOT NULL, -- IN_PROGRESS, COMPLETED
response_code int,
response_body jsonb,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (client_id, idem_key)
);

Notice that the key is scoped by client id. Two partners could generate the same key, by accident or because one uses a simple counter, and they must not see each other's responses. The request hash lets us tell a genuine retry from a different request that reuses a key.

3The Request Flow

Every request goes through the same decision. The first request for a key inserts the row and does the work; any other request with that key is a duplicate and is answered from the row.

Step throughHandling POST /payments with an Idempotency-Key
  1. Insert row: IN_PROGRESSclient id + key, request hash
  2. Unique violation?
    YesLoad the existing rowNoWe own the key: charge
  3. Same request hash?
    YesCheck statusNo422: key reused for another request
  4. Status COMPLETED?
    YesReturn stored responseNo409: still in progress, retry later
  5. Charge, then save responserow becomes COMPLETED

5 steps in order. Play them, or step through them one at a time.

Only the request that wins the insert ever calls the payment provider.

4The Spring Boot Code

Here is a compact version. The insert runs in its own short transaction, so the row is visible to other requests immediately, before the slow charge.

Java
@PostMapping("/payments")
ResponseEntity<String> pay(@RequestHeader("Idempotency-Key") String key,
@AuthenticationPrincipal Client client,
@RequestBody String body) {
String hash = sha256("POST /payments" + body);
try {
keys.insertInProgress(client.id(), key, hash); // own transaction, commits now
} catch (DuplicateKeyException dup) {
IdemRow row = keys.find(client.id(), key);
if (!row.requestHash().equals(hash))
return ResponseEntity.unprocessableEntity().body("key reused for a different request"); // 422
if (row.status() == IN_PROGRESS)
return ResponseEntity.status(409).header("Retry-After", "2").build(); // 409
return ResponseEntity.status(row.responseCode()).body(row.responseBody()); // replay
}
PaymentResult result = payments.charge(client.id(), body, "pay-" + client.id() + "-" + key);
keys.complete(client.id(), key, 201, toJson(result)); // store what we answer
return ResponseEntity.status(201).body(toJson(result));
}
// first request -> 201, card charged once
// retry, same body -> 201 with the stored body, no charge
// same key, other amount -> 422

Notice the order: insert, charge, store the response. If the server answered before storing, a retry arriving in between could find the row still IN_PROGRESS even though the payment was done. Also notice that we pass a key derived from the client key to the payment provider, which matters for crashes, as we will see.

5In-Progress and Mismatched Requests

A duplicate that arrives while the first request is still running sees status IN_PROGRESS. We cannot return a result we do not have yet, and we must not start a second charge, so we answer 409 Conflict, with Retry-After to suggest when to try again. Some APIs choose to wait briefly for the first request to finish instead; both are valid as long as they are documented.

A duplicate whose request hash differs is a client bug: the key was reused for a different payment, perhaps a different amount. Returning the stored response would hide the bug, and processing it would break the contract, so we reject it with 422 Unprocessable Content. Hashing a canonical form of the body, for example with fields in a fixed order, avoids false mismatches when a client serialises the same JSON differently.

6Crashes and Expiry

The dangerous case is a crash after the charge succeeded but before the response was saved. The row stays IN_PROGRESS forever, and every retry gets 409. We handle it in two ways. The charge itself is idempotent at the provider, because we sent a deterministic provider key, so a recovery process can safely call the provider again or query it by that key. And a scheduled job looks for rows IN_PROGRESS for longer than a limit, say 5 minutes, and resolves them by asking the provider what happened, then writes the real result into the row.

Finally, keys do not live forever. We keep them for a retention period that is longer than any client will retry, 24 hours is a common choice, and a scheduled job deletes older rows. The retention period is part of the API contract, because a retry after it expires is treated as a new payment.

Java
@Scheduled(cron = "0 0 * * * *")
void expireKeys() {
int n = jdbc.update("DELETE FROM idempotency_key WHERE created_at < now() - interval '24 hours'");
log.info("expired {} idempotency keys", n); // e.g. expired 18342 idempotency keys
}

7Follow-up questions

How do you handle a crash after charging but before saving the response?

The row is left IN_PROGRESS, so retries get 409 and no second charge happens. To finish it, a recovery job finds rows stuck IN_PROGRESS beyond a few minutes and asks the payment provider for the outcome using the deterministic provider key we sent, then stores the real response so the next retry gets it. If the provider shows no charge, the job can mark the row failed or delete it so the client's retry starts over. The provider key is what makes this safe: even if we call charge again, the provider returns the original charge instead of creating a new one.

Why should the key be scoped per client?

Because keys are generated by clients, and we cannot make independent clients coordinate to keep them globally unique. Without scoping, partner A's key could collide with partner B's, and B would receive A's stored payment response, which is both a correctness bug and a data leak. Scoping by the authenticated client id makes a key unique only within the client that created it.

Why not do the whole thing in one database transaction?

Because the charge is an external call and can take seconds. Holding a transaction open for it keeps the row locked and a connection busy, and a concurrent duplicate would block on the insert instead of getting a quick 409. Committing the IN_PROGRESS row first makes it visible immediately and keeps transactions short.

8Conclusion

In this answer, we implemented the Idempotency-Key contract for POST /payments. A table keyed by client id and key stores the request hash, status and response. The first request wins the insert and performs the charge; duplicates get the stored response when the hash matches, 409 while still in progress, and 422 if the key was reused for a different request. We store the response before answering, pass a deterministic key to the provider so a crash in the middle can be resolved safely, and expire keys after a documented retention period.

What to say in the interviewAbout 90 seconds aloud

Open with

I would keep a table keyed by client id and idempotency key, with the request hash, a status and the stored response code and body. When a POST /payments arrives, I compute a hash of the request and insert a row with status IN_PROGRESS in its own short transaction.

Then, if they want more

If the insert succeeds, this request owns the key: it charges the card, then updates the row to COMPLETED with the response, and only then returns. If the insert hits the unique constraint, it is a duplicate. I load the row: if the hash is different, the client reused the key for a different payment, so I return 422.

If the row is still IN_PROGRESS, I return 409 with Retry-After. If it is COMPLETED, I return exactly the stored response, so the client gets the same answer as the first time and nobody is charged twice. The unique constraint is what makes it safe across concurrent requests and multiple pods.

For crashes between the charge and saving the response, I pass a deterministic idempotency key to the payment provider, and a recovery job resolves rows stuck IN_PROGRESS by querying the provider. Keys are scoped per client so partners cannot collide or see each other's responses, and they expire after a documented retention period, for example 24 hours.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Implement idempotent handling for a POST /payments endpoint in Spring Boot that accepts...": https://scrivio-interview-library.netlify.app/spring-boot/distributed-data/f99c725957/