Skip to content

    Frontend System Design

    Undo, Redo and Event Sourcing in the UI

    Build undo and redo three ways: whole-state snapshots, commands with inverses and an append-only event log, with step grouping, barriers and a pure model.

    By Published 13 min read

    • frontend-system-design
    • undo-redo
    • event-sourcing
    • state-management
    Share

    Standard lessonadvancedTypeScript labFrontend System Design

    Before this: Command, Strategy, Adapter and Facade, Event-Driven UI Architecture

    What you'll learn: By the end of this lesson you will be able to compare three ways to remember the past (whole-state snapshots, commands with inverses, an append-only event log), explain why undo in an event-sourced UI appends events instead of deleting them, group keystrokes into undo steps, rebuild state from snapshots, mark the point after which nothing can be undone, and say what happens when someone else changes the thing you are undoing.

    Picture an accountant's ledger written in ink. When a line is wrong, the accountant does not scratch it out; a new line reverses it. The book still tells the whole story, including the mistake and the correction. An eraser is quicker, but afterwards nobody can say what the page used to hold.

    The running example is the picking list on a grocery order (the marketplace front end used in this course): a picker adds items, changes quantities and removes lines on a tablet, and wants Undo and Redo to behave like they do in any editor.

    The core idea

    1. Undo needs two things: a way back and a unit of "one thing". The way back is a stored past state or a stored inverse. The unit is the step: what one user gesture did, however many small changes that took.
    2. Keeping state as a fold over an event log makes the past a first-class value. Current state is what you get by applying the events in order. Undo is then a decision about which events to add next.
    3. Not everything can be undone. Once an effect has left the list (an order submitted, a message sent), a stack of inverses would lie. Mark that point and start a new stack.

    The command pattern and the event-driven UI style this builds on have their own lessons in this module (Command, Strategy, Adapter and Facade; Event-Driven UI Architecture). The server-side version of the idea is CQRS and Event Sourcing; this lesson keeps the log in the browser.

    Three ways to remember the past

    Whole-state snapshots (memento). Wikipedia describes the memento pattern as one that allows reverting the state of an object, with a memento that stores a saved snapshot and cannot be changed; undo is among its listed uses. Redux's guide shows the usual UI shape: past, present and future. A new action puts present at the end of past, computes a new present and clears future, so the redo branch is discarded. The guide says this suits Redux because state is already immutable and mutations are already discrete actions; in classical MVC frameworks you have to keep track of every past state by cloning all relevant models.

    Commands with inverses. Each action is an object that knows how to do itself and how to undo itself. The stack holds commands, not states, which is smaller, but every command needs a correct inverse and a way to detect that the state it expects is no longer there.

    An event log. Microsoft's event sourcing pattern stores the full series of actions in an append-only store that acts as the system of record, and derives current state by replaying events (it calls this rehydration). Martin Fowler's article says application state is "purely derivable" from the log, and that reversal is most straightforward when an event is cast as a difference. That last point shapes the event design below.

    Figure 1. From a gesture to the screen, with history on the side

    A UI built on an event logUI to Commands (gesture); Commands to Event log (append); Event log to Projection (reduce); Projection to UI (render); Commands to Step stacks (record step); Step stacks to Event log (append inverse)UI: gestures, undo, redoUIgestures, undo,redoCommands: decide the eventsCommandsdecide the eventsEvent log: append onlyEvent logappend onlyProjection: current stateProjectioncurrent stateStep stacks: undo and redoStep stacksundo and redogestureappendreducerenderrecord stepappend inverse

    How to read this: a gesture becomes events, the log keeps them, a pure reduce turns them into the state the UI draws. The step stacks remember which events belong to which gesture; Undo asks the log to append their inverses rather than reaching into the projection.

    Undo as more events

    In the lab (examples/frontend/labs/undo-event-sourcing) an item event carries enough data to be reversed: QtyChanged has from and to, and ItemRemoved keeps the item's name, quantity and index. The inverse of an event is another event of the same family; the inverse of a step is the inverses of its events in reverse order. Undo appends those, Redo appends the originals again, and a new edit clears the redo stack. The log only grows.

    Figure 2. One gesture, undone and redone

    sequenceDiagram accTitle: Undo and redo append events to the log accDescr: The user changes a quantity, which appends a QtyChanged event from 6 to 12 to the log. Undo appends the inverse event from 12 to 6. Redo appends the original event again. The log now holds three entries and the projection shows 12. participant U as User participant H as Step stacks participant L as Event log U->>H: set eggs to 12 H->>L: append qty eggs 6 to 12 (do) U->>H: Undo H->>L: append qty eggs 12 to 6 (undo) U->>H: Redo H->>L: append qty eggs 6 to 12 (redo) Note over L: three entries, eggs = 12

    How to read this: nothing is removed from the log. The user-visible state moves back and forth because each action adds an entry; the entry's cause (do, undo, redo) says why it is there.

    Illustration 1: the minimal example

    Expected output, captured from a real run (the first scenario of the lab demo):

    === 1. do, undo, redo on a picking list (undo appends inverse events; nothing is deleted)
      after three gestures   [milk=2, eggs=12]  undo depth 3  log 3
      undo "eggs to 12"      [milk=2, eggs=6]  undo depth 2  redo depth 1  log 4
      undo "add eggs"        [milk=2]  undo depth 1  redo depth 2  log 5
      redo "add eggs"        [milk=2, eggs=6]  undo depth 2  redo depth 1  log 6
      new edit "remove milk" [eggs=6]  undo depth 3  redo depth 0 (the undone branch is gone)
      last four log entries:
        #4 undo step3 qty eggs 12->6
        #5 undo step2 remove eggs@1
        #6 redo step2 add eggs(6)@1
        #7 do step4 remove milk@0

    The log grew from 3 to 7 entries while the user went back and forth. Undoing "add eggs" is recorded as remove eggs@1, and redoing it as add eggs(6)@1. After the new edit the redo stack is empty, as in Redux's shape. Microsoft's pattern page makes the same point for stores: the only way to undo a change is to add a compensating event, and the original stays in the stream.

    Events that can be reversed

    An event that says only "quantity is now 12" cannot be undone without the old value. Microsoft's guidance on event design recommends capturing the business intent in addition to the resulting state, and Fowler's remark that reversal is easiest for difference events points the same way. Two practical rules follow:

    • Carry the before-value. from in QtyChanged, the removed item's fields in ItemRemoved. Then the inverse is computed from the event alone.
    • Make the reducer strict. In the lab, reduce throws a StaleEventError when an event does not fit: the from is not the current quantity, an index is out of range. A strict reducer turns a silent wrong state into a loud failure, which is what keeps undo honest in the failure case later.

    Steps and coalescing

    Typing "1", "2", "3" into a quantity field is three changes but, to a user, one thing. Libraries use a time window. Yjs's UndoManager merges edits made within a captureTimeout that defaults to 500 ms, and stopCapturing() makes the next operation start a new step. CodeMirror's history has a newGroupDelay option, "the maximum time that adjacent events can be apart and still be grouped together", defaulting to 500, and a transaction annotation that stops one transaction being combined with others. ProseMirror's history documents the same delay default and a closeHistory function for the same purpose.

    The lab does it with an injected clock: perform(label, events, now, key) merges into the previous step when the key matches, the time gap is within the window and no redo is pending. The step keeps all its events; one undo reverses them all.

    Illustration 2: the realistic example

    Expected output, captured from a real run (the second scenario of the lab demo):

    === 2. coalescing: one step per burst of typing (window 500 ms, injected clock)
      five quantity edits 100 ms apart   undo depth 2  quantity 6  log 6
      one undo                           quantity 1  (all five edits reverted together)
      two edits 900 ms apart             undo depth 3  (the second is a new step)

    Five quick edits are one step on top of the "add" step; one Undo returns the quantity to 1. Two edits 900 ms apart are two steps. The window is a product decision: too long and Undo throws away a lot; too short and the user presses it five times to remove one number.

    Snapshots and replay cost

    Replaying a long log to get the current state is wasteful, so the lab keeps the current state as a cached projection and a snapshot every N entries. Microsoft's page recommends snapshots at intervals such as every N events, loading the most recent one and replaying only what follows, and says snapshots are an optimization, not a replacement for the stream.

    Expected output, captured from a real run (the fourth scenario of the lab demo):

    === 4. rehydrating from snapshots (a log of 33 entries, a snapshot every 8)
      entries 33, snapshots kept 5
      state at the end       replayed 1 events from the nearest snapshot (not 33)
      state after entry 20   replayed 4 events
      equals a replay from nothing: true

    Rehydrating the state at entry 20 took 4 events, not 20, and the result equals a full replay from nothing. The lab also runs 200 seeded random sessions (edits, a multi-event clear-all, undo, redo) and checks that the event and snapshot histories agree, the cached state equals a replay, and undoing every step returns the empty list.

    Expected output, captured from a real run (the last scenario of the lab demo):

    === 7. 200 seeded random sessions (40 gestures: edits, clear-all, undo, redo)
      event history and snapshot history agree     200 of 200
      cached state equals a replay of the log      200 of 200
      undoing every step returns to an empty list  200 of 200  (7999 log entries in total)

    Where the log costs more than snapshots

    Expected output, captured from a real run (the third scenario of the lab demo):

    === 3. the same 22 gestures kept as events and as whole states (10 adds, then 12 quantity changes)
      after the ten adds     events stored 10  item slots across stored states 55
      after twelve edits     events stored 22  item slots across stored states 175
      both end in the same list: true

    The event log grew by one entry per change; the snapshot stack by a whole list per change (55 item slots became 175). A real engine shares unchanged item objects between states, so slots are not bytes, and for a short list the snapshot approach can be perfectly fine. What it cannot give you is the reason for each change or an audit trail.

    What cannot be undone

    When the picker submits the order, an effect has happened outside the list. Fowler warns that replaying events can trigger repeated external messages, and recommends wrapping external systems in gateways that can be turned off during replay. For undo the rule is simpler: record the effect as a barrier, clear both stacks, and make later changes new forward events.

    Illustration 3: a failure and an edge

    Expected output, captured from a real run (the fifth and sixth scenarios of the lab demo):

    === 5. a step that cannot be undone: the order is submitted
      after submit           [milk=2] submitted  can undo false
      edit after submit      refused: the order is submitted; reopen it first
      reopened, edited       [milk=3]  undo depth 1  (the add before the submit is out of reach)
      log:
        #1 do step1 add milk(2)@0
        #2 do step0 submitted
        #3 do step0 reopened
        #4 do step2 qty milk 2->3
    === 6. undo after someone else changed the same item (a remote event reaches the log)
      local 3, remote sets 5 [milk=5]  log 3
      undo "milk to 3"       refused: QtyChanged does not fit the current state: quantity is 5, the event expects 3
      after the refusal      [milk=5]  log 3  undo depth 2 (nothing was half-applied)

    After the submit, Undo is unavailable and edits are refused until the order is reopened; reopening is a new event, not an undo. In the second case another person set the quantity to 5. Undoing "milk to 3" would set the quantity back to 2 over their change, so the strict reducer refuses, the log is unchanged and the stack still holds the step.

    Undo when other people edit

    Whose change does Undo undo? Yjs's UndoManager tracks, by default, local changes that do not specify a transaction origin, and trackedOrigins chooses what to track. ProseMirror's history source says that when its collab module receives remote changes, the history has to know about them. Undo reverts your work, not the other person's.

    The lab takes the simplest honest position: when the world has moved, refuse and tell the user. A better one transforms the stored inverse across the changes that arrived since, the way operations are rewritten in Collaborative Editing Basics (that lab has no undo and this one has no transform; combining them is an exercise). Merge rules that avoid the conflict are in CRDTs and Conflict Resolution.

    Trade-offs

    Approach Gain Cost
    Whole-state snapshots Trivial to write; no inverses; works with any state shape Memory grows per step; no reason, no audit; coarse steps
    Commands with inverses Small steps; explicit intent Every command needs a correct inverse; drifts when state changes underneath
    Event log with compensating events History, replay, audit and undo from one structure Event design effort; schema versions; log growth; personal data in an immutable log

    Microsoft's page warns that event sourcing is a complex pattern and that for most parts of most systems traditional data management is enough. For a UI: use the event log where history is itself a feature (audit, collaboration, replay), and snapshots where the state is small and Undo is the only need.

    Figure 3. Choosing a history strategy

    flowchart TD accTitle: Choosing an undo strategy accDescr: Start by asking whether the state is small and only undo is needed; if so use snapshots. Otherwise ask whether you need an audit trail, replay or other users' changes; if so use an event log with compensating events. If not, use commands with inverses. A{"State small, and undo is the only need?"} -->|yes| B["Whole-state snapshots"] A -->|no| C{"Need audit, replay or merging with other users?"} C -->|yes| D["Event log, undo as new events"] C -->|no| E["Commands with inverses"]

    How to read this: start at the top. The cheapest option that meets the real requirement wins, and the event log is chosen for what it adds, not because it is fashionable.

    Build it

    The lab is examples/frontend/labs/undo-event-sourcing: a pure model with no DOM, timers or network. src/events.ts holds the events, the reducer, the inverse function and the commands; src/log.ts the append-only log with snapshots; src/history.ts the step stacks, coalescing, barrier, and a snapshot history for comparison; src/session.ts the seeded random sessions.

    cd examples/frontend/labs/undo-event-sourcing
    ../../node_modules/.bin/vitest run   # 20 tests, including 200 seeded random sessions
    node src/demo.ts                     # the output shown above

    Verified. The tests passed and every captured block above is a verbatim excerpt of examples/frontend/golden/undo-event-sourcing.txt. It is a model: it has no persistence, no real clock and no UI, and its log is in memory.

    In practice: Undo on the picker's tablet

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    Pickers edit a picking list on a shared tablet. Undo restores a saved copy of the whole list. Support reports that Undo after "Submit" brings back lines the warehouse has already started, and that nobody can tell why a quantity changed.

    Starting architecture

    Figure 4. Starting point: a stack of copies

    Starting architecture: undo by copying the listPicker UI to Copy stack (push copy); Copy stack to Picker UI (restore copy); Picker UI to Orders API (submit)Picker UI: edits, UndoPicker UIedits, UndoCopy stack: one list per editCopy stackone list per editOrders API: SubmitOrders APISubmitpush copyrestore copysubmit

    How to read this: the warning box stores whole lists and knows nothing about Submit, so restoring an old copy after Submit shows a list the server no longer agrees with.

    Options considered

    Option What it fixes What it costs Risk
    Clear the copy stack on Submit The resurrected lines Nothing else changes Still no reasons for changes
    Commands with inverses Smaller steps An inverse per command Inverses drift from the state
    Event log, undo as events, barrier at Submit Reasons, grouping, a safe Submit Event design, a reducer that must stay strict Event shape changes over time

    The decision

    Field Decision record
    Context A short list, one picker at a time, with a Submit that has outside effects.
    Decision An in-memory event log per list, steps grouped by a 500 ms window, Submit recorded as a barrier.
    Consequences, good Submit can no longer be undone by accident; every change has a recorded cause.
    Consequences, bad A reducer that throws needs a user-facing message; events need versions if they are ever stored.
    Revisit when Two pickers edit one list at once, or the log must survive a reload.

    Rollout and verification

    1. Test the inverse law: apply an event, then its inverse, and compare states.
    2. Run seeded random sessions mixing edits, undo and redo, and compare the cached state with a full replay.
    3. Ship behind a flag for one warehouse, keeping the old copy stack running silently to compare final lists.
    4. Watch how often a stale-event refusal reaches the user.

    The 2 a.m. failure

    A picker taps Undo and nothing happens. Another picker had adjusted the same line from a second tablet, the sync appended their change, and the strict reducer refused the stale inverse. The UI swallowed the error and the button looked dead.

    First three checks: (1) is the refusal being logged with the event and the state it did not fit; (2) did a remote entry arrive between the original edit and the Undo; (3) does the UI show a message when Undo is refused. Mitigation: catch the refusal and say "someone changed this line". Follow-up: a test that appends a remote event between a step and its undo.

    Architect's notes

    • Choose the step before the storage. Users judge Undo by what one press reverts.
    • Keep the reducer pure and strict. Replay, snapshots and undo all depend on it.
    • Version events the day you store them. An in-memory log can change shape; a persisted one cannot.
    • Plan for personal data. Microsoft's page notes that an immutable store conflicts with deletion rules, and suggests keeping personal data outside the events or encrypting it per subject.

    Common mistakes

    • Storing only the new value in an event. Without the old value, Undo is a guess.
    • Deleting log entries on Undo. The history stops being a history.
    • One step per keystroke. The user presses Undo twenty times.
    • Letting Undo cross an external effect. Submit, send and pay need a barrier.
    • Ignoring other people's changes. Undo overwrites a newer value.

    Key takeaways

    • Undo is "go back one step", and a step is one user gesture.
    • Snapshots, commands with inverses and an event log trade memory, effort and history differently.
    • In an event-sourced UI, Undo and Redo append events; the log keeps everything.
    • Events that carry the before-value can be inverted; a strict reducer makes stale undo fail loudly.
    • Mark effects that cannot be undone and clear the stacks there.

    Practice exercises

    Exercise 1: Starter (30 min). In the lab, add a NoteChanged event with a from and a to, its inverse, and a test that apply-then-invert restores the state.

    Exercise 2: Intermediate (2 hours). Make a remote change to a different item not block Undo. What must you check, and when is it still unsafe?

    Exercise 3: Advanced (half day). Transform a stored inverse across a remote event instead of refusing, for quantities only. Where does the approach stop being correct?

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments