Start learning free

LESSON 124 OF 173 · BACKEND: SPEED

When the Cache Lies in JavaScript

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, remove what was remembered: the next read finds nothing, builds a fresh answer and remembers it. The delete operator takes a property out of an object, so reading it gives undefined again:

const prices = { Mug: 12, Pen: 2 };
delete prices.Mug;
console.log(prices.Mug);   // undefined
console.log(prices.Pen);   // 2

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 INSERT or the UPDATE has run. 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 route for POST /products and in the route for PATCH /products/:productId, delete the remembered list from cache right after the query has run.


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. delete is an operator, not a function: write it before the property, which is the object, a dot and the name.


STEP 1 OF 2
    Ctrl + Enter to check

    Cache Invalidate in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free