Backend
Where Redis caching helps a Django app, and where it does not
Picking what to cache, when to expire it, and when to leave the database alone.
A cache trades freshness for speed. You keep a copy of an answer somewhere fast and serve the copy instead of asking the database again. The copy can be out of date. Every caching decision is a decision about how stale, for how long, and for whom.
Django makes the mechanics easy, so the judgment matters more than the API.
How Django sits in front of Redis
Django has shipped a Redis cache backend since version 4.0. It needs the redis Python package (redis-py) and one entry in settings:
# settings.py
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.redis.RedisCache",
"LOCATION": "redis://127.0.0.1:6379",
"TIMEOUT": 300,
"KEY_PREFIX": "shop",
}
}TIMEOUT is the default lifetime in seconds for keys that do not set their own. It defaults to 300. None means keys never expire, and 0 means nothing is cached. KEY_PREFIX is prepended to every key, so two apps can share one Redis instance without colliding.
Three layers build on that setting.
The low-level API. You pick the key and the value. Values are pickled, so anything picklable can be stored. Plain lists and dicts are the safest choice: pickling a queryset evaluates it and stores all of its results.
from django.core.cache import cache
from django.db.models import Count
from .models import Product
def top_categories():
data = cache.get("top_categories")
if data is None:
data = list(
Product.objects.values("category__name")
.annotate(total=Count("id"))
.order_by("-total")[:10]
)
cache.set("top_categories", data, timeout=600)
return datacache.get_or_set(key, default, timeout) does the same read-then-fill in one call, and default can be a callable.
The per-view cache. The whole response is stored.
from django.shortcuts import render
from django.views.decorators.cache import cache_page
@cache_page(60 * 15)
def pricing(request):
return render(request, "pricing.html")The key comes from the URL, so /pricing/ and /pricing/?currency=eur are separate entries. Only responses to GET and HEAD requests with status 200 are stored. cache_page also sets Cache-Control and Expires headers on the response, so browsers and proxies may keep their own copy for those 15 minutes. No cache.delete() on the server reaches those copies.
The template fragment cache. One block of a template is stored.
{% load cache %}
{% cache 600 sidebar %}
<ul>
{% for category in categories %}
<li>{{ category.name }}</li>
{% endfor %}
</ul>
{% endcache %}The first argument is the timeout in seconds and the second is the fragment name. Extra arguments, such as request.user.pk, become part of the key. This only saves a query when categories is a lazy queryset: the query then runs inside the block, and a cache hit skips it.
What is worth caching
A value is a good candidate when all three of these hold:
- It is expensive to produce: an aggregate over a large table, a report with several joins, a call to a slow external API.
- It is read far more often than it changes.
- A slightly old answer does no harm.
Category counts, a navigation menu, a "popular this week" list and a public landing page all pass. If one test fails, the cache usually costs more than it saves.
Choosing a timeout
If invalidation fails, the timeout is the longest a wrong answer stays visible. Start from that question, not from how much load a long timeout would save.
Short timeouts do more than they seem to. A key that is read many times a second and rebuilt once every 30 seconds has already taken almost all of that load off the database. Going from 30 seconds to an hour saves very little more and lets a missed invalidation last up to an hour.
Avoid timeout=None unless you trust your invalidation completely, because nothing will ever correct a miss.
Invalidation on write, and why it is the hard part
The better answer to staleness is to delete the key when the data changes:
# signals.py, imported from the app's AppConfig.ready()
from django.core.cache import cache
from django.db import transaction
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from .models import Product
@receiver([post_save, post_delete], sender=Product)
def clear_top_categories(sender, **kwargs):
transaction.on_commit(lambda: cache.delete("top_categories"))This looks finished, and it is not. Three things make it hard.
First, every write path has to know every key that depends on it. A product change can affect the category list, the product page, a sidebar fragment and a search page. Nothing in the framework tracks that for you. For fragments, make_template_fragment_key("sidebar") from django.core.cache.utils returns the key to delete.
Second, not every write sends a signal. QuerySet.update(), bulk_create() and bulk_update() do not call save() and do not send post_save. Raw SQL, or another service writing to the same tables, bypasses the receiver too.
Third, timing. If you delete the key before the transaction commits, another request can read the old row and put it straight back. transaction.on_commit() runs the callback after a successful commit, or immediately when no transaction is open. Even then, a reader that fetched the old row just before the commit can write it after your delete.
So keep a timeout on every key, even the ones you invalidate. Invalidation makes the cache fresh in the normal case. The timeout bounds the damage in the cases you missed.
Cache stampedes and one simple guard
When a busy key expires, every request that arrives before the rebuild finishes sees a miss and runs the expensive query at the same time. That is a stampede. get_or_set() does not prevent it: each caller that misses runs the callable.
A simple guard is to let one caller rebuild. cache.add() stores a value only if the key does not exist yet, and returns True when it stored it. In Django's Redis backend that is a single SET with the NX flag, so only one caller wins.
import time
from django.core.cache import cache
def cached(key, build, timeout=600):
data = cache.get(key)
if data is not None:
return data
lock = f"{key}:lock"
if cache.add(lock, 1, timeout=30):
try:
data = build()
cache.set(key, data, timeout=timeout)
finally:
cache.delete(lock)
return data
for _ in range(20):
time.sleep(0.1)
data = cache.get(key)
if data is not None:
return data
return build()The losers wait about two seconds for the winner, each holding a worker while it sleeps, then fall back to building the value themselves. The lock timeout must be longer than build() takes, and build() must not return None. This is a guard, not a full distributed lock.
Where caching hurts
Per-user data. One key per user multiplies memory, and each key is read by one person, so the hit rate is low. Per-user pages are also the easy way to leak data: a response built for one user can be served to the next. cache_page keys on the URL plus the request headers named in the response's Vary header. A page that shows the logged-in user's details needs no page cache at all, or vary_on_cookie below cache_page, so the header is already set when cache_page stores the response.
Fast indexed queries. A lookup by primary key is already cheap. Replacing it with a network round trip to Redis and an unpickle saves little, and you now own invalidation for it.
Data that must be exact. Stock at checkout, account balances and permission checks belong in the database, read inside the transaction that acts on them.
A slow query that should be fixed. A cache makes the warm path fast. The cold path, after an expiry, a restart or a flush, is as slow as before, and it is where stampedes happen. Read the plan with QuerySet.explain(), add the missing index, and remove repeated queries with select_related() or prefetch_related() first. Cache what is still expensive after that.
One last check: with Redis empty, the app should still work, only slower. If it does not, the cache has become a data store and needs to be treated as one.