17 min read
Redis cache: what to store and when to clear it
In one sentence: A cache keeps, for a while, the answer to something that is asked for a lot and changes little, so the database isn’t asked every time. The shop keeps its catalog for a minute in a second Redis, deletes it as soon as a product changes (its stock too) and, if the cache fails, reads from PostgreSQL as before, with no errors.
What you will learn
- Explain cache-aside and measure what the shop gains from it.
- Decide what to cache, for how long and what never to cache.
- Delete from the cache what changes, at the right moment, and check it.
- Make sure a cache that is down or stuck doesn’t take the API down with it.
Before you start, read: 01-queues.md phase-5/10-nosql.md
The problem
Section titled “The problem”In the introduction you measured the product list: about 715 requests per second, with a median of 12 ms. Each one runs the same query against PostgreSQL, which gives the same answer every time: four products that change a few times a day.
Imagine the shop sends an email with a special offer and thousands of people open the catalog at once. PostgreSQL spends its time repeating the same answer, and the orders, which do need the database, wait their turn behind them.
The fix is to keep the answer for a while and hand it to everyone: a cache. The hard part is knowing when to throw it away: according to a famous line by Phil Karlton, in computer science there are only two hard things, cache invalidation and naming things.
The analogy
Section titled “The analogy”The analogy
In a bar, the waiter writes the day’s tapas on a blackboard in the morning. Whoever walks in looks at it, and nobody has to go to the kitchen to ask what there is.
When the omelet runs out, someone has to wipe it off the board; if not, people will keep ordering it. And even if it’s written up, when you order, the kitchen checks whether any is really left.
Where the analogy breaks down
- The blackboard doesn’t wipe itself. What the cache keeps does: it expires after a minute, even if nobody deletes it.
- In the bar, whoever changes the menu is standing next to the board. In the shop, changes come from several places in the code, and one of them can forget to delete.
How it really works
Section titled “How it really works”Four places where copies are kept
Section titled “Four places where copies are kept”A CacheA saved copy of an answer, so it doesn’t have to be fetched again. It saves time, at the cost of the copy possibly being stale until it expires.Go to definition is a saved copy, so you don’t ask for the same thing again. You already know two of them from Phase 2:
| Where | Who keeps the copy | Can you delete it when the data changes? |
|---|---|---|
| The browser | Each visitor, following your Cache-Control |
No: it only expires, or asks with the ETag |
| A CDN | Servers spread around the world | With its dashboard or its API |
| Your application | Your API, in a Redis | Yes: your code deletes what it wants, when it wants |
| The database | PostgreSQL, in its memory | No need: it’s never stale, PostgreSQL keeps it up to date |
This lesson’s is the third one: your code deletes it at the very moment the data changes, which in Phase 2 was the hard part.
Cache-aside: the cache first, and if it isn’t there, PostgreSQL
Section titled “Cache-aside: the cache first, and if it isn’t there, PostgreSQL”This is how the shop answers two people who ask for the same mug, one after the other:
- Cache (Redis) → The shop's API(nil), not there
- PostgreSQL → The shop's APIthe mug, 850 cents
- The shop's API → Browser200, the mug
- Cache (Redis) → The shop's APIthe mug
- The shop's API → Browser200, without asking PostgreSQL
It’s the diagram from Phase 5, now in the shop. It’s called Cache-asideA way of using a cache in which your application does the work. It looks in the cache first; if the answer is there, it uses it, and if not, it asks the database and saves the answer in the cache for next time.Go to definition (“the cache on the side”): the database doesn’t know the cache exists, and the application looks, reads and stores. In src/cache.ts:
// Cache-aside: the cache first. If it has the key, that is the answer, and PostgreSQL never// hears about it. If not, it is read from the database (read), stored in the cache for the next// ones, with its expiry, and returned. It is stored as JSON: Redis stores text.// If the cache fails, it is read from the database, just as without a cache: slower, never an// error.async fromCache<T>(key: string, seconds: number, read: () => Promise<T>): Promise<T> { let stored: string | null; try { stored = await ask(() => client.get(key)); } catch (error) { log.debug({ key, reason: (error as Error).message }, 'cache: cannot read'); return read(); } if (stored !== null) return JSON.parse(stored) as T; const value = await read(); // What doesn't exist (undefined, a product that isn't there) isn't stored: it is asked every time. if (value === undefined) return value; // It is stored without waiting: the answer is already there, and it needn't wait for Redis. // PX: the expiry, in milliseconds. After that time, Redis deletes the key by itself. ask(() => client.set(key, JSON.stringify(value), { PX: duration(seconds) })).catch( (error: Error) => log.debug({ key, reason: error.message }, 'cache: cannot store'), ); return value;},read: the function that asks PostgreSQL; it’s only called if the cache doesn’t have the key.ask(…): asks Redis for the key, with the time limit you’ll see below.JSON.parseandJSON.stringify: Redis stores text, so the product goes in as JSONJSON stands for JavaScript Object Notation.A format for writing data as text, with braces, quotes and colons: {"product":"mug","quantity":2}. People can read it, and so can almost any programming language, and it’s the most common format for the data that travels between a frontend and a backend.Go to definition.value === undefined: a product that doesn’t exist isn’t stored.- The
SEThas noawait: the response doesn’t wait for Redis to store it. - The
catchreturnsread(): if the cache fails, it reads from PostgreSQL. Slower, never an error.
One key for each different question
Section titled “One key for each different question”What gets stored, and under what name? In src/data.ts:
// The catalogue, with a cache (cache.ts, Phase 9): what is asked for most and changes least. Each// list has its own key, because each filter gives another: products:list:{} is the whole list, and// products:list:{"sort":"price"}, the one sorted by price. The filter, as JSON, always with the// fields in the same order (the one of this object), and without the ones that haven't arrived.// Each product, in products:<id>. A minute at most without asking PostgreSQL: if something// changes, it is deleted before then (forgetProducts).const SECONDS_IN_CACHE = 60;
export function listProducts(filter: Filter = {}): Promise<Product[]> { const { maxCents, sort, category } = filter; const key = `products:list:${JSON.stringify({ maxCents, sort, category })}`; return fromCache(key, SECONDS_IN_CACHE, () => readProducts(filter));}
export function findProduct(id: number): Promise<Product | undefined> { return fromCache(`products:${id}`, SECONDS_IN_CACHE, () => readProduct(id));}products:<id>: each product, under its own key. The mug isproducts:2.products:list:and the filter as JSON: each list, under its own. The whole one isproducts:list:{}; sorted by price,products:list:{"sort":"price"}. The fields always go in the same order, so the same question gives the same key.SECONDS_IN_CACHE = 60: a minute at most without asking PostgreSQL.
Every different value of ?category= is another key, including the ones that don’t exist: the cache’s memory limit keeps that from filling it up forever.
One minute, plus a bit of randomness
Section titled “One minute, plus a bit of randomness”Why does it expire, if the shop already deletes what changes? Because expiry is the safety net: if one day a change forgets to delete, the stale data lasts one minute at most. It’s the key’s TTL (time to live), the same EXPIRE from Phase 5. But it isn’t exactly one minute:
// How long a key lasts in the cache: the seconds asked for, plus up to 10 % at random. If all of// them lasted the same, the ones stored at the same time (at startup, or after deleting the lists)// would expire at the same time, and at that instant every request would go to PostgreSQL together:// a stampede. With 60 seconds, each one expires at some moment between 60 and 66, spread out.// random: Math.random, which gives a number between 0 and 1; in the tests, a fixed one.export function duration(seconds: number, random: () => number = Math.random): number { return Math.round(seconds * 1000 * (1 + 0.1 * random()));}duration(60) gives between 60,000 and 66,000 milliseconds, at random. When a key expires, the requests of that instant don’t find it and all go to PostgreSQL at once: that’s a Cache stampedeWhat happens when a heavily requested answer expires and, at that moment, many requests ask the database for it at once because none of them finds it in the cache. The database suddenly gets work that the cache used to save it.Go to definition. If many keys were stored at the same time (at startup, or after deleting the lists) and last the same, they expire together, and the stampedes all arrive at once. With the randomness, each one expires at a different moment.
Randomness doesn’t help with a single, very popular key: there is nothing to spread out. There, the fix is to let only one request read: with a short lock in Redis (SET products:2:lock 1 NX PX 2000, which only succeeds if the key doesn’t exist and expires after 2 seconds in case whoever holds it crashes), or, inside each copy of the API, with a single read that all the requests wait for (single flight).
The shop doesn’t need it: four products and a short query. With a query that takes seconds, it would.
What you don’t cache: what belongs to each person and what must be exact
Section titled “What you don’t cache: what belongs to each person and what must be exact”Not everything deserves a cache. The shop leaves out two things:
- What belongs to each person, like your orders. Each person would need their own key, which almost nobody else would read; and with a key that doesn’t include the person’s id, Carmen would see Marta’s orders.
- What has to be exact, like the stock when buying. The cache may show “60 left” right after a purchase, but buying never looks at the cache:
// The stock has gone down: the product and the lists go out of the cache, after the COMMIT. The// stock check above never looks at the cache: PostgreSQL does it, in the transaction. An old// number in the cache can be seen in the shop for a moment, but it can't be sold.if ('order' in result) await forgetProducts(productId);return result;The stock check is the UPDATE … WHERE stock >= quantity from Phase 5, inside a TransactionA group of SQL commands that the database treats as one: either all of them are saved, or none. It starts with BEGIN and ends with COMMIT, which saves it, or with ROLLBACK, which undoes all of it.Go to definition: PostgreSQL runs it with the real number. A stale number in the cache can be seen for a moment, but it can’t be sold. A test of the step checks it: with a stock of 1000 in the cache and 2 for real, buying 5 gives 409.
Invalidating: delete right after the change
Section titled “Invalidating: delete right after the change”In Phase 5 we promised you this: if Ana changes a price, the API deletes the key. That’s Cache invalidationMaking sure the saved copies of something that has changed stop being used. It’s hard because the server can’t notify the browsers that already have a copy; it only answers when asked. That’s why short expiration times are used, or the file gets a new name.Go to definition, and in the shop it’s a function:
// What to delete from the cache when a product changes, its stock too: the product (or products)// and every list, because they carry it inside. Always after the COMMIT.const forgetProducts = (...ids: number[]) => forget(...ids.map((id) => `products:${id}`), 'products:list:*');It deletes the product and every list, since they carry it inside. It’s called by the six places that change a product: creating it, changing it, deleting it and, the easy ones to forget, placing an order, changing its quantity and canceling one, which change its stock. Changing it is a new route, PATCH /v2/products/{id}: admin only, for the name, the price or both.
// Changes the name, the price or both (whichever arrive: Drizzle skips the undefined ones). After// the change, the product and the lists go out of the cache; and the product is read again from// PostgreSQL, with its categories, just as it ended up. undefined if it doesn't exist.export async function updateProduct( id: number, changes: { name?: string | undefined; priceCents?: number | undefined },): Promise<Product | undefined> { const changed = await db .update(products) .set(changes) .where(eq(products.id, id)) .returning({ id: products.id }); if (changed.length === 0) return undefined; await forgetProducts(id); return readProduct(id);}Notice the order: first the UPDATE, then forgetProducts. If it deleted first, another request could slip in between, read the old price from PostgreSQL and store it again, for a minute.
Even so, a small Race conditionA bug that only shows up when two operations run at the same time and the result depends on which one gets there first. For example, two buyers read that there’s one mug left, and both buy it.Go to definition remains: a read that started before the change can store the old price right after the delete. That’s why everything expires: stale data lasts, at most, its TTL.
And this is how the cache deletes:
// Deletes those keys from the cache, so the next read goes to the database. It is called after// changing something in PostgreSQL (after the COMMIT): if it were deleted before, another// request could store the old data again between the delete and the change. Even so, a read that// started before the change can store the old data right after the delete: that is why// everything expires, and the old data lasts, at most, its TTL.// A key with * is a pattern, as in redis-cli: products:list:* is every list. Redis can't delete// by pattern: SCAN finds them, a hundred at a time, and DEL deletes them. Walking the keys is// cheap in a small cache like this one; with millions, another way would be used (a version in// the name of the list keys, which changes on invalidation, and the old ones expire).// All of it, with a single 200 ms limit. If the cache fails, the change in the database is// already done and isn't undone, and the response doesn't wait: the cache stays down, and on// coming back it deletes everything about products (on-return).async forget(...keys: string[]): Promise<void> { try { await ask(() => remove(keys)); } catch (error) { log.debug({ keys, reason: (error as Error).message }, 'cache: cannot delete'); }},products:list:* is a pattern: all the lists. Redis can’t delete by pattern, so SCAN walks the keys a hundred at a time and DEL deletes the ones that match.
Two Redis, with opposite jobs
Section titled “Two Redis, with opposite jobs”The shop already had a Redis, the one for the login attempt limits and, since lesson 1, the queue. The cache goes in another one, because it needs exactly the opposite:
redis: the limits and the queue |
cache: the catalog |
|
|---|---|---|
| If it loses its data… | Notifications and emails are lost | It refills itself from PostgreSQL |
| On disk | Everything (--appendonly yes), in a volume |
Nothing |
| Memory limit | None: it grows up to what the machine has | 64 MB |
| To make room | Never deletes anything (noeviction) |
Deletes what nobody has read for the longest (allkeys-lru) |
Deleting data to make room is called EvictionDeleting data from a cache that has filled up to make room for other data. A rule decides what goes, such as removing whatever has gone unused the longest. Unlike expiry (TTL), which is based on time, eviction happens only because space ran out.Go to definition: for the queue it would mean losing jobs without warning; for the cache it’s welcome. LRU comes from least recently used. In compose.yaml:
# The cache (Phase 9, lesson 2): another Redis, with the same image and the opposite configuration# to the queue's. What it holds is a copy of what is in PostgreSQL: if it is lost, it fills itself# again. So:# --maxmemory 64mb: at most 64 MB of memory;# --maxmemory-policy allkeys-lru: at the limit, it deletes the keys nobody has read for the# longest (LRU, least recently used) to make room, instead of giving an error;# --save '' and --appendonly no: nothing on disk, and no volume. When it restarts, it starts empty.# No published port, like redis. Look inside with:# docker compose exec cache redis-cli keys '*'cache: image: redis:8@sha256:2c2dff791878316e3b083188be0d578423b24813cdda5de0e80ea4f7b3e6bfd6 command: [ 'redis-server', '--maxmemory', '64mb', '--maxmemory-policy', 'allkeys-lru', '--save', '', '--appendonly', 'no', ] healthcheck: test: ['CMD', 'redis-cli', 'ping'] interval: 2s timeout: 5s retries: 15The API finds it in CACHE_URL (redis://cache:6379), and the queue stays in REDIS_URL.
If the cache fails, the shop keeps going
Section titled “If the cache fails, the shop keeps going”A cache can fail in two ways:
- Down: the Redis stops and the connection is cut. The client knows right away.
- Stuck: the connection stays open, but no answer arrives. A frozen Redis, or a network that loses packets. The client sends the command and waits.
The first is solved by the client’s configuration:
// Its own client, not connectRedis's (redis-store.ts): a cache isn't waited for. The normal// client, with Redis down, keeps each command in a queue until it comes back, and the request// would wait with it.// disableOfflineQueue: without a connection, the command fails at once, without waiting in a// queue.// connectTimeout: one second to connect; then another attempt, and so on until it comes back.// That covers a cache that is down (the connection is cut). It doesn't cover one that is stuck: a// stopped Redis, or a network that loses the replies. The connection stays open, the client sends// the command and waits for the reply with no limit: node-redis has a timeout per command, but it// only counts while the command waits to go out, not after it is sent. That is why each command// goes with a clock of its own (withinTime, further down).const client = createClient({ url, disableOfflineQueue: true, socket: { connectTimeout: 1000 },});disableOfflineQueue: true: with no connection, the command fails at once. The limits’ client keeps commands until Redis comes back, and the request would wait along with them. Rate limits are worth waiting for; a cache isn’t.connectTimeout: 1000: one second to connect; then, another attempt.
The second has a story. node-redis, the Redis library, has a timeout per command, and the first version of this step relied on it. When we reviewed it, we found that it only counts while the command waits to go out, not after it has been sent: a test with a fake Redis that never answers kept waiting until its own 8-second limit cut it off.
The lesson: a time limit has to measure what your request waits for. The fix is in the down region of the same file:
withinTime(command): a race between the command and a 200 ms clock. Redis answers in under a millisecond; if it takes 200, something is wrong.ask(command), the onefromCacheandforgetuse: on the first failure it marks the cache as down, and while it is, it doesn’t even ask.- While it’s down, each request may send it a
PING(a command that only asks “are you there?”), one per second at most, to see whether it’s back. That way unanswered commands don’t pile up.
When it comes back, it deletes the whole catalog
Section titled “When it comes back, it deletes the whole catalog”While it was down, the shop may have changed a price without being able to delete it from the cache, and a frozen Redis keeps what it had:
// On coming back, the cache doesn't know what was lost: while it was down, the shop may have// changed products without deleting them from it (forget doesn't even ask), and Redis keeps what// it had (a network cut, a docker pause). So, before using it again, it deletes everything about// products (products:*: in this cache there is only catalogue, data.ts), with the same SCAN and// DEL as forget and the same 200 ms limit. If it can't, it stays down, and the next PING tries// again. It also happens the first time it connects: whatever was there from before this API// started (or from another copy), gone. Not FLUSHDB: it would delete everything in that Redis,// including what isn't the cache's.let returning = false;async function comeBack() { if (returning) return; returning = true; try { await withinTime(() => remove(['products:*'])); } catch (error) { markDown((error as Error).message); return; } finally { returning = false; } down = false; markReady(); if (warned) log.info('the cache is answering again'); warned = false;}The cache doesn’t know what it missed, so it deletes everything about products (products:*) before being used again. If it can’t do it within 200 ms, it stays down and tries again with the next PING. It also happens the first time the API connects. FLUSHDB would delete everything, including anything that isn’t catalog data.
Try it
Section titled “Try it”The goal: see what the cache stores, change the mug’s price and check that nobody sees the old one, and then knock the cache down without the shop ever stopping answering.
The outputs are from Docker in Colima (4 CPUs and 2 GiB) on an Apple M1 Pro, on October 21 and 22, 2026. We captured them with another Compose project name, changed here to the lesson’s, and with curl inside a container; the responses are the same. Your times, ids and dates will be different. The tables are from autocannon 8.0.0; 9.0.0 prints the same ones.
Get the step ready
Section titled “Get the step ready”Bring down the step 37 shop (-v deletes its practice data) and bring your project up to step 38, as in the introduction:
cd ~/backend-course/phase-3/shop-apidocker compose down -vcd ..curl -O https://backenddesdecero.com/practicas/shop-api/38-cache.tar.gztar -xzf 38-cache.tar.gzcp -R 38-cache/. shop-api/cd shop-apiWhat’s new: src/cache.ts, its use in src/data.ts, the PATCH route, CACHE_URL in config.ts and the cache service in both Compose files. There are no new packages. Start it:
1. Six containers
docker compose up --build --waitdocker compose ps --format "table {{.Name}}\t{{.Service}}\t{{.Status}}"What you will see:
…NAME SERVICE STATUSshop-api-1 api Up 10 seconds (healthy)shop-cache-1 cache Up 14 seconds (healthy)shop-db-1 db Up 14 seconds (healthy)shop-mailpit-1 mailpit Up 14 seconds (healthy)shop-redis-1 redis Up 14 seconds (healthy)shop-worker-1 worker Up 10 seconds (healthy)shop-cache-1 is the new Redis. If your API is on 3001 (docker compose port api 3000 tells you), use that port in the rest of the practice.
What does the cache store?
Section titled “What does the cache store?”2. The mug, twice
curl -s -w '\n' localhost:3000/v2/products/2docker compose exec cache redis-cli keys '*'curl -s -w '\n' localhost:3000/v2/products/2docker compose exec cache redis-cli keys '*'docker compose exec cache redis-cli pttl products:2What you will see:
{"id":2,"name":"Mug","priceCents":850,"stock":60,"categories":["Home","Gifts"]}(empty array){"id":2,"name":"Mug","priceCents":850,"stock":60,"categories":["Home","Gifts"]}1) "products:2"(integer) 63903After the first one, the cache is empty: the API opens the connection the first time it needs it, and that read goes to PostgreSQL. After the second, there’s products:2, and pttl tells you the milliseconds it has left: 63903, because of the randomness. keys '*' lists all the keys: fine in a small cache, but with millions it would block Redis for a while.
Ana changes the mug’s price
Section titled “Ana changes the mug’s price”Ana is one of the practice accounts, an admin, with her password in the project’s README. First ask for the mug and the whole list, so there are two keys:
3. The change, and the empty cache
curl -s -o /dev/null localhost:3000/v2/products/2curl -s -o /dev/null localhost:3000/v2/productsdocker compose exec cache redis-cli keys '*'curl -s -w '\n' -c ana.txt --json '{"email":"ana@shop.example","password":"ana-practice-2026"}' localhost:3000/v2/sessioncurl -s -w '\n' -b ana.txt -X PATCH --json '{"priceCents":900}' localhost:3000/v2/products/2docker compose exec cache redis-cli keys '*'What you will see:
1) "products:2"2) "products:list:{}"{"id":1,"email":"ana@shop.example","role":"admin"}{"id":2,"name":"Mug","priceCents":900,"stock":60,"categories":["Home","Gifts"]}(empty array)The PATCH answers with the mug at 900, and then, (empty array): it deleted both keys. If you get 401, repeat the ana.txt line; with 403, the account isn’t an admin.
4. The next read already gives the new price
curl -s -w '\n' localhost:3000/v2/products/2docker compose exec cache redis-cli keys '*'What you will see:
{"id":2,"name":"Mug","priceCents":900,"stock":60,"categories":["Home","Gifts"]}1) "products:2"900, and the key is back with the new price.
Challenge: Carmen (carmen@example.com, password carmen-practice-2026) buys a mug. Before she does, what do you expect to see in the cache after her order, and what stock will the mug show?Show answer
The keys disappear (an order changes the stock) and the mug shows one less. Ours, with both keys already in the cache:
$ curl -s -w '\n' localhost:3000/v2/products/2{"id":2,"name":"Mug","priceCents":900,"stock":60,"categories":["Home","Gifts"]}$ curl -s -o /dev/null localhost:3000/v2/products$ docker compose exec cache redis-cli keys '*'1) "products:2"2) "products:list:{}"$ curl -s -w '\n' -c carmen.txt --json '{"email":"carmen@example.com","password":"carmen-practice-2026"}' localhost:3000/v2/session{"id":3,"email":"carmen@example.com","role":"customer"}$ curl -s -w '\n' -b carmen.txt --json '{"productId":2,"quantity":1}' localhost:3000/v2/orders{"id":26,"productId":2,"quantity":1,"status":"pending","createdAt":"2026-10-22T14:43:31.278Z","customerId":3}$ docker compose exec cache redis-cli keys '*'(empty array)$ curl -s -w '\n' localhost:3000/v2/products/2{"id":2,"name":"Mug","priceCents":900,"stock":59,"categories":["Home","Gifts"]}With a cache and without one
Section titled “With a cache and without one”The Load testAn experiment in which a program sends many requests in a row to your server to measure how many it can take and how long it takes to answer. It tells you where the limit is before your users find it.Go to definition from the introduction, now with the cache. This output is from October 21, and we removed npm’s warning lines:
5. The load test, with a cache
docker run --rm --network shop_default node:26 npx -y autocannon@9.0.0 -d 10 http://api:3000/v2/productsWhat you will see:
Running 10s test @ http://api:3000/v2/products10 connections
┌─────────┬──────┬──────┬───────┬──────┬─────────┬─────────┬───────┐│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │├─────────┼──────┼──────┼───────┼──────┼─────────┼─────────┼───────┤│ Latency │ 0 ms │ 0 ms │ 1 ms │ 2 ms │ 0.21 ms │ 0.69 ms │ 29 ms │└─────────┴──────┴──────┴───────┴──────┴─────────┴─────────┴───────┘┌───────────┬─────────┬─────────┬─────────┬─────────┬──────────┬────────┬─────────┐│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │├───────────┼─────────┼─────────┼─────────┼─────────┼──────────┼────────┼─────────┤│ Req/Sec │ 9,799 │ 9,799 │ 12,295 │ 13,207 │ 12,129.6 │ 890.34 │ 9,793 │├───────────┼─────────┼─────────┼─────────┼─────────┼──────────┼────────┼─────────┤│ Bytes/Sec │ 9.15 MB │ 9.15 MB │ 11.5 MB │ 12.3 MB │ 11.3 MB │ 833 kB │ 9.15 MB │└───────────┴─────────┴─────────┴─────────┴─────────┴──────────┴────────┴─────────┘
Req/Bytes counts sampled once per second.# of samples: 10
121k requests in 10.01s, 113 MB readCompare Req/Sec, Avg column, with yours from the introduction: we went from 715.5 to 12,129.6 requests per second, about 17 times more, and the 99th PercentileA number that says what share of the measurements falls below it. If the 99th percentile of the responses is 400 ms, 99% of the requests took 400 ms or less and only one in a hundred took longer. It shows the slow cases that an average hides.Go to definition went from 42 ms to 2 (the 0 ms is rounding of 0.21). The test only reads, so nothing deletes the cache while it runs. Keep in mind that autocannon and the API share the same 4 CPUs of the Docker virtual machine, so the numbers are honest, but they aren’t those of a server that only handles the API.
Now stop the cache, as if it went down:
6. Without a cache, the shop keeps going
docker compose stop cachefor i in 1 2 3; do curl -s -o /dev/null -w '%{http_code} %{time_total}\n' localhost:3000/v2/products; donedocker compose logs api --since 1m | grep cacheWhat you will see:
…200 0.006907200 0.006842200 0.007086api-1 | {"level":40,"time":1792680212052,"pid":1,"hostname":"3d4dae2b00c7","reason":"Socket closed unexpectedly","msg":"the cache is not answering: reading from the database"}Three 200s (-w writes the code and the time, in seconds), and a single line in the log, of level 40 (warning).
7. The load test, with the cache stopped
docker run --rm --network shop_default node:26 npx -y autocannon@9.0.0 -d 10 http://api:3000/v2/productsWhat you will see:
…┌─────────┬──────┬───────┬───────┬───────┬──────────┬──────────┬────────┐│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │├─────────┼──────┼───────┼───────┼───────┼──────────┼──────────┼────────┤│ Latency │ 6 ms │ 14 ms │ 45 ms │ 70 ms │ 16.73 ms │ 15.71 ms │ 338 ms │└─────────┴──────┴───────┴───────┴───────┴──────────┴──────────┴────────┘┌───────────┬────────┬────────┬────────┬────────┬────────┬────────┬────────┐│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │├───────────┼────────┼────────┼────────┼────────┼────────┼────────┼────────┤│ Req/Sec │ 381 │ 381 │ 527 │ 735 │ 580.4 │ 112.88 │ 381 │…6k requests in 10.02s, 5.42 MB read580.4 per second: the speed of going to PostgreSQL every time, a bit below the introduction’s 715.5 because the machine was busier that day, and with no errors: the API doesn’t even ask a cache that’s down. We trimmed the start and the bytes row.
8. The cache comes back
docker compose start cachedocker compose logs api --since 2m | grep cacheWhat you will see:
…api-1 | {"level":40,"time":1792680212052,"pid":1,"hostname":"3d4dae2b00c7","reason":"Socket closed unexpectedly","msg":"the cache is not answering: reading from the database"}api-1 | {"level":30,"time":1792680240067,"pid":1,"hostname":"3d4dae2b00c7","msg":"the cache is answering again"}The client reconnects by itself, deletes the catalog (it was already empty here: it keeps nothing on disk) and says so: the cache is answering again. If it doesn’t show up yet, wait a few seconds.
A stuck cache
Section titled “A stuck cache”docker compose pause freezes the container: the connection stays open, but Redis doesn’t answer. It’s the hard case:
9. Freeze the cache
docker compose pause cachefor i in 1 2 3; do curl -s -o /dev/null -w '%{http_code} %{time_total}\n' localhost:3000/v2/products; donedocker compose logs api --since 1m | grep cacheWhat you will see:
…200 0.265092200 0.008280200 0.011517…api-1 | {"level":40,"time":1792680245490,"pid":1,"hostname":"3d4dae2b00c7","reason":"no answer in 200 ms","msg":"the cache is not answering: reading from the database"}The first request takes 0.265 seconds: the clock’s 200 ms, plus the PostgreSQL read. The next ones, between 8 and 12 ms: the cache is already marked as down. Without the clock, they would wait for Redis with no limit. The trimmed log lines are those from steps 6 and 8.
10. Unfreeze it
docker compose unpause cachefor i in 1 2 3; do curl -s -o /dev/null -w '%{http_code} %{time_total}\n' localhost:3000/v2/products; donedocker compose logs api --since 1m | grep cacheWhat you will see:
…200 0.012116200 0.006618200 0.001175…api-1 | {"level":40,"time":1792680245490,"pid":1,"hostname":"3d4dae2b00c7","reason":"no answer in 200 ms","msg":"the cache is not answering: reading from the database"}api-1 | {"level":30,"time":1792680249147,"pid":1,"hostname":"3d4dae2b00c7","msg":"the cache is answering again"}Once unfrozen, nobody notices until a request arrives: the API doesn’t ask it yet, but it sends it a PING along the way. Redis answers, the API deletes products:*, in case it held something stale, and starts using it again: the third request already comes from the cache. With no requests, the last line doesn’t show up.
When you’re done, delete the sessions, which don’t go to Git: rm ana.txt carmen.txt (carmen.txt only exists if you did the challenge).
On your server
Section titled “On your server”As in lesson 1, first the files the server reads from its disk, from ~/backend-course/phase-3, with your user and your IP:
rsync -av 38-cache/compose.production.yaml ubuntu@192.168.5.15:/opt/shop/rsync -av 38-cache/deployment/ ubuntu@192.168.5.15:/opt/shop/deployment/Then, the code: it’s already in your project, so commit and git push from shop-api. Nothing needs to be added to the server’s .env: compose.production.yaml gives the API CACHE_URL=redis://cache:6379, and deploy.sh starts the cache service next to db and redis. It adds up to 64 MB of data to the server’s memory, plus Redis itself.
You have already seen it
Section titled “You have already seen it”- “Only 3 left,” and at checkout, sold out. The product page came from a cache; the payment looked at the database, like the shop’s
409. - A “like” counter that is slow to go up. What you see can be a few seconds behind the truth. In lesson 6 you’ll see it has a name: eventual consistency.
- The Redis from Phase 5. The
SETand theEXPIREyou wrote by hand are whatfromCachedoes now, in a single command (SET … PX).
Common mistakes
Section titled “Common mistakes”- Deleting before changing the database, instead of after the
COMMIT. - Forgetting a place that changes the data, like orders, which change the stock.
- Deciding based on what the cache says: selling or granting permissions with data that may be stale.
- Storing one person’s data under a key that has no user id.
- Waiting for the cache with no limit: a stuck cache hangs the whole API.
- The queue and the cache in the same Redis: the queue can lose jobs to make room.
Summary
Section titled “Summary”- A cache keeps, for a while, what is asked for a lot and changes little. With cache-aside, the API looks in the cache first and, if it isn’t there, reads from PostgreSQL and stores it.
- In the shop, the catalog: in our test, about 17 times more requests per second, and a p99 of 2 ms.
- Every change to a product, its stock too, deletes the product and the lists, after the
COMMIT. The TTL, 60 to 66 seconds, is the safety net. - What must be exact doesn’t come from the cache: buying checks the stock in PostgreSQL.
- The cache is another Redis, which can lose everything. If it goes down or gets stuck, the API waits 200 ms at most, reads from PostgreSQL and, when the cache is back, deletes the catalog.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Key eviction, from the Redis documentation:
maxmemoryand each policy, fromnoevictiontoallkeys-lru. - SCAN and SET: walking keys without blocking Redis, and the
PXandNXoptions of the lock. - Caching Best Practices, from AWS: cache-aside, TTL and stampedes.
- Scaling Memcache at Facebook: how Facebook avoids stampedes and stale data in one of the largest caches in the world.
- TwoHardThings, by Martin Fowler: Phil Karlton’s line and its variants.