Making a Memoizing Python Function Safe for Many Threads
Data Structure DesignModel answerLast updated
Critique a Python function that caches expensive results in a dict, then make it thread-safe so each input is computed once, without blocking cache hits or unrelated inputs.
A teammate opens a pull request containing the helper below. You are asked to review it, knowing that it will be invoked from many threads inside one Python process.
results = {}
def fetch(key):
if key in results:
return results[key]
value = slow_call(key)
results[key] = value
return value
slow_call is slow and deterministic. Treat the questions below as a progression, as if a reviewer were pressing you for more detail at each step.
Questions to raise first
Before reviewing, state which assumptions you would check:
- Does
slow_callhave side effects, or is a repeated call merely wasteful? - Are the callers threads in a single process, or multiple processes or hosts?
- Should an exception be remembered, or should the next caller try again?
- Does the cache need a size limit?
- Which runtime is in use: standard CPython with a GIL, or a free-threaded build?
Part 1: First review pass
What would you flag, given concurrent callers? Illustrate the main problem with a concrete timeline of events, and mention any non-concurrency comments too.
Part 2: Compute each key at most once
Revise the function so that simultaneous callers asking for the same key trigger slow_call only one time. Explain why it stays correct when several threads miss at the same instant, including what threads that were waiting on the lock do once the first computation completes.
Part 3: Placing the lock
Which lines should sit inside the lock? Discuss what goes wrong when the lock is too wide and when it is too narrow, and propose a refinement so that work on different keys does not block each other.
Part 4: Dictionaries and concurrency
What does CPython guarantee when several threads read and write a dict simultaneously? Can a reader see the old value, the new value, or something partially updated? Why does a check followed by an action remain unsafe even if each dict operation is individually safe?
Hints
Hint 1
Write out a timeline with two threads that both evaluate the membership test before either one stores a result. What does each thread do next?
Hint 2
A single global lock around the whole function is correct but wasteful. Think about a fast path that reads without the lock, and a re-check after acquiring it.
Hint 3
To avoid blocking different keys, keep a small lock (or a placeholder object such as a Future or Event) per key, and guard only the creation of that placeholder with the global lock.
Hint 4
Individual dict operations are atomic in CPython because of the GIL (or per-object locks in free-threaded builds), but a sequence of two operations is not atomic as a whole.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Review comments
Main problem: a check-then-act race. The membership test and the store are separate steps, so nothing links them.
Timeline for the same key k:
- Thread A evaluates
k in resultsand gets False. - Thread B evaluates
k in resultsand also gets False, since A has not stored anything yet. - Both call
slow_call(k). - Both write
results[k]; the last writer wins.
With a deterministic, side-effect-free function, the result is only wasted work. Under a burst of identical requests (a cache stampede), cost can multiply by the number of threads, which is exactly when the cache was supposed to help. If slow_call has side effects (charging a card, writing to an external system), the duplicate is a real bug.
Other comments:
- The cache is unbounded, so memory grows with every distinct key. Consider
functools.lru_cacheor a size or TTL policy. - Exceptions: nothing is cached on failure, which is usually right, but any placeholder-based fix must remove failed entries so waiters do not hang or inherit a stale error forever.
- The global name
resultsis shared mutable state, which is hard to test. Wrap it in a class or closure. - Keys must be hashable.
- An in-process lock does nothing across processes or hosts. That needs a shared cache (for example Redis) with a lock or a single-flight mechanism.
Part 2: Single computation per key
Simplest correct version, using double-checked locking:
import threading
results = {}
lock = threading.Lock()
def fetch(key):
if key in results: # fast path, no lock
return results[key]
with lock:
if key in results: # re-check under the lock
return results[key]
value = slow_call(key)
results[key] = value
return value
Why it works: only one thread at a time can be inside the with block. The first thread to enter computes and stores the value. Every thread that was waiting then enters one by one, repeats the check, finds the key present, and returns without computing. The re-check is essential: without it, each waiter would recompute after acquiring the lock, giving the same duplication as before. The store must be inside the lock so that the re-check by the next thread observes it.
The unlocked fast-path read is safe in CPython because in and [] on a dict are each atomic, and a key is only ever added, never changed to a partial state (see Part 4).
Part 3: Where the lock goes
- Too wide (lock around the whole function, including the hit path): every cache hit queues behind any running computation. Throughput collapses to one call at a time, and a slow computation for key A stalls fast hits for key B. The version above avoids the hit-path cost but still has a flaw: misses for different keys serialize, because one lock covers all computations.
- Too narrow (locking only the dict read and the dict write separately): this protects the dict's structure but not the logic. Two threads can still both miss and both compute, so the original race remains.
Refinement: per-key single-flight. Hold the global lock only briefly, to look up or create a per-key placeholder, then compute outside it.
import threading
results = {}
inflight = {}
guard = threading.Lock()
def fetch(key):
if key in results:
return results[key]
with guard:
if key in results:
return results[key]
entry = inflight.get(key)
if entry is None:
entry = inflight[key] = threading.Event()
owner = True
else:
owner = False
if owner:
try:
results[key] = slow_call(key)
finally:
with guard:
del inflight[key]
entry.set()
return results[key]
entry.wait()
return fetch(key) # retry: hits if the owner succeeded, otherwise becomes the new owner
The owner computes without holding guard, so different keys run in parallel and hits never wait. Waiters block only on the event for their own key. If the owner fails, the finally clause releases waiters, and one of them retries. (A concurrent.futures.Future stored per key is an equivalent design that can also propagate the exception to waiters instead of retrying.)
Trade-off: more code and more states to get right. If computations for different keys are rare or short, the single lock version is acceptable and easier to reason about.
Part 4: Dicts under concurrency
In CPython, individual operations such as key in d, d[key], and d[key] = v are atomic. The GIL ensures that one bytecode-level operation on the dict completes without another thread interleaving inside it, so the internal structure is never corrupted. Free-threaded builds provide the same per-operation safety using per-object locks. Treat this as an implementation detail of the runtime, not a language-level promise you want to build a design on.
A concurrent reader sees either the old state or the new state of a single operation, never a half-written value. Reading results[k] during a write returns either the previous value (or a missing-key result) or the new one. It cannot see something in between.
However, atomic operations do not compose. The sequence "check, compute, store" spans many operations and the interpreter can switch threads between any two of them. The GIL therefore does not make the original code thread-safe; it only prevents dict corruption, not the logical race. Likewise, d[k] += 1 is a read followed by a write and can lose updates.
Common mistakes
- Claiming the GIL makes the function safe.
- Locking but omitting the re-check after acquisition.
- Holding one lock across all computations and calling it done without mentioning the throughput cost.
- Forgetting cleanup of placeholders on exceptions, which leaves waiters blocked forever.
- Ignoring unbounded growth and multi-process deployments.
In practice, prefer a vetted tool (functools.lru_cache for simple cases, noting it does not guarantee single execution under concurrent misses, or a library offering single-flight semantics) over hand-rolled locking when possible.