Atomic Transitions, Locking, and Idempotency
Build one protected gift-card redemption from claim through credit, ledger, and commit, then handle retries and other valid cards.
You’re reading a preview. Premium includes the full lesson and specialist practice. View the full curriculum.
The previous lesson allowed two requests to act on an unused gift card. Now we need one accepted redemption to produce one credit and one ledger record, with no half-finished result.
Claim the unused card → add its value → record the redemption → commit together
Atomic means the protected changes succeed or fail together. It does not mean every concurrency problem is solved by adding a transaction somewhere.
We'll build that one redemption first, explaining the job of each database operation. Then we'll distinguish a repeated request for the same operation from a different valid card crediting the same wallet.
Start from the invariant, then choose mechanisms
Write the required durable relationship: one accepted claim corresponds to one permitted credit and one ledger record. A denied duplicate claim creates no new credit. Two distinct valid claims both appear. A local failure leaves neither a consumed entitlement nor a partial credit. This statement tells you which rows and effects must be coordinated.
A conditional update can combine checking and claiming one row. A transaction can commit related rows together. Arithmetic updates can preserve concurrent increments. A unique constraint can prevent duplicate ledger identity. Idempotency can handle a caller retrying the same operation. Review the composition rather than checking for any one keyword.
Select each mechanism and identify its narrow guarantee.
Claim. Only the request that changes unused to consumed receives the right to continue.
UPDATE entitlements
SET consumed_at = CURRENT_TIMESTAMP
WHERE id = :id AND consumed_at IS NULL
RETURNING value_minor;
Apply. Arithmetic updates preserve distinct accepted credits.
UPDATE wallets
SET balance_minor = balance_minor + :value
WHERE id = :authorized_wallet;
Commit. Claim, credit, ledger, and operation result commit or roll back consistently.
BEGIN -> claim -> credit -> ledger/result -> COMMIT
any local failure -> ROLLBACK
Review question: The repair is the composition of mechanisms matching the complete invariant.