📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the Memento pattern? Explain how to take snapshots for undo without breaking an object's encapsulation, how immutable records and immutable collections make snapshots cheap, how Memento compares with Command-based undo, and how it relates to event sourcing snapshots.

Memento intent and roles (originator, memento, caretaker), opaque snapshots via a private nested type behind a marker interface, immutable records and with-expressions as free snapshots, structural sharing with ImmutableList<T>, memory costs and capping history, Memento vs Command undo, persisting and versioning snapshots, and snapshots in event sourcing.

Mid-Level Theory Intermediate design-patterns event-sourcing immutability memento records undo

🎯 Key points

  • Memento captures an object's internal state as a snapshot that can restore it later, without exposing that state to other code
  • Roles: the originator creates and restores mementos; the caretaker stores them (undo stack) but cannot read or change them
  • Encapsulation in C#: a public marker interface plus a private nested snapshot record that only the originator can create and read
  • Immutable records make snapshots cheap: keeping the previous instance is the snapshot, and with-expressions produce new states (with is shallow)
  • Immutable collections (ImmutableList<T>) share structure, so a snapshot of a large list costs O(log n) new nodes rather than a full copy
  • Memory: cap history (e.g. 100 entries), coalesce rapid edits, and avoid deep-copying large graphs per keystroke
  • Memento vs Command undo: Memento stores whole state (simple, memory-heavy); Command stores the operation and its inverse (compact, but every command needs a correct Undo)
  • Event sourcing stores the events, not states; snapshots every N events are mementos that speed up rehydration and must be versioned

⏱ 30-second answer

Memento captures an object's internal state as a snapshot so you can restore it later, without exposing that state. The originator creates and restores snapshots; the caretaker (an undo stack) stores them but can't look inside.

In C# the cleanest way is a private nested snapshot record behind a public marker interface, so only the originator can read it.

Immutability makes it cheap: with immutable records, the previous instance is the snapshot, and ImmutableList<T> shares structure, so snapshots don't copy everything.

Compared with Command-based undo, Memento stores whole states (simple, but memory-hungry) while Command stores operations and their inverses (compact, but each needs a correct Undo). In event sourcing, periodic snapshots are mementos that speed up rebuilding state from events.

The trade-off is memory per snapshot against simplicity of restore.

🗣 Full answer (senior)

How I would answer this in an interview

"Memento is how you take a snapshot of an object so you can put it back later, without making its internals public. There are three roles. The originator, say a FormDesign in a form builder, knows how to save its state into a memento and restore from one. The caretaker, an undo history, keeps a stack of mementos but treats them as opaque tokens. And the memento itself holds the state. The encapsulation part matters: if the history could read and edit snapshots, you've effectively made every private field public.

In C#, I get that by making the snapshot a private nested record inside the originator, implementing a public marker interface like IFormMemento. The caretaker can hold IFormMemento values but can't see the fields; only FormDesign.Restore can cast it back. What makes this practical is immutability. If the state is held in immutable records and ImmutableList<T>, taking a snapshot is just keeping a reference to the current values; nothing gets copied, and adding a field to a 5,000-field list creates a handful of new tree nodes, not a new list. If the whole originator is an immutable record, the previous instance is the memento, and a with expression gives you the next state. I keep in mind that with is shallow, so anything mutable inside it is shared.

The mistake I see is deep-copying a large object graph on every keystroke 'for undo', which is how an editor ends up using gigabytes. I cap history, coalesce rapid edits into one entry, and use structural sharing. I'd also compare it with Command-based undo: commands store the operation and its inverse, which is compact, but every command needs a correct Undo, and bugs there are subtle. Event sourcing is related but inverted: you store the events and rebuild state; snapshots every few hundred events are mementos that make loading fast. Memento trades memory for simplicity: restoring a snapshot can't be wrong the way an inverse operation can."


Roles

Role Responsibility In a form builder
Originator Creates snapshots, restores from them FormDesign
Memento Holds the state, opaque to others Private Snapshot record behind IFormMemento
Caretaker Stores and orders mementos, never reads them UndoHistory

Memento vs Command undo

Memento Command with Undo
Stores Whole state (or a reference to immutable state) Operation plus data to reverse it
Memory Higher, unless immutable sharing Low
Correctness risk Low: restore is a replace Each Undo must exactly invert Execute
Good for Complex state, many small edits, multi-field changes Discrete operations with clear inverses

Making snapshots cheap

Technique Effect
Immutable records Previous instance is the snapshot; no copy
ImmutableList<T> / ImmutableDictionary<K,V> Structural sharing; O(log n) new nodes per change
Coalescing Merge edits within, say, 500 ms into one undo entry
Capped history Keep the last N snapshots

