← Lessons

quiz vs the machine

Gold1480

Frontend

Optimistic UI with Rollback

Update the screen before the server confirms, then roll back if the request fails.

5 min read · core · beat Gold to climb

The optimistic pattern

An optimistic UI assumes the server will succeed and updates the screen immediately, before the network responds. A like button fills in the instant you tap it rather than after a round trip.

  • Apply the change to local state right away.
  • Send the request in the background.
  • If it succeeds, keep the change, perhaps reconciling with the server response.
  • If it fails, roll back to the previous state and show an error.

Doing it safely

Rollback needs the previous value, so capture it before mutating.

  • Save a snapshot of the affected data.
  • On failure, restore the snapshot and surface a clear message.
  • Watch for race conditions when several optimistic updates overlap, and key each by an identifier so a late failure rolls back only its own change.

The payoff is a UI that feels instant. The cost is extra logic to handle the unhappy path, which is where many implementations cut corners and leave stale state on failure.

Key idea

Optimistic UI updates the screen before the server confirms, so always snapshot the prior state and roll back on failure to avoid leaving stale data.

Check yourself

Answer to earn rating on the learn ladder.

1. What must you capture before an optimistic update?

2. What is the main benefit of optimistic UI?

3. What is a key risk with overlapping optimistic updates?