StackPractices
advanced By Mathias Paulenko

Complete Guide to Cache Invalidation

Cache invalidation strategies: TTL, event-driven, versioned keys, tag-based purging, write-through, multi-tier, race conditions and consistency.

Introduction

Phil Karlton’s joke survives because it’s true: cache invalidation is the hard half of caching. Every invalidation bug is the same shape — something changed in the database, the cache didn’t hear about it, and a user got stale data. The fixes range from “let it expire” to full event-driven purging, and choosing wrong in either direction hurts: too loose and you serve lies, too aggressive and the origin falls over under re-fetch storms.

This guide walks through the strategies that actually get deployed — TTL, event-driven, versioned keys, tags, write-through, multi-tier propagation — plus the race conditions and consistency models that decide between them. Code is Python + Redis because the patterns transfer; where a sibling resource goes deeper on a specific layer, this guide links out: the Redis caching strategies guide for the storage side, the CDN caching strategy guide for edge invalidation, and the cache invalidation pattern for the compact pattern treatment.

Why Cache Invalidation Is Hard

Write Flow:     App → Database → ??? → Cache
                              ↑
                    When do we invalidate?
                    How do we handle failures?
                    What about concurrent reads?

The fundamental tension: you want to serve data from cache (fast) but you need data to be fresh (correct). Every strategy in this guide is a different point on that freshness-vs-performance spectrum — and every one of them fails differently.

Invalidation Strategies Overview

StrategyFreshnessComplexityOrigin loadBest for
TTL expirationEventualLowMediumData that tolerates staleness
Event-drivenStrongMediumLowData that must be fresh after writes
Versioned keysStrongMediumLowImmutable data, cache busting
Tag-basedStrongHighLowComplex dependency graphs
Write-throughStrongMediumLowWrite-heavy with consistency needs
Purge-allN/ALowHighEmergency invalidation only

The practical default is a combination: TTL as a safety net under everything, plus event-driven or versioned keys where freshness actually matters. The rest of the guide is how to build each layer correctly.

TTL-Based Expiration

Every entry gets a time-to-live; after expiry, the next read goes to the origin. Simple, self-healing — and the only strategy that still works when your invalidation code is broken.

Basic TTL

import json
import redis

r = redis.Redis(host="localhost", port=6379, db=0)

def get_user(user_id: int) -> dict | None:
    cache_key = f"user:{user_id}"
    cached = r.get(cache_key)

    if cached:
        return json.loads(cached)

    user = db.users.find_by_id(user_id)  # db is app-provided
    if user:
        r.setex(cache_key, 3600, json.dumps(user))  # TTL: 1 hour
    return user

TTL with Jitter

If a thousand keys share the same TTL because they were written in the same batch, they expire together and the origin eats a thundering herd. Jitter spreads the cliff — see the Redis docs on SETEX for the base command:

import random

def set_with_jitter(key: str, value: str, base_ttl: int = 3600,
                    jitter_pct: int = 20):
    jitter = int(base_ttl * jitter_pct / 100)
    actual_ttl = base_ttl + random.randint(0, jitter)
    r.setex(key, actual_ttl, value)

Choosing TTL Values

TTL is a business decision, not a technical one — it encodes “how stale can this get before someone complains”:

TTL_CONFIG = {
    "user_profile": 300,        # 5 min — users tolerate slight staleness
    "product_catalog": 3600,    # 1 hour — changes infrequently
    "app_config": 86400,        # 24 hours — rarely changes
    "search_results": 60,       # 1 minute — changes constantly
    "real_time_stats": 0,       # no cache — must be real-time
}

def get_with_ttl(key: str, loader, data_type: str):
    ttl = TTL_CONFIG.get(data_type, 300)
    if ttl == 0:
        return loader()

    cached = r.get(key)
    if cached:
        return json.loads(cached)

    value = loader()
    if value:
        set_with_jitter(key, json.dumps(value), base_ttl=ttl)
    return value

Advantages

  • Simplest possible implementation — one EXPIRE
  • No coordination between write path and cache
  • Self-healing: even a total invalidation failure resolves at TTL

Disadvantages

  • Stale data for up to the full TTL window
  • Simultaneous expiries cause origin load spikes (hence jitter)
  • Cannot guarantee freshness — it’s a promise about worst case, not typical case

Event-Driven Invalidation

When data changes, explicitly delete the cache entry — strong freshness, at the price of coupling your write path to the cache. For the CDN-level version of this, the CDN cache invalidation recipe covers purge APIs and surrogate keys.

Write-Then-Delete Pattern

def update_user(user_id: int, data: dict) -> dict:
    # 1. Write to database
    user = db.users.update(user_id, data)

    # 2. Invalidate cache — after the write, not before
    r.delete(f"user:{user_id}")

    return user

