Start learning free

LESSON 124 OF 173 · BACKEND: SPEED

When the Cache Lies in C#

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:

var prices = new Dictionary<string, int> { ["Mug"] = 12, ["Pen"] = 2 };
prices.Clear();
Console.WriteLine(prices.Count);   // 0

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 command that saves the change 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 MapPost route, call cache.Clear() right after the line that runs the INSERT. In the MapPatch route, call it right after the if block that runs 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 dictionary, with nothing between the parentheses. In the MapPatch route, clearing after the if block means a missing product (404) leaves the cache alone.


STEP 1 OF 2
    Ctrl + Enter to check

    Cache Invalidate in C#

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