Thread-Safe Memoization: Fixing a Shared Cache for Concurrent Callers
System DesignModel answerLast updated
A dict-backed memoization wrapper is called from many threads simultaneously — identify the race conditions and redesign it to be safe without killing throughput.
Thread-Safe Memoization
You have a module-level dictionary that caches the results of a slow function:
cache = {}
def compute(x):
if x in cache:
return cache[x]
result = expensive(x)
cache[x] = result
return result
The function expensive(x) takes several seconds to return. Your application has started calling compute from a pool of worker threads, and things are going wrong in ways that are hard to reproduce.
Before you answer, consider
- Is running
expensive(x)twice for the same input harmful — for example, does it charge a fee, write a record, or produce a different value each time? - What should happen if
expensive(x)raises an exception? Should the failure be stored so later callers see it immediately, or should the next caller retry? - Can the set of distinct inputs grow without bound, or is it finite?
- Which Python runtime are you targeting — standard CPython with its GIL, a free-threaded (no-GIL) build, or something else?
- Is
expensivemostly blocked on I/O, or does it saturate the CPU?
Your answer should address two things:
Part 1 — Describe what can go wrong
Walk through at least one concrete sequence of thread interleaving that causes incorrect or undesirable behavior. Go beyond saying the code "isn't thread-safe" — show how it breaks and what the visible consequences are.
Cover:
- The window between the cache lookup and the cache write, and what multiple threads can do inside it
- What guarantees (and non-guarantees) CPython's dictionary gives you for concurrent access
- How the severity of the problem changes depending on whether
expensiveis idempotent and free of side effects
Part 2 — Fix it
Rewrite compute so it is safe for concurrent callers. Present at least two different approaches that differ in where the lock is placed, compare their throughput characteristics, and pick one with a justification.
Cover:
- Whether each approach allows duplicate computation or prevents it entirely
- What each lock serializes, and how that affects threads asking for different keys vs. the same key
- How waiting threads are handled when
expensiveraises, so that a failure neither corrupts the cache nor leaves threads permanently blocked
Hints
Hint 1
Trace through what happens when two threads both reach the `if x in cache` check at exactly the same moment, before either one has written to the cache. How many times will `expensive(x)` run?
Hint 2
Think about two possible lock placements: one that wraps the entire function body, and one that only locks the dictionary writes. The first is simpler — what does it cost? The second allows parallelism — what new problem does it introduce?
Hint 3
When `expensive(x)` raises inside a lock, the exception unwinds the stack. Make sure you release the lock correctly and that waiting threads aren't left blocking forever on a key that will never be populated.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1 — What Can Go Wrong
The check-then-act race
The core issue is a check-then-act race. The lookup (if x in cache) and the write (cache[x] = result) are two separate operations with no atomicity guarantee between them. Consider this interleaving with two threads both calling compute(42) for the first time:
Thread A: checks cache — key absent
Thread B: checks cache — key absent ← both miss
Thread A: calls expensive(42) …
Thread B: calls expensive(42) … ← both start work
Thread A: writes cache[42] = result_A
Thread B: writes cache[42] = result_B ← one result silently overwrites the other
Both threads do redundant (or harmful) work, and the final cached value is whichever write lands last — nondeterministic.
What CPython's GIL does and doesn't protect
In CPython, individual bytecode operations on a dict — a single __getitem__ or __setitem__ — are protected by the GIL against structural corruption (no segfault, no torn pointer). What the GIL does not protect is the logical sequence of "read, compute, write." The GIL can be released between any two bytecodes, which is exactly the gap exploited above.
In a free-threaded Python build (3.13+) or in any other language without a GIL, even the individual dictionary operations are unsafe without explicit locks.
When does it actually matter?
- Idempotent, side-effect-free
expensive: duplicate calls waste time and resources but produce the correct final value. - Non-idempotent or costly
expensive(charges a card, inserts a row, returns a unique token): duplicate calls cause real harm. expensivecan raise: without careful handling, a failure inside one thread may leave a half-written state or block other threads waiting on a result that never arrives.
Part 2 — Two Approaches and a Recommendation
Approach A — Coarse lock around the whole function
import threading
cache = {}
lock = threading.Lock()
def compute(x):
with lock:
if x in cache:
return cache[x]
result = expensive(x) # lock held during the entire call
cache[x] = result
return result
What it guarantees: exactly one call to expensive(x) per key, ever. The dictionary is always consistent.
The cost: every call — even cache hits, even calls for completely different keys — must acquire the same lock. While one thread runs expensive, all other threads queue up. If expensive is slow (it is), throughput collapses to one inflight computation at a time. This is the right choice only when duplicate computation is never acceptable (e.g., the call charges a fee).
Exception safety is automatically fine here: if expensive raises, the with block exits cleanly, the lock releases, and nothing is written to the cache. The next caller will retry.
Approach B — Per-key locks with a double-checked pattern (recommended)
Allow computations for different keys to proceed in parallel, while still preventing two threads from computing the same key twice.
import threading
cache = {}
cache_lock = threading.Lock() # protects the cache dict and key_locks dict
key_locks = {} # one lock per in-flight key
def compute(x):
# Fast path: key already in cache (no lock needed for the read on CPython)
try:
return cache[x]
except KeyError:
pass
# Slow path: get or create the per-key lock
with cache_lock:
if x in cache: # double-check after acquiring
return cache[x]
if x not in key_locks:
key_locks[x] = threading.Lock()
klock = key_locks[x]
# Hold only the per-key lock while doing the expensive work
with klock:
with cache_lock: # check again — another thread may have finished
if x in cache:
return cache[x]
try:
result = expensive(x)
except Exception:
# Don't cache the failure; let the next caller retry
raise
finally:
with cache_lock:
key_locks.pop(x, None) # release the per-key slot
with cache_lock:
cache[x] = result
return result
What it guarantees:
- Two threads asking for the same key: one runs
expensive, the other waits onklock, then gets the cached result. - Two threads asking for different keys: both proceed concurrently.
- If
expensiveraises: thefinallyblock removes the per-key lock, the cache stays clean, and the exception propagates to both callers (the waiter will re-enter the slow path on its next call and retry).
The cost: slightly more code and a brief moment of contention on cache_lock when a new key first appears. For long-running expensive calls, this contention is negligible.
Comparison summary
| Coarse lock (A) | Per-key lock (B) | |
|---|---|---|
| Different keys in parallel | No | Yes |
| Duplicate computation prevented | Yes | Yes |
| Exception handling | Clean | Clean (with finally) |
| Code complexity | Low | Medium |
| Best when | Duplication is harmful, low concurrency | High concurrency, I/O-bound expensive |
Common mistakes to avoid
- Locking only the write (
cache[x] = result) but not the read-then-compute sequence — this prevents dictionary corruption but not duplicate work. - Caching exceptions (storing the traceback) — usually wrong unless retrying is more expensive than serving a cached failure.
- Forgetting the double-check after acquiring the lock — leads to duplicate computation despite holding a lock.
- Unbounded cache growth — in production, wrap the dict with an LRU policy (
functools.lru_cacheis thread-safe on CPython and handles this for you when a simpler solution is acceptable).