Start learning free

LESSON 124 OF 188 · 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 dictionary's clear() method removes every key:

prices = {"Mug": 12, "Pen": 2}
prices.clear()
print(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 db.commit() has saved the change. 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 add_product and in change_price, empty the cache right after db.commit().


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 dictionary, with nothing between the parentheses.


STEP 1 OF 2
    Ctrl + Enter to check