Build a Thread-Safe Embedded Key-Value Engine from Hash Maps
System DesignModel answerLast updated
Design a concurrent embedded key-value store whose indexes are built only from hash maps, covering sharding, crash recovery, log compaction, expiry, and a testing plan.
You are asked to design the core of an embedded storage engine: a library that runs inside a single process and is called by many threads at once. There is no network layer.
Restriction: every in-memory index must be built from hash-map / dictionary primitives (plus ordinary primitives and arrays). No trees, skip lists or other ordered structures.
Required operations
put(key, value)stores or overwrites a value.get(key)returns the value, ornullif the key is absent.delete(key)removes a key.
Required properties
get,putanddeletemust run in expected O(1) time.- The store must be safe under concurrent access from multiple threads.
- Worth discussing: durability (surviving a crash), compaction (reclaiming space) and TTL / expiration.
What to deliver
Walk through your design:
- The assumptions you make about key/value sizes, data volume and load.
- The data model, meaning which maps exist and what they hold.
- The concurrency strategy.
- The persistence and recovery approach, if you include one.
- How you handle compaction and expiry.
- How you would test the library.
Hints
Hint 1
Decide early whether values live in RAM or on disk. That one choice determines memory use, whether you need a log, and how recovery works. A map from key to a file pointer keeps RAM proportional to the number of keys rather than the data volume.
Hint 2
A single global lock is correct but serializes everything. Consider splitting the main map into many shards, each with its own lock, and think about why two writes to the same key must be ordered identically in the map and in any log.
Hint 3
For expiry, combine a cheap check on read with a background sweep that uses a second map from time bucket to keys. For compaction, think about what happens when a concurrent write changes a key while its old record is being copied, and use a version number to resolve it.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size the problem
State assumptions up front:
- Keys and values are byte strings. Keys average about 32 B, values about 1 KB, with a cap of about 1 MB per value.
- About 10M keys. Values alone are around 10 GB; with overhead, a pure in-RAM design needs about 12 GB.
- If values sit on disk and RAM holds only
key + ~24 Bper entry, the index is roughly 600 MB. This is the central fork, so name it explicitly. - Target roughly 100k ops/s, read-heavy (about 80/20), with sub-millisecond p99 for in-memory hits.
- Consistency: each operation is linearizable per key. No multi-key transactions.
- Durability is configurable: none, fsync every N ms, or fsync on every write.
2. API semantics
put(key, value, ttl_ms=None) -> None
get(key) -> bytes | None
delete(key) -> bool # true if the key existed
open(dir, options) / close()
- An expired key reads as absent.
deleteis idempotent.putoverwrites the value and resets the TTL.
3. Data model (maps only)
| Structure | Shape | Role |
|---|---|---|
shards[i] | map: key to Entry | Primary index, split into N partitions |
Entry | value or (segment, offset, length), plus seq, expire_at | The value, or a pointer to it |
expiry_buckets | map: second to set of keys | Coarse timing wheel for TTL |
segments | map: segment id to open file | Handles for log files |
Two modes exist. In pure in-memory mode the entry holds the value, which is simplest. In log-structured (Bitcask-style) mode the entry holds a pointer into an append-only log. Present both, then choose the log-structured mode if durability matters, since you need the log anyway.
Complexity: get is one hash lookup plus at most one disk read. put and delete are one hash write plus one sequential append. All are expected O(1).
4. Architecture
put/get/delete
|
hash(key) & (N-1)
|
Shard 0 ... Shard N-1 (each: map + read/write lock)
| (writes)
Append-only log -> group-commit fsync thread
|
Active segment + immutable segments
-> compactor thread, TTL sweeper thread
Write path (under the shard write lock):
- Take
seqfrom an atomic counter. - Append
[crc | seq | key_len | val_len | expire_at | key | value]to the log under a short log mutex. - Update the shard map.
- Release the lock. If
sync=always, wait for the fsync before returning.
Read path (under the shard read lock): look up the entry, treat it as missing if expire_at < now, otherwise return the value or pread it from the stored offset.
Delete path: append a tombstone, then remove the key from the map.
5. Concurrency
- A global lock is correct but serializes everything. Mention it, then improve.
- Lock striping: use 64 to 256 shards, each with its own reader-writer lock. Different keys rarely contend, and the same key always maps to the same lock, which gives per-key linearizability.
- Append inside the shard lock. Two writes to the same key must hit the log in the same order they hit the map, or replay could resurrect a stale value. Across shards the interleaving is irrelevant, and
seqlets recovery order records deterministically. - The log mutex is only held for a memcpy into a buffer. A background thread batches fsyncs (group commit) so the 1 to 10 ms fsync cost is amortized across many writes.
- Lock-free reads are possible with copy-on-write entries or a concurrent hash map. Mention it but default to RW locks for clarity.
- Compound check-then-act sequences need locks even in runtimes with a global interpreter lock.
6. Durability and recovery
The append-only log is both data and write-ahead log. On open():
- Load each segment's hint file if present (a compact
key -> (offset, seq, expire_at)snapshot written at compaction) to avoid reading values. - Replay remaining records in order. Tombstones remove keys. Apply a record only if its
seqis newer than what the map holds. - Verify every CRC. At the first bad or short record in the tail segment, truncate: it was a torn write.
Guarantees: with sync=always, an acknowledged write is never lost. With sync=every 10ms, up to about 10 ms of acknowledged writes can be lost. State this trade-off plainly.
7. Compaction
Overwrites and deletes leave dead bytes in the log.
- Roll the active segment at 64 to 256 MB; it becomes immutable.
- The compactor scans immutable segments. A record is live only if
shard[key].seq == record.seqand it has not expired. Live records go to a new segment plus a hint file. - For each copied key, take the shard lock and swap the pointer only if
seqis unchanged (compare-and-swap style). A concurrentputwins. - Delete old segments afterward. In-flight readers keep their handle via reference counting.
- Drop a tombstone only when no older segment still holds that key.
Trigger on a dead-byte ratio (say above 50%) and rate-limit compaction I/O to protect foreground p99.
8. TTL
- Lazy expiry:
getchecksexpire_at. This alone guarantees correctness. - Active sweep: reclaims memory for keys never read again.
expiry_buckets[second]maps to the keys due in that second. A sweeper wakes each second, pops due buckets and deletes a key only if its current entry still has thatexpire_at, which handles keys re-put with a new TTL. This keeps insert and removal at O(1) using only maps.
9. Testing
- Unit tests: overwrite, delete of a missing key, expiry boundaries, large values.
- Concurrency stress: many threads doing random operations on a small key space, compared against a model protected by one global lock. Run under a race detector.
- Linearizability checks on short histories for a single key.
- Crash tests: kill the process at random points, including mid-write and mid-compaction, truncate the log at random byte offsets, then reopen and verify that all acknowledged writes (under
sync=always) are present and nothing is corrupt. - Compaction races: run writers against a compactor and assert that the latest write always wins.
- Property/fuzz tests comparing the engine to a plain in-memory map across random operation sequences, including reopen events.
Common mistakes
- Using one global lock and calling it done.
- Appending to the log outside the per-key ordering, allowing stale replays.
- Compaction that overwrites a newer pointer with an older one.
- Dropping tombstones too early so deleted keys reappear.
- Relying only on a sweeper for expiry, so expired keys can still be returned.
- Claiming durability without saying when fsync happens.