Caching Strategies — DevOps

A cache keeps a copy of an answer so a request stops before it reaches the source. For notes-api the order is the CDN (servers in many cities, closest to the…

You've switched the CDN on in front of notes-api. A CDN (Content Delivery Network) is a network of servers in many cities that keep copies of your answers and answer visitors from the nearest place. Each of those places is called an edge. Then a Facebook post links to the popular notes page, and web-1 is still overloaded with requests, as if the CDN weren't there.

To see why, start with what a cache does. Caching means keeping a copy of an answer somewhere along the way, so the same request doesn't have to travel all the way to its source. The place that keeps the copy is called a cache. Picture a bakery chain. The white bread that's the same for everyone sits in the display case of the branch near your house, so you never go to the factory. At the factory's kitchen door there's a rack of loaves fresh out of the oven, for the couriers from the branches who arrive a few seconds later. In the kitchen fridge there's dough ready to bake, so not every loaf starts from flour. Every loaf has an expiry date. A birthday cake with your name on it is never put on display. When the recipe changes, the old loaves are taken out of the display case. notes-api has exactly the same layers: the CDN (the branch display case), nginx proxy_cache on web-1 (the rack at the kitchen door), Redis (the fridge: a very fast database kept in memory) and Postgres (the flour store: the real data). The expiry date is how long each copy may live. The cake with a name is data that belongs to one user (a person who is logged in). Taking old loaves out of the display case is deleting old copies on a deploy.

Four layers in front of notes-api

A request travels from the outside in, and stops at the first layer that has a copy:

Layer Where Keeps what For how long
CDN (Cloudflare) edges in Jakarta, Surabaya, Singapore public answers that are the same for everyone the s-maxage from the header
nginx proxy_cache the disk of web-1 answers from Node that may be shared 10 seconds (in the config)
Redis memory, next to the app query results, per key EX 60 per key
Postgres the database disk the real data forever

The last column is how long a copy may live. s-maxage and EX 60 are explained in the CDN and Redis sections below. Before the CDN there is still the browser cache, on the visitor's own device (covered in the lesson HTTP Caching: Cache-Control, ETag, Validation, Web Fundamentals track). Of the layers you run on servers, the CDN is the closest to the user: in distance and in order.

One minute of notes-api traffic

The Lab sends 10 requests a second for 1 minute, so 600 requests. Every second, 4 go to /assets/app.3f9a1c.js, 3 to /notes/popular, 1 to /notes/popular?fbclid=..., and 2 to /notes. fbclid is a code Facebook adds to a link when someone clicks it, different for each click. /notes is the list of notes of the logged-in user (20 users taking turns). Visitors come in through 3 edges. The time for each step is only an example: edge 15 ms (milliseconds), edge to web-1 30 ms, Redis 2 ms, the popular query 150 ms. The result:

Turned on Answered by the edge Reaches web-1 Reaches Node Postgres queries Average
no cache yet 0 (0%) 600 360 360 97 ms
CDN 414 (69%) 186 183 183 45.6 ms
CDN + nginx 414 (69%) 186 126 126 30.9 ms
CDN + nginx + Redis 414 (69%) 186 126 21 26.6 ms
all + cache key without query 474 (79%) 126 121 21 23.6 ms

The difference between the web-1 column and the Node column is the assets, which nginx sends straight from disk. The hit ratio is the percentage of requests answered from a cache: hit / total × 100. A hit means the copy was found in the cache, a miss means it wasn't. 414 of 600 makes 69%. Each layer catches the requests the layer before it didn't answer, so Postgres queries drop from 360 to 21.

CDN: s-maxage, Cache Rule and cache key

The CDN follows the Cache-Control header the app sends. This header decides who may keep an answer, and for how long:

app.get("/notes/popular", async (req, res) => {
  res.set("Cache-Control", "public, max-age=0, s-maxage=60");
  res.json(await getPopular());
});

app.get("/notes", requireLogin, async (req, res) => {
  res.set("Cache-Control", "private, no-store");
  res.json(await getUserNotes(req.user.id));
});

On Cloudflare, a path without a static file extension, such as /notes/popular, is not cached at all (its status is DYNAMIC). It is only cached once you create a Cache Rule (a caching rule in Cloudflare) that marks it eligible for cache (allowed to be cached).

The cache key is the name the CDN uses to decide whether two requests ask for "the same file". By default it is the full URL, query string (the part after ?) included. So /notes/popular?fbclid=IwAR1000 and ?fbclid=IwAR1001 are two different keys, and a new key is always a MISS. In one minute there are 60 Facebook clicks to /notes/popular?fbclid=..., each with its own fbclid. All 60 requests reach web-1. That's why the CDN seems not to work. Set this path's cache key to ignore the query string, and the hit ratio goes from 69% to 79%. The requests that still reach web-1 are almost all /notes (20% of all requests), which must never be kept on the CDN anyway.

nginx proxy_cache on web-1

The CDN has many edges, and each edge misses on its own. nginx on web-1 (from the lesson Reverse Proxy & Load Balancing) keeps one copy for all the edges:

# /etc/nginx/sites-available/notes-api
proxy_cache_path /var/cache/nginx/notes levels=1:2 keys_zone=notes:10m max_size=100m inactive=10m;

server {
    server_name notes.example.com;

    location /notes/popular {
        proxy_pass http://127.0.0.1:3000;
        proxy_cache notes;
        proxy_cache_key $scheme$host$uri;
        proxy_cache_valid 200 10s;
        proxy_ignore_headers Cache-Control;
        add_header X-Cache-Status $upstream_cache_status;
    }
}

The result: the 63 popular requests the CDN didn't answer (3 misses from the edges plus 60 fbclid clicks) become 6 that reach Node, one every 10 seconds. A PHP app (Laravel through PHP-FPM) uses fastcgi_cache, the PHP version of proxy_cache, the same way.

Redis: cache-aside for application data

A request that reaches Node still doesn't have to touch Postgres. The most common pattern is called cache-aside (or lazy loading): check the cache first. If the data isn't there (a miss), fetch it from the database, then store it in the cache for the next request.

async function getUserNotes(userId) {
  const key = `notes:user:${userId}`;
  const cached = await redis.get(key);
  if (cached !== null) return JSON.parse(cached); // HIT
  const { rows } = await db.query("SELECT id, title, content FROM notes WHERE user_id = $1", [userId]);
  await redis.set(key, JSON.stringify(rows), { EX: 60 }); // MISS: keep 60 seconds
  return rows;
}

Deploys: purge from the inside out

The hardest part of caching is cache invalidation: making sure a copy is deleted or replaced as soon as the real data changes. There are three ways:

On a deploy, the CDN can be emptied early with a purge (deleting the copies in a cache). In the Lab, if you deploy a new version at second 30 without a purge, 192 answers in the next minute are still the old version. The reason: the edges refill their copies from nginx and Redis, which still hold the old version too. With a purge, it's 0. The order is from the inside out: Redis, then nginx, then the CDN through Cloudflare's API:

# the end of deploy.sh
redis-cli DEL notes:popular
sudo find /var/cache/nginx/notes -type f -delete
curl -X POST "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/purge_cache" \
  -H "Authorization: Bearer $CF_API_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{"files":["https://notes.example.com/notes/popular"]}'

Assets need no purge, because their new file name has never been in any cache.

Reading Cache-Control the way a CDN does

In the exercise, parseCacheControl(header) turns the header into an object. Split the header on commas, then trim() each part (remove the spaces at its ends). A part containing = is split into a key and a number (Number). A part without = becomes a key with the value true. The keys follow the order of the header:

Call Result
parseCacheControl("public, max-age=86400") { public: true, "max-age": 86400 }
parseCacheControl("private, no-cache, no-store") { private: true, "no-cache": true, "no-store": true }
parseCacheControl("public, max-age=3600, s-maxage=7200") { public: true, "max-age": 3600, "s-maxage": 7200 }

⚠️ Caches that leak, split, or go stale

TL;DR: A cache keeps a copy of an answer so a request stops before it reaches the source. For notes-api the order is the CDN (servers in many cities, closest to the user), nginx proxy_cache on web-1, Redis (a database in memory) next to the app, then Postgres. In the Lab, 360 queries a minute drop to 21. Hit ratio (the percentage of requests answered from a cache) = hit / total × 100. The CDN follows the Cache-Control header: public, max-age=31536000, immutable for hashed assets (their file name changes when the content changes), s-maxage for shared caches such as the CDN and nginx, and private, no-store for per-user data. The default cache key (the name the CDN uses to match requests) is the full URL, query string (the part after ?) included, so a random query string means the copy is not found (a MISS). Redis uses cache-aside: check the cache, on a miss fetch from the database, then store it with EX (a lifetime in seconds). The main problem of caching is cache invalidation, which means deleting copies that are out of date: use a TTL (a lifetime), delete when the data changes, or change the file name. On a deploy, purge (empty) the caches from the inside out: Redis, nginx, then the CDN.

⚡ Four layers, stop at the first with a copy

Write:

CDN  ->  nginx proxy_cache  ->  Redis  ->  Postgres

Meaning: These are notes-api's four layers, from the outside in: the CDN (servers in many cities), nginx on web-1, Redis (a database in memory) next to the app, then Postgres, which holds the real data. A request stops at the first layer that has a copy. Hit ratio (the percentage of requests answered from a cache) = hit / total × 100: if the CDN answers 414 of 600 requests, its hit ratio is 69%.

⚡ The header decides who may keep it

Write:

app.get("/notes/popular", async (req, res) => {
  res.set("Cache-Control", "public, max-age=0, s-maxage=60");
  res.json(await getPopular());
});

Meaning: The Cache-Control header decides who may keep an answer. max-age=0 makes the browser always ask again, but s-maxage=60 lets a shared cache (a cache used by many visitors) such as the CDN or nginx keep it for 60 seconds. Per-user data uses private, no-store, so user 3's notes are never given to user 7.

⚡ The cache key: the full URL

Guess first: the CDN matches copies by their cache key, which by default is the full URL. There are 60 Facebook clicks to /notes/popular?fbclid=..., each with its own fbclid. How many reach web-1?

All 60. The default cache key is the full URL, query string (the part after ?) included. So every new fbclid is a new key, and a new key is always a MISS (there is no copy).

Meaning: Set the cache key of /notes/popular to ignore the query string, and the hit ratio goes from 69% to 79%.

⚡ Cache-aside in Redis

Write:

async function getUserNotes(userId) {
  const key = `notes:user:${userId}`;
  const cached = await redis.get(key);
  if (cached !== null) return JSON.parse(cached); // HIT
  const { rows } = await db.query("SELECT id, title, content FROM notes WHERE user_id = $1", [userId]);
  await redis.set(key, JSON.stringify(rows), { EX: 60 }); // MISS: keep 60 seconds
  return rows;
}

Meaning: This is the cache-aside pattern in Redis. Check the cache first. If the data isn't there, fetch it from the database, then store it with a TTL (how long the copy may live) of 60 seconds for the next request. The key is per user, so per-user data is cached here, not on the CDN.

What you will learn