KatInterview

Thread-Safe Memoization: Fixing a Shared Cache for Concurrent Callers

System DesignModel answer
MediumModel answerSystem Designconcurrencythreadingpython

Last 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 expensive mostly 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 expensive is 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 expensive raises, 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.