In-Memory Versioned Store with Snapshot and Compaction
System DesignModel answerLast updated
Build an in-memory key-value store that stages changes, creates atomic snapshots, supports historical queries, and limits retention to K versions.
Problem
You're building a document editor's backend storage layer. Users make changes to key-value pairs, create save points, and occasionally need to examine earlier states. Design an in-memory service that tracks these versions while preventing memory from growing without bound.
Core Operations
Your system must support:
- Stage changes:
set(key, value)andremove(key)operations that accumulate in a draft area - Create snapshots:
save()that atomically freezes the current draft into an immutable version, returning a sequential version number - Query history:
read(key, version=latest)that retrieves a key's value as it existed at a specific version - Limit retention: Keep only the most recent N versions (e.g., N=50); collapse older history into a base state
Behavior Details
- Version numbers start at 1 and increment with each
save() - Reading from the current draft (before the next save) returns staged values
- If a key didn't exist or was removed at the requested version, return null
- Queries for versions older than your retention window should signal that history is unavailable
- Snapshot isolation: once created, a version never changes, even as new saves occur
Scale Context
- Typical workload: 50,000 keys per workspace, 1KB average value size
- Target retention: 50 historical versions
- Expected load: 5,000 read/write operations per second
- Memory budget: avoid full dataset copies per version
Your Design Should Address
- Storage structure: How you represent keys, values, versions, and deletions to enable fast lookups and memory sharing
- Operation mechanics: Detailed flow for staging, snapshotting, and querying specific versions
- Compaction strategy: How you collapse old versions when exceeding the N-version limit without disrupting active readers
- Trade-offs: Comparison of at least two approaches (e.g., per-key version chains vs. copy-on-write trees) with concrete pros and cons
Hints
Hint 1
Consider whether storing one full copy per version is feasible given the memory numbers, then explore incremental approaches
Hint 2
Think about how deletions differ from 'never existed'—you'll need a way to distinguish these in historical queries
Hint 3
Collapsing old versions means rewriting history; determine which snapshot becomes your new baseline and what data can safely be discarded
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
1. Requirements Clarification and Capacity Planning
Before selecting structures, nail down the semantics:
- Empty snapshots: I'd allow them—each
save()increments the version counter even if no changes were staged, maintaining a monotonic timeline. - Compacted version reads: When querying a version older than the retention window, return a distinct "history unavailable" error rather than null, since null means "key didn't exist," which would misrepresent the past.
- Concurrency model: Single writer with multiple concurrent readers initially; multi-session staging is a natural extension.
Memory calculation:
- Base dataset: 50k keys × 1KB = 50 MB
- If we kept 50 full copies: 50 × 50 MB = 2.5 GB (unacceptable)
- Delta approach: assume 2% of keys change per version. That's ~1,000 changes × 1 KB = 1 MB per delta. Fifty deltas = 50 MB overhead.
- Total footprint: ~100 MB, which fits comfortably in memory.
This math confirms we need incremental versioning, not full snapshots.
2. API Surface
set(key, value) # stage a write
remove(key) # stage a deletion
save() -> version_id # atomically publish staged changes
read(key, version=None) -> value | null | HistoryUnavailable
3. Design Approach: Per-Key Version Chains (MVCC Style)
I'll use multi-version concurrency control with per-key version lists because it offers the simplest implementation for linear history:
Core structures:
history: Map<key -> List<(version, value|DELETED)>> # sorted by version
affected: Map<version -> Set<key>> # reverse index for compaction
draft: Map<key -> value|DELETED> # staging area
oldest_version: int # compaction watermark
newest_version: int # latest published snapshot
Why MVCC over copy-on-write trees?
A persistent HAMT (hash array mapped trie) with structural sharing is elegant for branching histories, but introduces overhead here:
- Read complexity: O(log₃₂ n) pointer chases vs. O(log V) binary search where V ≤ 51
- Memory churn: Each save copies ~4 tree levels per changed key, creating garbage
- Implementation complexity: Node reference counting or epoch-based reclamation
For a single-line history with bounded V, version lists have lower constant factors and simpler memory accounting. The HAMT becomes attractive if we later add branching or forking.
4. Operation Implementation
Staging Changes
set(k, v): writedraft[k] = vdirectly (O(1))remove(k): writedraft[k] = DELETEDmarker
The DELETED sentinel is critical: it distinguishes "removed at version V" from "never existed." Without it, querying version V+1 would incorrectly resurrect the old value.
Creating a Snapshot
Execute under an exclusive writer lock:
- Increment
v = newest_version + 1 - For each
(k, val)in draft:- Append
(v, val)tohistory[k] - Add
ktoaffected[v]
- Append
- Commit point: atomically publish
newest_version = v - Clear draft
- If
newest_version - oldest_version + 1 > N, trigger background compaction
The atomic store of newest_version is what makes the snapshot visible. Appended entries with version v remain invisible until this publication step.
Thread safety: Readers performing binary search on history[k] must never see the list mutate mid-search. Two options:
- Use append-only arrays and publish the length atomically after appending
- Replace the entire list reference copy-on-write (cheap since lists stay ≤ N+1 entries)
Querying a Version
For read(k, v):
- If
vis None, snapshotv = newest_versiononce at request start - If
v < oldest_version, returnHistoryUnavailable - Binary search
history[k]for the rightmost entry whereentry.version ≤ v - Return:
- No match found: null (never existed at that version)
- Match is
DELETED: null (was removed) - Otherwise: entry's value
Binary search runs in O(log(N+1)) = O(log 51) ≈ 6 comparisons, effectively constant time.
5. Compaction Mechanics
Goal: retain versions [M+1, M+N] where M = newest_version - N, and collapse everything older into a baseline.
Algorithm:
For each version e in (oldest_version, M]:
- For each key
kinaffected[e]:- In
history[k], find the last entry withversion ≤ M(call itbase_entry) - Delete all entries before
base_entry - If
base_entryisDELETED, remove it too (absence at baseline reads as null naturally) - If the list is now empty, delete
history[k]entirely
- In
- Delete
affected[e]
Finally, set oldest_version = M + 1.
Why this works:
- Any query for version ≥ M+1 will find the first entry at or after M+1, or fall back to
base_entry - We've preserved exactly the state visible at version M for every key
- Tombstones evaporate during compaction—they never accumulate long-term
Cost and concurrency:
- Compaction touches only keys changed in evicted versions, not the entire keyspace
- Amortized O(changes per version), spread across N versions
- Runs on a background thread; each key's list is rewritten atomically (copy-on-write swap)
- Readers hold references to old list objects until their query completes (automatic in GC languages; use epoch-based reclamation in manual-memory environments)
Separating logical eviction (oldest_version advance) from physical memory reclamation prevents disrupting in-flight queries.
6. Edge Cases and Gotchas
- Remove then re-set in one draft: Last write wins; only one entry is committed
- Hot key modified every version: Its list caps at N+1 entries due to compaction
- Query for future version (version > newest): return an error, not the latest snapshot
- Tombstone at baseline: Dropped during compaction—
history[k]may vanish entirely if the key is absent at the new baseline - N=1 retention: Store degenerates to one snapshot plus the draft; each save triggers immediate compaction
7. Alternative: Copy-on-Write Persistent Tree
If requirements change to support branching (multiple parallel editing sessions), switch to a persistent HAMT:
- Each version is a root pointer to an immutable tree
- Mutations path-copy O(log n) nodes, sharing unchanged subtrees
- No tombstones needed—deletions physically remove keys from the new root
- Snapshot isolation is automatic (readers hold immutable roots)
- Compaction is trivial: drop old root pointers and let GC reclaim unreachable nodes
Trade-off: 3–4× more memory churn and pointer overhead, but natural support for branching and merging.
8. Key Design Insights
Strong candidates demonstrate:
- Capacity math proving full copies are infeasible, justifying deltas
- Tombstone necessity for correct historical reads of deletions
- Atomic commit point: single publication step makes snapshots visible
- Proportional compaction: cost tied to changes, not total keyspace
- Reader isolation: logical vs. physical reclamation separation
- Comparative analysis: MVCC vs. persistent structures with concrete trade-offs
The core insight is that bounded history depth (N=50) allows simple per-key version lists to outperform fancier structures in this specific context.