Skip to lesson

Cache invalidation and stale data

A ShopLite price drops for the sale, but the category page still shows the old price. With two stores, many servers and requests running at the same time, it is easy to leave one old copy behind.

Your turn: the price changed, the page did not

Product 1 now costs 59,990 in MySQL, but shoppers still see 64,990. Before reading on, write down what you would check and how you would prevent it. Nothing is graded.

  • When a price changes, which copies could exist, and which of them should the update code touch?
  • Two admins change the same price at almost the same moment. Could the cache end up with the older value? How?
  • What number would you ask the product owner for: how many seconds of an old price are acceptable?

Why copies go stale

Stale data is a cached copy that no longer matches the database.

The program below changes a price in the database and prints whether the cache still agrees after each step.

Example 1 · Two copies that drift apart

TwoCopiesDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class TwoCopiesDemo {    static final Map<Integer, Integer> db = new HashMap<>();    static final Map<Integer, Integer> cache = new HashMap<>();
    static void show(String when) {        String state = db.get(5).equals(cache.get(5)) ? "agree" : "DISAGREE";        System.out.printf("%-38s db=%d cache=%d  %s%n", when, db.get(5), cache.get(5), state);    }
    public static void main(String[] args) {        db.put(5, 64990);                  // HP Victus 15 Gaming        cache.put(5, 64990);        show("Start");
        db.put(5, 59990);                  // admin forgets the cache        show("DB updated, cache not touched");
        cache.put(5, 59990);        show("Cache fixed by hand");
        cache.put(5, 54990);               // cache written first...        boolean dbWriteFailed = true;        if (!dbWriteFailed) {            db.put(5, 54990);        }        show("Cache first, DB write failed");    }}
Output
Start                                  db=64990 cache=64990  agree
DB updated, cache not touched          db=59990 cache=64990  DISAGREE
Cache fixed by hand                    db=59990 cache=59990  agree
Cache first, DB write failed           db=59990 cache=54990  DISAGREE

What this code does

  • Updating only the database leaves the cache with 64990 while the database says 59990.
  • Writing the cache first is worse: when the database write fails, the cache shows a price (54990) that was never saved anywhere.

Stale data appears whenever the two stores are updated separately: one write succeeds and the other is forgotten, fails or arrives late. There is no single transaction that covers MySQL and Redis together.

The database is the source of truth: when the two disagree, the database is right. So every update must change the database first and then make sure the old copy cannot be served for long.

One good design: delete the entry, do not update it

Invalidation is removing or replacing a cached copy when the original data changes. Deleting the entry is the safer way.

A price update can write the new value into the cache or delete the entry. The program below replays two writers that finish in a bad order, once for each choice.

Example 2 · Updating vs deleting under a race

UpdateVsDeleteRaceDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class UpdateVsDeleteRaceDemo {    static Map<Integer, Integer> db = new HashMap<>();    static Map<Integer, Integer> cache = new HashMap<>();
    static void reset() {        db = new HashMap<>(Map.of(7, 2199));      // Mi Power Bank        cache = new HashMap<>(Map.of(7, 2199));    }
    static void step(String text) {        System.out.printf("  %-36s db=%d cache=%s%n", text, db.get(7), cache.get(7));    }
    public static void main(String[] args) {        // Two admins change the price at the same moment. The steps are written        // in the order the two threads happened to run (an interleaving).        System.out.println("Strategy 1: update the cache");        reset();        db.put(7, 1999);       step("A writes DB = 1999");        db.put(7, 1899);       step("B writes DB = 1899");        cache.put(7, 1899);    step("B writes cache = 1899");        cache.put(7, 1999);    step("A writes cache = 1999 (late)");        System.out.println("  -> cache stays wrong until it expires");
        System.out.println("Strategy 2: delete the cache entry");        reset();        db.put(7, 1999);       step("A writes DB = 1999");        db.put(7, 1899);       step("B writes DB = 1899");        cache.remove(7);       step("B deletes cache");        cache.remove(7);       step("A deletes cache (late)");        cache.put(7, db.get(7)); step("next read loads from DB");        System.out.println("  -> cache and DB agree");
        System.out.println("Strategy 2, rare case: a slow reader");        reset();        cache.remove(7);       step("entry expired");        int readerSaw = db.get(7); step("reader R loads 2199 from DB");        db.put(7, 1999);       step("writer W writes DB = 1999");        cache.remove(7);       step("W deletes cache");        cache.put(7, readerSaw); step("R puts its old 2199 (late)");        System.out.println("  -> stale until the TTL ends; a second delete shortly after W fixes it");    }}
Output
Strategy 1: update the cache
  A writes DB = 1999                   db=1999 cache=2199
  B writes DB = 1899                   db=1899 cache=2199
  B writes cache = 1899                db=1899 cache=1899
  A writes cache = 1999 (late)         db=1899 cache=1999
  -> cache stays wrong until it expires
Strategy 2: delete the cache entry
  A writes DB = 1999                   db=1999 cache=2199
  B writes DB = 1899                   db=1899 cache=2199
  B deletes cache                      db=1899 cache=null
  A deletes cache (late)               db=1899 cache=null
  next read loads from DB              db=1899 cache=1899
  -> cache and DB agree
Strategy 2, rare case: a slow reader
  entry expired                        db=2199 cache=null
  reader R loads 2199 from DB          db=2199 cache=null
  writer W writes DB = 1999            db=1999 cache=null
  W deletes cache                      db=1999 cache=null
  R puts its old 2199 (late)           db=1999 cache=2199
  -> stale until the TTL ends; a second delete shortly after W fixes it

What this code does

  • With updates, admin A's late cache write puts back 1999 although the database has B's 1899.
  • With deletes, the late delete does no harm. Only the slow-reader case can still put an old value back, which the TTL or a second delete clears.

With updating, two writers can finish in the wrong order: the database ends with the newer price but the cache ends with the older one, and it stays wrong until the TTL. With deleting, the order does not matter: both deletes leave the entry empty and the next read loads whatever the database holds.

One rare race remains: a slow reader loads the old value, a writer updates and deletes, then the reader puts its old value back. A TTL limits the damage, and a double delete (delete again a moment later, often from a background job) removes the late copy.

Predict the output

Update or delete under a race

Follow the steps exactly as they happen and pick the result.

Round 1 of 3

The update-the-cache strategy. What do the stores hold at the end?

A writes DB = 1999
B writes DB = 1899
B writes cache = 1899
A writes cache = 1999 (A was slow)
Each step in Example 2 is written out in a fixed order to show one possible interleaving of two threads. Real threads produce such orders by chance, which is why these bugs are rare and hard to reproduce.

A stale price on the category page

A derived key is a cached result built from many rows, such as a category page, search results or the home page deals.

The program below changes one price and deletes only product:1, then deletes both product:1 and category:2.

Example 3 · Bug and fix: the category page keeps the old price

StalePriceListDemo.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
record Product(int id, String name, int categoryId, int price) { }
class CatalogueService {    final Map<Integer, Product> db = new HashMap<>();    final Map<String, Object> cache = new HashMap<>();    private final boolean deleteListsToo;
    CatalogueService(boolean deleteListsToo) {        this.deleteListsToo = deleteListsToo;        db.put(1, new Product(1, "Redmi Note 13 5G", 2, 17999));        db.put(2, new Product(2, "Samsung Galaxy M35", 2, 19999));    }
    Product product(int id) {        return (Product) cache.computeIfAbsent("product:" + id, k -> db.get(id));    }
    @SuppressWarnings("unchecked")    List<String> categoryPage(int categoryId) {        return (List<String>) cache.computeIfAbsent("category:" + categoryId, k -> {            List<String> lines = new ArrayList<>();            db.values().stream().filter(p -> p.categoryId() == categoryId)                    .forEach(p -> lines.add(p.name() + " Rs " + p.price()));            return lines;        });    }
    void changePrice(int id, int newPrice) {        Product old = db.get(id);        db.put(id, new Product(id, old.name(), old.categoryId(), newPrice));        cache.remove("product:" + id);                    // the product's own key        if (deleteListsToo) {            cache.remove("category:" + old.categoryId()); // every cached list that shows it        }    }}
public class StalePriceListDemo {    static void run(String label, boolean deleteListsToo) {        CatalogueService s = new CatalogueService(deleteListsToo);        s.product(1);        s.categoryPage(2);                                // both cached        s.changePrice(1, 15999);        System.out.println(label);        System.out.println("  product page:  Rs " + s.product(1).price());        System.out.println("  category page: " + s.categoryPage(2));    }
    public static void main(String[] args) {        run("Bug: only product:1 deleted", false);        run("Fix: product:1 and category:2 deleted", true);    }}
Output
Bug: only product:1 deleted
  product page:  Rs 15999
  category page: [Redmi Note 13 5G Rs 17999, Samsung Galaxy M35 Rs 19999]
Fix: product:1 and category:2 deleted
  product page:  Rs 15999
  category page: [Redmi Note 13 5G Rs 15999, Samsung Galaxy M35 Rs 19999]

What this code does

  • changePrice always deletes product:1, so the product page shows the sale price 15999.
  • The cached list category:2 was built before the change. Only the fixed version also deletes it, so the category page shows 15999 too.

When one product changes, every derived key that shows it is stale too. The update path must know all the keys a change touches: product:1 and also category:2.

A good habit is one method that lists the keys for a product, called by every update path. If that list grows too long, give derived pages a short TTL instead.

Find the bug

Find the missed copy

Each update path leaves a wrong copy behind. Tap the wrong line.

A price change in the admin screen.

Round 1 of 2

Cache stampede and its fixes

A cache stampede (also called the thundering herd) is when a popular key expires, many requests miss at the same moment and all run the same heavy query.

The programs below send 50 users at one expired key, then keep a hot key from ever expiring in front of users.

Example 4 · A stampede of 50 users, then one loader per key

StampedeDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.CyclicBarrier;import java.util.concurrent.atomic.AtomicInteger;
public class StampedeDemo {    static final int USERS = 50;    static final AtomicInteger dbCalls = new AtomicInteger();
    static String loadFromDb(String key) {        dbCalls.incrementAndGet();        try {            Thread.sleep(100);                       // a heavy query: the home page deals        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }        return "deals of the day";    }
    static void runUsers(Runnable request) throws InterruptedException {        List<Thread> threads = new ArrayList<>();        for (int i = 0; i < USERS; i++) {            Thread t = new Thread(request);            threads.add(t);            t.start();        }        for (Thread t : threads) {            t.join();        }    }
    public static void main(String[] args) throws InterruptedException {        // 1. No protection: every user sees the miss and queries the DB        Map<String, String> cache = new ConcurrentHashMap<>();        CyclicBarrier allMissed = new CyclicBarrier(USERS);   // forces the worst case every run        runUsers(() -> {            String v = cache.get("home:deals");            if (v == null) {                try {                    allMissed.await();                } catch (InterruptedException | BrokenBarrierException e) {                    return;                }                cache.put("home:deals", loadFromDb("home:deals"));            }        });        System.out.println("Without a lock: " + dbCalls.get() + " DB calls for 1 key");
        dbCalls.set(0);        Map<String, String> cache2 = new ConcurrentHashMap<>();        runUsers(() -> cache2.computeIfAbsent("home:deals", StampedeDemo::loadFromDb));        System.out.println("With one loader per key: " + dbCalls.get() + " DB call");    }}
Output
Without a lock: 50 DB calls for 1 key
With one loader per key: 1 DB call

What this code does

  • The CyclicBarrier makes all 50 threads see the miss before any of them loads, so the worst case happens on every run: 50 copies of the same heavy query.
  • computeIfAbsent on a ConcurrentHashMap runs the loader once for the key; the other 49 threads wait and get the same value.

Example 5 · Early refresh keeps a hot key from ever missing

EarlyRefreshDemo.javaJava
public class EarlyRefreshDemo {    static final int TTL = 60;                  // seconds    static final int REFRESH_AFTER = 48;        // refresh early at 80% of the TTL
    static String value = null;    static int storedAt = -1;    static int version = 0;
    static String load(int now) {        version++;        storedAt = now;        value = "deals v" + version;        return value;    }
    static void read(int now) {        int age = value == null ? -1 : now - storedAt;        String result;        if (value == null || age >= TTL) {            result = "MISS, user waits for " + load(now);        } else if (age >= REFRESH_AFTER) {            String old = value;            load(now);                          // in real code: one background task            result = "HIT (" + old + "), refreshed early to " + value;        } else {            result = "HIT (" + value + ")";        }        System.out.printf("t=%3d s  age=%3s  %s%n", now, age < 0 ? "-" : String.valueOf(age), result);    }
    public static void main(String[] args) {        int[] readTimes = {0, 20, 47, 50, 90, 99, 130};        for (int t : readTimes) {            read(t);        }    }}
Output
t=  0 s  age=  -  MISS, user waits for deals v1
t= 20 s  age= 20  HIT (deals v1)
t= 47 s  age= 47  HIT (deals v1)
t= 50 s  age= 50  HIT (deals v1), refreshed early to deals v2
t= 90 s  age= 40  HIT (deals v2)
t= 99 s  age= 49  HIT (deals v2), refreshed early to deals v3
t=130 s  age= 31  HIT (deals v3)

What this code does

  • Reads younger than 48 s are plain hits. A read at 48 s or older still gets the cached value at once, and a refresh starts.
  • Only the very first read misses. After that the copy is renewed before it reaches 60 s, so no user waits for the database.

The database gets a sudden spike exactly when the site is busiest. Two fixes are common. One loader per key (a lock, or ConcurrentHashMap.computeIfAbsent inside one server) lets the first request load while the others wait for its result. Early refresh reloads a hot key in the background shortly before it expires, so users never see the miss.

Where each fix applies:

  • computeIfAbsent runs the loader once per key per server; with 10 servers you still get up to 10 loads, which is usually fine.
  • Across servers, a short lock in the shared cache (for example Redis SET key value NX EX 5) lets one server load.
  • Early refresh at about 80% of the TTL suits a few very hot keys like the home page deals.

Predict the output

How many database queries?

A hot key just expired. Count the database queries.

Round 1 of 2

200 requests for the key arrive before the first load finishes, with no lock.

for each of 200 requests:
value = cache.get("home:deals");
if (value == null) value = loadFromDb(); // 2 seconds
cache.put("home:deals", value);

How stale is acceptable?

A staleness budget is how old a cached copy may be before it causes harm. You set it for each kind of data.

Decide the budget with the product owner, then choose the TTL and the invalidation from it. The map below is a starting point for ShopLite.

Java
Map<String, Duration> maxStale = Map.of(    "category list",       Duration.ofMinutes(30),  // changes a few times a month    "product description", Duration.ofMinutes(10),    "product price",       Duration.ofMinutes(1),   // plus delete on every change    "order status",        Duration.ofSeconds(5),    "stock at checkout",   Duration.ZERO);          // always read the database
  • Money and stock at the moment of paying: zero; read the database inside the order transaction.
  • Things a user just changed: they expect to see it now, so delete on change.
  • Lists, counts and descriptions: minutes are usually fine.

Next step

Check your understanding

12 quick questions