Scrivio Interview library
DesignIntermediate8 min read · updated 12 November 2026

A form-heavy application must support undo across many edits on large objects. Compare full-state mementos with storing commands or diffs.

Full-state mementos are the simplest undo design, but their memory cost is the size of the state times the length of the history, which hurts with large objects and many edits. Command-based undo stores each operation with its inverse, so history is tiny, but every command must undo itself correctly. Diffs or structural sharing with persistent data structures keep snapshot semantics while storing only what changed; persisted drafts additionally need a stable, versioned format. We choose by state size, edit frequency and how much correctness risk the team can carry.

Why this question is asked

Undo in a small dialog is easy: copy the object, restore it on cancel. Undo across hundreds of edits on a large insurance claim form, a product configurator or a spreadsheet-like screen is a design problem, because the naive approach multiplies memory quickly and the clever approaches introduce new ways to be wrong. Interviewers ask this to see whether we can compare designs with numbers and pick one for a reason. In this answer, we will put numbers on full snapshots, look at command-based undo with its inverse operations, see how diffs and structural sharing get the best of both, cover what changes when undo history is saved as a draft, and finish with how to choose.

1A Quick Recap and the Numbers for Full Mementos

A memento is a snapshot of an object's state that lets us restore it later. The simplest undo design takes a full snapshot before each edit and keeps a stack of them. Undo pops the latest one. It is easy to understand and almost impossible to get wrong, because restoring a snapshot needs no knowledge of what the edit did.

The cost is easy to compute. Suppose the form object, serialised or held in memory, is about 400 KB, with hundreds of fields, nested lists of line items and attachments metadata. Users make about 300 edits in a session, and we want to undo all of them. A full snapshot per edit costs 400 KB x 300 = 120 MB per user session. With 200 concurrent users on a server that keeps sessions in memory, that is 24 GB. Even in a browser, holding 120 MB for undo is too much. Full mementos are the right choice only when the state is small or the history is short.

2Command-Based Undo: Store What Changed and How to Reverse It

The alternative is to store the operations instead of the states. Each edit becomes a command object that knows how to apply itself and how to apply its inverse. The history is a stack of commands, and undo calls the latest command's undo method.

Java
interface EditCommand {
void apply(ClaimForm form);
void undo(ClaimForm form);
}
record SetField(String path, Object oldValue, Object newValue) implements EditCommand {
public void apply(ClaimForm f) { f.set(path, newValue); }
public void undo(ClaimForm f) { f.set(path, oldValue); }
}
record AddLineItem(int index, LineItem item) implements EditCommand {
public void apply(ClaimForm f) { f.lineItems().add(index, item); }
public void undo(ClaimForm f) { f.lineItems().remove(index); }
}
// 300 edits of about 200 bytes each: roughly 60 KB of history instead of 120 MB

The memory gain is dramatic, because a typical command stores a path and two small values. But there is a catch: correctness now lives in every command. SetField is trivially reversible because it captured the old value. Other operations are harder. Sorting line items cannot be undone by sorting again; it must remember the previous order. Deleting an item that had attachments must remember the attachments. A recalculation triggered by an edit, such as updating totals, must also be reversed, or undo must re-run the calculation. Every new kind of edit is a new chance to write an undo that leaves the form in a state that never existed, and these bugs appear only after a specific sequence of edits, which makes them hard to find in testing.

Teams that use command undo successfully keep the set of command types small, generate inverses from recorded old values rather than computing them, and test every command with a property-style check: for random forms and random commands, apply followed by undo must give back a form equal to the original.

3Diffs and Structural Sharing: Snapshots Without the Copies

A middle path keeps the simplicity of snapshots while storing much less. One version stores diffs: after each edit, compute the difference between the old and new state, for example as a JSON Patch, and keep the reverse patch. That costs about as little as commands, and undo applies a generic patch instead of hand-written inverse logic, so the correctness risk moves into one well-tested diff library.

Another version is structural sharing with persistent data structures, which are immutable collections where an update returns a new version that shares all unchanged parts with the old one. If the form is a tree of immutable records and persistent lists, changing one field in one line item creates a new line item, a new list node path and a new root, perhaps a few hundred bytes, while the other 399 KB are shared by both versions. Each history entry is then a full snapshot from the code's point of view, restore is just switching to an older root, yet memory grows only with what changed.

Java
record LineItem(String code, int quantity, BigDecimal price) {}
record ClaimForm(String claimant, PersistentVector<LineItem> items) {} // a persistent list type
ClaimForm v1 = loadForm(); // 400 KB in total
ClaimForm v2 = new ClaimForm(v1.claimant(),
v1.items().with(17, v1.items().get(17).withQuantity(3))); // hypothetical persistent API
// v2 shares the claimant string and all line items except item 17 with v1
// history = [v1, v2]: about 400 KB plus a few hundred bytes, not 800 KB

