Caching with Flask-Caching and Redis

Caching with Flask-Caching and Redis in Flask: --- A busy dry-cleaner has a motorised overhead carousel behind the counter -- a chain conveyor hung with…


The Analogy: The Dry-Cleaner's Automated Garment Carousel

A busy dry-cleaner has a motorised overhead carousel behind the counter -- a chain conveyor hung with finished, pressed garments in clear bags. When you drop off a suit, the clerk staples a numbered ticket to it and hands you the stub. Cleaning and pressing that suit takes hours and ties up staff and machines, so the carousel exists for one reason: when you return, the clerk does not re-clean anything. They punch your ticket number into the controller, the carousel rotates the matching bag to the pickup window, and you are gone in seconds. The expensive work happened once; every later pickup is a cheap lookup.

The entire system rests on one rule: the ticket number must identify exactly one garment. The carousel is the cache; the finished, bagged garment is the cached value -- the result of work you do not want to repeat; the ticket number is the cache key; punching a ticket the controller recognises is a cache hit; punching one it does not is a cache miss, which sends the job back to the cleaning floor to be done from scratch. The pickup is only ever as trustworthy as the ticket that describes it.

Two more rules keep the rack honest. First, garments left uncollected are pulled off the carousel after thirty days and moved to long-term storage, because nobody trusts a bag that has hung there indefinitely -- that is a time-to-live. Second, if you bring the same suit back for a fresh clean, the old finished bag under that ticket must be taken down, or the clerk will hand you back the un-recleaned one -- that is invalidation on write, and it has to happen after the new job is truly finished, not before. And a chain has a carousel in every branch: a ticket Baker Street can find is not hanging on Camden's rack at all, which is what independent per-process caches feel like.

The dangerous shortcut is stamping the ticket with only a description -- "navy two-piece" -- instead of a number unique to you and your order. It saves a step until two customers drop off navy two-pieces the same morning. Now the controller holds two bags under one "navy two-piece" label; whoever asks first is handed a navy suit, and nothing reveals it is the wrong one until the customer finds someone else's tailoring, someone else's cleaning tag, and someone else's receipt in the pocket. The carousel worked perfectly and fast; the ticket simply failed to say which garment it meant, and a stranger walked out wearing your suit.


Syntax or Core Structure

Flask-Caching wraps a backend and hands you a decorator that stores a view's return value under a key derived from the request. You configure a backend, attach it to the app, and decorate. Here the backend is SimpleCache -- an in-process dictionary -- so the example is fully self-contained; in production the identical code points at Redis. The counter below is the whole point: it increments only when the view body actually runs.

from flask import Flask, jsonify
from flask_caching import Cache

app = Flask(__name__)
cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 300})
cache.init_app(app)

work = {"runs": 0}


@app.get("/report")
@cache.cached()                 # sits BELOW the route so the route binds the wrapper
def report():
    work["runs"] += 1           # runs only on a cache miss
    return jsonify(total=42)


client = app.test_client()
print("first :", client.get("/report").get_json(), "runs:", work["runs"])
print("second:", client.get("/report").get_json(), "runs:", work["runs"])
print("third :", client.get("/report").get_json(), "runs:", work["runs"])

Output:

first : {'total': 42} runs: 1
second: {'total': 42} runs: 1
third : {'total': 42} runs: 1

The body ran once. The second and third requests never entered it: Flask-Caching found the stored response under the path key and returned it directly, so runs stays at 1. Decorator order is not optional -- @cache.cached() must sit below @app.get(...) so the route registers the caching wrapper rather than the bare function. CACHE_DEFAULT_TIMEOUT is the fallback time-to-live in seconds for any entry whose decorator does not set its own.


Technical Depth: What the Key Contains Is the Whole Contract

Backends: what you attach to

Cache(config=...) chooses a backend by name. The code you write does not change; only the store behind it does.

BackendWhen to reach for it
NullCacheTests and debugging; every get misses, so behaviour is deterministic
SimpleCacheA single-process dev server; entries live in that one process only
RedisCacheAny deployment with more than one worker or box; one shared store
MemcachedCacheExisting Memcached estates; no persistence, fewer data types

SimpleCache is the production trap. With four Gunicorn workers you have four independent dictionaries: a value written by worker one is invisible to worker three, and cache.delete clears one of the four. That is the per-branch carousel from the analogy, and it is why invalidation "works on my machine" and mysteriously fails once more than one process is serving traffic. Redis gives every worker a single shared rack.

The default key is the path and nothing else

By default a cached view keys on the request path alone; the query string is not part of the key, so two different queries collide on one stored entry. Passing query_string=True folds the sorted query arguments into the key. The two endpoints below differ only in that flag.

from flask import Flask, request, jsonify
from flask_caching import Cache

app = Flask(__name__)
cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 300})
cache.init_app(app)


@app.get("/bad")
@cache.cached()                       # key = path only; the query string is ignored
def bad():
    return jsonify(q=request.args.get("q"))


