← Back to Django, page 2

django-0031 · Medium mid

What caching options does Django provide, and how do you choose between them?

Django has a cache framework with backends such as Redis, Memcached, local memory and database. You can cache whole views with @cache_page, template fragments with {% cache %}, or any value with the low-level API (cache.get, cache.set, cache.get_or_set). Choose by how much of the response is shared between users and how stale it may be, and plan invalidation from the start.

Full answer

Configure caches in the CACHES setting. Common backends:

  • django.core.cache.backends.redis.RedisCache (built in since Django 4.0) or memcached.PyMemcacheCache for production, shared across processes and servers.
  • locmem.LocMemCache: per process, good for development and tests.
  • db.DatabaseCache and filebased.FileBasedCache: rarely the best choice.
  • dummy.DummyCache: caches nothing, useful to switch caching off.

Levels of caching, from widest to narrowest:

  1. Per-site: UpdateCacheMiddleware and FetchFromCacheMiddleware. Caches every anonymous GET. Rarely right for apps with logged-in users.
  2. Per-view: @cache_page(60 * 15). Cache key includes the URL and headers listed in Vary. Safe for public pages, dangerous for personalised ones unless you vary on cookie.
  3. Template fragment: {% cache 600 sidebar request.user.id %} caches a slow part of a page.
  4. Low-level API: cache.get(key), cache.set(key, value, timeout), cache.get_or_set(key, callable, timeout), cache.delete(key), cache.incr(key). Best control; cache computed results such as "class average for 10A".

Invalidation strategies:

  • Time-based expiry (timeout). Simple, accepts some staleness.
  • Delete on write: when marks change, cache.delete(f"class-avg:{room_id}"). Do it in transaction.on_commit so readers do not repopulate the cache with old data before the commit.
  • Versioned keys: include a version or updated_at in the key so new data gets a new key.

Watch for cache stampedes: when a popular key expires, many requests recompute it at once. Mitigate with slightly random timeouts, a lock, or background refresh. Cache what is expensive and read often; caching cheap queries only adds complexity.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.core.cache import cache
from django.db import models, connection
from django.db.models import Avg
from django.test.utils import CaptureQueriesContext

settings.CACHES = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}


class Mark(models.Model):
    room = models.CharField(max_length=5)
    score = models.IntegerField()
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Mark)

Mark.objects.bulk_create([Mark(room="10A", score=s) for s in (70, 80, 90)])


def class_average(room):
    return cache.get_or_set(
        f"class-avg:{room}",
        lambda: Mark.objects.filter(room=room).aggregate(a=Avg("score"))["a"],
        timeout=300,
    )


def add_mark(room, score):
    Mark.objects.create(room=room, score=score)
    cache.delete(f"class-avg:{room}")  # in real code: inside transaction.on_commit


with CaptureQueriesContext(connection) as ctx:
    print(class_average("10A"), class_average("10A"))
print("queries for two reads:", len(ctx.captured_queries))

add_mark("10A", 40)
print("after new mark:", class_average("10A"))

cache.set("visits", 0)
cache.incr("visits"); cache.incr("visits")
print("visits:", cache.get("visits"))

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): 80.0 80.0 queries for two reads: 1 after new mark: 70.0 visits: 2

Key points

  • Redis or Memcached in production; locmem for dev
  • Per-site, per-view, fragment and low-level caching
  • cache.get_or_set for computed values
  • Invalidate on write with on_commit, or use versioned keys
  • Watch for stampedes on hot keys

Common mistakes

  • Caching personalised pages with cache_page and showing one user's data to another
  • Using LocMemCache in production with several processes, so each has a different cache
  • Deleting the cache key before the transaction commits
  • Caching everything without measuring what is slow

Follow-ups

  • How would you prevent a cache stampede on a popular key?
  • How do you cache an API response that differs per user?
  • What is the Vary header and how does cache_page use it?

Tips

  • Name the four caching levels
  • Always talk about invalidation, not just storing
  • Mention Redis as the common production backend