Production example

A browser-based form designer backed by a .NET API kept a deep-copied FormDefinition per edit on the server for undo. Large forms (about 3,000 fields) used roughly 40 MB per session after an hour. Switching to immutable records with ImmutableList<T>, coalescing edits within 500 ms and capping history at 100 entries brought that to under 2 MB per session with identical undo behaviour.

🔍 What the interviewer is checking

Checks that the candidate can implement snapshots without breaking encapsulation, understands the memory implications and the role of immutability, and can compare Memento with Command and event sourcing.

Green flags

  • Names originator, memento and caretaker correctly.
  • Shows an opaque memento in C# (private nested type or internal members).
  • Explains immutable records and structural sharing, and that with is shallow.
  • Compares with Command undo and connects to event sourcing snapshots.

Red flags

  • Snapshot is a public copy of all fields.
  • Thinks with deep-copies.
  • No awareness of memory growth or capping history.

📚 Learn in depth

1. Structure

Caretaker (UndoHistory)            Originator (FormDesign)
  stack<IFormMemento> ──Save()──▶    Save()    → new Snapshot(state)
                     ◀──Restore()─  Restore(m) → state = ((Snapshot)m).state

«interface» IFormMemento  (public, exposes nothing useful)
        ▲
Snapshot (private nested record inside FormDesign)

GoF describes a "wide" interface for the originator and a "narrow" one for everyone else. C# expresses that with a public marker interface and a private nested implementation.

2. Encapsulation options in C#

Approach Who can read the state Notes
Private nested record + public marker interface Only the originator Strongest; caretaker holds the interface
internal members on a public memento class The originator's assembly Fine if the domain lives in its own project
Public record of state Everyone Not really Memento; acceptable for simple DTO-like state
Serialised blob (JSON) Anyone who deserialises it Useful for persistence; needs versioning

3. Immutability and structural sharing

With mutable state, a snapshot must copy (and a shallow copy shares nested mutable objects, so later edits corrupt old snapshots). With immutable state, the current values can't change, so keeping a reference is a correct snapshot.

ImmutableList<T> is a balanced binary tree; Add, SetItem and RemoveAt create O(log n) new nodes and share the rest with the previous version. Reads are O(log n) rather than O(1), so for small, read-heavy lists ImmutableArray<T> (copy on write) can be better. Records give value equality and with expressions, but with is a shallow member-wise copy: a List<T> property is shared between the old and new record.

4. Managing history

  • Cap the stacks (drop the oldest beyond N).
  • Coalesce typing: if the last snapshot is younger than a threshold and the same kind of edit, replace rather than push.
  • Clear redo on any new edit after an undo.
  • Measure snapshot cost with BenchmarkDotNet's memory diagnoser and session memory with dotnet-counters.

5. Persisting mementos

Autosaved drafts are mementos written to storage. Once persisted, they need a schema version: add a Version field and upgrade old snapshots on load, or a deployment will fail to restore last week's drafts. Keep personal data in mind: a draft history may retain information the user deleted, which matters for privacy obligations such as APP 11's requirement to destroy or de-identify information no longer needed.

6. Relation to event sourcing

Event sourcing persists the sequence of events (FieldAdded, FieldRenamed) and rebuilds state by replaying them. That gives a complete history and audit trail. Replaying thousands of events on every load is slow, so stores take a snapshot every N events: a memento of the aggregate's state at version V. Loading means: read the latest snapshot, then replay events after V. Snapshots must be versioned and are disposable: they can always be rebuilt from events.

EF Core's change tracker uses a related idea: it keeps original values for each tracked entity (a snapshot) to detect changes at SaveChanges.

Try it yourself

  1. Implement FormDesign with a private nested snapshot and an UndoHistory; confirm the caretaker can't access the fields.
  2. Make the state mutable with List<T> and a shallow copy; show an old snapshot changing after an edit.
  3. Switch to ImmutableList<T> and benchmark snapshot cost for 10,000 fields with BenchmarkDotNet's [MemoryDiagnoser].
  4. Add coalescing for edits within 500 ms and a cap of 100 entries.
  5. Rebuild the same feature with Command-based undo and compare code size and the risk in each Undo.

💻 Code

An originator with opaque mementos, a capped caretaker, and immutable records as snapshots.

namespace Designer;

using System.Collections.Immutable;

public sealed record Field(string Name, string Type, bool Required);

// The narrow interface: the caretaker can hold it but learns nothing from it
public interface IFormMemento
{
    DateTimeOffset TakenAt { get; }
}

// Originator
public sealed class FormDesign(TimeProvider clock)
{
    private string _title = "Untitled";
    private ImmutableList<Field> _fields = [];          // structural sharing: snapshots don't copy the list