Order matters. Invalidate before the write and a concurrent read repopulates the cache with pre-update data that then looks fresh forever.

Pub/Sub for Multi-Instance Invalidation

Each app instance keeps its own in-memory L1; a Redis DEL can’t reach them. Pub/sub broadcasts the invalidation to every listener — see Redis PUBSUB docs for semantics:

import threading

# Publisher: called when data changes
def invalidate_cache(key: str):
    r.delete(key)                      # Redis L2
    r.publish("cache-invalidation", key)  # notify all instances' L1

# Subscriber: runs once per instance, in a daemon thread
def invalidation_subscriber(local_cache):
    pubsub = r.pubsub()
    pubsub.subscribe("cache-invalidation")

    for message in pubsub.listen():
        if message["type"] == "message":
            key = message["data"].decode()
            local_cache.delete(key)

threading.Thread(target=invalidation_subscriber,
                 args=(local_cache,), daemon=True).start()

Database Triggers for Invalidation

If writes can bypass your app (migrations, admin tools, other services), in-app invalidation misses them. PostgreSQL LISTEN/NOTIFY pushes the signal from the database itself:

CREATE OR REPLACE FUNCTION notify_cache_invalidation()
RETURNS TRIGGER AS $$
BEGIN
    PERFORM pg_notify('cache_invalidation',
        json_build_object('table', TG_TABLE_NAME, 'id', NEW.id)::text);
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER user_cache_invalidation
AFTER UPDATE ON users
FOR EACH ROW EXECUTE FUNCTION notify_cache_invalidation();

Advantages

  • Strong freshness — invalidation happens immediately after write
  • Low origin load — nothing re-fetches unless it actually changed
  • Precise — only affected entries die

Disadvantages

  • Write path and cache are now coupled — a failed DEL leaves stale data until TTL
  • More moving parts to debug at 3 a.m.
  • Pub/sub is fire-and-forget: an instance that was down misses the message entirely (which is exactly why TTL stays on as the safety net)

Versioned Cache Keys

Put a version number in the key. Bump the version on write; old entries become unreachable garbage that TTL cleans up. It’s the server-side equivalent of style.v123.css.

Versioned Keys Pattern

def get_user(user_id: int) -> dict | None:
    raw = r.get(f"user_version:{user_id}")
    version = raw.decode() if raw else "1"   # r.get returns bytes!
    cache_key = f"user:{user_id}:v{version}"

    cached = r.get(cache_key)
    if cached:
        return json.loads(cached)

    user = db.users.find_by_id(user_id)
    if user:
        r.setex(cache_key, 3600, json.dumps(user))
    return user

def update_user(user_id: int, data: dict) -> dict:
    user = db.users.update(user_id, data)
    # Old key is now unreachable — no explicit delete needed
    r.incr(f"user_version:{user_id}")
    return user

The .decode() is easy to miss and easy to regret: raw is b'2', and without decoding the key becomes user:1:vb'2' — reads silently miss, writes keep generating new garbage, and you “fixed” nothing.

Cache Busting with Versioned Keys

CDNs use the same trick at the URL level: style.v123.css instead of style.css?v=123, because some proxies ignore query strings when hashing the cache key. New version, new URL, guaranteed revalidation.

Advantages

  • No explicit invalidation — old entries are unreachable by construction
  • No read-modify-write race on the key itself
  • Plays well with CDN cache busting

Disadvantages

  • Dead entries burn memory until TTL
  • One extra read (GET user_version) per cache lookup
  • Key bookkeeping gets noisy across many entities

Tag-Based Invalidation

Tag entries with the entities they depend on; when an entity changes, purge everything tagged with it. This is how you invalidate “every cache entry that renders product 42” without knowing their keys.

Setting Tags

def get_product_with_tags(product_id: int) -> dict | None:
    cache_key = f"product:{product_id}"
    cached = r.get(cache_key)

    if cached:
        return json.loads(cached)

    product = db.products.find_by_id(product_id)
    if product:
        r.setex(cache_key, 3600, json.dumps(product))
        # Index this entry under each entity it depends on
        r.sadd(f"tag:product:{product_id}", cache_key)
        r.sadd(f"tag:category:{product.category_id}", cache_key)
        r.expire(f"tag:product:{product_id}", 3600)
        r.expire(f"tag:category:{product.category_id}", 3600)
    return product

Purging by Tag

def invalidate_tag(tag: str):
    keys = r.smembers(f"tag:{tag}")
    if keys:
        r.delete(*keys)          # delete all entries tagged with it
    r.delete(f"tag:{tag}")       # and the tag index itself

