Module 2 · Data Access and Production Reliability · Lesson 4 of 9
Idempotency, Retries, and Transaction Boundaries
Diagnose before reading
A payment provider accepts a charge. The process crashes before marking the local payment completed, and the client retries. Trace the next request without inventing a distributed transaction. Decide which identity must stay stable and where you can discover the first attempt's outcome.
Write your answer first. Then use this trace to check the boundary you chose.
| Failure window | Durable evidence / guard | Recovery question |
|---|---|---|
| Two callers claim the same local key | Unique tenant + operation + key constraint | Which transaction won, and does the committed payload hash match? |
| Local commit succeeds but reply is lost | Saved operation/result under the same key | Can the caller retrieve/replay the original outcome? |
| Provider succeeds before local completion | Provider idempotency identity and operation lookup | Can you reconcile instead of issuing a new charge? |
| Outbox send succeeds before sent-marker commit | Durable pending event plus consumer deduplication | How is duplicate delivery made harmless? |
Idempotency definition
An operation is idempotent when applying the same logical request multiple times produces the same intended effect as applying it once. HTTP GET, PUT, and DELETE are defined with idempotent semantics for the intended server effect; repeated responses and incidental logging may differ. An implementation can still violate those semantics. POST is not inherently non-idempotent; it can be protected with an idempotency key.
Choosing the key
The client should generate a stable key for one business command, such as CreatePayment for one checkout attempt. A random key generated on every retry defeats deduplication. Scope the key by authenticated tenant and operation to avoid cross-tenant/operation collisions; a supplied tenant ID or key is not authorization. Recheck authorization before replaying a stored response. Store a hash of the canonical request payload so that reusing a key with different input returns a conflict instead of silently replaying the wrong response.
Persistence model
A robust idempotency record can contain tenant ID, operation, key, request hash, status, response code, response body or resource ID, created time, and expiry. Enforce uniqueness in the database, with non-null key components and well-defined case/normalization rules. Protect stored request/response data and retain only what is needed. Expiry ends this deduplication window: a late replay may execute again unless longer-lived business uniqueness or provider safeguards prevent it.
CREATE UNIQUE INDEX UX_Idempotency ON IdempotencyRecords(TenantId, Operation, IdempotencyKey);
Do not rely on "check then insert" without a unique constraint. Two concurrent requests can both see no record and both execute. The database constraint is the concurrency guard for that record identity. It does not undo external side effects performed before the race is resolved or protect a different command key.
Atomic local transaction
When the business change and idempotency record share one database, write them in one transaction. The following service-method fragment assumes your EF Core context and domain types. CreateValidatedPayment constructs a local payment record; it must not call a payment provider. Generate stablePaymentId before any retry delegate and retain it across retries.
await using var transaction = await db.Database.BeginTransactionAsync(token);
var payment = CreateValidatedPayment(request, stablePaymentId);
db.Payments.Add(payment);
db.IdempotencyRecords.Add(IdempotencyRecord.Completed(
tenantId, operation, key, requestHash, payment.Id));
await db.SaveChangesAsync(token);
await transaction.CommitAsync(token);Handle the specific idempotency-constraint race by rolling back/disposing the failed transaction and using a clean context/transaction to load the committed record, compare its request hash, and return the documented completed/in-progress/conflict outcome. Do not blindly replay a different payload. Distinguish that constraint from unrelated database errors; provider behavior and isolation affect retry/read visibility.
In-progress records and leases
Long operations may first create an InProgress record. Concurrent duplicates can receive a documented 409 Conflict, or 202 Accepted with a status URL when the operation is still processing. Specify a polling/backoff contract. 425 Too Early concerns replay risk from HTTP early data; it is not a general-purpose “job still running” response. If a worker can crash, the record needs a lease or recoverable state; otherwise it may remain in progress forever. A takeover policy must be conservative because the original external side effect may have happened.
External side effects
A local transaction cannot atomically commit your database and a third-party payment. Use the provider's idempotency key where available. Record the provider operation ID. Reconcile uncertain outcomes by querying the provider rather than issuing another charge with a new key.
For publishing events after a database change, use the transactional outbox. In the same database transaction, save the aggregate change and an outbox message. A separate dispatcher sends the message and marks it sent. A reliable dispatcher with durable retry normally provides at-least-once delivery, not exactly-once effects: a crash between sending and marking can duplicate a message. Consumers still need idempotent handling. Permanent delivery failures require monitoring and recovery, not an assumption that every message inevitably arrives.
Retry classification
Retry only eligible transient failures when the operation is also replay-safe or protected by idempotency. A connection reset may occur after an effect committed; a 429 with Retry-After or short service-unavailable period may be retryable according to the API contract and remaining budget. Do not retry validation failures, authentication failures, payload errors, or deterministic constraint violations.
Use exponential backoff with jitter so many clients do not retry at the same instant. Bound attempts by the end-to-end deadline. Honor server retry hints. Log the attempt number and delay, but avoid one error log per retry plus another final error that inflates alert volume.
A conceptual retry policy:
- Attempt 1 immediately.
- Attempt 2 after a small randomized delay.
- Attempt 3 after a larger randomized delay.
- Stop when the deadline would be exceeded.
- Return or route the command for controlled recovery.
Retries and transactions
With EF Core retrying execution strategies, an explicit user transaction must be executed as a unit through the strategy (for example, CreateExecutionStrategy().ExecuteAsync with transaction creation inside the delegate); BeginTransactionAsync alone is not automatically compatible with implicit retries. The strategy may replay that unit on eligible transient failures. The earlier transaction fragment omits this wrapper and ambiguous-commit recovery. Every action inside the retry delegate must be replay-safe. Never call a non-idempotent external API inside a database retry block. Generate stable IDs outside the delegate when repeated inserts must represent the same entity. After an ambiguous commit, verify the durable record/result rather than assuming failure; a stable ID helps detect duplicates but does not itself make every replay successful.
Isolation and concurrency
Idempotency is not a substitute for domain concurrency rules. Two different keys can still try to reserve the last item. Use optimistic concurrency tokens, conditional updates, or appropriate isolation. For example:
UPDATE Inventory SET Available = Available - @quantity WHERE ProductId = @productId AND Available >= @quantity;
Validate @quantity > 0, make ProductId unique (and include authorized tenant scope where applicable), and enforce a nonnegative inventory invariant. Then require exactly one affected row for success. With all reservation writers using the appropriate atomic condition, the update protects this stock decrement without a global application lock; it can still take database locks and does not make the rest of a multi-step order atomic.
Message consumers
A broker commonly provides at-least-once delivery. Store a processed-message ID with the business update in one transaction. Acknowledge only after commit. If processing fails before commit, redelivery is safe only for the rolled-back local changes and other explicitly replay-safe effects; external calls still need their own idempotency or reconciliation. If acknowledgement fails after commit, the deduplication record makes the next delivery a no-op or replays the recorded result.
Ordering complicates the model. Deduplication stops repeated messages but does not stop an older distinct message from arriving later. Use aggregate sequence numbers, version checks, or partitioning when order matters.
Cancellation and ambiguous completion
If the caller cancels while commit is in progress, do not assume the transaction failed. The server should finish or reconcile the critical section according to its design. The client should retry with the same idempotency key. The API can then return the completed response or a known in-progress state.
Testing the hard cases
- Send two concurrent requests with the same key; assert one business effect.
- Reuse the key with a different payload; assert conflict.
- Simulate a timeout after commit; retry and assert the original response.
- Crash the worker after external success but before local completion; reconcile.
- Redeliver the same message; assert no duplicate state.
- Inject transient failures and verify bounded backoff.
- Verify non-transient failures are not retried.
- Test expiry boundaries and late replay explicitly; retain records or durable business uniqueness for the required replay window.
Interview scenario
Design a CreateOrder endpoint that reserves inventory, charges payment, and emits OrderCreated. A credible answer refuses to pretend one distributed ACID transaction exists. It uses a stable order ID and idempotency key, an inventory concurrency check, provider-side payment idempotency, durable state transitions, and an outbox. It explains compensation or reconciliation for partial progress and exposes a status endpoint for uncertain client outcomes.
Operational signals
Track duplicate-hit rate, in-progress age, conflict count, retry attempts, exhausted retries, outbox lag, reconciliation backlog, and provider mismatch count. Alert on stuck in-progress records and growing outbox age rather than on expected duplicate requests.
Check the boundary
An outbox dispatcher sends an event successfully, then crashes before marking the row sent. What contract should the consumer support?
Show answer
Correct answer: A
Sending and updating the sent marker are separate boundaries. A repeat send can be correct recovery. Consumer deduplication and local atomicity address repeated local effects; external calls still need their own replay safety or reconciliation.
Hint: Put the crash between the two durable boundaries.
Two-minute interview practice
Attempt both before comparing. State the assumption, the repair and one limit of your evidence.
- A key is retained for 24 hours and replayed after 25 hours. What guarantee has ended?
- Two different operation keys both reserve the last unit of stock. Why does idempotency alone not protect inventory?
Hint. Revisit the ownership, time, transaction or measurement boundary in the trace table.
Check your reasoning.
- The documented key-based deduplication window has ended. A replay may execute again unless longer-lived business uniqueness or provider safeguards apply. Define retention and late-replay behavior.
- They are distinct logical commands. Validate a positive quantity and apply an atomic stock condition/concurrency rule with the appropriate authorized product scope; check the affected-row result and keep the rest of the transaction explicit.
Evidence for the repair
Test concurrent duplicate claims, payload conflicts, lost responses after commit and provider-success/local-failure recovery separately. A unit test of a dictionary cannot establish a database uniqueness race or a real provider's idempotency contract.
Practice
TechInterviewNotes Editorial Team · Updated 28 Oct 2026 ·