IC Improve Code Recipes

Recipe 3.1 · Python

Cache-Aside with GetOrCreateAsync

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

A list of countries, tax rates or product categories is read on every request and changes a few times a year. Reading it from the database each time is wasteful. The usual hand-written cache around it has race conditions and never expires.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

The data never expires, so a new country requires an application restart. Two threads that miss at the same moment both load. Hashtable tolerates one writer with many readers, but a Dictionary swapped in later during a "modernization" would corrupt itself under concurrent writes. And the cast at the end will break the first time someone stores the wrong type under that key.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Static dictionary cache with check-then-read and no expiry (p060_r3_1_static_hashtable_cache_before.py)
"""Static dictionary cache with check-then-read and no expiry

Source: ImproveCode, Chapter 3, Recipe 3.1 "Cache-Aside with GetOrCreateAsync"
Section: The way it's often written
Book page: 60  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
Hashtable -> module-level dict; DataTable -> untyped list of rows.
"""

from typing import Any


class CountryData:
    @staticmethod
    def load_all() -> list[Any]:
        raise NotImplementedError


# Not to copy: static dictionary, check-then-read, no expiry.
class CountryCache:
    _cache: dict[str, Any] = {}

    @staticmethod
    def get_countries() -> list[Any]:
        if CountryCache._cache.get("Countries") is None:
            CountryCache._cache["Countries"] = CountryData.load_all()
        return CountryCache._cache["Countries"]

The improved recipe

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Cache-aside: get-or-create the country list with a 6-hour expiry (p060_r3_1_cache_aside_get_or_create.py)
"""Cache-aside: get-or-create the country list with a 6-hour expiry

Source: ImproveCode, Chapter 3, Recipe 3.1 "Cache-Aside with GetOrCreateAsync"
Section: The improved recipe
Book page: 60-61  -- original C# listing
Converted from C# to Python.
IMemoryCache -> the small MemoryCache below (dict + lock, per-entry absolute/sliding expiry, size
limit, change tokens) since cachetools has no per-entry options; later Chapter 3 files import it.
Like IMemoryCache.GetOrCreateAsync, get_or_create does NOT prevent concurrent duplicate loads.
"""

import threading
import time
from collections.abc import Awaitable, Callable, Hashable
from dataclasses import dataclass, field
from datetime import timedelta
from typing import Any, Protocol


class ChangeToken(Protocol):
    """Equivalent of IChangeToken: once has_changed is True the entry expires."""

    @property
    def has_changed(self) -> bool: ...


@dataclass
class CacheEntry:
    key: Hashable
    value: Any = None
    absolute_expiration_relative_to_now: timedelta | None = None
    sliding_expiration: timedelta | None = None
    size: int | None = None
    expiration_tokens: list[ChangeToken] = field(default_factory=list)
    _created: float = field(default_factory=time.monotonic)
    _last_access: float = field(default_factory=time.monotonic)

    def add_expiration_token(self, token: ChangeToken) -> None:
        self.expiration_tokens.append(token)

    def is_expired(self, now: float) -> bool:
        if any(t.has_changed for t in self.expiration_tokens):
            return True
        ttl = self.absolute_expiration_relative_to_now
        if ttl is not None and now - self._created >= ttl.total_seconds():
            return True
        slide = self.sliding_expiration
        return slide is not None and now - self._last_access >= slide.total_seconds()


