Cache-aside, step by step
After this: Write the four steps of cache-aside as a function, run it, and say where the cache sits.
On this page · 5 sections · 3 checks
In lesson 1 you counted hits and misses by hand. The app server did the same few things on every read. This lesson writes those things down as steps, then as a function you can run.
The four steps
On every read of a key, the app server does this:
- Look in the cache.
- If the key is there (a hit), return the cached answer. Stop.
- If it is not there (a miss), read the answer from the database.
- Store the answer in the cache under the key, then return it.
This way of using a cache has a name: . The name says where the cache sits: to the side. The app server talks to the cache and to the database separately, and the database does not know the cache exists. All the work of filling the cache is done by the app's own code, in step 4.
The steps in code
The cache is a dictionary in Python and a HashMap in Java, from key to price. A second map stands in for the database. A third map, stats, holds two counts, hits and misses, and the function adds 1 to one of them on every call.
Step through three reads first: p1, p2, then p1 again.
- Run the programRun it and step through. Each call opens a frame for the price function. Watch which branch it takes, and watch the boxes cache and stats change after each call.
database = {"p1": 5, "p2": 8}cache = {}stats = {"hits": 0, "misses": 0}
def get_price(key): if key in cache: stats["hits"] += 1 return cache[key] stats["misses"] += 1 value = database[key] cache[key] = value return value
for key in ["p1", "p2", "p1"]: get_price(key)print(stats["hits"], stats["misses"])run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
The first call misses, so it takes the lower path: it reads database, stores the price in cache, and returns it. The second call does the same for p2. The third call finds p1 in cache and returns the cached price at once. The program prints 1 2.
Here is the same function over the ten reads of lesson 1.
database = {"p1": 5, "p2": 8, "p3": 3, "p4": 9}cache = {}stats = {"hits": 0, "misses": 0}
def get_price(key): if key in cache: stats["hits"] += 1 return cache[key] stats["misses"] += 1 value = database[key] cache[key] = value return value
for key in ["p1", "p2", "p1", "p3", "p1", "p2", "p4", "p1", "p2", "p3"]: get_price(key)print(stats["hits"], stats["misses"])6 4
import java.util.*;
public class Main { static Map<String, Integer> database = Map.of("p1", 5, "p2", 8, "p3", 3, "p4", 9); static Map<String, Integer> cache = new HashMap<>(); static Map<String, Integer> stats = new HashMap<>(Map.of("hits", 0, "misses", 0));
static int getPrice(String key) { if (cache.containsKey(key)) { stats.put("hits", stats.get("hits") + 1); return cache.get(key); } stats.put("misses", stats.get("misses") + 1); int value = database.get(key); cache.put(key, value); return value; }
public static void main(String[] args) { for (String key : List.of("p1", "p2", "p1", "p3", "p1", "p2", "p4", "p1", "p2", "p3")) { getPrice(key); } System.out.println(stats.get("hits") + " " + stats.get("misses")); }}6 4
Read it against the four steps:
- if key in cache:if (cache.containsKey(key)) { is step 1: look in the cache.
- The two lines under it are step 2: count a hit and return the cached price.
- The next two lines are step 3: count a miss and read the price from the database.
- cache[key] = valuecache.put(key, value); is step 4: store the answer. Then the function returns it.
The loop at the bottom makes the ten reads, and the last line prints the hits and the misses: 6 4, the same as the strip in lesson 1.
Run it
Java does not run here. Switch to Java to read the Java version, or paste it into a Java tool on your computer. The Python version runs below.
Try deleting the store line and running it again: every read misses, and it prints 0 10.
Predict, then watch
Before you press Run it below, write the ten keys on paper and mark each one H or M. Then step through and compare. On each miss, look for the two steps of the database read and the fill.
- Cache-aside: 10 requestsWrite the ten keys down and mark each one H or M before you press Run it. Then step through and compare. On each miss, find the two steps: the read from the database, and the fill that puts the key in the cache.
Press Run it, then step through and watch the requests move.
Check yourself
Cache-aside, on a miss. The app has looked in the cache and the key is not there. What does it do next, in order?
Complete the line that stores the answer in the cache after a miss, so that the program prints 6 4 for the ten reads.
database = {"p1": 5, "p2": 8, "p3": 3, "p4": 9}cache = {}stats = {"hits": 0, "misses": 0}
def get_price(key): if key in cache: stats["hits"] += 1 return cache[key] stats["misses"] += 1 value = database[key] __________________ # ← store the answer in the cache return value
for key in ["p1", "p2", "p1", "p3", "p1", "p2", "p4", "p1", "p2", "p3"]: get_price(key)print(stats["hits"], stats["misses"])import java.util.*;
public class Main { static Map<String, Integer> database = Map.of("p1", 5, "p2", 8, "p3", 3, "p4", 9); static Map<String, Integer> cache = new HashMap<>(); static Map<String, Integer> stats = new HashMap<>(Map.of("hits", 0, "misses", 0));
static int getPrice(String key) { if (cache.containsKey(key)) { stats.put("hits", stats.get("hits") + 1); return cache.get(key); } stats.put("misses", stats.get("misses") + 1); int value = database.get(key); __________________ // ← store the answer in the cache return value; }
public static void main(String[] args) { for (String key : List.of("p1", "p2", "p1", "p3", "p1", "p2", "p4", "p1", "p2", "p3")) { getPrice(key); } System.out.println(stats.get("hits") + " " + stats.get("misses")); }}The same function, five reads: a b a a c. What does it print (hits, then misses)?
database = {"a": 1, "b": 2, "c": 3}cache = {}stats = {"hits": 0, "misses": 0}
def get_price(key): if key in cache: stats["hits"] += 1 return cache[key] stats["misses"] += 1 value = database[key] cache[key] = value return value
for key in ["a", "b", "a", "a", "c"]: get_price(key)print(stats["hits"], stats["misses"])import java.util.*;
public class Main { static Map<String, Integer> database = Map.of("a", 1, "b", 2, "c", 3); static Map<String, Integer> cache = new HashMap<>(); static Map<String, Integer> stats = new HashMap<>(Map.of("hits", 0, "misses", 0));
static int getPrice(String key) { if (cache.containsKey(key)) { stats.put("hits", stats.get("hits") + 1); return cache.get(key); } stats.put("misses", stats.get("misses") + 1); int value = database.get(key); cache.put(key, value); return value; }
public static void main(String[] args) { for (String key : List.of("a", "b", "a", "a", "c")) { getPrice(key); } System.out.println(stats.get("hits") + " " + stats.get("misses")); }}- List the four steps of cache-aside: look in the cache; on a hit return; on a miss read the database; store the answer, then return it.
- Say where the cache sits: beside the app server, which talks to the cache and the database separately.
- Write the price function with a map as the cache, and run it over the ten reads to print 6 4.
- Say that a cache inside each app server is fast but not shared, while a cache server such as Redis is shared but reached over the network.