def update_product(product_id: int, data: dict) -> dict:
    product = db.products.update(product_id, data)
    invalidate_tag(f"product:{product_id}")

    # Category moved? Everything tagged under the old one dies too
    if "category_id" in data:
        invalidate_tag(f"category:{data['category_id']}")
    return product

Advantages

  • One purge call kills a whole dependency subtree
  • Handles graphs that are impossible to enumerate by key pattern
  • The model CDNs use (Fastly surrogate keys, Cloudflare tags)

Disadvantages

  • Tag indexes cost memory proportional to the dependency graph
  • TTL’d entries leave dead key refs in tag sets — purge is still correct, but the sets leak stale pointers
  • Genuinely hard to get right under concurrent writes

Write-Through Invalidation

In write-through, the write updates both database and cache in the same operation — there is nothing to invalidate because the cache is written fresh:

def update_user_write_through(user_id: int, data: dict) -> dict:
    user = db.users.update(user_id, data)
    # Cache holds the post-write state immediately
    r.setex(f"user:{user_id}", 3600, json.dumps(user))
    return user

Advantages

  • Cache is never behind the database for entries that exist
  • No separate invalidation step, no stale-after-write window
  • Pairs naturally with write-through population on reads

Disadvantages

  • Every write pays for two stores — latency adds up on write-heavy paths
  • A failed cache write still leaves a stale entry (TTL remains the net)
  • Writes a cache entry for data nobody might ever read

Multi-Tier Invalidation

With L1 (in-memory) plus L2 (Redis), a single DEL only fixes half the problem — every instance’s L1 needs the message too:

import threading

class MultiTierInvalidation:
    def __init__(self, redis_client, local_cache):
        self.redis = redis_client
        self.local = local_cache
        self._setup_subscriber()

    def invalidate(self, key: str):
        self.redis.delete(key)                    # L2
        self.local.delete(key)                    # own L1
        self.redis.publish("cache-invalidation", key)  # other instances' L1

    def _setup_subscriber(self):
        pubsub = self.redis.pubsub()
        pubsub.subscribe("cache-invalidation")

        def listen():
            for message in pubsub.listen():
                if message["type"] == "message":
                    self.local.delete(message["data"].decode())

        threading.Thread(target=listen, daemon=True).start()
Multi-tier invalidation propagation: a write updates the database, the writing instance deletes its L1 cache and the L2 Redis entry, then publishes the key to the cache-invalidation channel so every other instance deletes its own L1 entry too.

The gap nobody plans for: an instance that was restarting when the publish fired missed it and keeps serving its L1. This is why L1 entries need short TTLs (seconds-to-minutes) even when L2 holds longer ones.

Race Conditions

Read-Then-Write Race

Thread A: Read cache (miss) → Read DB → Write cache
Thread B: Write DB → Invalidate cache
Result: Thread A repopulates the cache with pre-update data,
        AFTER Thread B already invalidated it
Read-then-write race condition timeline: thread A misses the cache and reads the database; thread B writes new data and invalidates; thread A then writes the stale value back into the cache.

Solution: Lock or Version Check

import time

def get_user_safe(user_id: int) -> dict | None:
    cache_key = f"user:{user_id}"
    lock_key = f"lock:{cache_key}"

    cached = r.get(cache_key)
    if cached:
        return json.loads(cached)

    # NX + EX: acquire only if free, auto-release in 10s
    if r.set(lock_key, "1", nx=True, ex=10):
        try:
            cached = r.get(cache_key)     # double-check after lock
            if cached:
                return json.loads(cached)

            user = db.users.find_by_id(user_id)
            if user:
                r.setex(cache_key, 3600, json.dumps(user))
            return user
        finally:
            r.delete(lock_key)
    else:
        time.sleep(0.05)                  # someone else is loading
        return get_user_safe(user_id)     # retry — will hit fresh cache

Delayed Double-Delete

When a read is mid-flight during your write, a second delete after a short delay catches the repopulated stale entry:

import threading

def update_user_safe(user_id: int, data: dict) -> dict:
    # 1. Delete cache BEFORE the write (closes the pre-update window)
    r.delete(f"user:{user_id}")

    # 2. Write to database
    user = db.users.update(user_id, data)

    # 3. Delete again — catches entries repopulated during step 2
    threading.Timer(0.5, lambda: r.delete(f"user:{user_id}")).start()

    return user

The delay is a heuristic, not a guarantee — it needs to exceed your slowest realistic read path. For stricter needs, versioned keys sidestep the race entirely.

Consistency Models

Strong Consistency

Cache and database agree at all times — requires write-through or synchronous invalidation, and you pay in latency and coupling. Rarely what you actually need.

Eventual Consistency

Stale reads allowed for a bounded window — TTL gives you this for free. The honest default for most read-heavy data.

Read-Your-Writes Consistency

