KatInterview

Making a Memoizing Python Function Safe for Many Threads

Data Structure DesignModel answer
MediumModel answerData Structure Designpythonconcurrencycaching

Last 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_call have 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.