Optimistic UI and concurrent writes
Keep the interface responsive while making confirmed data, retries and conflicting updates explicit.
What you will be able to do
- Separate confirmed data from speculative patches.
- Reconcile success and rejection without losing unrelated edits.
- Explain idempotency and optimistic concurrency control.
- Design a database invariant that holds across multiple clients.
Before this lesson
Display a prediction, keep a source of truth
An optimistic interface shows the outcome it expects before the server confirms it. A cart can appear to add an item immediately, but inventory and authorization still decide whether the addition is accepted. Maintain a confirmed base and identify pending operations separately. A visible pending marker is useful because the screen currently represents an intention as well as a fact.
React useOptimistic provides temporary optimistic state in an action or transition. It does not commit the write, authenticate it, or invent a conflict policy. The reducer should be pure and deterministic. Choose whether your optimistic operation is an absolute assignment, an increment, or an append, because those operations behave differently when replayed over a newer base.
Resolve one operation without erasing another
Imagine adding product A and then B. If A fails, replacing the entire cart with a snapshot taken before A would also remove B. Instead remove or compensate only A using its operation identifier, then derive the visible cart from the latest confirmed base plus remaining pending operations. This separates rollback from accidentally restoring stale application state.
Server acknowledgements may arrive out of order when you use independent HTTP requests or multiple clients. Associate each response with its operation, discard already processed responses, and decide how server versions replace older base data. The pure exercise below models this reconciliation rule. It deliberately does not claim to simulate React scheduling or a database transaction.
Reject stale replacement writes
A form that replaces a record can carry the version the user edited. The server updates only when the stored version still equals that expected version, increments it atomically, and reports a conflict otherwise. The user can then compare the newer record, merge intentional changes, or choose to overwrite through an explicit new request. Silent last-write-wins is a policy, not an absence of policy.
The following SQL statement is an adapter contract sketch, not an executable database connection in the article. Bind the values with your database driver and check the returned row count. The authorization predicate and version predicate must constrain the same write; checking ownership and version in earlier independent reads creates a race window.
Server execution
export const updateProductSql = `
UPDATE products
SET name = $1, version = version + 1
WHERE id = $2 AND owner_id = $3 AND version = $4
RETURNING id, name, version
`;
export function classifyWrite(rowCount: number) {
return rowCount === 1 ? "saved" : "missing-forbidden-or-conflict";
}Retries need a durable identity
A client may time out after a payment-like operation has committed. Retrying with a new operation identifier can create a second effect. Define an idempotency key scoped to the actor and operation, bind it to a hash of the normalized payload, and persist its status and result. Reusing the same key with different input must fail rather than return an unrelated prior result.
The idempotency record and database effect need atomic coordination, typically a transaction plus a unique constraint. An in-memory Set only coordinates one process and disappears on restart. Disabling a button only coordinates one rendered interface. For effects outside the database, discuss an outbox or the external service idempotency contract instead of promising exactly-once delivery from a local flag.
Choose the smallest enforceable invariant
Two buyers can both read stock equals one. If each independently writes stock minus one, the result depends on the race. Express the condition in the write itself, for example updating where stock is at least the requested quantity, and inspect whether a row changed. When several rows must change together, define a transaction with an appropriate isolation or locking strategy.
Practice explaining a conflict without blaming the framework. React coordinates interface state; Next.js coordinates request/render integration; the storage system coordinates durable concurrent writes. The client dispatcher may serialize actions within one client, but another browser, user or Route Handler can still submit concurrently. Your database invariant must survive that wider execution model.
Misconceptions to replace
Compare the tempting shortcut with the model you can verify in code.
- CLAIM TO CHALLENGEOptimistic UI confirms that a write succeeded.
- A more accurate model
It displays an expected result before confirmation and needs rejection/reconciliation behavior.
- How to check it
React useOptimistic documentation and the operation-reconciliation kata.
- CLAIM TO CHALLENGEAn in-memory Set provides durable idempotency across replicas.
- A more accurate model
Each process has its own state and can restart; use a shared durable contract where required.
- How to check it
The retry scenario and multi-instance deployment lesson expose the missing guarantee.
Mistakes to catch in your own code
- Rolling back an entire stale snapshot after one operation fails.
- Treating action dispatch order as a database lock.
- Reusing idempotency keys for different payloads.
- Calling an in-memory array durable storage.
Write it by hand
JavaScript logic playground
Reconcile optimistic operations
Implement solve(input). This sandbox runs the lesson's logic with FrontendX's isolated code runner. Next.js server behavior is verified in the project lab below.
- Input contains base, pending [{id,delta}], and event {id,accepted,confirmed}.
- If the event ID is pending, remove only that operation. On acceptance replace base with confirmed; on rejection keep base.
- Ignore an event for an unknown ID. Return {base,pending,visible}, where visible is base plus remaining deltas.
Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.
Inspect 3 test cases
- Reject only the first operation
Input
{ "base": 10, "pending": [ { "id": "a", "delta": 2 }, { "id": "b", "delta": 3 } ], "event": { "id": "a", "accepted": false, "confirmed": 0 } }Expected
{ "base": 10, "pending": [ { "id": "b", "delta": 3 } ], "visible": 13 } - Apply a confirmation
Input
{ "base": 10, "pending": [ { "id": "a", "delta": 2 }, { "id": "b", "delta": 3 } ], "event": { "id": "a", "accepted": true, "confirmed": 12 } }Expected
{ "base": 12, "pending": [ { "id": "b", "delta": 3 } ], "visible": 15 } - Ignore duplicate acknowledgement
Input
{ "base": 12, "pending": [ { "id": "b", "delta": 3 } ], "event": { "id": "a", "accepted": true, "confirmed": 11 } }Expected
{ "base": 12, "pending": [ { "id": "b", "delta": 3 } ], "visible": 15 }
Reveal the worked solution and reasoning
function solve(input) {
const known = input.pending.some(item => item.id === input.event.id);
const pending = known ? input.pending.filter(item => item.id !== input.event.id) : input.pending.slice();
const base = known && input.event.accepted ? input.event.confirmed : input.base;
return { base, pending, visible: pending.reduce((sum, item) => sum + item.delta, base) };
}Operation identity prevents a failure from undoing unrelated work.
The model assumes each accepted confirmed value is an authoritative base for this exercise; a real protocol also needs record or stream versions to handle stale confirmations.
Deriving visible state avoids maintaining a third independent value that can drift.
Verify it in a real Next.js application
Next.js application lab
Reconcile an optimistic task with a stale server version
Open the local application route /dashboard after starting the workbench. Follow the experiment and collect the evidence described below.
Make the change
- Sign in and inspect components/task-toggle.tsx, toggleTask in app/actions.ts, and app/api/tasks/[id]/route.ts. The shipped checkbox uses useOptimistic while the server compares the supplied task version.
- Open the same workspace in two tabs. Update a task in one tab, then submit the old version from the other tab without refreshing it. Observe the conflict message and the optimistic checkbox returning to its confirmed state.
- Use the task API to read a current version, PATCH it once with the configured local Origin, then repeat the old version. Record the successful response and the subsequent 409 conflict.
- Implementation extension: build a cart operation queue with operation IDs and independent rollback. The current /cart uses a local reducer and storage restoration; it does not send cart writes to a server.
- Implementation extension: replace the file store with a transactional adapter using a conditional version update and an idempotency constraint. Test concurrent requests from separate processes before claiming durable concurrency safety.
Check the behavior
- The existing task checkbox exposes pending work and reports a stale-version failure without treating the rejected value as committed.
- A successful task mutation increments its version; another write using that previous version is rejected.
- For the cart extension, rejecting one operation preserves unrelated accepted operations.
- For the storage extension, the database enforces the stated invariant across processes. The lab write queue establishes only its single-process teaching contract.
Review the application reasoning
The lesson kata isolates reconciliation arithmetic. The dashboard supplies a real optimistic Server Action and HTTP version-conflict example. Cart persistence, database transactions and distributed idempotency require the explicitly assigned implementation work.
Open the project files and run instructions
A complete App Router application with catalogue routing, cart state, a task dashboard, practice sessions, tenant checks, cached data, hydration repairs, and HTTP streaming. Next.js 16.4.6 and React 19.3.0 are pinned in the project.
The playground opens a new editable copy. A local Node.js 22.14+ installation also runs the project. Use the local production build when measuring caching, streaming, or deployment behavior.
cd nextjs-interview-lab
npm ci
npm run dev
# In a second terminal
npm test
# Stop dev, then verify the production application
npm run build
npm start
# In a second terminal, install the test browser once
npx playwright install chromium
npm run test:e2eOpen http://localhost:3003. The project includes a credential-free practice account selector and a single-process file store. Those choices make experiments reproducible; the security and deployment lessons show what a production system needs.
Explain it in an interview
Give your answer aloud before opening the explanation. Then answer the follow-ups using your implementation as evidence.
01When should a mutation avoid optimistic UI?
When the prediction is unreliable or showing an unconfirmed result would be misleading, I keep a pending state instead. A destructive permission change or insufficient-stock purchase needs especially clear confirmation semantics.
I can still make the interface responsive by preserving the draft and showing progress. Optimistic rendering is a product choice that must include rejection and reconciliation behavior.
Follow-up questions
- Which parts of a checkout can safely be optimistic?
- What does the user see when authorization fails?
- React useOptimisticOfficial documentation
- Forms with Server ActionsOfficial documentation
02How do a version number and an idempotency key solve different problems?
A version detects that the record changed since the user read it. An idempotency key detects a retry of the same logical operation. A request can need both: retry it safely while refusing to overwrite someone else's newer edit.
I scope the key to the actor and validate its payload identity. I enforce version comparison and the write atomically in the database.
Follow-up questions
- What happens when the network fails after commit?
- Can two different edits share one key?
- Server Actions and mutationsOfficial documentation
- Data securityOfficial documentation
03Does Next.js serialize all Server Actions across all users?
No. Current documentation describes sequential dispatch per client. The server still receives independent requests from multiple clients and executes their work.
I do not depend on the dispatcher for stock, uniqueness, balance or record-version invariants. If independent work should run in parallel, it can run inside one action or through a suitable request design.
Follow-up questions
- Why might Promise.all of client action calls disappoint?
- Where should transactional protection live?
- Server Actions and mutationsOfficial documentation
04Why is restoring the old list a dangerous rollback?
That list can predate other successful or pending changes. Replacing the whole list repairs one failed operation by erasing unrelated work.
I retain the confirmed base and pending operations keyed by identity. A rejection removes its own operation; a confirmation updates the base and removes that operation. The visible result is derived again.
Follow-up questions
- How do you handle duplicate acknowledgements?
- What if the confirmed version is older than one already received?
- React useOptimisticOfficial documentation
Check your understanding
Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.
Your checkpoint
Loading your local progress.
Sources and further reading
- React useOptimisticOfficial documentation
- Server Actions and mutationsOfficial documentation
- Forms with Server ActionsOfficial documentation
- Data securityOfficial documentation