IC Improve Code Recipes

Recipe 3.3 · Python

Invalidation

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 user updates a price list and immediately reloads the page. The cache still holds the old list for another 25 minutes, the user files a bug, and someone "fixes" it by turning the cache off. Expiration alone cannot give read-your-writes behavior. When the application knows the data changed, it should say so.

The way it's often written

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

This walks every entry in the cache, depends on everyone spelling the prefix the same way, and it is often called before the database transaction commits, so a concurrent request can reload the old data in between.

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

Python Clearing cached prices by enumerating the whole cache (p065_r3_3_clear_cache_by_enumeration_before.py)
"""Clearing cached prices by enumerating the whole cache

Source: ImproveCode, Chapter 3, Recipe 3.3 "Invalidation"
Section: The way it's often written
Book page: 65  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
HttpRuntime.Cache -> a process-wide dict; enumeration uses a snapshot of the items, as the
ASP.NET cache enumerator does.
"""

from typing import Any

HTTP_RUNTIME_CACHE: dict[str, Any] = {}


# Not to copy: clearing everything by enumerating the cache.
def clear_price_cache() -> None:
    for key, _ in list(HTTP_RUNTIME_CACHE.items()):
        if key.startswith("Price"):
            HTTP_RUNTIME_CACHE.pop(key, None)

The improved recipe

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

Python Invalidate one price list by key, or all of them with a reset token (p065_r3_3_price_list_invalidation_tokens.py)
"""Invalidate one price list by key, or all of them with a reset token

Source: ImproveCode, Chapter 3, Recipe 3.3 "Invalidation"
Section: The improved recipe
Book page: 65-66  -- original C# listing
Converted from C# to Python.
IMemoryCache -> MemoryCache stand-in from the Recipe 3.1 file; CancellationTokenSource +
CancellationChangeToken -> a ResetSignal wrapping threading.Event, registered as an entry's
expiration token; lock(_gate) -> threading.Lock.
"""

import threading
from dataclasses import dataclass
from datetime import timedelta
from decimal import Decimal
from typing import Protocol

from p060_r3_1_cache_aside_get_or_create import CacheEntry, MemoryCache


class ResetSignal:
    """CancellationTokenSource + CancellationChangeToken in one object."""

    def __init__(self) -> None:
        self._event = threading.Event()

    def cancel(self) -> None:
        self._event.set()

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


@dataclass(frozen=True)
class PriceList:
    customer_group: str
    prices: dict[str, Decimal]


class PriceListRepository(Protocol):
    async def load(self, customer_group: str) -> PriceList: ...


class PriceListCache:
    def __init__(self, cache: MemoryCache, repository: PriceListRepository) -> None:
        self._cache = cache
        self._repository = repository
        self._gate = threading.Lock()
        self._reset = ResetSignal()

    async def get(self, customer_group: str) -> PriceList | None:
        reset_token = self._current_reset_token()

        async def create(entry: CacheEntry) -> PriceList:
            entry.absolute_expiration_relative_to_now = timedelta(minutes=30)
            entry.add_expiration_token(reset_token)
            return await self._repository.load(customer_group)

        return await self._cache.get_or_create(self._key(customer_group), create)

    # Call after the database change has committed.
    def invalidate(self, customer_group: str) -> None:
        self._cache.remove(self._key(customer_group))

    # Expires every price list at once, e.g. after a bulk import.
    def invalidate_all(self) -> None:
        with self._gate:
            old = self._reset
            self._reset = ResetSignal()
        # Entries created moments ago may still hold the old signal;
        # cancelling it expires them too.
        old.cancel()

    def _current_reset_token(self) -> ResetSignal:
        with self._gate:
            return self._reset

    @staticmethod
    def _key(customer_group: str) -> str:
        return "pricelist:" + customer_group.upper()

How it works

There are two kinds of invalidation here. Invalidate removes one key, for the common case where one customer group's prices changed. Because the key is built by one private method, the code that writes and the code that reads cannot disagree about its spelling.

InvalidateAll handles the case where everything changed. Every entry is created with an expiration token linked to the current CancellationTokenSource. Cancelling that source expires all the entries that were linked to it in one step, without enumerating the cache. The next reads miss, reload and link themselves to the new source. The lock makes swapping the source safe when several threads call GetAsync and InvalidateAll at the same time.

The class holds state, so register it as a singleton: services.AddSingleton<PriceListCache>();.

The order of operations matters. Commit the database change first, then invalidate. If you invalidate first, a request that arrives between the two steps reloads the old data from the database and caches it again for another 30 minutes.

Variations and pitfalls

  • Several web servers. IMemoryCache lives in one process. Invalidating on server A does nothing for server B. Either keep lifetimes short enough that the staleness is acceptable, move the data to a distributed cache (Recipe 3.5), or broadcast invalidations, for example with a Redis pub/sub channel that every server subscribes to.
  • Versioned keys. Another way to invalidate a group is to put a version number in the key (pricelist:v7:RETAIL) and increment it. Old entries become unreachable and age out. This works well in distributed caches, where there is no cancellation token to share.
  • Database-driven invalidation. SqlDependency and query notifications can tell you when data changed, but they are fragile and need Service Broker. I prefer invalidating from the code that makes the change, plus an absolute expiration as a safety net for changes made outside the application.
  • Never rely on invalidation alone. Somebody will update the table by hand. Every cached entry still gets an absolute expiration.