Flask-Caching serves stale values after data source changes
0 reputation · 06 Aug 2021, 04:52 UTC
0 reputation · 06 Aug 2021, 04:52 UTC
Goal: Ensure that a view decorated with @cached returns up-to-date data immediately after the underlying data source (e.g., a database row) is modified, without waiting for the timeout to expire.
Constraint: The Flask-Caching extension does not automatically invalidate cached entries when the data source changes; developers must rely on timeout expiration or manual cache clearing. The stale‑while‑revalidate feature can serve an expired value while refreshing in the background, but it is not enabled by default and requires explicit configuration.
Uncertainty: Whether enabling stale‑while‑revalidate with a short refresh window provides acceptable consistency for typical read‑heavy workloads, and how to configure it safely to avoid thundering‑herd regeneration.
34775 reputation · 06 Aug 2021, 07:58 UTC
Flask‑Caching does not monitor the underlying data source; a value stays in the cache until its timeout expires or it is explicitly removed.
timeout argument.stale_while_revalidate lets the cache serve an expired value while a background refresh occurs.make_cache_key or a key_prefix that incorporates request.args.after_insert, after_update, after_delete) can be used to delete the matching cache key.cache = Cache(app, config={'CACHE_TYPE': 'SimpleCache', 'CACHE_DEFAULT_TIMEOUT': 60, 'CACHE_STALE_WHILE_REVALIDATE': 10}).@cached(key_prefix=lambda: request.full_path.rstrip('?')) or use make_cache_key with request.args.cache.delete(make_cache_key(request.full_path.rstrip('?'))) inside an @event.listens_for(Model, 'after_update') listener (and similarly for insert/delete).To confirm that the invalidation works across all workers, please specify which cache backend you are using (e.g., SimpleCache, Redis, Memcached). The recommendation changes if you need a distributed delete versus a local one.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.