Quick revision
The short answer
We store each Idempotency-Key with a fingerprint of the request body, a status and the final response, under a unique constraint on (client, key). The key is inserted first in its own transaction, so a unique violation reveals a duplicate: if the original is still in progress we return 409, if it completed we replay the stored status and body, and if the body differs we reject with 422. The payment and the key's completion are committed together, or coordinated through an outbox when an external provider is called, and keys expire after a documented window such as 24 hours.
What to remember
In this answer, we built idempotent POST /payments. Keys are stored per client with a request hash, a status and the stored response under a unique constraint. The key is claimed first in its own transaction, so concurrent duplicates are detected by the database and receive 409, completed replays receive the stored status and body, and mismatched bodies receive 422. The payment and the key's completion commit together, external providers are handled with provider keys and an outbox, and keys expire after a documented 24-hour window.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We store each Idempotency-Key with a fingerprint of the request body, a status and the final response, under a unique constraint on (client, key). The key is inserted first in its own transaction, so a unique violation reveals a duplicate: if the original is still in progress we return 409, if it completed we replay the stored status and body, and if the body differs we reject with 422. The payment and the key's completion are committed together, or coordinated through an outbox when an external provider is called, and keys expire after a documented window such as 24 hours.
Why this question is asked
Payments are the classic case where a retry must never do the work twice. A customer taps pay, the network stalls, the app retries, and without protection the card is charged twice. Interviewers ask this design question because a correct implementation has to handle storage, races between concurrent duplicates, replays, body mismatches, failures in the middle and cleanup, and each piece has a subtle reason. In this answer, we will design the key table, walk through the request flow, write the Spring code, handle the external provider, and finish with expiry and a reusable component.
1A Quick Recap of the Idempotency Key
An idempotency key is a unique value, usually a UUID, that the client generates once for one intended payment and sends in the Idempotency-Key header on the first attempt and on every retry. The server promises that all requests carrying the same key from the same client produce one payment and the same response. The key identifies the client's intention; the server's job is to remember what it did for that intention.
2Storage: The Key Table
We keep keys in the same database as the payments, so we can update both in one transaction.
Notice that the key is unique per client, not globally: two different clients may happen to choose the same value, and that must not make one see the other's payment. The request hash lets us detect a client that reuses a key for a different payment, which is a client bug we must not paper over.
3The Request Flow
The order of steps is what makes this correct under concurrency. We insert the key before doing any work, in its own short transaction. The database's unique constraint is the referee: if two identical requests arrive at the same moment, exactly one insert succeeds, and the other receives a unique violation.
- Insert key as IN_PROGRESSown transaction, unique (client_id, idem_key)
- Insert succeeded?YesProcess the paymentNoLoad the existing row
- Same request hash?YesCheck its statusNoReject with 422
- Existing status COMPLETED?YesReplay stored code and bodyNoReturn 409, try again later
- Commit payment and COMPLETED key togetherone transaction, response stored
5 steps in order. Play them, or step through them one at a time.
4Implementing It in Spring
Here is the core of the service. TransactionTemplate gives us explicit control over the two transactions.
The first transaction commits immediately, so the claim is visible to every other request at once; if we claimed the key inside the payment transaction, a concurrent duplicate would wait on the lock and then fail without a clear answer. The second transaction commits the payment and the COMPLETED key atomically, so there is never a payment without a stored response, or a stored response without a payment.
If the work fails with an error that the client may retry, such as a validation error from a downstream check, we either store that error response as the final result or delete the key so a corrected retry can proceed; the policy must be documented. Replaying a stored 4xx is the common choice, because the same request will fail the same way.
5When an External Provider Is Involved
Real payments usually call a payment provider over the network, and that call cannot be part of our database transaction. If we charge the card and then crash before committing, our key says IN_PROGRESS forever while the money has moved. Two techniques handle this. First, we pass our idempotency key, or a key derived from it, to the provider, since most providers accept one; then calling the provider again is itself safe. Second, we use an outbox: in one local transaction we write the payment as PENDING and an outbox row describing the provider call, and a worker performs the call, retries it with the same provider key and records the result. The key's response is then 202 with the payment's status, or the final result once the worker finishes.
6Expiry and Cleanup
Keys cannot live forever, or the table grows without limit. We document a window, for example 24 hours, within which retries are guaranteed to be deduplicated, and a scheduled job deletes older rows: DELETE FROM idempotency_keys WHERE created_at < now() - interval '24 hours', in batches to avoid long locks. Clients must not retry with the same key after the window; if they do, the server treats it as a new payment, which is why the window must be longer than any client's retry policy. Rows stuck IN_PROGRESS past a timeout are picked up by a recovery job that checks the provider or the outbox rather than being deleted blindly.
7Follow-up questions
What if the downstream payment provider times out after you stored the key?
We do not know whether the provider charged the card, so we must not mark the payment failed or let the client start a new payment. The key stays IN_PROGRESS and the payment PENDING, and the client gets 202 or 409 if it retries. A recovery process then either retries the provider call with the same provider idempotency key, which returns the original outcome if the charge happened, or queries the provider for the status of that key. Once the outcome is known, we commit the payment status and the stored response together, and the next client retry receives the final answer.
How would you implement this as a reusable filter or aspect?
We can define an @Idempotent annotation for controller methods and an aspect, or a HandlerInterceptor plus a ResponseBodyAdvice, that reads the header and hashes the body (with a ContentCachingRequestWrapper so the body can be read twice), claims the key, and either replays the stored response or lets the method run and stores what it returned. The generic part handles the protocol; the business code must still commit its own data and the key completion in one transaction, so the component should expose a completion call that joins the method's transaction instead of storing the response after it commits.
Why return 409 for an in-progress duplicate instead of waiting?
Waiting ties up a request thread for as long as the original takes and can pile up under retries. Returning 409 with a Retry-After tells the client to come back shortly, and its next retry will usually see the completed result. Short waits of a second or two are a reasonable refinement for fast payments.
8Conclusion
In this answer, we built idempotent POST /payments. Keys are stored per client with a request hash, a status and the stored response under a unique constraint. The key is claimed first in its own transaction, so concurrent duplicates are detected by the database and receive 409, completed replays receive the stored status and body, and mismatched bodies receive 422. The payment and the key's completion commit together, external providers are handled with provider keys and an outbox, and keys expire after a documented 24-hour window.
Open with
I would add a table of idempotency keys with the client id, the key, a SHA-256 hash of the canonical request body, a status, and the stored response code and body, with a primary key on client id and key.
Then, if they want more
When POST /payments arrives, the first step is to insert the key as IN_PROGRESS in its own short transaction. The unique constraint is the referee for concurrent duplicates: only one insert can win. If the insert fails, I load the existing row. If the hash differs, the client is reusing a key for a different payment, so I return 422.
If it is still in progress, I return 409 with Retry-After. If it is completed, I replay the stored status and body, so the client sees exactly the original response. If the insert succeeds, I process the payment and, in the same transaction, write the payment and mark the key COMPLETED with its response, so the two can never disagree.
When a payment provider is called, that call is outside our transaction, so I pass our key on to the provider and use an outbox with a worker, and a timeout leaves the payment pending until we know the outcome. Keys expire after a documented window, say 24 hours, and a cleanup job deletes old rows in batches.
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.
- Official documentation
- Spring Framework reference, Spring Web MVC
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 "Design idempotent POST /payments in a Spring Boot service using an Idempotency-Key...": https://scrivio-interview-library.netlify.app/spring-boot/rest-api-design/ba0461edb2/