A cache keeps an answer so that the next request doesn't have to work it out again. That makes an application faster and relieves the database. It has a price, though: The kept answer can be stale, it takes up memory, and it can end up with the wrong person. In this lesson you get to know four kinds of caches, from the memory of one replica to the browser, and build one into the Kladde: for the free times of the public appointment booking, with a measurement before and after.

New packages in this lesson:

Package Version What for
Microsoft.Extensions.Caching.Hybrid 10.11.0 HybridCache
Microsoft.Extensions.DependencyInjection 10.0.14 only for the file-based apps without the web SDK (BuildServiceProvider)

Measure first

The first rule of this lesson is: Only cache what is worth it by measurement. A cache that nobody needed makes the code harder to understand, and its errors (a stale display, an entry with the wrong person) are harder to find than a slow query. Before you build in a cache, answer four questions:

  1. Is it slow? The load test from lesson 3.8.6 and the queries from lesson 3.4.4 tell you which requests take too long at the 95th percentile and how many database calls they trigger.
  2. Is the same answer needed often? A cache helps only if the same question comes several times before the answer changes.
  3. How old may the answer be? A few seconds, a minute, not at all? That is a decision for the office, not a technical one.
  4. Who may see it? An answer for everyone may go into a shared cache. An answer with personal data may not.

The free times of the public booking pass all four questions. Every display of the booking page works them out for one day from the opening hours and the existing appointments (K2 2.5.6), many visitors see the same days, a few seconds of delay bother nobody, and the answer contains no names. An important point here: The cache decides nothing. Whether a time is really free is checked by the booking itself, with the rule in the model and the unique constraint in the database (K2 2.4.10). If the cache shows a time that somebody else has just booked, the second visitor gets the friendly message "already taken", but never a double booking.