@app.get("/good")
@cache.cached(query_string=True)      # key folds in the sorted query args
def good():
    return jsonify(q=request.args.get("q"))


client = app.test_client()
print("bad  drill :", client.get("/bad?q=drill").get_json())
print("bad  hammer:", client.get("/bad?q=hammer").get_json())
print("good drill :", client.get("/good?q=drill").get_json())
print("good hammer:", client.get("/good?q=hammer").get_json())

Output:

bad  drill : {'q': 'drill'}
bad  hammer: {'q': 'drill'}
good drill : {'q': 'drill'}
good hammer: {'q': 'hammer'}

/bad?q=hammer returns drill: the second request hit the entry the first stored under the bare path /bad, because the key never mentioned q. That is the wrong-navy-suit handover -- the label was too coarse to tell two jobs apart. /good keys on the sorted query arguments, so each query gets its own entry and hammer is served hammer.

Memoising a function keys on its arguments

@cache.memoize() decorates any function, not just a view, and builds the key from the function name plus the arguments it was called with. Each distinct argument tuple gets its own entry, so a counter reveals exactly how many real computations happened.

from flask import Flask
from flask_caching import Cache

app = Flask(__name__)
cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 300})
cache.init_app(app)

computed = []


@cache.memoize(timeout=300)
def exchange_rate(base, quote):
    computed.append((base, quote))
    return round(1.05 + len(base + quote) * 0.01, 4)


with app.app_context():
    print("USD/EUR:", exchange_rate("USD", "EUR"))
    print("USD/EUR:", exchange_rate("USD", "EUR"))   # same args -> hit
    print("USD/GBP:", exchange_rate("USD", "GBP"))   # new args -> miss
    print("distinct computations:", len(computed))
    print("computed pairs      :", computed)

Output:

USD/EUR: 1.11
USD/EUR: 1.11
USD/GBP: 1.11
distinct computations: 2
computed pairs      : [('USD', 'EUR'), ('USD', 'GBP')]

The body ran twice, not three times: the repeated USD/EUR call was served from the cache, while USD/GBP was a new argument tuple and missed. The two rates happen to print the same number, which is the point of the counter -- the return value alone could not tell you a cache hit occurred, but distinct computations: 2 proves it. Two constraints follow from keying on arguments. The arguments must have a stable repr: pass an ORM object and the key contains a memory address that changes every process and never hits. And the function must be pure with respect to its arguments -- if it reads session or current_user internally, those inputs are absent from the key and you have built a leak.

Choosing a time-to-live

DataReasonable TTLWhy
Reference lists like countries or categoriesHoursChanges are rare and announced
A catalogue pageOne to five minutesSome staleness is visible but tolerable
Third-party rates or geo lookupsMinutesBounds both the cost and the staleness
Something the user just editedNo cache, or explicit invalidation"I saved it and it did not change" is a support ticket

A time-to-live is a promise about how stale a value may become. Pick the largest span the business can tolerate, then use explicit invalidation for the cases where stale is unacceptable. A short TTL is not free: the shorter it is, the more often a miss falls through to the slow path, and a popular key expiring under load lets every concurrent request miss at the same instant and pile onto the database -- a stampede.


Real World Example: A Shared Catalogue Cache and the Invalidation That Missed

A product catalogue is the textbook thing to cache: the same paginated list is served to everyone, it is expensive to assemble, and it changes only when an admin edits an item. Below, /catalogue caches each page under a key that carries the page number, and the write endpoint invalidates on save. SimpleCache stands in for Redis, and DB stands in for the database, carrying a version counter so staleness is visible directly in the output.

from flask import Flask, request, jsonify
from flask_caching import Cache

app = Flask(__name__)
cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 300})
cache.init_app(app)

DB = {"items": ["alpha", "bravo", "charlie", "delta"], "version": 1}
PAGE_SIZE = 2


def page_key():
    return "catalogue:v1:page:" + request.args.get("page", "1")


@app.get("/catalogue")
@cache.cached(make_cache_key=page_key)
def catalogue():
    page = int(request.args.get("page", 1))
    start = (page - 1) * PAGE_SIZE
    window = DB["items"][start:start + PAGE_SIZE]
    return jsonify(page=page, items=window, version=DB["version"])


@app.put("/items/<int:idx>")
def rename(idx):
    DB["items"][idx] = request.get_json()["name"]
    DB["version"] += 1
    cache.delete("catalogue:v1:page:1")          # BUG: only page 1 is invalidated
    return jsonify(ok=True)


client = app.test_client()
print("p1 warm :", client.get("/catalogue?page=1").get_json())
print("p2 warm :", client.get("/catalogue?page=2").get_json())
client.put("/items/2", json={"name": "CHARLIE-2"})   # 'charlie' lives on page 2
print("p1 after:", client.get("/catalogue?page=1").get_json())
print("p2 after:", client.get("/catalogue?page=2").get_json())

Output:

