Concurrent In-Memory Cache with Sharded Locking
Data Structure DesignModel answerLast updated
Build a thread-safe in-memory cache supporting concurrent reads and writes, choosing data structures and synchronization primitives to minimize contention.
You're building an in-memory cache for a multi-threaded application. Multiple threads will simultaneously insert, retrieve, and remove entries from this cache, all within a single process.
Your task is to design a thread-safe cache class that supports these operations:
put(key, value): store or update the value associated with a keyget(key): retrieve the value for a key, returningnull/Noneif not founddelete(key): remove a key and its value if present
Requirements:
- Thread safety: Operations must be safe under concurrent access with no data corruption or lost updates
- Atomicity: Each operation should behave as if it executes instantaneously from the caller's perspective
- Performance: Minimize blocking between threads; avoid unnecessary serialization
- Scope: Single-process only (no distributed system concerns)
- Types: Keys are strings; values can be any object type
Answer these questions:
-
What underlying data structure would you choose to hold the key-value mappings? Justify your choice.
-
What synchronization approach would you use? Compare at least three options (such as: global mutex, reader-writer locks, sharded locks, lock-free structures, or language-provided concurrent collections). Explain the benefits and drawbacks of each.
-
Pick one synchronization strategy and implement it in a language that lacks a built-in concurrent map (like Python with a standard
dict). Show or describe how you'd implementput,get, anddelete. -
How would you verify correctness and detect race conditions? Describe your testing approach, including any concurrency-specific techniques or tools.
-
What production considerations would matter if this cache were deployed in a real system? Think about monitoring, resource limits, input validation, and performance tuning.
Hints
Hint 1
A hash table gives O(1) operations for point lookups—do you need ordering or range queries?
Hint 2
Dividing the cache into independent segments, each with its own lock, reduces contention proportionally to the segment count.
Hint 3
When acquiring multiple locks (for operations like size()), always take them in a consistent order to prevent deadlock.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Concurrent In-Memory Cache Design
Core Approach
Use a hash table as the storage backbone, protected by sharded locking (also called lock striping). Divide the hash table into a fixed number of independent segments, each guarded by its own mutex. Route each key to a specific segment based on its hash value. Operations acquire only the lock for their target segment, allowing concurrent operations on different segments to proceed in parallel.
This balances simplicity with scalability: it's straightforward to implement and reason about, while dramatically reducing contention compared to a single global lock.
1. Data Structure Selection
Choice: Hash table (hash map, dictionary)
Rationale:
- All three operations—
put,get,delete—are point lookups by key - Hash tables provide O(1) average-case time for these operations
- No requirement for ordering, range scans, or sorted iteration
Alternatives considered:
- Sorted tree (B-tree, red-black tree): O(log n) operations. Only valuable if you need range queries or ordered traversal—neither is required here
- Array with linear search: O(n) lookups. Unacceptable for a cache
- Trie: Useful for prefix searches on string keys. Overkill and slower for exact-match lookups
Sharded layout:
- Maintain an array of N segments, where N is a power of 2
- Each segment contains: (1) a mutex, (2) a hash table
- Map keys to segments via:
segment_index = hash(key) & (N - 1) - Using a bitmask instead of modulo is faster and equivalent when N is a power of 2
2. Synchronization Strategy Comparison
| Approach | Advantages | Disadvantages |
|---|---|---|
| Global mutex | Simple to implement; trivially correct; easy to add whole-cache operations (size, clear) | All threads serialize on every operation; contention scales linearly with thread count; poor scalability |
| Reader-writer lock | Multiple concurrent readers; only writers block | Writer starvation possible; high overhead for short critical sections; Python lacks built-in support; marginal benefit when ops are fast |
| Sharded locking | Contention reduced by factor of N; bounded memory overhead; simple reasoning | Whole-cache operations require all locks; hot keys still contend within their segment |
| Per-key fine-grained locks | Maximum parallelism; no false sharing | Must synchronize the lock map itself; lock object creation/destruction overhead; high memory cost; complex lifecycle management |
| Lock-free / built-in concurrent map | True parallelism with CAS operations; battle-tested implementations | Language/platform dependent; limited customization; harder to debug; not universally available |
Recommendation:
- If available: Use language-provided concurrent maps (Java's
ConcurrentHashMap, Go'ssync.Map, Rust's dashmap) - If implementing from scratch: Sharded locking with 16–64 segments, tuned to expected thread count
Python GIL note: While CPython's Global Interpreter Lock makes individual dict operations atomic today, this is an implementation detail. Free-threaded Python (3.13+) removes the GIL. Always use explicit synchronization for portability and correctness.
3. Implementation with Sharded Locking (Python)
import threading
from typing import Any, Generic, List, Optional, Tuple, TypeVar
V = TypeVar("V")
_SENTINEL = object()
class ConcurrentCache(Generic[V]):
"""Thread-safe cache using lock striping.
Keys hash to one of N segments, each with independent lock and dict.
Operations on different segments run in parallel; operations on the
same key serialize on that key's segment lock.
"""
def __init__(self, num_segments: int = 32) -> None:
if num_segments <= 0 or (num_segments & (num_segments - 1)) != 0:
raise ValueError("num_segments must be a power of two")
self._mask = num_segments - 1
self._segments: List[Tuple[threading.Lock, dict]] = [
(threading.Lock(), {}) for _ in range(num_segments)
]
def _get_segment(self, key: str) -> Tuple[threading.Lock, dict]:
"""Route key to its segment."""
if not isinstance(key, str):
raise TypeError("Keys must be strings")
idx = hash(key) & self._mask
return self._segments[idx]
def put(self, key: str, value: V) -> None:
"""Insert or update the value for key."""
lock, store = self._get_segment(key)
with lock:
store[key] = value
def get(self, key: str) -> Optional[V]:
"""Retrieve value for key, or None if absent."""
lock, store = self._get_segment(key)
with lock:
return store.get(key)
def delete(self, key: str) -> bool:
"""Remove key if present. Returns True if key existed."""
lock, store = self._get_segment(key)
with lock:
if key in store:
del store[key]
return True
return False
def put_if_absent(self, key: str, value: V) -> Optional[V]:
"""Atomic: insert only if key missing; return existing value or None."""
lock, store = self._get_segment(key)
with lock:
existing = store.get(key, _SENTINEL)
if existing is _SENTINEL:
store[key] = value
return None
return existing
def size(self) -> int:
"""Return total entry count. Acquires all locks for consistency."""
# Acquire in index order to prevent deadlock
for lock, _ in self._segments:
lock.acquire()
try:
return sum(len(store) for _, store in self._segments)
finally:
# Release in reverse order
for lock, _ in reversed(self._segments):
lock.release()
Why this works:
- Correctness: Each key deterministically maps to one segment. All operations on that key serialize through the segment lock, providing mutual exclusion
- Atomicity: Each method executes its read or write within a single lock acquisition, making it atomic from callers' perspective
- No data races: Segment dictionaries are only accessed while holding the corresponding lock
- Deadlock-free: Single-key ops take one lock;
size()takes locks in ascending order, preventing cycles
Complexity:
- Time: O(1) average for put/get/delete; O(N) for size (N = segment count)
- Space: O(entries + segments)
- Contention probability: ~1/N for uniformly distributed keys
4. Testing and Validation
Unit tests (single-threaded):
- Basic operations: put/get round-trip, overwrite, delete existing and non-existing keys
- Edge cases: empty cache, None values (ambiguity with missing keys), invalid key types
- Initialization: invalid segment counts (non-power-of-two, zero, negative)
Concurrency stress tests:
- Hammer test: Spawn many threads performing random put/get/delete operations on overlapping key sets. Verify no exceptions or data corruption
- Linearizability check: Record operation timestamps and results; verify that a valid sequential ordering exists matching observed outcomes
- Lost update detection: Multiple threads incrementing counters via get-modify-put sequences should reveal race conditions (some increments will be lost without proper synchronization)
Concurrency tools:
- Thread sanitizers: Clang ThreadSanitizer, Valgrind's Helgrind detect data races
- Stress testing frameworks: Java's JCStress, Python's threading + pytest-repeat
- Deterministic testing: Tools like Microsoft's CHESS or Lincheck systematically explore thread interleavings
- Assertions: Check invariants (size matches sum of segment sizes, keys appear in expected segments)
Example stress test pattern:
def test_concurrent_access():
cache = ConcurrentCache[int]()
errors = []
def worker(thread_id: int):
try:
for i in range(1000):
key = f"key_{i % 100}"
cache.put(key, thread_id)
val = cache.get(key)
if val is not None:
assert isinstance(val, int)
except Exception as e:
errors.append(e)
threads = [threading.Thread(target=worker, args=(i,)) for i in range(20)]
for t in threads: t.start()
for t in threads: t.join()
assert not errors, f"Concurrency errors: {errors}"
5. Production Considerations
Input validation:
- Enforce key type constraints (strings only, or support hashable types)
- Validate segment count at initialization
- Consider max key/value size limits
Resource limits:
- Capacity cap: Implement eviction policy (LRU, LFU, TTL) to prevent unbounded growth
- Memory monitoring: Track size() periodically; alert when approaching limits
- Graceful degradation: Return errors when full rather than crashing
Monitoring and observability:
- Metrics: Hit rate, miss rate, operation latency (p50, p99), size, eviction count
- Lock contention metrics: If available, track wait times per segment to identify hot spots
- Logging: Error conditions, configuration changes, evictions
Performance tuning:
- Segment count: Tune based on thread count and contention profile (typically 16–64)
- Hash function: Ensure uniform distribution to avoid segment imbalance
- Profiling: Measure under realistic load; identify bottlenecks
Operational concerns:
- Configuration: Make segment count tunable via environment variable or config file
- Persistence: If needed, add periodic snapshots or write-ahead logging
- Warmup: Prepopulate cache on startup for predictable performance
- Testing in production: Canary deployments, gradual rollout with monitoring
Common mistakes to avoid:
- Storing
Noneas a value makesget()ambiguous—document or providecontains()method - Mutable values: cache holds references; unsynchronized mutations by callers cause inconsistency
- Compound operations from outside are not atomic: provide atomic methods like
put_if_absent,compare_and_swap - Taking locks in inconsistent order causes deadlock in operations requiring multiple locks