Caching: Not Computing Things Twice

Caching: Not Computing Things Twice in Python: The fastest code is code that does not run. Caching trades memory for time: store the result of an expensive…

Concept Explanation

The fastest code is code that does not run. Caching trades memory for time: store the result of an expensive operation, and return the stored value the next time the same input arrives.

It is the highest-leverage optimisation available because it changes complexity rather than constants. Naive recursive Fibonacci is O(2ⁿ); with a cache it is O(n). That is not a speedup, it is a different algorithm.

functools.cache — One Line

from functools import cache

@cache
def fib(n: int) -> int:
    return n if n < 2 else fib(n - 1) + fib(n - 2)

fib(35) takes seconds without the decorator and microseconds with it. @cache is unbounded; @lru_cache(maxsize=1024) evicts the least-recently-used entry when full, which is what you want for anything long-running.

Both add methods to the function:

fib.cache_info()     # CacheInfo(hits=33, misses=36, maxsize=None, currsize=36)
fib.cache_clear()    # empty it

cache_info() is how you tell whether a cache is earning its memory. A hit rate near zero means you are paying storage costs for nothing.

The Rules for What You Can Cache

A cached function must be pure: same input, same output, no side effects.

Safe to cacheNever cache
Pure computationAnything reading mutable global state
Parsing, formattingFunctions returning the current time
Deterministic lookupsFunctions with side effects (writes, emails)
Immutable argumentsFunctions returning mutable objects

Two traps in particular. Arguments must be hashable, so a list or dict argument raises TypeError: unhashable type — convert to a tuple or frozenset. And if the function returns a mutable object, every caller gets the same object, so one caller mutating it corrupts the cache for everyone. Return a tuple, or a copy.

Caching Methods Leaks Memory

class Service:
    @lru_cache(maxsize=128)     # WRONG
    def lookup(self, key): ...

The cache is on the class, and self is part of the key — so every instance ever passed is held alive forever. Use functools.cached_property for per-instance values, or put the cache on a module-level function.

cached_property

For an expensive attribute computed once per instance:

class Report:
    @cached_property
    def summary(self) -> dict:
        return expensive_aggregation(self.rows)

First access computes and stores it in the instance __dict__; later accesses are plain attribute reads. It requires the class to have a __dict__ (so not with __slots__).

Invalidation

Phil Karlton's line — "there are only two hard things in computer science: cache invalidation and naming things" — is a joke about a real problem. A cache returns stale data when the underlying source changes. The three strategies:

StrategyHowUse when
TTLEntries expire after n secondsData changes on a predictable schedule
ExplicitClear on writeYou control every writer
Key versioningInclude a version in the keyDistributed, no coordination

TTL is the pragmatic default: it bounds staleness without needing to know who changed what.

Beyond In-Process

functools.cache lives in one process. Restart and it is gone; run four workers and you have four separate caches. For anything shared, use Redis — which also gives you TTL, eviction policies, and persistence for free.


Code Example #1 (Basic)

The complexity change, and the hazards.

import time
from functools import cache, lru_cache


# --- Exponential without a cache, linear with one ---
def fib_slow(n: int) -> int:
    return n if n < 2 else fib_slow(n - 1) + fib_slow(n - 2)


@cache
def fib_fast(n: int) -> int:
    return n if n < 2 else fib_fast(n - 1) + fib_fast(n - 2)


start = time.perf_counter()
fib_slow(30)
slow = time.perf_counter() - start

start = time.perf_counter()
fib_fast(30)
fast = time.perf_counter() - start

print(f"fib(30) uncached: {slow * 1000:>9.2f} ms   (O(2^n), ~1.6M calls)")
print(f"fib(30) cached:   {fast * 1000:>9.4f} ms   (O(n), 31 calls)")
print(f"{slow / fast:,.0f}x faster -- and fib(200) is now instant: {fib_fast(200)}")
print(f"{fib_fast.cache_info()}\n")


# --- Bounded cache for long-running processes ---
@lru_cache(maxsize=3)
def expensive_lookup(key: str) -> str:
    time.sleep(0.05)                      # pretend this is a database query
    return f"value-for-{key}"


for key in ["a", "b", "c", "a", "d", "b"]:
    start = time.perf_counter()
    expensive_lookup(key)
    ms = (time.perf_counter() - start) * 1000
    print(f"  lookup({key!r}) {ms:>6.1f} ms  {'HIT' if ms < 10 else 'miss'}")

