Concurrency Strategies for a Shared In-Memory Key-Value Store
System DesignModel answerLast updated
Compare global, striped, and lock-free locking for a concurrent hash map, then design an optimal strategy for read-heavy workloads.
Building a Concurrent In-Memory Store
You are designing an in-memory key-value store that supports two operations — get(key) and put(key, value) — and must serve hundreds of concurrent threads without data corruption.
The underlying storage is a hash map. Your job is to choose and justify a locking strategy that maximises throughput while keeping tail latency (p99) low.
Three candidate strategies
Strategy 1 — Single global lock. One mutex guards the entire map. Every operation acquires it before touching any data.
Strategy 2 — Stripe locking. The map's buckets are divided into groups called stripes. Each stripe has its own lock. An operation only locks the stripe that its key hashes into.
Strategy 3 — Lock-free with CAS. Entries are updated with atomic compare-and-swap instructions. No thread ever blocks another.
What you need to address
- How does each strategy behave under heavy contention? Consider throughput scaling, p99 latency, and the effect of a single "hot" key.
- What are the trade-offs across memory overhead, implementation complexity, and correctness hazards?
- If reads outnumber writes by roughly 10:1, which strategy (or combination) would you recommend, and how would you tune its parameters?
Specific design questions to cover
- For stripe locking: how do you pick the number of stripes, how do you assign buckets to stripes, and how do you safely resize the underlying table?
- For lock-free CAS: what happens when the table needs to grow while threads are actively reading and writing?
There is no code judge. Write a structured answer that explains your reasoning, quantifies trade-offs where possible, and includes a reference implementation of your recommended approach.
Hints
Hint 1
A global lock's throughput ceiling is determined entirely by serialisation — think about what Amdahl's law implies when the serial fraction is 100%.
Hint 2
For stripe locking, consider what property your stripe-assignment function needs to preserve across a table resize, and why a power-of-two stripe count makes that easy.
Hint 3
Read-write locks let concurrent readers share a stripe without blocking each other; the tricky part is preventing a continuous stream of readers from starving writers.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Core Insight
Lock granularity controls how many threads can make progress simultaneously. Coarser locks are simpler but serialize more work; finer locks (or no locks) increase parallelism at the cost of complexity. For a read-heavy workload, the best default is a fixed array of read-write locks — one per stripe — so that concurrent readers never block each other and the complexity of lock-free reclamation is avoided entirely.
Analysing the Three Strategies
Strategy 1 — Single global lock
Every operation acquires the same mutex, so only one thread runs at a time regardless of how many cores are available. Throughput is capped at roughly one core's worth of work (Amdahl's law: serial fraction = 100%). Under contention, the lock's cache line bounces between cores and queuing delay accumulates; p99 latency grows roughly linearly with the number of waiting threads. With 200 concurrent writers, the 199th thread waits for all others to finish.
- Memory: one lock.
- Complexity: trivial, obviously correct.
- Verdict: acceptable for low concurrency; wrong for hundreds of threads.
Strategy 2 — Stripe locking
The map is divided into S stripes. Two threads contend only when their keys land on the same stripe. With uniform hashing, the per-pair collision probability is about 1/S, so throughput scales nearly linearly until S is comfortably larger than the number of active threads. A hot key still serializes on its stripe, but that is an unavoidable consequence of the data dependency rather than a design flaw.
- Memory:
Slocks, independent of map size. - Complexity: moderate. The hard case is resizing, which must quiesce all stripes.
- Verdict: the right default for most production deployments.
Strategy 3 — Lock-free CAS
No thread ever blocks, so a preempted thread cannot stall others. This gives the best theoretical tail latency and progress guarantees. The costs are significant:
- Under write contention on the same entry, CAS retry loops waste CPU and throughput can fall below a well-tuned stripe lock.
- Safe memory reclamation (hazard pointers or epoch-based reclamation) is required to avoid use-after-free and ABA bugs.
- Resizing is the hardest part. Two known techniques: split-ordered lists (Shalev–Shavit), where the table grows without moving nodes; or incremental migration (used by Java 8's
ConcurrentHashMap), where a forwarding sentinel marks migrated bins and threads help complete the transfer. - Extremely difficult to implement correctly or test exhaustively.
| Global | Striped | Lock-free | |
|---|---|---|---|
| Throughput scaling | None | Near-linear to ~S | Best for reads; degrades on hot writes |
| p99 under contention | Poor | Good | Best (non-blocking) |
| Memory overhead | O(1) | O(S) | Per-node atomics + reclamation structures |
| Resize complexity | Trivial | Moderate | Very high |
Recommended Design for Read-Heavy Workloads
Use S read-write locks (lock striping with RW semantics). get acquires a shared (read) lock on the relevant stripe; put acquires an exclusive (write) lock. Concurrent reads on the same stripe proceed in parallel, while writes exclude only that stripe.
Choosing S: make it a power of two, typically 2–4× the expected number of concurrently active threads. Values in the range 64–256 cover most workloads. Beyond that, collision probability is already negligible and extra locks waste cache lines.
Assigning buckets to stripes: set initial_buckets to a power-of-two multiple of S. Stripe for key k = hash(k) & (S-1). The bucket index = hash(k) & (len(table)-1). Crucially, because S is a factor of every valid table size, hash(k) & (S-1) is invariant across resizes — a thread can lock its stripe before reading the table pointer.
Resizing: acquire all S write locks in ascending index order, double the bucket array, rehash all entries, then release. Resizes are rare (amortized O(1) inserts) and the fixed acquisition order prevents deadlock. Use writer-preferring RW locks so a steady stream of readers cannot starve writes.
Reference Implementation (Python)
CPython's GIL limits true parallelism, but the structure maps directly to Java, C++, or Go.
import threading
class RWLock:
"""Writer-preferring readers-writer lock."""
def __init__(self):
self._cond = threading.Condition(threading.Lock())
self._readers = 0
self._writer = False
self._waiting_writers = 0
def acquire_read(self):
with self._cond:
while self._writer or self._waiting_writers:
self._cond.wait()
self._readers += 1
def release_read(self):
with self._cond:
self._readers -= 1
if self._readers == 0:
self._cond.notify_all()
def acquire_write(self):
with self._cond:
self._waiting_writers += 1
while self._writer or self._readers:
self._cond.wait()
self._waiting_writers -= 1
self._writer = True
def release_write(self):
with self._cond:
self._writer = False
self._cond.notify_all()
class StripedKVStore:
def __init__(self, num_stripes=64, initial_buckets=256, load_factor=0.75):
assert num_stripes & (num_stripes - 1) == 0, "num_stripes must be a power of two"
assert initial_buckets & (initial_buckets - 1) == 0, "initial_buckets must be a power of two"
assert initial_buckets >= num_stripes
self._S = num_stripes
self._mask_s = num_stripes - 1
self._locks = [RWLock() for _ in range(num_stripes)]
self._counts = [0] * num_stripes # per-stripe; avoids a shared atomic counter
self._buckets = [[] for _ in range(initial_buckets)]
self._load_factor = load_factor
def _stripe(self, h):
return h & self._mask_s # stable across resizes
def get(self, key, default=None):
h = hash(key)
lock = self._locks[self._stripe(h)]
lock.acquire_read()
try:
table = self._buckets
for k, v in table[h & (len(table) - 1)]:
if k == key:
return v
return default
finally:
lock.release_read()
def put(self, key, value):
h = hash(key)
s = self._stripe(h)
lock = self._locks[s]
lock.acquire_write()
try:
table = self._buckets
bucket = table[h & (len(table) - 1)]
for entry in bucket:
if entry[0] == key:
entry[1] = value
return
bucket.append([key, value])
self._counts[s] += 1
needs_resize = sum(self._counts) > self._load_factor * len(table)
finally:
lock.release_write()
if needs_resize: # never resize while holding a stripe lock
self._resize()
def _resize(self):
# Acquire all write locks in ascending order to prevent deadlock.
for lock in self._locks:
lock.acquire_write()
try:
old = self._buckets
new_size = len(old) * 2
new_table = [[] for _ in range(new_size)]
mask = new_size - 1
for bucket in old:
for k, v in bucket:
new_table[hash(k) & mask].append([k, v])
self._buckets = new_table
finally:
for lock in self._locks:
lock.release_write()
Common Mistakes
- Forgetting resize coordination. Doubling the bucket array while a reader holds a stripe lock can give it a view of a partially migrated table. Always resize outside of any stripe lock, after acquiring all write locks.
- Using a single element counter. A shared atomic counter for total size creates contention on every write. Per-stripe counts avoid this; sum them only when needed.
- Reader starvation of writers. A plain reader-preference RW lock under a 10:1 read ratio will indefinitely delay writes. Use writer-preference or a fair queuing policy.
- Non-power-of-two sizes. If
Sdoes not divide the bucket count evenly, the stripe assignment changes after a resize and threads can lock the wrong stripe, causing races or unnecessary contention.