Start learning free

LESSON 124 OF 173 · BACKEND: SPEED

When the Cache Lies

Practice

A cache that never forgets serves stale answers: answers that were true once and aren't any more. Add a product, and the cached list doesn't show it. Change a price, and customers see the old one.

The cure is to forget at the right moment. When the data changes, empty the cache: the next read finds nothing, builds a fresh answer and remembers it. A map's clear() method removes every key:

Map<String, Integer> prices = new HashMap<>(Map.of("Mug", 12, "Pen", 2));
prices.clear();
System.out.println(prices);   // {}

This is the rule of caching: every route that changes the data must clear what was remembered about it, and forgetting a single route is enough for the list to lie. Clear right after the line that saves the change (the INSERT or the UPDATE). Your code must give these answers, in this order:

GET /products  →  200  [{"category": "kitchen", "id": 1, "name": "Mug", "price": 12, …}, … 8 products]
POST /products  {"name": "Vase", "price": 18}  →  201  {"id": 9, "name": "Vase", "price": 18}
GET /products  →  200  [… the 8 products, {"category": null, "id": 9, "name": "Vase", "price": 18, "stock": 0}]
PATCH /products/1  {"price": 13}  →  200  {"id": 1, "price": 13}
GET /products  →  200  [{"category": "kitchen", "id": 1, "name": "Mug", "price": 13, …}, … 9 products]
GET /debug/queries  →  200  {"queries": 5}

The 5 queries are the three lists, each built from the database because the cache was empty, plus the INSERT and the UPDATE.

Your task: in addProduct and in changePrice, empty the cache with cache.clear() right after the line that runs the INSERT or the UPDATE.


Assignment
Follow the Coding Tutorial to clear the cache in both routes that change products.


Hint
Run the code first: the second and third lists are stale. clear() is called on the map, with nothing between the parentheses, and the line ends with a semicolon.


STEP 1 OF 2
    Ctrl + Enter to check