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. Go's built-in clear function removes every key from a map:

prices := map[string]int{"Mug": 12, "Pen": 2}
clear(prices)
fmt.Println(prices)   // map[]

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 runExec has saved the change: SQLite saves each statement at once. 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 the POST /products handler and in the PATCH /products/{id} handler, empty the cache right after the runExec line.


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


Hint
Run the code first: the second and third lists are stale. clear is a built-in function, not a method: the map goes between its parentheses.


STEP 1 OF 2
    Ctrl + Enter to check