← Back to Django, page 5

django-0093 · Hard senior

What is a cache stampede and how do you prevent it in Django using locks, TTL jitter and stale-while-revalidate?

A cache stampede (dogpile) happens when a popular key expires and many requests recompute it simultaneously, overloading the database. Prevent it with a short-lived lock using cache.add() (atomic on Redis and Memcached) so one request recomputes while others wait or serve stale data, add random jitter to TTLs so keys do not expire together, refresh early before expiry, and warm hot keys from a background job.

Full answer

Scenario: an expensive leaderboard query takes 2 seconds and is cached for 60 seconds. At expiry, 500 concurrent requests all miss the cache and run the query, saturating the database; some time out and retry, making it worse.

Techniques:

  1. Single flight with a lock: the first request that gets cache.add("lock:leaderboard", 1, timeout=10) (returns True only for one caller) computes and sets the value; others either wait briefly and re-read, or serve a stale copy. The lock needs its own timeout so a crashed worker does not block forever, and must be released (delete) after setting the value. cache.add is atomic on Redis and Memcached; LocMemCache is atomic only within one process.
  2. TTL jitter: timeout = base + random.randint(0, base // 10) so many keys written together do not expire together.
  3. Soft expiry (stale-while-revalidate): store (value, soft_expiry) with a long hard TTL. After the soft expiry, one caller refreshes (under the lock) while the rest keep serving the old value.
  4. Probabilistic early refresh: each request has a small chance of refreshing before the expiry, increasing as expiry nears.
  5. Warm the cache from a scheduled job and let requests only read.
  6. Reduce the cost: better query, precomputed tables, shorter work.

Other points: cache.get_or_set() does not prevent stampedes (several callers can compute at once). Negative caching (caching "not found" briefly) stops repeated misses on missing keys. Per-view cache_page has the same stampede behaviour at expiry. Redis-based locks from libraries (django-redis cache.lock) offer owned, auto-extending locks. Remember that cache invalidation on writes can trigger stampedes too, so prefer updating the value or refreshing in the background.

Measure: log cache misses and recompute counts; a spike of simultaneous recomputes of one key is the signature.

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()

import random
import threading
import time

from django.core.cache import cache

compute_count = {"naive": 0, "locked": 0}
counter_lock = threading.Lock()


def expensive(kind):
    with counter_lock:
        compute_count[kind] += 1
    time.sleep(0.3)                                       # a slow query
    return {"top": "Asha"}


def naive(key):
    value = cache.get(key)
    if value is None:
        value = expensive("naive")
        cache.set(key, value, 60)
    return value


def single_flight(key):
    value = cache.get(key)
    if value is not None:
        return value
    if cache.add(f"lock:{key}", 1, timeout=10):             # atomic: only one caller wins
        try:
            value = expensive("locked")
            cache.set(key, value, 60 + random.randint(0, 6))   # jittered TTL
        finally:
            cache.delete(f"lock:{key}")
        return value
    for _ in range(100):                                    # losers wait briefly and re-read
        time.sleep(0.02)
        value = cache.get(key)
        if value is not None:
            return value
    return expensive("locked")


def stampede(fn, key, n=8):
    start = threading.Barrier(n)
    results = []

    def worker():
        start.wait()
        results.append(fn(key))

    threads = [threading.Thread(target=worker) for _ in range(n)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    return results


stampede(naive, "board:naive")
stampede(single_flight, "board:locked")
print("naive recomputations:", compute_count["naive"])
print("single-flight recomputations:", compute_count["locked"])
print(cache.add("lock:x", 1, timeout=5), cache.add("lock:x", 1, timeout=5))

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. LocMemCache is the default cache, so locks only coordinate threads inside this one process; use Redis or Memcached in production. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): naive recomputations: 8 single-flight recomputations: 1 True False

Key points

  • Stampede: many requests recompute an expired hot key
  • cache.add() as an atomic, expiring lock gives single-flight recompute
  • Jitter TTLs and use soft expiry with stale serving
  • get_or_set() does not prevent stampedes
  • Warm hot keys from background jobs

Common mistakes

  • Assuming get_or_set prevents duplicate computation
  • Using a lock without a timeout, so a crashed worker blocks everyone
  • Giving all keys the same TTL so they expire together
  • Using LocMemCache locks across several worker processes

Follow-ups

  • How does stale-while-revalidate work in practice?
  • What are the risks of a distributed lock?
  • How would you warm the cache on deploy?

Tips

  • Describe the stampede in one sentence
  • Give two prevention techniques
  • Note the lock timeout