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
- 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.
- 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.
- 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
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
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.
frominQtyChanged, the removed item's fields inItemRemoved. Then the inverse is computed from the event alone. - Make the reducer strict. In the lab,
reducethrows aStaleEventErrorwhen an event does not fit: thefromis 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
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
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
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
- Test the inverse law: apply an event, then its inverse, and compare states.
- Run seeded random sessions mixing edits, undo and redo, and compare the cached state with a full replay.
- Ship behind a flag for one warehouse, keeping the old copy stack running silently to compare final lists.
- 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?
Related reading
In this course:
- CQRS and Event Sourcing: the server-side pattern behind the log.
- Collaborative Editing Basics: operations, ordering and transforming across concurrent edits.
- CRDTs and Conflict Resolution: merge rules that need no central order.
- Optimistic Updates and Rollback: a different kind of "go back".
- State Persistence and Synchronization: saving and migrating stored state.
Official documentation
- Redux: Implementing Undo History:
past,presentandfuture, and discarding the redo branch. - Microsoft Learn: Event Sourcing pattern: append-only store, snapshots, compensating events, trade-offs.
- Martin Fowler: Event Sourcing: state derived from a log, reversal, external effects.
- Yjs: Y.UndoManager: merge window and tracked origins.
- CodeMirror history source:
newGroupDelayandminDepthdefaults. - Wikipedia: Memento pattern: originator, caretaker and memento.