Optimistic updates and consistency

Intermediate · 5 min

Update the screen before the server answers, then roll back if it says no. The snapshot, the rollback, the final refetch, and where optimism is a bad idea.

Before thisServer state vs UI stateForms from submit to database

The Coderlog · 5 min

Optimistic updates and consistency

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by The CoderlogReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • An optimistic update writes the expected result into the client cache before the server confirms, so the interface responds immediately instead of waiting a network round trip.
  • Before changing the cache you cancel in-flight fetches and save a snapshot, because a late response for the old data would overwrite your guess and the snapshot is what you restore on failure.
  • On error, restore the snapshot and tell the user, and on settle, refetch from the server so that the server's version always has the last word.
  • Optimism suits changes that almost always succeed and are easy to undo, such as ticking a task done, and it is a poor fit for payments or anything with side effects the user must see confirmed.
  • Consistency is the real work: concurrent edits, retries and responses arriving out of order mean the final refetch matters more than the optimistic guess.

Why waiting feels broken

Ticking a task as done in Taskboard sends PATCH /api/tasks/1. The server takes 80 ms on a good day and 800 ms on a bad one. If the checkbox waits for the answer, it feels dead for that long, and on a slow connection people click again.

Optimistic update means: assume the server will say yes, show the result now, and fix the screen only if it says no. Think of ordering at a counter where the cashier writes your order on the ticket and starts the sandwich before your card finishes processing. If the card is declined, they throw the sandwich away. That works when declines are rare and the sandwich is cheap, and not when the thing being made is a car.

For most task-board actions, such as ticking, reordering, renaming, the “yes” rate is very high, and the cost of reversal is a flicker. Those are good candidates.

Four steps in the cache

This builds on server state vs UI state: the board is a cached copy, so an optimistic update is a temporary edit to that copy. In TanStack Query terms there are four steps.

  1. Cancel any in-flight fetch for that key. If a fetch started a moment ago and lands after your edit, it carries the old data and would erase your change.
  2. Snapshot the current value so you can put it back.
  3. Write the expected value into the cache. Components subscribed to that key re-render immediately.
  4. Send the request.

Then two outcomes. On error, restore the snapshot. Either way, on settled, refetch so the server’s version wins.

I ran the cache logic in Node with @tanstack/react-query 5.108.2, no React, and a fake server call that either succeeds or fails after 50 ms:

async function move(status, fail) {
  await qc.cancelQueries({ queryKey: key });
  const prev = qc.getQueryData(key);
  qc.setQueryData(key, (b) => ({ tasks: b.tasks.map(t => t.id === 1 ? { ...t, status } : t) }));
  console.log("optimistic:", qc.getQueryData(key).tasks[0].status);
  try { await server(fail); }
  catch { qc.setQueryData(key, prev); console.log("rolled back:", qc.getQueryData(key).tasks[0].status); }
}
await move("done", false);
await move("todo", true);

The output was:

optimistic: done
optimistic: todo
rolled back: done

The first move succeeded and the cache showed done instantly. The second move showed todo instantly, then the fake server failed and the snapshot put done back. That is the whole mechanism. In a component you write the same four steps as onMutate, onError and onSettled on useMutation, which is what the video builds. For the API surface, see caching, invalidation and mutations, and the Next.js version in optimistic updates.

The part that is actually hard: consistency

The sandwich analogy hides something. The snapshot-and-restore pattern is correct for one change. Real use has several at once, and that is where optimism earns its reputation.

Overlapping edits. The user ticks task 1, then immediately renames task 2. Two mutations are in flight, each with its own snapshot. If the first fails and restores its snapshot, it also rolls back the rename that happened afterwards, because the snapshot was the whole board. Fixes: snapshot only what you changed, or on any failure just invalidate and refetch instead of restoring by hand.

Out-of-order responses. Mutation A’s response can arrive after B’s. If each response writes into the cache, the older one wins. Writing nothing from the response and only refetching on settle avoids that.

The server changed something else. Maybe a database trigger set updated_at, or another teammate also moved the card. Your optimistic guess knew about neither. This is why onSettled refetches even after success: the guess is a placeholder, and the server’s version is the truth. A subtle consequence is that the screen may change once more after the request, so design for small corrections, not for “it never changes after my click”.

Failure messaging. A silent rollback is confusing. The task jumps back and the user wonders why. Pair the rollback with a short notice: “Couldn’t save. Reverted.” The error shape from error handling across the stack gives you the message to show.

Where not to be optimistic

Be optimistic when the action is likely to succeed, cheap to undo, and local in effect. Avoid it when:

  • Money or external effects are involved: checkout, sending an email, deleting a shared file. Show a pending state and wait. The payments and webhooks lesson later in the roadmap treats the server as the authority for exactly this reason.
  • The result depends on server computation you cannot predict, such as a generated id or a calculated price. You can show a placeholder row, but a fake id that later changes breaks keys and links.
  • Validation is likely to fail. If one in five submits is rejected, optimism creates more flicker than it removes.
  • Permissions are in doubt. If the user might not be allowed, the server’s 403 should arrive before the screen claims success.

A useful middle path is the pending but visible state: show the change dimmed with a small spinner until confirmed. It feels fast, and it is honest.

Idempotency pairs naturally

When the client can retry automatically, the server must tolerate repeats, otherwise optimism plus retry creates duplicates. That is the same point as in forms from submit to database: make a repeat of the same request harmless.

What the video covers

The Coderlog’s “Why wait for the server? Optimistic updates with TanStack Query” is about five minutes, published October 2026, and builds on a Vite and React app. Its chapters are The wait (0:00), The stand-in: onMutate (0:40), When the server says no: onError (2:23), The last word: onSettled (3:35) and Recap (4:48). That maps one to one onto the four steps above. Its description mentions using the Network tab and TanStack DevTools to watch each step, and the cancelQueries, getQueryData and setQueryData calls. I could not read a transcript. It is a recent and tight match. Codevolution’s older episode on the same feature is linked as a second view; it dates from 2021 and may use an older API version.

Where this fits

Optimistic updates handle your own actions. Teammates’ actions arrive from somewhere else, and the cache has to hear about them without a click. Next: real-time updates end to end.

Check yourself

  1. 01Why call cancelQueries before writing the optimistic value?

    A fetch that started earlier could land afterwards and overwrite the optimistic value with stale data, so you cancel it first.

  2. 02What does onError restore, and where did it come from?

    The snapshot of the previous cache value, which onMutate saved before it changed anything.

  3. 03Why still refetch after a successful mutation if the optimistic value was right?

    The server may have changed other fields or other users may have edited the data, so a final refetch makes the cache match the server.

  4. 04When is an optimistic update a bad idea?

    When the action is hard to undo or has external effects, such as charging a card, because showing success and then reversing it is worse than a short wait.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark