Quick revision
The short answer
The safest design changes the operation from 'subtract 10' to 'the order has discount D10 applied', so repeating it sets the same state again. Where the operation must stay incremental, we record each operation id in a table with a unique constraint in the same transaction, and we guard the update with a condition on the expected previous state or version. A replay returns the stored result of the first call, and we prove it all with tests that deliver duplicates and out-of-order messages.
What to remember
In this answer, we designed an apply-discount operation that is safe to retry. We made it state-based so that applying the same discount sets the same value, recorded operation ids with a unique constraint in the same transaction for operations that must stay incremental, guarded updates with a version or expected-state condition, returned the stored result on replays, and proved the behaviour with duplicate, concurrent and out-of-order tests.
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.
The safest design changes the operation from 'subtract 10' to 'the order has discount D10 applied', so repeating it sets the same state again. Where the operation must stay incremental, we record each operation id in a table with a unique constraint in the same transaction, and we guard the update with a condition on the expected previous state or version. A replay returns the stored result of the first call, and we prove it all with tests that deliver duplicates and out-of-order messages.
Why this question is asked
Applying a discount looks like the simplest operation in an order service, yet it is exactly the kind of operation that goes wrong under retries. A mobile client times out and taps again, an API gateway retries on a 503, a message broker redelivers after a rebalance, and each time the order total drops by another 10 euros. Interviewers ask this design question to see whether we can make an operation safe to repeat without relying on luck. In this answer, we will see why the incremental version breaks, make it state-based, add operation ids and conditional updates for the cases that need them, decide what a replay returns, and finish with how to test it.
1Why Applying Twice Doubles the Discount
The naive implementation reads the order, subtracts the discount from the total and saves it. Each call is a change relative to the current value, which we call an incremental operation. An incremental operation can never tell a retry apart from a genuinely new request, because both look the same: subtract 10 from whatever the total is now.
The client only wanted one discount. Two deliveries of the same intent produced two effects. To fix it, either the operation has to stop being incremental, or the system has to remember which requests it has already applied.
2Option 1: Make the Operation State-Based
The strongest fix is to change what the operation means. Instead of subtracting an amount, we record which discount is applied to the order and compute the total from that. Setting a value to D10 twice leaves it at D10, so a retry has nothing to do.
Notice that the retry is now harmless without any extra table or lock. This also matches the business rule better: an order usually may carry one discount of a kind, and the data model now says so. If several discounts can stack, we store them as rows in an order_discount table with a unique key on (order_id, discount_code), so the same discount cannot be added twice.
3Option 2: Record Operation Ids in the Same Transaction
Some operations really are incremental, such as adding loyalty points or a manual goodwill credit that may legitimately happen twice. For those, the client or the producer gives each request an operation id, for example an Idempotency-Key header on the API or an event id in the message. We store it in a table with a unique constraint, in the same transaction as the change.
6 messages in order. Play them, or step through them one at a time.
The lookup at the start handles the common sequential retry. The unique constraint handles the race where two copies arrive at the same moment: both may pass the lookup, but only one insert can commit, and the other transaction fails and rolls back its subtraction too. Because the marker and the change are in one transaction, they can never disagree.
4Option 3: Guard the Update With the Expected State
A conditional update only applies if the row is still in the state the caller saw. The usual tool is a version column, which every change increments. The client sends the version it read; if someone else has changed the order since then, including our own earlier attempt, the update matches no row.
With JPA, an @Version field gives us the same check automatically and raises an optimistic locking failure when the version no longer matches. On its own, a conditional update tells us that something changed, not whether that something was our own earlier attempt, so we combine it with option 1 or 2 to give the caller the right answer.
5What a Replay Should Return
A retry happens because the caller did not see the first answer. If the replay returns an error such as 409 already applied, many clients treat it as a failure and show the customer a wrong message. So a replay should return the same result as the original call, which is why option 2 stores the result alongside the operation id. For a state-based operation, returning the current order is usually enough, since it already reflects the discount.
One more rule: if a request arrives with a known operation id but different content, for example the same key with a 20 euro discount, that is a client bug, and we reject it with an error rather than silently returning the old result.
6Testing Duplicates and Out-of-Order Delivery
We do not trust idempotency until a test has tried to break it. The tests send the same request twice in a row and assert the total dropped once, send two identical requests concurrently from two threads against a real database and assert one row in applied_operation, and replay a message after a later change, for example 'discount applied' redelivered after 'discount removed', to check it does not quietly re-apply an old intent. That last case is why version checks or event timestamps matter: a broker can deliver an old message late, and the state it carries should not overwrite a newer decision.
7Follow-up questions
Where should the idempotency key come from?
From the caller, because only the caller knows that two requests are the same intent. For an API, the client generates a UUID per user action and sends it in a header on every retry. For events, the producer puts a unique event id in the message. A key generated by the server on each request cannot detect retries.
Can we use a cache such as Redis for the operation ids?
It works for short retry windows, but it is weaker than the database table because the marker and the change are not in the same transaction. A crash between the two leaves them inconsistent, and an eviction makes old keys forgettable. For money, the table in the same database is the safer choice.
How do we handle messages that arrive out of order?
We include a version or a sequence number for the order in each event and apply an event only if it is newer than what we have stored, discarding or parking older ones. State-based events, which carry the full intended state rather than a change, make this easier because the newest event alone is enough to know the correct state.
8Conclusion
In this answer, we designed an apply-discount operation that is safe to retry. We made it state-based so that applying the same discount sets the same value, recorded operation ids with a unique constraint in the same transaction for operations that must stay incremental, guarded updates with a version or expected-state condition, returned the stored result on replays, and proved the behaviour with duplicate, concurrent and out-of-order tests.
Open with
The root problem is that subtracting 10 is incremental, so a retry is indistinguishable from a new request. My first choice is to make it state-based: the order records that discount SPRING10 of 10 euros is applied, and the total is computed from that.
Then, if they want more
Setting the same discount twice changes nothing, and if discounts can stack I keep them as rows with a unique key on order id and discount code.
If the operation must stay incremental, I require an idempotency key from the caller, an API header or the event id, and store it in an applied_operation table with a unique constraint, together with the result, in the same transaction as the change.
A sequential retry finds the key and gets the stored result back; a concurrent duplicate fails on the unique constraint and rolls back. I would also guard updates with a version column, so a stale or late message cannot overwrite a newer state, for example re-applying a discount that was removed afterwards.
Replays should return the same successful result, not an error, because the caller retried precisely because it missed the first answer, and the same key with a different payload should be rejected. Finally, I would test it with two identical requests in a row, two concurrent ones against a real database, and an out-of-order redelivery.
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 Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
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 an idempotent 'apply discount to order' operation that may be retried by clients...": https://scrivio-interview-library.netlify.app/databases/locking-and-concurrency-control/c31c8afefc/