Java's standard library has no persistent collections, so this design uses a library that provides them, or a model where each part of the form is an immutable record and we only rebuild the path from the root to the changed part. The design fits naturally with immutable domain objects and is also what front-end state libraries do, which is why undo is cheap in many modern UIs. The cost is a different programming style: every update creates new objects, and code that mutates the form in place breaks the sharing.

4Persisting Undo History as Drafts

Many form-heavy applications also save drafts, so a user can close the browser and continue tomorrow, sometimes with the undo history intact. Once mementos or commands leave memory, they need a stable serialisation format: Java serialisation of internal classes is a poor choice, because any refactoring of those classes makes old drafts unreadable. A JSON document with an explicit schema version is the usual answer, together with migration code that upgrades version 3 drafts to version 4 when they are loaded. Commands are harder to persist than snapshots, because each command type and its fields become part of a long-lived format; snapshots or diffs over a documented JSON structure are easier to version. A sensible compromise is to persist the current state as the draft and keep the fine-grained undo history only in memory.

5Choosing Between Them

The choice follows from three properties of the problem: how large the state is, how often it is edited, and how costly a wrong undo would be. The table summarises the trade-offs.

Undo strategies for large, frequently edited objects
StrategyMemory per editCorrectness riskBest when
Full mementoWhole state, e.g. 400 KBVery lowSmall state or short history
Command with inverseTens to hundreds of bytesHigh: every command must undo itselfFew operation types with obvious inverses
Reverse diffSize of the changeLow: one generic diff libraryMutable models, large state
Structural sharingChanged path onlyLow, but needs immutable modelImmutable domain objects

For our large form with hundreds of edits, I would choose structural sharing if the domain model can be immutable, because it gives snapshot correctness at diff cost. If the model is already mutable and large, I would store reverse diffs computed by a generic library. I would reserve hand-written command undo for editors whose operations are naturally commands, such as drawing tools, where the set of operations is small and each inverse is obvious, and I would test those inverses systematically.

6Follow-up questions

How do you limit memory even with commands or diffs?

Cap the history by count or by bytes, and merge fine-grained edits into one step, for example all keystrokes in one field within a second. Some editors also take a full snapshot every 50 commands, so they can drop old commands and still restore cleanly, which is the same idea as snapshots plus an event log.

What about undo when two users edit the same form?

Then undo must reverse only my changes, not my colleague's, which snapshots cannot do because restoring an old state would erase their edits. Commands or operations with inverses are needed, and they must be transformed against concurrent changes, which is the territory of operational transformation and CRDTs. It is a much bigger problem and worth naming as out of scope unless required.

Do immutable snapshots put pressure on the garbage collector?

They create many small short-lived objects, which modern collectors handle very cheaply in the young generation. The snapshots we keep in history are long-lived, but with structural sharing they are mostly shared, so the extra retained memory is small.

7Conclusion

In this answer, we compared three ways to support undo on large objects. Full mementos are simple but cost state size times history length, 120 MB in our example. Command-based undo stores small operations with inverses but puts correctness risk in every command. Reverse diffs and structural sharing with persistent data structures keep snapshot semantics while storing only what changed. Persisted drafts need a stable, versioned format, which is easier with snapshots or diffs than with commands, and the final choice depends on state size, edit frequency and correctness risk.

What to say in the interviewAbout 90 seconds aloud

Open with

I would start with the numbers. A full memento per edit costs the state size times the history length, so a 400 KB form with 300 edits is 120 MB per session, which is too much for many users or a browser.

Then, if they want more

Full mementos are perfect for small state because restore needs no knowledge of what changed, so they are almost impossible to get wrong.

Command-based undo stores each edit with its inverse, like SetField with the old and new value, and the history drops to kilobytes, but every command has to undo itself correctly, including side effects like recalculated totals or a sort order, and those bugs only show up after specific edit sequences. The middle ground is diffs or structural sharing.

Reverse diffs put the undo logic in one generic diff library. With an immutable model and persistent collections, each version shares everything unchanged with the previous one, so each history entry behaves like a full snapshot but costs only the changed path.

If drafts are persisted, I need a stable JSON format with a schema version and migrations, which is easier with snapshots than with commands. For a large form I would pick structural sharing if the model can be immutable, otherwise reverse diffs, and keep command undo for small, well-defined operation sets with systematic apply-then-undo tests.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A form-heavy application must support undo across many edits on large objects. Compare...": https://scrivio-interview-library.netlify.app/java/behavioral-patterns/799ba5a4a8/