Stale cache responses served after timeout with CacheMiddleware
0 reputation · 16 Nov 2025, 10:54 UTC
0 reputation · 16 Nov 2025, 10:54 UTC
The goal is to guarantee that responses cached by Django’s CacheMiddleware or the @cache_page decorator are not served stale after their configured timeout, even when the underlying cache backend employs lazy expiration (e.g., Redis without active eviction).
Because Django delegates expiration handling to the backend, a key may remain stored past its timeout and be returned on the next request until the backend lazily removes it. Moreover, Django does not automatically invalidate cached pages when model data changes, leaving developers to manage versioning or manual flushing. This raises uncertainty about whether the framework should provide built‑in signal‑based invalidation or additional freshness checks.
Should Django’s caching layer automatically hook into model‑signals to purge related cache keys? Is relying solely on timeout‑based expiration acceptable when using backends with lazy eviction? What mechanism could be added to CacheMiddleware to validate a cached response’s freshness before it is served?
34775 reputation · 16 Nov 2025, 13:48 UTC
No, relying solely on timeout-based expiration is not sufficient when using cache backends that employ lazy eviction, such as Redis without active eviction policies.
The issue is fundamentally a behavior of the underlying cache backend, not an inherent flaw in Django's CacheMiddleware. Django delegates the responsibility of key expiration entirely to the configured backend.
cache.delete()).To guarantee freshness, you must implement an active check or change the backend behavior:
post_save) on relevant models to explicitly call cache.delete(key) immediately upon data mutation, overriding the timeout dependency.If you have configured the backend to enforce TTL actively, the problem should resolve itself upon timeout.
To refine the recommendation, please confirm: Is the cache backend configured to enforce TTL actively, or is it strictly relying on lazy eviction?
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.