p1 warm : {'items': ['alpha', 'bravo'], 'page': 1, 'version': 1}
p2 warm : {'items': ['charlie', 'delta'], 'page': 2, 'version': 1}
p1 after: {'items': ['alpha', 'bravo'], 'page': 1, 'version': 2}
p2 after: {'items': ['charlie', 'delta'], 'page': 2, 'version': 1}

The custom make_cache_key puts the page number into the key, so page 1 and page 2 occupy separate entries -- already an improvement over the default path-only key, which would have served page 1's body to a page 2 request. The v1 segment is deliberate: when the response shape changes, bumping it to v2 retires every old entry at once, because nothing will ever request a v1 key again and the abandoned entries expire on their own.

Walk the output. The two warm calls populate both page entries at version 1. The PUT renames the item at index 2 -- charlie, which sits on page 2 -- and bumps the database version to 2. Then the same two pages are fetched again. Page 1 now reports version 2, because its key was deleted and the view recomputed straight from the database.

Page 2 is the problem. It still reports charlie and version 1: the rename that actually changed page 2 is invisible on page 2, because the write deleted only catalogue:v1:page:1. Note that invalidating after the version bump rather than before it is correct here -- deleting the key first and then rolling back would have repopulated the cache from the old row -- but the delete simply targeted the wrong key.

The genuine design flaw is that invalidation is hard-coded to a single page while the data is paginated. The delete list is written once and silently drifts out of step with the pages that actually exist; the moment the catalogue spans more than one page, every page after the first serves stale data until its TTL expires. This is exactly why coarse, versioned keys beat precise per-page deletes: had the key been catalogue:v{N}:page:{p} with N stored beside the data, the single version bump in the write would have invalidated every page in one move, with no list of keys to keep in sync. Enumerating keys to delete is a maintenance burden that fails toward staleness -- the bug users report as "I edited it and the site still shows the old value."


Common Mistakes

  1. Putting @cache.cached above the route decorator. Decorators apply from the bottom up, so @cache.cached() must sit below @app.get(...); reversed, the route binds the bare function and the cache never runs.
  1. Caching a per-user response under a path-only key. @cache.cached() on /api/me/orders stores the first user's orders under the bare path and serves them to everyone for the whole TTL. Either do not cache authenticated responses, or put the user id in the key.
  1. Forgetting the query string. The default key ignores query arguments, so ?q=drill and ?q=hammer collide on one entry. Pass query_string=True or a make_cache_key that includes them.
  1. Memoising a function that reads hidden state. If the function consults session, g, or current_user internally, those inputs are absent from the key and one caller receives another's result.
  1. Passing unstable arguments to memoize. An ORM instance or any object without a stable repr yields a key containing a memory address that changes every process and never hits.
  1. Invalidating before the write commits. Delete the key, then let the transaction roll back, and the next read repopulates the cache from the old row -- now cache and database disagree with no TTL to save you. Invalidate after commit.
  1. Trusting SimpleCache in production. With multiple workers each holds its own dictionary, so writes and deletes reach only one of them. Use Redis or Memcached the moment more than one process serves traffic.
  1. Building invalidation on KEYS pattern* in Redis. It is a blocking scan of the entire keyspace that stalls the server under load; use versioned key prefixes instead.
  1. Caching in front of a missing index. A cache hides a slow query until it goes cold, then every miss hits the slow path at once. Fix the query first, then cache what is still genuinely expensive.

Best Practices

  • Write down every input that changes the output before you write the key; an input missing from the key is a leak waiting to happen.
  • Version your keys so a shape change retires all old entries at once, and a single version bump can replace a fragile list of deletes.
  • Prefer a few coarse keys over many precise ones; a dozen keys to delete per write is a bug waiting to happen.
  • Cache the expensive shared pieces inside a view rather than caching a whole personalised response.
  • Set the longest TTL the business can tolerate, and reserve explicit invalidation for the places where stale is genuinely unacceptable.
  • Send Cache-Control: private, no-store on authenticated responses so a CDN or proxy never serves one user's page to a stranger.
  • Stagger TTLs or hold a short lock around repopulation of a hot key so its expiry does not trigger a stampede.
  • Re-check authorisation on every request and cache only the data; a cached "allowed" outlives the permission that granted it.

Practice Exercises

  1. A dashboard endpoint is decorated with @cache.cached(timeout=300) and returns the logged-in user's unpaid invoices. Describe exactly what the second user to hit it sees, then give two different fixes and say which you would ship and why.
  1. Fix the catalogue example's invalidation flaw. Change the key scheme so a single write invalidates every page at once, and show the p2 after line finally reflecting the rename. Explain why your scheme needs no list of keys to delete.
  1. Write a make_cache_key for a multi-tenant /catalogue that must not leak one tenant's page to another and must still key on the page number. State which request attribute carries the tenant and what must happen if it is absent.
  1. Add a computation counter like work["runs"] to a memoised function, call it with a mix of repeated and new arguments, and assert the number of real computations. Explain why asserting on the counter is a better cache test than asserting on the return value.