    public string Title => _title;
    public IReadOnlyList<Field> Fields => _fields;

    public void Rename(string title) => _title = title;
    public void AddField(Field field) => _fields = _fields.Add(field);
    public void RemoveField(string name) => _fields = _fields.RemoveAll(f => f.Name == name);

    public IFormMemento Save() => new Snapshot(_title, _fields, clock.GetUtcNow());   // O(1): just references

    public void Restore(IFormMemento memento)
    {
        if (memento is not Snapshot s)
            throw new ArgumentException("Memento was not created by this designer.", nameof(memento));
        _title = s.Title;
        _fields = s.Fields;
    }

    // The wide interface: only FormDesign can see inside
    private sealed record Snapshot(string Title, ImmutableList<Field> Fields, DateTimeOffset TakenAt) : IFormMemento;
}

// Caretaker: orders and caps mementos, never reads them
public sealed class UndoHistory(int capacity = 100)
{
    private readonly LinkedList<IFormMemento> _undo = new();
    private readonly Stack<IFormMemento> _redo = new();

    public void Record(IFormMemento before)
    {
        _undo.AddLast(before);
        if (_undo.Count > capacity) _undo.RemoveFirst();   // cap memory
        _redo.Clear();                                    // a new edit invalidates redo
    }

    public void Undo(FormDesign design)
    {
        if (_undo.Last is not { } last) return;
        _redo.Push(design.Save());
        _undo.RemoveLast();
        design.Restore(last.Value);
    }

    public void Redo(FormDesign design)
    {
        if (!_redo.TryPop(out var next)) return;
        _undo.AddLast(design.Save());
        design.Restore(next);
    }
}

// var design = new FormDesign(TimeProvider.System);
// var history = new UndoHistory();
// history.Record(design.Save()); design.AddField(new Field("Email", "email", true));
// history.Record(design.Save()); design.Rename("Signup");
// history.Undo(design);   // title back to "Untitled", Email field still there
namespace Designer;

using System.Collections.Immutable;

// When the whole state is an immutable record, the previous instance IS the memento
public sealed record FormState(string Title, ImmutableList<Field> Fields)
{
    public static FormState Empty { get; } = new("Untitled", []);
}

public sealed class RecordBasedEditor
{
    private readonly Stack<FormState> _undo = new();
    public FormState Current { get; private set; } = FormState.Empty;

    public void Apply(Func<FormState, FormState> edit)
    {
        _undo.Push(Current);              // snapshot = keep the old reference
        Current = edit(Current);
    }

    public void Undo()
    {
        if (_undo.TryPop(out var previous)) Current = previous;
    }
}

// editor.Apply(s => s with { Title = "Signup" });
// editor.Apply(s => s with { Fields = s.Fields.Add(new Field("Email", "email", true)) });
// Note: 'with' is shallow. A mutable List<T> property would be shared between states and break undo.

⚠ Common mistakes

  • Mistake: Exposing the memento's state as public properties. Why it is wrong: The caretaker or any caller can read and change internals, breaking encapsulation. Instead: A private nested snapshot behind a marker interface, or internal members in a domain assembly.
  • Mistake: Taking a shallow copy of state that contains mutable collections. Why it is wrong: Old snapshots share the lists and change when the current state changes, so undo restores the wrong data. Instead: Use immutable collections or deep-copy deliberately.
  • Mistake: Assuming a record with expression makes a deep copy. Why it is wrong: with copies members shallowly; reference-type members are shared. Instead: Make nested members immutable too.
  • Mistake: Snapshotting a large graph on every keystroke with no cap. Why it is wrong: Memory grows without bound per session. Instead: Structural sharing, coalescing and a capped history.
  • Mistake: Persisting mementos without a version. Why it is wrong: A schema change makes saved drafts impossible to restore. Instead: Store a version and migrate old snapshots on load.
  • Mistake: Keeping indefinite draft histories containing personal information. Why it is wrong: Data the user removed lingers, conflicting with retention obligations. Instead: Expire histories and include them in deletion requests.
  • Mistake: Using Memento when operations have trivial inverses and state is huge. Why it is wrong: Storing whole states wastes memory. Instead: Command-based undo, or event sourcing if you need the history anyway.

🏛 Senior insight: trade-offs

Memento is less about the pattern's classes and more about choosing a state model that makes snapshots cheap and correct. Immutable state turns Memento from "copy everything carefully" into "keep a reference", which is why I push for immutable records and collections in anything with undo, drafts or time travel.