info = expensive_lookup.cache_info()
print(f"{info}")
print(f"hit rate: {info.hits / (info.hits + info.misses):.0%}")
print("  'b' was evicted when 'd' arrived -- maxsize=3, least-recently-used goes\n")


# --- Trap 1: unhashable arguments ---
@cache
def total(numbers):
    return sum(numbers)


print(f"tuple works: {total((1, 2, 3))}")
try:
    total([1, 2, 3])
except TypeError as exc:
    print(f"list fails:  {exc}")
print("  Fix: convert to a tuple at the call site, or wrap the function.\n")


# --- Trap 2: returning a mutable object ---
@cache
def get_config_bad(env: str) -> dict:
    return {"env": env, "retries": 3}


a = get_config_bad("prod")
a["retries"] = 99                          # caller mutates the CACHED dict
b = get_config_bad("prod")
print(f"second caller sees: {b}   <- corrupted by the first caller")


@cache
def _config_frozen(env: str) -> tuple:
    return (("env", env), ("retries", 3))


def get_config_good(env: str) -> dict:
    return dict(_config_frozen(env))       # a fresh dict every call


c = get_config_good("prod")
c["retries"] = 99
print(f"safe version:       {get_config_good('prod')}   <- unaffected")

The mutable-return trap is the one that causes real production bugs, because it works fine until a second caller appears. Cache immutable data and construct the mutable view per call.

Code Example #2 (Intermediate)

TTL, explicit invalidation, cached properties, and measuring whether it helped.

import functools
import hashlib
import json
import random
import threading
import time
from collections import OrderedDict
from functools import cached_property


# ==================== A TTL cache with statistics ====================
class TTLCache:
    """Thread-safe, size-bounded, time-expiring cache."""

    def __init__(self, maxsize: int = 256, ttl: float = 30.0):
        self.maxsize, self.ttl = maxsize, ttl
        self._data: OrderedDict[str, tuple[float, object]] = OrderedDict()
        self._lock = threading.Lock()
        self.hits = self.misses = self.expired = self.evicted = 0

    def get(self, key):
        with self._lock:
            entry = self._data.get(key)
            if entry is None:
                self.misses += 1
                return None
            stored_at, value = entry
            if time.monotonic() - stored_at > self.ttl:
                del self._data[key]
                self.expired += 1
                self.misses += 1
                return None
            self._data.move_to_end(key)         # mark as recently used
            self.hits += 1
            return value

    def set(self, key, value):
        with self._lock:
            self._data[key] = (time.monotonic(), value)
            self._data.move_to_end(key)
            while len(self._data) > self.maxsize:
                self._data.popitem(last=False)  # drop the oldest
                self.evicted += 1

    def invalidate(self, prefix: str = "") -> int:
        """Explicit invalidation -- clear everything under a key prefix."""
        with self._lock:
            doomed = [k for k in self._data if k.startswith(prefix)]
            for k in doomed:
                del self._data[k]
            return len(doomed)

    @property
    def stats(self) -> dict:
        total = self.hits + self.misses
        return {"hits": self.hits, "misses": self.misses,
                "hit_rate": round(self.hits / total, 3) if total else 0.0,
                "expired": self.expired, "evicted": self.evicted,
                "size": len(self._data)}


def cached(store: TTLCache, prefix: str):
    """Decorator that routes a function through a TTLCache."""
    def decorator(fn):
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            # A stable key from the arguments, hashable or not
            payload = json.dumps([args, sorted(kwargs.items())],
                                 sort_keys=True, default=str)
            key = f"{prefix}:{hashlib.sha256(payload.encode()).hexdigest()[:16]}"
            hit = store.get(key)
            if hit is not None:
                return hit
            value = fn(*args, **kwargs)
            store.set(key, value)
            return value
        wrapper.cache_key_prefix = prefix
        return wrapper
    return decorator


product_cache = TTLCache(maxsize=64, ttl=2.0)
_db_calls = 0


@cached(product_cache, prefix="product")
def fetch_product(product_id: int) -> dict:
    global _db_calls
    _db_calls += 1
    time.sleep(0.02)                            # a database round trip
    return {"id": product_id, "name": f"Widget {product_id}", "price": 19.99}


print("=== TTL cache ===")
random.seed(2)
for _ in range(60):
    fetch_product(random.choice([1, 2, 3, 1, 1, 2]))
print(f"  60 calls, {_db_calls} actually hit the database")
print(f"  {product_cache.stats}")

print("\n  waiting for the 2s TTL to expire...")
time.sleep(2.1)
fetch_product(1)
print(f"  after expiry: {product_cache.stats}")

