Versioned In-Memory Set with Snapshot Iterators and WAL Contracts
Data Structure DesignModel answerLast 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
| Operation | Required complexity |
|---|---|
add, remove, contains | O(1) average |
iterator() construction | O(1) |
| Memory for deleted elements | May 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:
-
Acknowledgment boundary — At what point is it safe to return success to the caller of
addorremove? What are the trade-offs between acknowledging after an in-memory buffer write versus after anfsyncor a storage lease? -
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?
-
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…
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: MVCC Snapshot Set
Core Idea
This is a small multi-version concurrency control (MVCC) problem. Four mechanisms carry the design:
1. Logical clock. A global integer clock increments on every mutation. Each call to iterator() records the current value as its snapshot version snap.
2. Versioned nodes. Every node stores a half-open lifetime [added, deleted). A node is visible to snapshot s when added <= s < deleted. Deletion sets deleted to the current clock; it does not remove the node. Re-inserting the same value creates a fresh node with a new added, so no two versions of the same value have overlapping lifetimes and a snapshot never yields duplicates.
3. Prepend-to-list, capture-at-iterator. Nodes are prepended to a doubly linked list with a sentinel head. iterator() records head.next as its starting position in O(1). Any node added after this moment is spliced in front of that starting node and is therefore unreachable by the iterator. A hash map val → node gives O(1) add, remove, and contains on the live set.
4. Deferred garbage collection. A tombstone with deleted = d is relevant only to iterators whose snap < d. Once the global minimum active snapshot is ≥ d, the node can be unlinked. Keep open snapshots in an OrderedDict[snap → refcount]; its first key is the minimum. Tombstones are created in monotonically increasing deleted order, so a FIFO deque of pending tombstones is always sorted — pop from the front while front.deleted <= min_snap. Importantly, when unlinking a node, do not clear its next pointer. An iterator parked on an unlinked node can still walk forward safely, the same trick lock-free linked lists use.
Correctness Argument
- No phantom inserts: new nodes land between the sentinel and the old first node. The iterator started at or behind that old first node, so it cannot reach any new node. The visibility predicate
added <= snapis a second line of defence. - No phantom deletes: a node removed after the snapshot has
deleted > snap, so it stays visible to that iterator. GC cannot unlink it while the iterator is active becausemin_snap <= snap < deleted. - No duplicates: the live map holds at most one node per value; historical versions have disjoint lifetimes, so at most one is visible per snapshot.
Complexity
| Operation | Complexity | Notes |
|---|---|---|
add, contains | O(1) avg | dict lookup + head splice |
remove | O(1) amortized | each tombstone unlinked exactly once |
iterator() | O(1) | records snap and start pointer |
| Full traversal | O(L) | L = list length at snapshot time |
close | O(1) amortized | may drain several GC-ready tombstones |
Space is O(live elements + retained tombstones). Tombstones accumulate only as long as the oldest iterator is alive.
Python Implementation
from collections import OrderedDict, deque
INF = float("inf")
class _Node:
__slots__ = ("val", "added", "deleted", "prev", "next")
def __init__(self, val: int, added: int):
self.val = val
self.added = added
self.deleted = INF
self.prev = None
self.next = None
class SnapshotIterator:
def __init__(self, owner: "SnapshotSet", snap: int, start: _Node | None):
self._owner = owner
self._snap = snap
self._cur = start
self._closed = False
def _visible(self, n: _Node) -> bool:
return n.added <= self._snap < n.deleted
def has_next(self) -> bool:
if self._closed:
return False
# Advance past nodes not visible to this snapshot
while self._cur is not None and not self._visible(self._cur):
self._cur = self._cur.next
if self._cur is None:
self.close() # auto-release on exhaustion
return False
return True
def next(self) -> int:
if not self.has_next():
raise StopIteration
val = self._cur.val
self._cur = self._cur.next
return val
def close(self) -> None:
if not self._closed:
self._closed = True
self._cur = None
self._owner._release(self._snap)
class SnapshotSet:
def __init__(self):
self._clock = 0
self._sentinel = _Node(-1, 0) # dummy head; never yielded
self._live: dict[int, _Node] = {}
self._snap_refs: OrderedDict[int, int] = OrderedDict()
self._tombstones: deque[_Node] = deque()
# ── internal helpers ──────────────────────────────────────────────
def _min_snap(self) -> float:
return next(iter(self._snap_refs)) if self._snap_refs else INF
def _prepend(self, node: _Node) -> None:
node.next = self._sentinel.next
node.prev = self._sentinel
if self._sentinel.next:
self._sentinel.next.prev = node
self._sentinel.next = node
def _unlink(self, node: _Node) -> None:
# Preserve node.next so iterators parked here can still advance
if node.prev:
node.prev.next = node.next
if node.next:
node.next.prev = node.prev
node.prev = None
def _gc(self) -> None:
threshold = self._min_snap()
while self._tombstones and self._tombstones[0].deleted <= threshold:
self._unlink(self._tombstones.popleft())
def _release(self, snap: int) -> None:
if snap in self._snap_refs:
self._snap_refs[snap] -= 1
if self._snap_refs[snap] == 0:
del self._snap_refs[snap]
self._gc()
# ── public API ────────────────────────────────────────────────────
def add(self, val: int) -> bool:
if val in self._live:
return False
self._clock += 1
node = _Node(val, self._clock)
self._live[val] = node
self._prepend(node)
return True
def remove(self, val: int) -> bool:
if val not in self._live:
return False
self._clock += 1
node = self._live.pop(val)
node.deleted = self._clock
self._tombstones.append(node)
self._gc()
return True
def contains(self, val: int) -> bool:
return val in self._live
def iterator(self) -> SnapshotIterator:
snap = self._clock
self._snap_refs[snap] = self._snap_refs.get(snap, 0) + 1
return SnapshotIterator(self, snap, self._sentinel.next)
Common Mistakes
- Forgetting that the same
snapvalue can be shared by multiple iterators — use a reference count, not a set. - Clearing the
nextpointer during unlink, which strands an iterator parked on that node. - Calling
closewithout an idempotency guard leads to double-decrement of the refcount.
Part 2: Durable Write Contract
Acknowledgment Boundary
The choice is a latency/durability trade-off:
- Ack after in-memory buffer write (group commit, fsync deferred): lowest latency, but data in the buffer is lost on a crash before fsync. Acceptable for caches or best-effort systems; not acceptable for financial or transactional workloads.
- Ack after fsync (or after a storage lease on a replicated log): guarantees the write survives a crash. Latency is typically 1–10 ms per fsync on SSDs. Group commit amortizes this by batching multiple operations into one fsync, recovering throughput while preserving durability.
- Ack after replication quorum (e.g., Raft): survives node failure, not just process crash. Higher latency than single-node fsync but the gold standard for fault-tolerant systems.
A reasonable default for a durable SnapshotSet: buffer writes in memory, fsync at configurable intervals or on explicit flush(), and acknowledge after the WAL record is fsynced when durability is required.
Ordering and Idempotency
Each WAL record should carry: a monotonically increasing sequence number (LSN), an operation (add or remove), the value, and a client-assigned operation ID (UUID or clientId + requestSeq).
- Out-of-order arrival: the WAL applies records strictly in LSN order. Records arriving out of order are held in a reorder buffer until the gap is filled.
- Idempotency on retry: before applying a record, check whether its client operation ID has already been applied (a small in-memory bloom filter or a bounded dedup log). If it has, return success without re-applying. This makes retries safe across network partitions and process restarts.
- Fencing: if using a replicated log, issue a fence token (epoch + LSN) with each write lease. Stale leaders with an outdated token are rejected.
Crash Recovery
The WAL uses a standard commit-marker protocol:
- Each record is written with a checksum and a
PENDINGstatus. - After fsync, a
COMMITmarker is appended and fsynced. - On recovery, replay records from the last known-good checkpoint. Any record without a following
COMMITmarker (or with a checksum mismatch) is a torn write — discard it and all records after it.
For snapshot integrity: the logical clock value is persisted as part of each WAL record. On recovery, the clock is restored to the LSN of the last committed record. Iterators created before the crash are gone (in-memory state is lost), so there are no stale snapshots to reconcile. The live set is rebuilt by replaying committed records in order; the snapshot timeline starts clean from the recovered clock value.