Idempotency, Transactions & Side Effects
A mutation is reliable only if it behaves correctly when the network, user, database, or downstream services behave imperfectly.
The happy path is not enough.
submit once
β
server succeeds
β
UI updates
Production reality includes:
double click
browser retry
proxy retry
network timeout after server commit
multiple tabs
concurrent users
partial downstream failure
Idempotencyβ
An operation is idempotent when repeating the same logical request does not create additional unintended effects.
Naturally idempotent-ish:
set project name to "Alpha"
mark task completed
set preference = dark
Not naturally idempotent:
charge card Β£25
create order
send invitation
append audit event
provision VM
These need explicit duplicate protection.
UI disabling is not idempotencyβ
This helps UX:
<button disabled={pending}>Pay</button>
But it does not stop:
- repeated HTTP requests
- another browser tab
- scripted calls
- retries after timeout
Server-side guarantees are still required.
Idempotency keysβ
For high-impact create operations:
client creates logical operation ID
β
action submits ID
β
server stores/claims key
β
repeated same key returns same result
Example shape:
type CreatePaymentInput = {
idempotencyKey: string
invoiceId: string
}
The key must be scoped to the correct actor/resource and protected by server constraints.
Database unique constraintsβ
Sometimes the database can enforce the invariant directly.
Example:
one membership per (userId, organisationId)
Use a unique constraint so two concurrent actions cannot create duplicate memberships.
Application checks alone can race.
Transactionsβ
Use transactions when several writes form one logical invariant.
create order
reserve inventory
create order items
record payment intent reference
If these must succeed/fail together inside one database, wrap them transactionally.
But a database transaction cannot atomically include arbitrary external services.
External side effectsβ
Consider:
DB write
+ payment provider
+ email
+ analytics
There is no ordinary cross-system ACID transaction across all of these.
Define ordering and recovery explicitly.
Outbox patternβ
For important downstream events:
DB transaction
βββ domain state write
βββ outbox event write
β
background worker
β
email / webhook / queue / search index
This ensures the durable intent to perform the side effect commits with the database state.
A Server Action can complete after the transaction while a worker handles downstream delivery.
Do not hold user requests open for durable work unnecessarilyβ
Bad:
form submit
β
15 external calls
β
30-second response
If only the core write is required for user success, move secondary work into a queue/durable workflow.
Retry safetyβ
Before retrying a failed mutation, ask:
Did the server definitely fail before commit?
Or did the client merely fail to receive the success response?
If uncertain, blind retry can duplicate effects.
That is why idempotency keys matter for payments/orders/provisioning.
State-machine guardsβ
For workflows:
draft β submitted β approved β fulfilled
Actions should enforce valid transitions.
Bad:
await db.order.update({ data: { status: requestedStatus } })
Better:
approveOrder
cancelOrder
fulfillOrder
Each action verifies current state and permission.
Conditional updatesβ
Prevent stale mutation:
const result = await db.document.updateMany({
where: {
id,
version: expectedVersion,
},
data: {
body,
version: { increment: 1 },
},
})
if (result.count === 0) {
return { status: 'conflict' }
}
This detects concurrent edits instead of silently overwriting them.
Pessimistic lockingβ
For some critical invariants, lock rows/resources during the transaction.
Trade-offs:
- stronger serialization
- longer lock duration
- deadlock risk
- reduced throughput
Use only where domain correctness requires it.
Side effect orderingβ
Example purchase:
validate
β
authorize
β
create payment intent
β
commit order state
β
queue email
β
invalidate cache
β
redirect
The exact order depends on provider guarantees and your compensation strategy.
Do not copy a generic sequence without understanding failure cases.
Compensationβ
When a distributed workflow partially succeeds:
inventory reserved
payment failed
Possible compensation:
release reservation
For workflows where rollback is impossible, model reconciliation instead.
Audit before/after stateβ
For important mutations, logs may need:
actor
resource
operation
old state summary
new state summary
result
correlation ID
Keep sensitive fields out of logs.
Cache invalidation after transactionβ
Invalidate only after committed state is authoritative.
transaction commit
β
updateTag / revalidateTag / revalidatePath
If invalidation occurs before commit and the write later fails, consumers can refetch misleading state.
Redirect after required workβ
Likewise:
required write
β
required invalidation
β
redirect
Non-critical side effects can be asynchronous.
File-processing mutationsβ
For uploaded files:
receive metadata/upload reference
β
validate ownership/type
β
store durable record
β
queue virus scan/processing
β
state = processing
Avoid making a single action synchronously decode/transform huge files unless that is truly appropriate for the runtime/deployment.
Common mistakesβ
βUser can only click onceββ
False assumption.
Check-then-insert without unique constraintβ
Two requests can race.
Retrying non-idempotent external calls blindlyβ
Can duplicate real-world effects.
Treating DB transaction as distributed transactionβ
External services are outside it.
Doing all side effects before respondingβ
Hurts latency and reliability if those effects are not required for core success.
Mutation failure matrixβ
For every high-value action, write:
| Failure point | State after failure | Safe retry? | Recovery |
|---|---|---|---|
| validation | no write | yes after fix | user corrects input |
| DB before commit | none | usually | retry/idempotency |
| DB committed, response lost | committed | only if idempotent | return prior result |
| email failed | core state committed | yes via queue | retry worker |
| cache invalidation failed | DB fresh, cache stale | yes | repair invalidation |
This design work prevents incident-time guesswork.
Debugging checklistβ
- Reproduce double submission.
- Simulate timeout after commit.
- Submit same idempotency key twice.
- Race two conflicting updates.
- Fail downstream email/payment/search integration independently.
- Confirm transaction rollback behaviour.
- Confirm cache invalidation occurs after commit.
- Confirm audit logs identify operation without secrets.
- Confirm retries cannot duplicate irreversible effects.
- Confirm state-machine transitions reject invalid current states.
Interview questionsβ
Why isn't disabling the submit button enough for payments?
Because duplicate requests can still occur outside that UI path; idempotency must be enforced server-side/provider-side.
What does a database transaction solve?
Atomicity and consistency for operations inside that database transaction; it does not automatically cover external providers.
What is the outbox pattern?
Commit domain state and an event record together, then have a durable worker deliver downstream side effects.
How would you avoid lost updates?
Use version checks/conditional writes, transactions, locks, or domain-specific merge rules.
Exerciseβ
Design the mutation lifecycle for:
checkout order
invite member
publish article
upload invoice
provision workspace
Document transaction scope, idempotency key, side effects, retry policy, cache invalidation, and failure recovery.