← Back to Frontend, page 3

frontend-0058 · Hard senior

How do you build an optimistic update for a like button, and what goes wrong with rollback when several actions are in flight?

An optimistic update changes the screen at once and sends the request in the background. If the request fails, the change is undone. Restoring a saved snapshot is wrong when other actions finished in between, so undo only the failed action, by applying its inverse or by re-deriving state from a log of pending actions.

Full answer

Waiting for the server before showing a result makes simple actions feel slow. With an optimistic update the interface assumes success:

  1. Apply the change to local state at once.
  2. Send the request.
  3. On success, keep the state, and optionally replace it with the server's value.
  4. On failure, undo the change and tell the user.

The hard part is the undo. A common first version saves the old value and restores it on failure:

js
const prev = state.likes; state.likes += 1;
try { await api.like(); } catch { state.likes = prev; }

This breaks when two clicks are in flight. If click A fails after click B has already been applied, restoring A's snapshot also removes B's change, even though B succeeded. The screen is wrong until a refetch.

Better approaches:

  • Apply the inverse. On failure of A, subtract A's own change (likes -= 1) so that B stays.
  • Keep a list of pending actions, and compute the displayed state as the server state plus all pending actions. When one fails, remove it from the list, and the display is recomputed. This is what query libraries do with optimistic mutations.
  • After the queue settles, refetch the true state from the server so that the display cannot drift.
  • Disable or serialise actions that cannot be combined, such as "like" then "unlike" on the same item, or send only the latest intent.

Other points for a complete answer:

  • Use idempotent requests or an idempotency key, so that a retry does not double count.
  • Show a small failure message and a retry option, not only a silent rollback.
  • Not every action is a good fit. Payments and destructive actions should wait for the server.
  • Keep ordering rules on the server, or send the intended final state ("liked: true") instead of "toggle".

The script simulates two likes. The first request fails and the second succeeds. A snapshot rollback ends with the wrong count, and the inverse rollback keeps the successful like.

javascript
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// The first call fails after 30 ms, the second succeeds after 60 ms.
const makeApi = () => { let n = 0; return { like: async () => { n += 1; if (n === 1) { await sleep(30); throw new Error('offline'); } await sleep(60); } }; };

async function run(rollback) {
  const api = makeApi();
  const state = { likes: 3 };
  const like = async () => {
    const prev = state.likes;
    state.likes += 1;                       // optimistic
    try { await api.like(); }
    catch { rollback(state, prev); }
  };
  await Promise.all([like(), like()]);
  return state.likes;
}
console.log('snapshot rollback ends at:', await run((s, prev) => { s.likes = prev; }));
console.log('inverse rollback ends at:', await run((s) => { s.likes -= 1; }));

Run with Node 24.22.1. The output matched the text in the answer in two runs. The short snapshot rollback code shown in the answer text is the same pattern as the first run in the script and was not run on its own.

Key points

  • Optimistic UI applies the change first and confirms later.
  • On failure, undo only that action. Snapshot restore breaks with concurrent actions.
  • Use the inverse, or recompute from server state plus pending actions.
  • Refetch after the queue settles, and use idempotency keys.
  • Wait for the server when the action is costly or irreversible.

Common mistakes

  • Saving a snapshot and restoring it for every failure.
  • Silent rollback with no message to the user.
  • Optimistic updates for payments.
  • Sending toggle commands that can repeat and flip the wrong way.

Follow-ups

  • How do query libraries model optimistic mutations?
  • Why is an idempotency key useful here?
  • How do you handle a failure after the user left the page?

Tips

  • State the idea, show the naive rollback, then explain why it fails.
  • Say that you would send the intended end state and not a toggle.