နားလည်ထားရမယ့် အချက်
Cache-aside တွင် application က Redis ကိုအရင်ဖတ်ပြီး miss ဖြစ်မှ PostgreSQL ကိုဖတ်ကာ result ကို TTL နဲ့ cache ထဲထည့်ပါတယ်။ Write လုပ်ရာတွင် database commit အောင်မြင်ပြီးမှ သက်ဆိုင်ရာ cache key ကိုဖျက်ရပါတယ်။ Hit rate မြင့်သော်လည်း stale data၊ stampede နဲ့ cold-start behavior ကို ဒီဇိုင်းထဲထည့်ရပါတယ်။
လက်တွေ့ scenario နဲ့ ချိတ်ကြည့်မယ်
Tutorial detail ကို `tutorial:42:v1` key ဖြင့် cache လုပ်မယ်။ Miss ဖြစ်လျှင် parameterized SQL ဖြင့်ဖတ်၊ JSON serialize လုပ်ပြီး jitter ပါသော TTL ထည့်မယ်။ Update commit ပြီးလျှင် key ကို `DEL` လုပ်မယ်။ Redis မရလျှင် database သို့ fallback လုပ်ပေမယ့် overload protection ထားရမယ်။
အတူတူ စမ်းရေးကြည့်မယ်
async function getTutorial(id: number) {
const key = `tutorial:${id}:v1`;
const cached = await redis.get(key);
if (cached) return JSON.parse(cached);
const tutorial = await db.oneOrNone(
'SELECT id, title, summary FROM tutorials WHERE id = $1', [id]
);
if (tutorial) await redis.set(key, JSON.stringify(tutorial), { EX: 300 + Math.floor(Math.random() * 30) });
return tutorial;
}ပထမ request က PostgreSQL ဖတ်ပြီး နောက် request များ Redis hit ဖြစ်မည်။၅ မိနစ် စမ်းကြည့်
Tutorial list pagination အတွက် cache key scheme၊ TTL နဲ့ invalidation events ရေးပါ။
သတိလေးတစ်ချက်
Database update မတိုင်မီ cache ဖျက်ရင် concurrent reader က old DB value ကို cache ပြန်ဖြည့်နိုင်ပါတယ်။
Redis — Client-Side Caching — Redis