Option When it fits Cost When not to
Memento with immutable state Undo/redo, drafts, complex multi-field edits O(log n) per change with structural sharing Very large state with frequent tiny edits and no sharing
Memento with deep copies Small state, mutable model you can't change Full copy per snapshot Large graphs or per-keystroke snapshots
Command undo Discrete operations with clear inverses Each Undo must be correct Edits that touch many fields at once
Event sourcing + snapshots You need full history and audit anyway Infrastructure, event versioning Just an undo button

I measure it with BenchmarkDotNet ([MemoryDiagnoser] on save and restore) and with session memory in production; the number to watch is bytes per undo entry.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says immutable state makes snapshots cheap Why: Checks immutability design in C# and its benefits
    How to answer

    Prefer immutable types for values, messages, configuration, cache entries and anything shared across threads: an object that cannot change is automatically thread-safe, safe to cache and share, safe as a dictionary key, and easier to reason about. C# gives you readonly fields, init and get-only properties, records with with, readonly struct, ImmutableArray<T>/ImmutableList<T> and FrozenDictionary/FrozenSet for read-mostly data. Remember that read-only is not immutable: IReadOnlyList<T> over a List<T> can still change underneath. Keep mutability where it is natural and contained: entities whose state changes through methods that guard invariants, builders, and hot loops where allocating new objects would cost too much.

  2. When: Candidate mentions with-expressions or copying state Why: Checks shallow vs deep copy and record with-expressions from the Prototype angle
    How to answer

    Prototype creates new objects by copying a configured instance instead of building from scratch. It's useful when setup is expensive or when you want variations of a template.

    • A shallow copy duplicates top-level fields, but reference fields still point to the same objects. A deep copy duplicates the whole graph.
    • MemberwiseClone() makes a protected, shallow, field-by-field copy without running constructors.
    • ICloneable is discouraged: Clone() returns object and doesn't say whether the copy is deep or shallow.
    • record with uses a compiler-generated copy constructor, so it's shallow. A List<T> property is shared, and changing the copy's list changes the original's too.

    The modern answer is usually immutability: immutable members make shallow copies safe and cheap. The trade-off is that you need a hand-written copy constructor whenever a mutable reference has to be deep-copied.

  3. When: Candidate compares snapshot undo with storing operations Why: Checks Command-based undo as the alternative
    How to answer

    Command turns a request into an object. Once "place this order" or "rename this file" is data rather than a method call, you can queue it, retry it, log it for audit, or undo it.

    • GoF style: the command has Execute() (and Undo()); an invoker runs it without knowing what it does. Good for undo stacks and macros.
    • Modern style: an immutable record (PlaceOrder) plus a separate handler (ICommandHandler<PlaceOrder>). Splitting data from behaviour lets the command be serialised to a Channel<T>, Azure Service Bus or an audit table.

    A command is an imperative request with one handler that may reject it; an event is a past-tense fact with any number of handlers.

    The trade-off: an extra type per operation and indirection, so plain method calls are fine when you need none of queuing, retry, undo or audit.

🛠 Real-world problems: how you handle them

Undo history used 40 MB per session in the form designer
Situation
Form designer API at [company] holding editing sessions in memory on [3] App Service instances; enterprise customers built forms with [~3,000] fields. Undo was implemented by deep-cloning the form definition on every edit.
Signals
Instance memory alerts at [85%] during business hours; App Service restarts under load; Application Insights showed memory proportional to active sessions; users reported lag on large forms.
Investigation
`dotnet-counters` showed gen 2 and LOH growth during editing. A `dotnet-gcdump` diff showed thousands of `FormDefinition` copies and their `List<Field>` arrays held by per-session undo stacks. A BenchmarkDotNet run measured ~120 KB allocated per snapshot for a large form.
Resolution
Immediate: capped undo history at 50 entries and coalesced edits within 500 ms. Real fix: moved the form state to immutable records with `ImmutableList<Field>`, made snapshots opaque references via a private nested record, and kept redo/undo in a capped caretaker. Snapshot cost dropped to a few hundred bytes.
Prevention
A memory benchmark for snapshot cost in CI with a budget; session memory metrics in Application Insights; an ADR making immutable state the default for any feature with undo or drafts; draft retention limited to [30 days].

How to tell it (STAR)

**S:** At [company], our form designer's API instances were restarting under load because each editing session used about [40 MB]. **T:** I was asked to cut memory without changing undo behaviour users relied on. **A:** Using `dotnet-gcdump` diffs I found the undo stacks deep-cloned the whole form on every edit. I added a cap and edit coalescing as an immediate fix, then moved the state to immutable records with `ImmutableList<T>` so a snapshot became a reference, with an opaque memento type so nothing outside the designer could change snapshots. **R:** Memory per session fell to under [2 MB], restarts stopped, and large-form edit latency improved by [about 60%].

↩ Usually asked after

More in Behavioral Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me