KatInterview

Build a Thread-Safe Embedded Key-Value Engine from Hash Maps

System DesignModel answer
MediumModel answerSystem Designkey-value-storeconcurrencyhash-map

Last 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, or null if the key is absent.
  • delete(key) removes a key.

Required properties

  • get, put and delete must 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:

  1. The assumptions you make about key/value sizes, data volume and load.
  2. The data model, meaning which maps exist and what they hold.
  3. The concurrency strategy.
  4. The persistence and recovery approach, if you include one.
  5. How you handle compaction and expiry.
  6. 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.