print(f"\n  explicit invalidation cleared {product_cache.invalidate('product')} entries")


# ==================== cached_property ====================
class SalesReport:
    def __init__(self, rows: list[dict]):
        self.rows = rows
        self._computations = 0

    @cached_property
    def summary(self) -> dict:
        """Computed on first access, then stored in the instance __dict__."""
        self._computations += 1
        time.sleep(0.05)
        total = sum(r["amount"] for r in self.rows)
        return {"count": len(self.rows), "total": round(total, 2),
                "mean": round(total / len(self.rows), 2)}

    def invalidate(self) -> None:
        # The cached value lives in __dict__ -- deleting it forces a recompute
        self.__dict__.pop("summary", None)


report = SalesReport([{"amount": random.random() * 100} for _ in range(5_000)])

print("\n=== cached_property ===")
for i in range(3):
    start = time.perf_counter()
    report.summary
    print(f"  access {i + 1}: {(time.perf_counter() - start) * 1000:>7.2f} ms")
print(f"  computed {report._computations} time(s) across 3 accesses")

report.rows.append({"amount": 500.0})
report.invalidate()                             # data changed -> drop the cache
print(f"  after invalidate + new row: count={report.summary['count']}")
print(f"  computed {report._computations} time(s) total")


# ==================== The method-cache memory leak ====================
print("\n=== Why @lru_cache on a method leaks ===")


class LeakyService:
    @functools.lru_cache(maxsize=128)           # WRONG: keyed on self
    def lookup(self, key: str) -> str:
        return f"{id(self)}:{key}"


for i in range(3):
    LeakyService().lookup("x")                  # instances cannot be collected
print(f"  cache holds {LeakyService.lookup.cache_info().currsize} entries "
      f"-- one per instance, each keeping that instance alive forever")
print("  Fix: cached_property for per-instance values, or a module-level cached function.")

The stats property is the part to copy into real code. A cache with a 5% hit rate is pure overhead — it costs memory and lookup time and saves nothing. Without measuring, you cannot tell that from a cache doing its job, and teams routinely keep both.


Common Mistakes

  1. Caching an impure function: anything reading a database, the clock, or mutable global state will return stale results forever.
  2. @lru_cache on a method: self becomes part of the key, so every instance is retained. Memory leak.
  3. Unhashable arguments: lists and dicts raise TypeError. Convert to tuples or hash a serialised form.
  4. Returning a mutable object from a cached function: one caller's mutation corrupts every future caller.
  5. Unbounded @cache in a long-running service: memory grows without limit. Use lru_cache(maxsize=...).
  6. No invalidation strategy: the cache is correct on day one and lying by day three.
  7. Never checking cache_info(): a low hit rate means you are paying for nothing.
  8. Caching something cheap: if the function takes a microsecond, the cache lookup costs more than the call.
  9. Assuming a process-local cache is shared: four Gunicorn workers means four caches and a 4× miss rate on first requests.
  10. Caching per-user data under a global key: the classic security bug — user B receives user A's cached response. Include the user id in the key.
  11. No lock around a cache in threaded code: concurrent writes can corrupt the structure.

Best Practices

  • Cache pure functions only. If it touches the clock, the database, or a global, it is not a caching candidate as written.
  • Prefer @lru_cache(maxsize=...) over @cache in anything long-running.
  • Check cache_info() in development and delete caches whose hit rate does not justify them.
  • Use cached_property for expensive per-instance attributes — never lru_cache on a method.
  • Give every cache entry a TTL unless you control every writer and invalidate explicitly.
  • Include everything that affects the result in the key: user id, locale, tenant, feature flags.
  • Return immutable values — tuples, frozensets, or a fresh copy per call.
  • Cache at the highest level that is still correct: caching a whole rendered response beats caching six sub-queries.
  • Use Redis when the cache must outlive the process or be shared between workers.
  • Measure before and after with realistic access patterns; a cache tested on repeated identical inputs always looks brilliant.
  • Log or expose the hit rate in production so you notice when it collapses.

Practice Exercises

  1. The Complexity Change: Time fib(32) with and without @cache, then print cache_info(). Explain in a comment why this is a change in complexity rather than a constant-factor speedup.
  2. The Mutation Bug: Write a @cache-decorated function returning a dict, mutate the result in one caller, and show a second caller receiving the corrupted value. Then fix it and prove the fix works.
  3. The TTL Cache: Implement a cache with a 3-second TTL and a hit-rate counter, wrap a function that sleeps 50 ms, call it 40 times with 5 distinct arguments, and report the hit rate before and after the TTL expires.