How does caching work in Django and what backends are available?
Learn how caching works in Django, the available backends like Redis, Memcached and LocMem, the four caching levels, timeouts and invalidation, with examples.
Expected Interview Answer
Django caching stores the result of expensive work — rendered pages, query results, or arbitrary values — in a fast store so later requests reuse it instead of recomputing, reducing database load and latency. You configure a backend under the CACHES setting and access it through a consistent cache API regardless of which backend you pick.
Django ships several backends: LocMemCache (per-process in-memory, the default), Memcached and Redis (fast networked stores shared across processes and servers), DatabaseCache (a cache table in your database), FileBasedCache (serialized files on disk), and DummyCache (a no-op for development). You can cache at multiple levels: the whole site via middleware, a single view with cache_page, template fragments with the {% cache %} tag, or specific values through the low-level cache.get / cache.set API. Each cached entry has a timeout after which it expires, and choosing a shared backend like Redis matters once you run more than one server or process.
- Cuts database and computation load dramatically
- Lowers response latency for repeated requests
- One consistent API across every backend
- Granular levels: whole-site, per-view, fragment, or low-level
- Shared backends (Redis, Memcached) scale across processes and servers
AI Mentor Explanation
Caching is a scorer keeping the running total on a whiteboard so nobody re-adds every delivery from the start each time it is needed; the timeout is how long before that whiteboard figure is wiped and recomputed. The different backends are like keeping that whiteboard at your own seat versus a shared one visible to every scorer in the ground.
Step-by-Step Explanation
Step 1
Configure a backend
Define the CACHES setting, choosing a backend such as Redis, Memcached, LocMemCache, or DatabaseCache with a LOCATION and TIMEOUT.
Step 2
Pick a caching level
Decide between site-wide middleware, per-view cache_page, template fragment caching, or the low-level cache API.
Step 3
Store values
Use cache.set(key, value, timeout) or a decorator to place the expensive result into the store.
Step 4
Read on later requests
cache.get(key) returns the stored value on a hit, avoiding the database or recomputation.
Step 5
Expire or invalidate
Entries drop out when their timeout lapses, or you call cache.delete to invalidate stale data explicitly.
What Interviewer Expects
- Caching stores expensive results to avoid recomputation
- Names several backends (LocMem, Memcached, Redis, Database, File, Dummy)
- The four caching levels in Django
- Why shared backends matter for multi-process/multi-server setups
- Awareness of timeouts and cache invalidation
Common Mistakes
- Using LocMemCache in production across multiple processes and expecting shared state
- Never setting or thinking about a timeout
- Ignoring cache invalidation when underlying data changes
- Caching per-user data under a shared key and leaking it between users
- Confusing the low-level cache API with per-view cache_page
Best Answer (HR Friendly)
“Django caching saves the results of slow or repeated work so the app can hand back a ready answer instead of redoing it, which makes pages faster and eases database load. You choose where to store that saved data — options include fast tools like Redis or Memcached, the database, files, or in-memory for one process.”
Code Example
# settings.py
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.redis.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379',
'TIMEOUT': 300,
}
}
# anywhere in your code
from django.core.cache import cache
def get_dashboard_stats():
stats = cache.get('dashboard_stats')
if stats is None: # cache miss
stats = expensive_query()
cache.set('dashboard_stats', stats, timeout=300)
return statsFollow-up Questions
- When would you choose Redis over Memcached for a Django cache?
- What are the four levels at which Django can cache?
- How do you invalidate a cached value when its data changes?
- Why is LocMemCache unsuitable for a multi-server deployment?
- How does per-view caching with cache_page differ from the low-level API?
MCQ Practice
1. Which Django cache backend is a no-op used during development?
DummyCache implements the cache interface but stores nothing, letting you keep cache code active without real caching.
2. Why is LocMemCache a poor choice across multiple server processes?
LocMemCache is per-process, so separate processes and servers do not share cached data, unlike Redis or Memcached.
3. Which method retrieves a value from Django's low-level cache?
cache.get(key) returns the stored value on a hit or None on a miss, part of the low-level cache API.
Flash Cards
What does caching store? — The result of expensive work so later requests reuse it instead of recomputing.
Name Django cache backends. — LocMemCache, Memcached, Redis, DatabaseCache, FileBasedCache, and DummyCache.
What are the caching levels? — Whole-site middleware, per-view cache_page, template fragments, and the low-level API.
Why prefer Redis/Memcached in production? — They are shared across processes and servers, unlike per-process LocMemCache.