Recipe 3.2 · Python
Expiration and Size Limits
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
An in-memory cache with no limits is a memory leak with a nicer name. A cache of product details keyed by product ID grows with every product anyone views, and on a catalog of two million products the web server eventually spends more time in garbage collection than serving pages. Meanwhile items that nobody has asked for in days stay in memory.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Unbounded product cache that never evicts
Source: ImproveCode, Chapter 3, Recipe 3.2 "Expiration and Size Limits"
Section: The way it's often written
Book page: 62 -- 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 with NoAbsoluteExpiration/NoSlidingExpiration -> a process-wide dict.
"""
from typing import Any
HTTP_RUNTIME_CACHE: dict[str, Any] = {}
class ProductData:
@staticmethod
def load(id: int) -> Any:
raise NotImplementedError
# Not to copy: unbounded and never evicted.
def get_product(id: int) -> Any:
key = "Product_" + str(id)
cached = HTTP_RUNTIME_CACHE.get(key)
if cached is not None:
return cached
cached = ProductData.load(id)
HTTP_RUNTIME_CACHE[key] = cached # no expiration of any kind
return cached
The improved recipe
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Product cache with a size limit, sliding plus absolute expiry, and short negative caching
Source: ImproveCode, Chapter 3, Recipe 3.2 "Expiration and Size Limits"
Section: The improved recipe
Book page: 62-63 -- original C# listing
Converted from C# to Python.
MemoryCache(MemoryCacheOptions) -> the MemoryCache stand-in from the Recipe 3.1 file
(size_limit, compaction_percentage); IDisposable -> context manager; statistics -> entry count.
"""
from dataclasses import dataclass
from datetime import timedelta
from decimal import Decimal
from types import TracebackType
from typing import Protocol
from p060_r3_1_cache_aside_get_or_create import CacheEntry, MemoryCache
@dataclass(frozen=True)
class ProductDetails:
product_id: int
name: str
list_price: Decimal
class ProductRepository(Protocol):
async def find(self, product_id: int) -> ProductDetails | None: ...
class ProductDetailsCache:
SLIDING = timedelta(minutes=10)
ABSOLUTE = timedelta(hours=1)
NOT_FOUND = timedelta(minutes=1)
def __init__(self, repository: ProductRepository) -> None:
self._cache = MemoryCache(
size_limit=5_000,
compaction_percentage=0.20,
track_statistics=True)
self._repository = repository
async def get(self, product_id: int) -> ProductDetails | None:
async def create(entry: CacheEntry) -> ProductDetails | None:
entry.size = 1
product = await self._repository.find(product_id)
if product is None:
entry.absolute_expiration_relative_to_now = self.NOT_FOUND
else:
entry.sliding_expiration = self.SLIDING
entry.absolute_expiration_relative_to_now = self.ABSOLUTE
return product
return await self._cache.get_or_create(product_id, create)
@property
def current_entry_count(self) -> int:
return self._cache.current_entry_count
def dispose(self) -> None:
self._cache.dispose()
def __enter__(self) -> "ProductDetailsCache":
return self
def __exit__(self, exc_type: type[BaseException] | None,
exc: BaseException | None, tb: TracebackType | None) -> None:
self.dispose()
How it works
This class owns a private MemoryCache instance with a SizeLimit. The limit is in units that you define, not bytes. Here each entry has Size = 1, so the limit is simply "at most 5,000 products". When an insert would push the total over the limit, the cache refuses that insert and starts a background compaction that removes 20% of the entries, expired ones first and then the least recently used.
Each found product gets two expirations. The sliding expiration removes it after ten minutes without a read, so cold entries leave on their own. The absolute expiration removes it after one hour no matter how often it is read, so a popular product cannot keep a stale price forever. Use both together; a sliding expiration on its own can keep a hot entry alive indefinitely.
Products that do not exist are cached too, but only for a minute. That is negative caching. It stops a bot that requests random IDs from hitting the database for each one, without hiding a newly added product for long.
TrackStatistics (.NET 7 and later) enables GetCurrentStatistics(), which reports the entry count, hits, misses and estimated size. Expose those numbers on a health or diagnostics page; a cache whose hit rate you cannot see is a cache you cannot tune.
Variations and pitfalls
- Use a private instance for size limits. Once
SizeLimitis set, every entry must setSize, or the insert throws anInvalidOperationException. The sharedIMemoryCachefromAddMemoryCache()is used by other libraries that do not set sizes, so put size-limited caches in their ownMemoryCache, as this class does, and register the class as a singleton. - Size by weight when items vary. If some entries are a single record and others are a 5,000-row report, give them sizes that reflect it, such as an estimated kilobyte count.
- Expiration is lazy. An expired entry is removed when it is next accessed or during a periodic scan (
ExpirationScanFrequency, one minute by default). It is never returned after it expires, but it may hold memory a little longer. - Do not set tiny lifetimes to fix staleness. A 5-second cache on data that changes hourly is mostly misses. Fix staleness with invalidation (next recipe) and keep lifetimes realistic.