KatInterview

Versioned In-Memory Set with Snapshot Iterators and WAL Contracts

Data Structure DesignModel answer
HardModel answerData Structure DesignMVCCsnapshot isolationWAL

Last updated

Design an MVCC-backed mutable set with O(1) snapshot iterators and specify the durability, ordering, and crash-recovery contracts for a write-ahead log.

Background

Storage engines like RocksDB, PostgreSQL, and LMDB rely on a core technique: separating point-in-time reads from concurrent writes. Readers see a stable snapshot; writers mutate the live structure in parallel. Underneath, both a clever versioning scheme and strict durability contracts make this work safely.

This problem has two parts that together cover the read and write sides of that design.


Part 1: Snapshot-Isolated Set

Implement a mutable integer set called SnapshotSet. It supports the usual membership operations — insert, delete, and lookup — plus the ability to open a snapshot iterator. An iterator must reflect the exact contents of the set at the moment it was created, with no influence from any inserts or deletes that happen afterward.

Hard constraint: copying the entire set at iterator creation time is not allowed. Iterator construction must be O(1).

class SnapshotIterator:
    def has_next(self) -> bool:
        """True if the snapshot view still has elements to yield."""
        pass

    def next(self) -> int:
        """Returns the next element in the snapshot view."""
        pass

    def close(self) -> None:
        """Releases any resources held by this iterator."""
        pass


class SnapshotSet:
    def __init__(self):
        pass

    def add(self, val: int) -> bool:
        """Inserts val. Returns True if val was not already in the set."""
        pass

    def remove(self, val: int) -> bool:
        """Removes val. Returns True if val was present."""
        pass

    def contains(self, val: int) -> bool:
        """Returns True if val is currently a member."""
        pass

    def iterator(self) -> SnapshotIterator:
        """Returns a snapshot iterator for the current state of the set."""
        pass

Complexity and Memory Requirements

OperationRequired complexity
add, remove, containsO(1) average
iterator() constructionO(1)
Memory for deleted elementsMay only be freed once every iterator that could see them is closed or exhausted

Part 2: Durability and Recovery Contract

Now imagine the same SnapshotSet is backed by a persistent Write-Ahead Log (WAL). Address the following three questions concretely, with trade-offs:

  1. Acknowledgment boundary — At what point is it safe to return success to the caller of add or remove? What are the trade-offs between acknowledging after an in-memory buffer write versus after an fsync or a storage lease?

  2. Ordering and idempotency — How should the system handle concurrent writes that arrive out of order, and client retries caused by network partitions or crashes? What metadata is required to make retries safe?

  3. Crash recovery — After a restart, how does the system distinguish committed mutations from torn or partial writes? How does it restore the snapshot timeline without corrupting it?

Your answer should be precise enough that an engineer could use it to implement the WAL layer.

Hints

Hint 1

For Part 1, think about assigning a monotonically increasing version number to each mutation. Each element in the set isn't just a value — it's a value plus the version interval during which it exists. An iterator captures the version at creation time and only yields elements whose interval covers that version.

Hint 2

New insertions can be prepended to a linked list. If an iterator records the list's starting node at creation time, any node added later appears before that starting node and is never reachable by the iterator — no copying needed. Deletion only marks a node with a tombstone version; the node stays in the list until no active iterator can see it.

Hint 3

For garbage collection, track the minimum snapshot version among all open iterators (a reference-counted ordered map works well). A tombstoned node can be physically unlinked only when the global minimum snapshot version has advanced past that node's deletion version. Make sure unlinking a node doesn't break iterators currently parked on it — keeping the unlinked node's forward pointer intact solv…