Building a High-Performance In-Memory Cache
System DesignModel answerLast updated
Design a fast, thread-safe in-memory cache with automatic expiration and crash recovery capabilities.
Problem
You need to build a high-performance, in-memory caching system that stores key-value pairs. The cache must support basic operations with extremely low latency while handling concurrent access from multiple clients.
Core Operations
Your cache must implement:
SET(key, value): Store or update a key-value pairGET(key): Retrieve the value for a given key (return null if absent)DELETE(key): Remove a key and its valueEXPIRE(key, ttl): Mark a key for automatic removal after a specified duration
System Constraints
- Performance goal: Operations should complete in under 1 millisecond
- Concurrency: Support thousands of simultaneous client connections
- Crash recovery: Minimize data loss when the system restarts unexpectedly
Scale Parameters
- Expected dataset: 10 million keys
- Typical value size: 1 KB per entry
- Traffic pattern: 90% read operations, 10% writes
What to Cover
- Choose and justify the core data structures for storing entries
- Design a concurrency control approach that avoids bottlenecks
- Implement efficient automatic expiration without scanning all keys
- Create a persistence strategy that doesn't compromise performance
Explain your reasoning for each decision and discuss the trade-offs involved.
Hints
Hint 1
Start by calculating total memory requirements—this tells you whether a single machine suffices
Hint 2
For concurrency, consider how to reduce lock contention: sharding the data across multiple independent structures is often better than one global lock
Hint 3
Expiration needs both correctness (never return expired data) and efficiency (reclaim memory without constant scanning)
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution: High-Performance In-Memory Cache Design
This problem focuses on internal architecture decisions: memory layout, contention patterns, scheduling time-based cleanup, and durability mechanisms. A strong solution starts with capacity planning, then designs each component with explicit reasoning.
1. Requirements Clarification and Capacity Analysis
Before designing, nail down edge cases:
- When you
SETan existing key, does it clear any prior expiration? (Yes, following Redis semantics) - Can you set an expiration on a non-existent key? (No, return failure)
- Are values treated as opaque binary data?
- After a crash, how much data loss is tolerable? (Assume 1 second is acceptable)
Memory calculation:
| Component | Size |
|---|---|
| Value storage | 10M keys × 1 KB = 10 GB |
| Key storage (avg 32 bytes) | 320 MB |
| Metadata per entry (hash bucket, expiration timestamp, reference count, ~70 bytes) | 700 MB |
| Total working set | ~11 GB |
With 32–64 GB of RAM, everything fits comfortably on one machine. Writing 11 GB to disk at 1 GB/s takes about 11 seconds, meaning persistence must happen asynchronously.
Key insight from sizing: This is a single-machine problem where memory management and lock contention matter more than network partitioning.
2. Core Data Structure: Sharded Hash Tables
Use multiple independent hash tables instead of one global table:
- Divide keys across 256 shards (or 4–8× your CPU core count)
- Route each key to its shard via
shard_id = hash(key) % num_shards - Each shard contains:
- A hash table (open addressing or separate chaining)
- An independent lock
- An expiration tracking structure (detailed in section 4)
Why sharding works:
- Two operations collide only if they hit the same shard (1/256 probability)
- Each shard can resize independently without blocking others
- Provides natural CPU cache locality
Hash table resizing:
Use incremental rehashing to avoid latency spikes. When a shard needs to grow:
- Allocate the new table but keep the old one
- Migrate a few buckets on each operation touching that shard
- Look in both tables during migration
- This spreads the O(n) resize cost across many operations
Entry structure:
{
key: bytes,
value_ptr: pointer, // points to immutable buffer
expire_at: timestamp, // 0 means no expiration
version: uint64 // for lazy invalidation
}
Store values as immutable, reference-counted buffers. Readers can copy the pointer under a lock, then release the lock before copying the actual 1 KB data.
3. Concurrency Control: Minimizing Lock Contention
For a 90% read workload, choose between these strategies:
Option A: Per-Shard Reader-Writer Locks (baseline)
- Writers take exclusive lock, readers take shared lock
- Keeps critical sections minimal: just the hash lookup and pointer swap
- Downside: Reader count is a shared counter that bounces between CPU cores
- Works well but has overhead on highly contended shards
Option B: Lock-Free Reads with Seqlock or RCU (recommended for read-heavy)
- Readers never take locks; they use atomic loads
- Writers atomically swap pointers after preparing new entries
- Old values are freed via epoch-based reclamation: track which "epoch" each reader is in, defer frees until all readers have advanced
- Benefit: Zero lock overhead for reads, perfect for 90% read traffic
- Complexity: Requires careful memory ordering and reclamation logic
Option C: Thread-Per-Core Architecture
- Each CPU core owns a subset of shards exclusively
- No locks within a shard—single-threaded event loop per core
- Requests route to the owning core via lock-free queues
- Achieves best tail latency but complicates multi-key operations
- (This is the KeyDB/Dragonfly approach)
Recommendation: Start with Option A or B. Option B gives better read performance but requires more careful implementation. Mention Option C as a future optimization if single-key latency becomes critical.
Consistency guarantee: Each key's operations are linearizable because each key lives in exactly one shard with atomic updates.
4. Efficient Expiration: Lazy Deletion + Active Cleanup
The expire_at timestamp in each entry is the authoritative source. Expiration happens on two paths:
Passive expiration (ensures correctness):
- On every
GET,SET, orDELETE, checkif now >= expire_at - If expired, treat the key as non-existent and delete it immediately
- Guarantees clients never observe stale data
Active cleanup (reclaims memory):
Per-shard, maintain a min-heap ordered by expiration time:
- Push
(expire_at, key, version)onto the heap when setting a TTL - A background thread per shard periodically:
- Peeks the heap root
- If the earliest expiration hasn't arrived, sleep
- Otherwise, pops items and deletes them in small batches
Lazy invalidation trick:
When a key's TTL is updated or the key is deleted, don't remove the old heap entry (O(n) operation). Instead:
- Increment the key's
versionfield - When popping from the heap, compare the heap entry's version with the current entry
- If they don't match, discard the heap entry as stale
This makes TTL updates O(log n) instead of O(n).
Alternative approaches to mention:
- Timing wheel: O(1) insertion, better for coarse-grained TTLs (second-level granularity)
- Probabilistic sampling (Redis approach): Randomly sample 20 keys with TTLs; if >25% are expired, repeat. No memory overhead but not deterministic.
5. Persistence: Write-Ahead Log + Snapshots
Combine two mechanisms:
Write-Ahead Log (WAL):
- Append every mutation (
SET,DELETE,EXPIRE) to a sequential log file - Include absolute expiration timestamps, not relative TTLs
- A background thread flushes the buffer to disk
Fsync policies:
| Policy | Data loss risk | Write latency impact |
|---|---|---|
| Fsync every write with group commit | ~0 ms | +0.1–2 ms per write |
| Fsync every 1 second (recommended) | ≤1 second | None |
| OS-controlled | ~30 seconds | None |
Snapshots:
- Periodically write a full memory image tagged with its WAL position (LSN)
- Two approaches:
- Fork-based:
fork()the process; child writes while parent continues serving. Simple but can temporarily double memory usage. - Iterator-based: Lock each shard briefly, copy bucket pointers (cheap since values are immutable), then write. Lower memory overhead.
- Fork-based:
- After snapshot completes, truncate the WAL before that LSN
Recovery process:
- Load the most recent snapshot
- Replay WAL entries from the snapshot's LSN forward
- Discard entries with
expire_atin the past - Use checksums per record to detect incomplete writes at the tail
Why this works:
- WAL provides durability with minimal latency
- Snapshots bound recovery time (replaying 1 second of log is fast)
- Combined, they lose at most 1 second of data
6. Key Trade-Offs to Discuss
A complete answer explicitly names these choices:
- Locking strategy: RW locks are simpler; RCU/seqlock is faster for reads but harder to implement correctly
- Expiration index: Min-heap balances simplicity and efficiency; timing wheels are faster but less precise; sampling uses no memory but is probabilistic
- Persistence fsync policy: Determines the durability-latency-throughput triangle
- Snapshot mechanism: Fork is easy but memory-hungry; iterative snapshotting is more complex but safer under tight memory
Common mistakes to avoid:
- Using a single global lock (kills concurrency)
- Scanning all keys to find expired ones (O(n) periodically is too slow)
- Blocking writes during snapshots (violates latency SLA)
- Forgetting to handle torn writes in the WAL during recovery
Summary
This design achieves sub-millisecond latency through sharding and lock-free or fine-grained locking, handles expiration efficiently via dual-path cleanup, and ensures durability without blocking the hot path. The architecture scales to 10 million keys on a single machine while leaving room to scale horizontally by partitioning shards across multiple nodes in the future.