Belajar
← All lessons

How cache-aside works

Miss, fill, hit

Redis
App
Database

products.js

async function getProduct(id) {  const key = `product:${id}`;  const cached = await redis.get(key); // try Redis first  if (cached) return JSON.parse(cached);  // miss: go to the database  const row = await db.query(    "SELECT * FROM products WHERE id = $1", [id]);  // keep it for 60 s  await redis.set(key, JSON.stringify(row), "EX", 60);  return row;}

products.js

async function setPrice(id, price) {  // write the database first  await db.query(    "UPDATE products SET price = $1 WHERE id = $2",    [price, id]);  await redis.del(`product:${id}`); // then drop the cached copy}

Read, write, and let time pass then catch a stale read

TTL60 s120 snoneOn writeDelete the keyLeave the cache
In Redis t = 0 s
In the database
Last read

products.js

async function getProduct(id) {  const key = `product:${id}`;  const cached = await redis.get(key); // try Redis first  if (cached) return JSON.parse(cached);  // miss: go to the database  const row = await db.query(    "SELECT * FROM products WHERE id = $1", [id]);  // keep it for 60 s  await redis.set(key, JSON.stringify(row), "EX", 60);  return row;}

products.js

async function setPrice(id, price) {  // write the database first  await db.query(    "UPDATE products SET price = $1 WHERE id = $2",    [price, id]);  await redis.del(`product:${id}`); // then drop the cached copy}

A hot key expires and every reader misses at once

Requests that arrive during the 38 ms refill
Refill lockOffOne refill at a time
Database queries for product:42

This database runs 40 queries at a time. The rest queue behind them

products.js

async function getProduct(id) {  const key = `product:${id}`;  const cached = await redis.get(key);  if (cached) return JSON.parse(cached);  // only one request may refill the key  const got = await redis.set(`lock:${key}`, 1, "NX", "PX", 2000);  if (!got) {    await sleep(5); // the others wait a moment, then read Redis    return getProduct(id);  }  const row = await db.query("SELECT …", [id]);  await redis.set(key, JSON.stringify(row), "EX", 60);  await redis.del(`lock:${key}`);  return row;}

Topics

Next: How consistent hashing works

Open lesson