Skip to main content

Caching expensive calls

The cache-aside pattern, and memoize, a decorator that caches a function’s results.

The page takes 900 ms, and 850 of them are one query that returns the same ten rows it returned a second ago. Everyone has met this page. Caching is how you stop paying for the same answer twice: before doing something slow (a database query, an API call, rendering a big page), ask the cache. If it knows, you’re done in a microsecond or two. If not, do the work and leave the answer for whoever asks next, which with a shared directory means every worker process on the machine, today and after the next restart.

Cache-aside

import tempfile
import time

from diskcache_oxide import Cache

cache = Cache(tempfile.mkdtemp(), timeout=1.0, durable=True)  # an outage is a miss, not an error

def load_popular_episodes() -> list[dict]:
    time.sleep(0.2)  # stands in for a slow database query
    return [{'id': 512, 'title': 'Rust for Python developers'}]

def popular_episodes() -> list[dict]:
    episodes = cache.get('episodes:popular')
    if episodes is None:
        episodes = load_popular_episodes()
        cache.set('episodes:popular', episodes, expire=300)
    return episodes

start = time.perf_counter()
popular_episodes()
print(f'first call:  {(time.perf_counter() - start) * 1000:.1f} ms')

start = time.perf_counter()
for _ in range(1000):
    popular_episodes()
print(f'cached:      {(time.perf_counter() - start) * 1000:.1f} µs per call')  # 1000 calls, so ms total = µs each
first call:  202.1 ms
cached:      1.2 µs per call

Always give cached values an expire. It bounds how stale a value can get if an invalidation is ever missed.

When None is a real value

If the function can legitimately return None, cache.get(key) can’t tell “cached as None” from “not cached”, and you’ll recompute every time. Use a sentinel default:

MISSING = object()

value = cache.get(key, default=MISSING)
if value is MISSING:
    value = compute()
    cache.set(key, value, expire=300)

A caching decorator: memoize

The same pattern wrapped up for reuse. memoize keys each call on the function’s full name and its arguments, and caches None results too.

calls = 0

@cache.memoize(expire=600)
def episode_details(episode_id: int, *, include_transcript: bool = False) -> dict:
    global calls
    calls += 1
    return {'id': episode_id, 'transcript': include_transcript}

episode_details(512)
episode_details(512)
episode_details(512, include_transcript=True)
print(f'{calls} real calls for 3 lookups')

# The key a call uses, to forget one result:
print(episode_details.__cache_key__(512))
cache.delete(episode_details.__cache_key__(512))
2 real calls for 3 lookups
('__main__.episode_details', 512, None)
True

Call it with parentheses, @cache.memoize(), even with no options. It’s diskcache’s memoize, with the same keys, so code written for diskcache keeps working.

A few things to keep in mind:

  • Arguments become part of the key, so they must be key types: str, bytes, int, float, bool, None, or tuples of those. Anything else (a list, a date, a UUID, an enum member, an object) raises TypeError before the function runs, and registering a type with register_type() doesn’t change that: registered types are for values. Pass str(user_id) for a UUID, plan.value for an enum, and a tuple instead of a list.
  • Leave out arguments that don’t change the answer, like a database connection, with ignore=. It takes keyword names and positions: ignore=('db',) drops db when it’s passed as db=..., and ignore=(0,) drops the first positional argument.
  • Keyword and positional calls are different entries: f(1, 2) and f(1, b=2) are cached separately, as in diskcache. Keys compare by exact type, so f(1), f(1.0) and f(True) are three entries too.
  • Return values must be storable, which means built-in types (dicts, lists, tuples, sets, datetimes and so on). A dataclass or Pydantic model raises TypeError at set() until you register it once with register_type() (see Storing your own types); return a dict instead, or use a cache opened with pickle=True. See Serialization.
  • async def functions are refused with TypeError, since the decorator would cache the coroutine object. Cache inside the coroutine with get and set instead, as Using the cache from asyncio shows.
  • tag= tags every result it stores, so cache.evict(tag) forgets them all at once. See Invalidating groups of keys.
  • Long keys are fine. A key is just indexed bytes.

Thundering herds

When a popular entry expires, every worker that asks for it in the next moment misses at the same time, and all of them recompute it. For most values that’s harmless. When the computation is expensive enough that doing it eight times at once hurts, memoize_stampede keeps the herd from forming. It’s memoize with early recomputation: as a result gets close to its expiry, each call has a growing chance of recomputing it, and the first caller to do so starts the work in a background thread while every caller, that one included, keeps getting the cached result. The chance grows with how long the function took last time, so a slow function starts its refresh earlier.

from diskcache_oxide import memoize_stampede

renders = 0

@memoize_stampede(cache, expire=300)
def front_page(region: str) -> dict:
    global renders
    renders += 1
    return {'region': region, 'episodes': [512, 513]}

front_page('us')
front_page('us')
print(f'{renders} render for 2 calls')
cache.delete(front_page.__cache_key__('us'))   # forget one result, as with memoize
1 render for 2 calls
True

What to know about it:

  • It’s a function that takes the cache first, and expire is required: memoize_stampede(cache, expire=300). It also takes name, typed, tag and ignore, with memoize’s meanings and argument rules, and beta (default 1), where a larger value starts refreshes earlier.
  • It protects an entry that exists. On a real miss (the first call, or after the entry was evicted or deleted), every caller that arrives before the first one finishes runs the function, as with memoize. If that first computation is the expensive part, warm the entry from a job at startup, or have callers compute it under a Lock.
  • Results are stored as (result, seconds it took). Read them through the decorated function, not with cache.get().
  • “Close to expiry” is measured with time.time(), as diskcache does, even on a cache opened with a clock=.
  • It works on a NullCache (every call runs the function) and on a durable=True cache, where an outage runs the function too.

When the expensive keys are known in advance, a scheduled job that refreshes them ahead of expiry also works and keeps readers from ever seeing a miss; see Running a job once across workers and Serving stale values while refreshing.