class MemoryCache:
    """Minimal in-process stand-in for Microsoft.Extensions.Caching.Memory.MemoryCache."""

    def __init__(self, size_limit: int | None = None,
                 compaction_percentage: float = 0.05,
                 track_statistics: bool = False) -> None:
        self._entries: dict[Hashable, CacheEntry] = {}
        self._lock = threading.Lock()
        self.size_limit = size_limit
        self.compaction_percentage = compaction_percentage
        self.track_statistics = track_statistics

    def try_get(self, key: Hashable) -> tuple[bool, Any]:
        now = time.monotonic()
        with self._lock:
            entry = self._entries.get(key)
            if entry is None:
                return False, None
            if entry.is_expired(now):
                del self._entries[key]
                return False, None
            entry._last_access = now
            return True, entry.value

    def set(self, key: Hashable, value: Any, time_to_live: timedelta | None = None,
            size: int | None = None) -> None:
        self._store(CacheEntry(key, value, time_to_live, size=size))

    def remove(self, key: Hashable) -> None:
        with self._lock:
            self._entries.pop(key, None)

    async def get_or_create[T](self, key: Hashable,
                               factory: Callable[[CacheEntry], Awaitable[T]]) -> T:
        found, value = self.try_get(key)
        if found:
            return value
        entry = CacheEntry(key)
        entry.value = await factory(entry)
        self._store(entry)
        return entry.value

    @property
    def current_entry_count(self) -> int:
        with self._lock:
            return len(self._entries)

    def dispose(self) -> None:
        with self._lock:
            self._entries.clear()

    def _store(self, entry: CacheEntry) -> None:
        with self._lock:
            if self.size_limit is not None:
                if entry.size is None:
                    raise ValueError("Cache entry must specify a size when size_limit is set.")
                self._entries.pop(entry.key, None)
                if self._used() + entry.size > self.size_limit:
                    self._compact()
                    if self._used() + entry.size > self.size_limit:
                        return  # like MemoryCache: entry is not added
            self._entries[entry.key] = entry

    def _used(self) -> int:
        return sum(e.size or 0 for e in self._entries.values())

    def _compact(self) -> None:
        now = time.monotonic()
        for k in [k for k, e in self._entries.items() if e.is_expired(now)]:
            del self._entries[k]
        count = int(len(self._entries) * self.compaction_percentage)
        oldest = sorted(self._entries.values(), key=lambda e: e._last_access)
        for e in oldest[:count]:
            del self._entries[e.key]


# --- The recipe ---

@dataclass(frozen=True)
class Country:
    code: str
    name: str


class CountryRepository(Protocol):
    async def get_all(self) -> list[Country]: ...


class CountryService:
    CACHE_KEY = "countries:all"

    def __init__(self, cache: MemoryCache, repository: CountryRepository) -> None:
        self._cache = cache
        self._repository = repository

    async def get_all(self) -> list[Country]:
        async def create(entry: CacheEntry) -> list[Country]:
            entry.absolute_expiration_relative_to_now = timedelta(hours=6)
            return await self._repository.get_all()

        countries: list[Country] | None = await self._cache.get_or_create(
            self.CACHE_KEY, create)

        return countries or []

How it works

Cache-aside means the application owns the logic: look in the cache, and on a miss, load from the source and put the result in the cache. GetOrCreateAsync packages that into one call. It returns the cached value if there is one. Otherwise it creates a cache entry, runs your factory, stores the result and returns it.

The factory receives the ICacheEntry, which is where you set the entry's lifetime. Here the list lives for six hours, then the next request reloads it. Six hours is a business decision, not a technical one: ask how stale this data is allowed to be, and write that number down in the code.

The cached type is an immutable record in a read-only list. That matters more than it looks. IMemoryCache stores a reference, not a copy, so every caller gets the same object. If the cached value were a List<Country> or a DataTable, one caller could add or remove a row and change the data for everyone else. Cache immutable things.

Register the cache once with builder.Services.AddMemoryCache(); and the service as a singleton or scoped service, depending on its other dependencies.

Variations and pitfalls

  • GetOrCreateAsync returns TItem?. The factory might return null, and the cache stores it. The ?? [] turns that into an empty list so callers never see null.
  • The factory is not locked. Two requests that miss at the same moment both run the factory, and the second result wins. For cheap loads that is fine. For expensive ones, see Recipe 3.4.
  • Capturing the token. The factory uses the token of the request that happened to miss. If that request is cancelled, the load fails, nothing is cached, and the next request tries again. That is acceptable for small loads. The single-flight cache in Recipe 3.4 shows how to decouple the shared load from any one caller.
  • Do not cache per-user data under a shared key. A key like "orders" that holds the current user's orders will show them to the next user. Put the user or tenant ID in the key.

On .NET Framework

Microsoft.Extensions.Caching.Memory supports .NET Framework 4.6.2 and later through .NET Standard 2.0, so the same code works there. System.Runtime.Caching.MemoryCache is the older built-in option; it works, but its API is string-keyed and synchronous.