← Semua pelajaran
Cara kerja cache-aside
Miss, isi, hit
Redis
Aplikasi
Database
products.js
async function getProduct(id) { const key = `product:${id}`; const cached = await redis.get(key); // coba Redis dulu if (cached) return JSON.parse(cached); // miss: ke database const row = await db.query( "SELECT * FROM products WHERE id = $1", [id]); // simpan selama 60 s await redis.set(key, JSON.stringify(row), "EX", 60); return row;}products.js
async function setPrice(id, price) { // tulis ke database dulu await db.query( "UPDATE products SET price = $1 WHERE id = $2", [price, id]); await redis.del(`product:${id}`); // lalu buang salinan di cache}Baca, tulis, dan biarkan waktu jalan lalu tangkap pembacaan yang basi
Di Redis t = 0 s
Di database
Pembacaan terakhir
products.js
async function getProduct(id) { const key = `product:${id}`; const cached = await redis.get(key); // coba Redis dulu if (cached) return JSON.parse(cached); // miss: ke database const row = await db.query( "SELECT * FROM products WHERE id = $1", [id]); // simpan selama 60 s await redis.set(key, JSON.stringify(row), "EX", 60); return row;}products.js
async function setPrice(id, price) { // tulis ke database dulu await db.query( "UPDATE products SET price = $1 WHERE id = $2", [price, id]); await redis.del(`product:${id}`); // lalu buang salinan di cache}Key populer kedaluwarsa dan semua pembaca miss bersamaan
Query database untuk product:42
Database ini menjalankan 40 query sekaligus. Sisanya mengantre di belakang
products.js
async function getProduct(id) { const key = `product:${id}`; const cached = await redis.get(key); if (cached) return JSON.parse(cached); // hanya satu request yang boleh mengisi ulang key const got = await redis.set(`lock:${key}`, 1, "NX", "PX", 2000); if (!got) { await sleep(5); // yang lain menunggu sebentar, lalu baca 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;}Topik
Berikutnya: Cara kerja consistent hashing
Buka pelajaran