Project

Key-Value Store

Build a production-grade key-value store from scratch. Combine a hash map for O(1) lookups, an LRU eviction policy for bounded memory, and a write-ahead log for crash durability. This is the architecture behind Redis, LevelDB, and RocksDB.

Operation flow — animated

set / get / evict lifecyclestep 1/4

// Array state

WAL
WAL
hash
hash
LRU
[2]
_
[3]
_
[4]
_
[5]
→ set('user:1', {...}): Write to WAL first — crash-safe. Then insert into hashMap at bucket hash('user:1')%capacity.

// Pseudocode

1// Key-Value Store — core operations
2class KVStore:
3 hashMap = HashMap() // O(1) average get/set
4 lruCache = LRUCache(maxSize) // evict least-recently-used
5 wal = WriteAheadLog() // durability
6 
7 function set(key, value):
8 wal.append(SET, key, value) // durability first
9 lruCache.put(key, value) // update eviction order
10 hashMap.put(key, value) // store
11 
12 function get(key):
13 if not hashMap.has(key): return NULL
14 lruCache.touch(key) // mark recently used
15 return hashMap.get(key)
16 
17 function delete(key):
18 wal.append(DELETE, key)
19 lruCache.remove(key)
20 hashMap.remove(key)

Build it in layers

1 / 4
1

Layer 1 — Hash Map

The core storage: a hash map provides O(1) average-case get, set, and delete. Choose a load factor (0.7 is standard). Handle collisions with open addressing or chaining.

1 of 4

Core pseudocode

kv-store.pseudo
1// Key-Value Store — core operations
2class KVStore:
3 hashMap = HashMap() // O(1) average get/set
4 lruCache = LRUCache(maxSize) // evict least-recently-used
5 wal = WriteAheadLog() // durability
6 
7 function set(key, value):
8 wal.append(SET, key, value) // durability first
9 lruCache.put(key, value) // update eviction order
10 hashMap.put(key, value) // store
11 
12 function get(key):
13 if not hashMap.has(key): return NULL
14 lruCache.touch(key) // mark recently used
15 return hashMap.get(key)
16 
17 function delete(key):
18 wal.append(DELETE, key)
19 lruCache.remove(key)
20 hashMap.remove(key)

Complexity

get — hash map lookup + LRU touchO(1)

Constant time

set — hash map insert + LRU update + WAL appendO(1)

Constant time

delete — hash map remove + LRU removeO(1)

Constant time

Space — keys + values + LRU doubly-linked listO(n)

Linear time

🔍TTL and expiry
Add a TTL (time-to-live) field to each entry. Use a min-heap keyed on expiry time. A background job pops expired entries from the heap and deletes them from the hash map. This is how Redis EXPIRE works.

🎯 Quick Check

Why write to the WAL BEFORE updating the hash map?