Thuta Learning
ရှာဖွေရန်
Redis
IntermediateData & Databasesbeginner

Cache-Aside Pattern

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Cache-Aside Pattern concept ကို နားလည်ရှင်းပြနိုင်ရန်
  • နမူနာ Redis command/code ကို ကိုယ်တိုင် run ပြီး output စစ်နိုင်ရန်
  • Tutorial Platform project နှင့် production scenario တွင် မှန်ကန်စွာအသုံးချနိုင်ရန်

နားလည်ထားရမယ့် အချက်

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 ထားရမယ်။

အတူတူ စမ်းရေးကြည့်မယ်

typescript
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;
}
You should see
ပထမ 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 CachingRedis

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • Database update မတိုင်မီ cache ဖျက်ရင် concurrent reader က old DB value ကို cache ပြန်ဖြည့်နိုင်ပါတယ်။
  • နမူနာ command ကို production Redis ပေါ် တိုက်ရိုက်မစမ်းဘဲ local/test instance နဲ့ recoverable data ပေါ်တွင် အရင်အတည်ပြုပါ။

လေ့ကျင့်ခန်း

Tutorial list pagination အတွက် cache key scheme၊ TTL နဲ့ invalidation events ရေးပါ။

You'll know it worked when: ပထမ request က PostgreSQL ဖတ်ပြီး နောက် request များ Redis hit ဖြစ်မည်။

Cache-Aside Pattern | Thuta Learning