ML Foundations

Python cache is thread-safe but not single-flight

functools.cache keeps its internal mapping coherent across threads, but simultaneous misses may call the wrapped function more than once.

Example results for Python cache is thread-safe but not single-flight. results: 49 49
Illustration: Original illustration by Tensor Almanac
Evidence and testing

Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.

Thread-safe does not promise one computation per key

`functools.cache` protects the integrity of its internal cache data structure when multiple threads use the wrapped function. That guarantee is commonly described as thread-safe. It does not guarantee that only one thread computes a missing key. If concurrent calls arrive before the first result is cached, the wrapped function may run more than once for that key. [1]

That distinction matters when the function performs expensive work or a side effect. A coherent cache can still allow duplicate in-flight misses. Treat caching as reuse of completed results, not automatically as a per-key lock or a single-flight request coordinator. The documented behavior is explicit about possible repeated calls during a race. [1, 2]

References: [1], [2]

Verify ordinary reuse without implying concurrency behavior

The example wraps a small deterministic calculation with `cache`, calls it twice sequentially for the same key, and counts function executions. The cached result is returned the second time without another call. This tests ordinary reuse of a completed value; it does not attempt to create a thread race. [1]

When designing a single-flight layer, coordinate in-progress work separately from storing completed values. For example, a per-key future or lock can let later callers wait for the first calculation. That design recommendation is engineering guidance; the standard-library cache itself does not supply that stronger behavior. [1, 2]

Executed with Python 3.12.14, standard library only; assertions passed.

"""Show a sequential cache hit; thread safety is not single-flight."""
from functools import cache

calls = [0]
@cache
def compute(key):
    calls[0] += 1
    return key * key

first = compute(7)
second = compute(7)
print("results:", first, second)
print("function executions:", calls[0])
assert (first, second) == (49, 49)
assert calls[0] == 1

Recorded output

results: 49 49
function executions: 1

References: [1], [2]

Keep cache semantics and side effects separate

A function passed to a cache should generally be safe to call again for the same arguments because simultaneous misses are allowed to repeat work. If it sends a payment, writes a unique record, or performs another non-idempotent action, a cache hit is not a substitute for deduplication. The cache documentation describes result reuse and thread safety, not transactional exactly-once execution. [1, 2]

This guide covers `functools.cache` and its equivalent unbounded `lru_cache` behavior. It does not benchmark contention, specify a scheduling order, or implement a single-flight wrapper. The local example confirms only a sequential cache hit, and the concurrency limitation is taken from the official documentation. [1]

References: [1], [2]

Sources

  1. Python: functools.cache
  2. Python: functools.lru_cache