The one model users actually feel: after I update my profile, my next view must show it. Other users can lag. Implement it with a short bypass flag:

def update_user_session(user_id: int, data: dict,
                        session_id: str) -> dict:
    user = db.users.update(user_id, data)
    r.delete(f"user:{user_id}")

    # This session skips the cache for 10s — long enough for replication
    r.setex(f"bypass_cache:{session_id}", 10, "1")
    return user

def get_user_session(user_id: int, session_id: str) -> dict | None:
    if r.exists(f"bypass_cache:{session_id}"):
        return db.users.find_by_id(user_id)   # straight to origin
    return get_user(user_id)

Monitoring Invalidation

Invalidation that silently fails is worse than none — you think you have freshness and you don’t. Track: invalidation latency (write → cache delete), stale-read rate, invalidation failures, and post-invalidation hit rate (should drop to zero for the key, then recover).

import time

def invalidate_with_metrics(key: str):
    start = time.time()
    try:
        r.delete(key)
        r.publish("cache-invalidation", key)
        latency = (time.time() - start) * 1000
        metrics.histogram("cache.invalidation.latency", latency)
        metrics.increment("cache.invalidation.success")
    except Exception:
        metrics.increment("cache.invalidation.failure")
        raise

metrics here is your statsd/Prometheus client — app-provided. Alarm on failure spikes and on hit-rate that doesn’t recover; both mean your invalidation pipeline died quietly.

Best Practices

  1. TTL on everything, always. It’s the safety net under every fancier strategy — the day your event pipeline breaks, TTL is the only thing standing between you and immortal staleness.
  2. Invalidate after the write, not before. Pre-write invalidation opens a repopulation window for stale data.
  3. Short L1 TTLs in multi-tier setups. Pub/sub misses instances that were down; a 30-60s L1 TTL bounds the damage.
  4. .decode() every Redis read used in strings. r.get returns bytes — the versioned-key bug in this guide’s own example shows how subtle the breakage is.
  5. Measure invalidation, not just hit rate. A green hit-rate dashboard says nothing about whether your deletes are landing.
  6. One retry path for failed invalidations. A small queue for failed DELs beats discovering staleness from support tickets.

Common Mistakes

  • No TTL “because we have event-driven invalidation”. The first time the publisher crashes, stale data lives forever. Net under every strategy.
  • Bytes in cache keys. f"v{raw}" on a b'2' produces vb'2' — reads miss silently while memory fills with garbage.
  • Publishing to L1-only listeners with long L1 TTLs. Missed pub/sub messages plus hour-long L1 expiry = permanently stale local caches.
  • Tag sets without expiry. The entries die by TTL, the tag index lives forever — slow memory leak that shows up as maxmemory evictions.
  • Purge-all in response to “something looks stale”. It’s a fix for exactly nothing and an origin-killing thundering herd for everything else.
  • Cache write inside the request timeout. If the user-facing write path blocks on cache, a Redis blip becomes user-visible latency. Queue the invalidation when you can.

Production Checklist

  • TTL set on every cache entry
  • TTL jitter to prevent stampedes
  • Event-driven invalidation for write-heavy data
  • Pub/sub for multi-instance L1 invalidation
  • Race condition handling (locks or delayed double-delete)
  • Versioned keys for CDN-friendly cache busting
  • Tag-based invalidation for complex dependencies
  • Invalidation failure monitoring and alerting
  • Fallback to TTL if event-driven invalidation fails
  • Stale read rate monitored
  • Invalidation latency tracked

See Also

Frequently Asked Questions

What is the best cache invalidation strategy?

There isn't one — there's a stack. TTL as the always-on safety net, event-driven where freshness matters, versioned keys for bustable data, tags for dependency graphs. If you can only pick one, pick TTL and accept bounded staleness.

How do I handle invalidation failures?

TTL is the floor — a failed event-driven delete still resolves at expiry. Log and alert on failures, and retry through a small queue rather than inline retries that block the request path.

What is the delayed double-delete pattern?

Delete cache → write to DB → delete cache again after a short delay. The second delete catches stale entries that a concurrent read repopulated during the write. It's a heuristic — for hard guarantees, use versioned keys.

How do I invalidate cache across multiple app instances?

Redis pub/sub: the invalidating instance publishes the key, every instance deletes its L1 copy. Instances that were down during the publish miss it — which is why L1 entries need short TTLs regardless.

Should I invalidate before or after the database write?

After. Invalidate first and a concurrent read can refill the cache with pre-write data between your delete and the update. Double-delete handles the race if you need both.

How do I test cache invalidation?

Integration tests for the failure modes: write → read shows fresh data; concurrent read during write doesn't serve stale; failed invalidation still expires at TTL; pub/sub reaches every instance. Unit tests alone won't catch the races — that's the whole point of them.