Thuta Learning
AWS Advanced
Data at ScaleDevOpsအဆင့်မြင့်

ElastiCache နဲ့ Caching Strategy များ

AWS Advancedသင်ခန်းစာ 2240 မိနစ်

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

  • Cache-aside (lazy loading) နဲ့ write-through ရဲ့ trade-off တွေကို ရှင်းပြနိုင်မယ်
  • TTL, invalidation နဲ့ eviction policy ကို မှန်ကန်စွာ ပေါင်းသုံးနိုင်မယ်
  • Cache stampede ဘာကြောင့်ဖြစ်လဲ၊ jittered TTL နဲ့ lock နဲ့ ဘယ်လိုကာကွယ်လဲ ရှင်းပြနိုင်မယ်
  • Valkey/Redis OSS နဲ့ Memcached၊ cluster mode၊ Multi-AZ နဲ့ ElastiCache Serverless ကြား ရွေးချယ်နိုင်မယ်

ရိုးရိုးလေး ရှင်းပြမယ်

ရိုးရိုးလေး ရှင်းရရင်

Database ကို စားသောက်ဆိုင်ရဲ့ မီးဖိုချောင်လို့ စဉ်းစားကြည့်ပါ — ဟင်းတိုင်းကို အစကနေ ချက်ရလို့ နှေးပါတယ်။ Cache ကတော့ လူကြိုက်များတဲ့ ဟင်းတွေကို ပန်းကန်ထဲ အသင့်ထည့်ထားတဲ့ ကောင်တာပါ။ Customer အများစုက ကောင်တာကနေ ချက်ချင်း ယူသွားကြပြီး မီးဖိုချောင်က ကောင်တာမှာ မရှိတဲ့ ဟင်းကိုပဲ ချက်ရပါတယ်။

Amazon ElastiCache က ဒီကောင်တာကို managed service အဖြစ် ပေးပါတယ် — Valkey, Redis OSS ဒါမှမဟုတ် Memcached ကို run ပေးပြီး memory ထဲကနေ microsecond ပိုင်းအတွင်း data ပြန်ပေးပါတယ်။ ခက်တာက cache ကိုယ်တိုင် မဟုတ်ပါဘူး၊ ကောင်တာပေါ်က ဟင်းကို ဘယ်အချိန် လဲမလဲ၊ အေးသွားတဲ့ ဟင်းကို ဘယ်လို ဖယ်မလဲ ဆိုတဲ့ စည်းမျဉ်းတွေပါ။

Problem → Why → Solution

ပြဿနာ: တူညီတဲ့ row တွေကို တစ်စက္ကန့် ထောင်ချီ ဖတ်ခြင်း

Online shop တစ်ခုရဲ့ product page က request တိုင်းမှာ product row, price နဲ့ review အရေအတွက်ကို database ကနေ ဖတ်ပါတယ်။ Sale ရက်မှာ product တစ်ရာလောက်က traffic အများစုကို ယူပြီး database CPU က 90% ကျော်သွားပါတယ် — query တွေက တူညီတဲ့ data ကိုပဲ ထပ်ခါထပ်ခါ မေးနေတာပါ။

Team က အမြန်ဖြေရှင်းဖို့ application server တွေထဲမှာ dictionary cache တစ်ခု ထည့်လိုက်ပါတယ်။ Load ကျသွားပေမဲ့ ပြဿနာအသစ် နှစ်ခု ပေါ်လာပါတယ် — price ပြောင်းပြီး ရက်အတော်ကြာအထိ ဈေးဟောင်း ပြနေတယ်၊ deploy လုပ်လိုက်တိုင်း cache အားလုံး ပျောက်ပြီး traffic အားလုံးက database ပေါ် တစ်ပြိုင်နက် ပြန်ကျလာပါတယ်။

naive_cache.py
cache = {}  # per-process dict: lost on every deploy, different on every server


def get_product(db, product_id):
    key = f"product:{product_id}"
    if key in cache:
        return cache[key]
    product = dict(db[product_id])
    cache[key] = product  # BAD: no TTL, so a stale entry lives forever
    return product


def update_price(db, product_id, price):
    db[product_id]["price"] = price  # BAD: the cached copy is never invalidated

Cache တိုင်းမှာ freshness စည်းမျဉ်း လိုပါတယ်

Cache ဆိုတာ data ရဲ့ copy တစ်ခုပါ၊ copy တိုင်းက မူရင်းနဲ့ ကွဲလွဲနိုင်ပါတယ်။ ဘယ်လောက်ကြာကြာ ယုံမလဲ (TTL)၊ မူရင်းပြောင်းရင် ဘာလုပ်မလဲ (invalidation)၊ memory ပြည့်ရင် ဘာကို ဖယ်မလဲ (eviction) ဆိုတာ မသတ်မှတ်ရင် cache က မြန်ပေမဲ့ မှားတဲ့ data ပြန်ပေးပါလိမ့်မယ်။ Process ထဲက cache က server တစ်ခုချင်းစီ မတူဘဲ restart တိုင်း ပျောက်တာမို့ shared cache တစ်ခု လိုပါတယ်။

အဓိက သဘောတရား: Strategy, TTL, invalidation, eviction

Cache-aside (lazy loading)
Application က cache ကို အရင်ကြည့်ပါတယ်။ Miss ဖြစ်ရင် database ကနေ ဖတ်ပြီး ရလာတဲ့ data ကို TTL နဲ့အတူ cache ထဲ ထည့်ပါတယ်။ Cache က database နဲ့ တိုက်ရိုက် မဆက်သွယ်ပါဘူး။

Cache-aside က အသုံးအများဆုံး pattern ပါ၊ တကယ် တောင်းဆိုခံရတဲ့ data ကိုပဲ cache ထဲ ရောက်လို့ memory ကို ထိရောက်စွာ သုံးပါတယ်။ Cache node ပျက်သွားရင်လည်း application က နှေးသွားရုံပါပဲ၊ မပျက်ပါဘူး — database ကနေ ဆက်ဖတ်လို့ရလို့ပါ။ အားနည်းချက်ကတော့ key တစ်ခုစီရဲ့ ပထမ request က miss ဖြစ်ပြီး round trip သုံးခု (cache, database, cache) ကုန်တာပါ။

Write-through ကတော့ database ကို write လုပ်တိုင်း cache ကိုပါ တစ်ပြိုင်နက် update လုပ်ပါတယ်။ Cache က အမြဲ နောက်ဆုံး data ဖြစ်နေပေမဲ့ ဘယ်တော့မှ မဖတ်မယ့် data တွေပါ cache ထဲ ရောက်ပြီး write တိုင်း နှေးသွားပါတယ်။ လက်တွေ့မှာ cache-aside ကို write-time invalidation နဲ့ တွဲသုံးကြတာ များပါတယ်။

TTL က freshness အတွက် နောက်ဆုံး အာမခံချက်ပါ — invalidation တစ်ခုခု လွတ်သွားရင်တောင် stale data က TTL ကုန်တဲ့အထိပဲ ရှင်သန်ပါတယ်။ Data ပြောင်းတဲ့အခါ ပိုလုံခြုံတဲ့ အစီအစဉ်က database ကို အရင် write လုပ်ပြီးမှ cache key ကို delete လုပ်တာပါ၊ cache ကို update မလုပ်ပါနဲ့။ Delete လုပ်ထားရင် နောက် read က database ကနေ အသစ် ပြန်ဖြည့်ပါလိမ့်မယ်။

Eviction ကတော့ memory ပြည့်တဲ့အခါ ဖြစ်ပါတယ်။ Valkey/Redis OSS မှာ maxmemory-policy က ဘာကို ဖယ်မလဲ ဆုံးဖြတ်ပါတယ် — ElastiCache ရဲ့ default က volatile-lru (TTL ပါတဲ့ key တွေထဲက မကြာသေးခင် အသုံးအနည်းဆုံးကို ဖယ်) ပါ။ Cache သက်သက်ဆိုရင် allkeys-lru က များသောအားဖြင့် ပိုသင့်တော်ပါတယ်။ Evictions metric တက်နေရင် node သေးလွန်းနေတာပါ။

Strategyဘယ်လိုအလုပ်လုပ်လဲTrade-off
Cache-asideRead miss ဖြစ်မှ cache ကို ဖြည့်Memory ချွေတာ၊ ပထမ read နှေး၊ stale ဖြစ်နိုင်
Write-throughWrite တိုင်း cache ကိုပါ updateအမြဲ fresh၊ write နှေး၊ မသုံးတဲ့ data ပါ cache ထဲရောက်
TTL onlyKey တွေ အချိန်ကုန်ရင် ပျောက်ရိုးရှင်း၊ TTL ကုန်တဲ့အထိ stale ဖြစ်နိုင်
text
CACHE-ASIDE READ AND WRITE PATHS
--------------------------------
  READ PATH
  app --GET product:p1--> [ cache ]
          |
     hit? +--yes--> return value (no database call)
          |
          no
          v
  app --SELECT--> [ database ]
          |
          +--SET product:p1 EX 300 (+/- jitter)--> [ cache ]
          v
     return value

  WRITE PATH
  app --UPDATE--> [ database ]  then  app --DEL product:p1--> [ cache ]
Mental model: cache က TTL ပါတဲ့ copy တစ်ခု
  1. Read: try the cache first
  2. Miss: read DB, SET with jittered TTL
  3. Write: update DB, then DEL the key
  4. Full memory: eviction policy decides

Database က source of truth ပါ။ Cache ကို အချိန်မရွေး ဖျက်ပစ်လို့ရတယ်လို့ ယူဆပြီး design လုပ်ပါ။

Pattern: ElastiCache Serverless cache တစ်ခု ဖန်တီးခြင်း

create-cache.sh
# A Valkey serverless cache in two private subnets, with usage limits as a cost guard
aws elasticache create-serverless-cache \
  --serverless-cache-name product-cache \
  --engine valkey \
  --cache-usage-limits 'DataStorage={Maximum=10,Unit=GB},ECPUPerSecond={Maximum=5000}' \
  --subnet-ids subnet-0a1b2c3d4e5f67890 subnet-0f9e8d7c6b5a43210 \
  --security-group-ids sg-0cac4e1a2b3c4d5e6

# Wait for status "available", then read the single endpoint
aws elasticache describe-serverless-caches \
  --serverless-cache-name product-cache \
  --query "ServerlessCaches[0].[Status,Endpoint.Address,Endpoint.Port]"

Serverless cache က node type နဲ့ shard အရေအတွက် ရွေးစရာ မလိုဘဲ load အလိုက် အလိုအလျောက် scale လုပ်ပါတယ်။ --cache-usage-limits က data storage နဲ့ ECPU တစ်စက္ကန့်နှုန်းကို အများဆုံး ဘယ်လောက်အထိ ခွင့်ပြုမလဲ သတ်မှတ်ပြီး bill ကို ထိန်းပေးပါတယ်။ Security group မှာ application ရဲ့ security group ကနေ port 6379 ကိုပဲ ခွင့်ပြုပါ။ Serverless cache တွေက in-transit encryption ကို အမြဲ သုံးတာမို့ client မှာ TLS ဖွင့်ရပါမယ်။

Hit/miss ကို ပြတဲ့ deterministic cache-aside

ဒီ example မှာ InMemoryCache class က Valkey/Redis client ရဲ့ get, set(ex=..., nx=...), delete ကို အတုလုပ်ထားပါတယ်။ Production မှာ redis-py ဒါမှမဟုတ် valkey-glide client နဲ့ အစားထိုးရုံပါပဲ၊ pattern က အတူတူပါ။ FakeClock က အချိန်ကို လက်နဲ့ ရွှေ့ပေးလို့ TTL ကုန်တာကို စက္ကန့် ၄၀၀ မစောင့်ဘဲ မြင်ရပါတယ်။

Jitter အတွက် random number ကို seed 42 နဲ့ ထုတ်ထားတာက output ကို အမြဲတူအောင်ပဲ ဖြစ်ပါတယ်။ Production code မှာ seed မထည့်ပါနဲ့ — jitter ရဲ့ ရည်ရွယ်ချက်က key တွေ မတူညီတဲ့ အချိန်မှာ expire ဖြစ်ဖို့ပါ။

cache_aside.py
import json
import random


class FakeClock:
    """Simulated time so TTL expiry is deterministic in this demo."""

    def __init__(self):
        self.now = 0


class InMemoryCache:
    """Stand-in for a Valkey/Redis client: get, set(ex=, nx=), delete."""

    def __init__(self, clock):
        self.clock, self.data = clock, {}

    def get(self, key):
        item = self.data.get(key)
        if item is None or item[1] <= self.clock.now:
            self.data.pop(key, None)  # expired keys behave like misses
            return None
        return item[0]

    def set(self, key, value, ex, nx=False):
        if nx and self.get(key) is not None:
            return False
        self.data[key] = (value, self.clock.now + ex)
        return True

    def delete(self, key):
        self.data.pop(key, None)


clock = FakeClock()
cache = InMemoryCache(clock)
rng = random.Random(42)  # seeded only so this demo prints the same numbers
DB = {"p1": {"name": "Mohinga kit", "price": 12}}
stats = {"hit": 0, "miss": 0, "db_reads": 0}
BASE_TTL = 300


def ttl_with_jitter():
    # +/- 10% spreads expiry so hot keys do not all expire together
    return int(BASE_TTL * rng.uniform(0.9, 1.1))


def get_product(product_id):
    key = f"product:{product_id}"
    cached = cache.get(key)
    if cached is not None:
        stats["hit"] += 1
        return json.loads(cached), "HIT"
    stats["miss"] += 1
    stats["db_reads"] += 1
    product = DB[product_id]  # the slow database read
    ttl = ttl_with_jitter()
    cache.set(key, json.dumps(product), ex=ttl)
    return product, f"MISS (cached for {ttl}s)"


def update_price(product_id, price):
    DB[product_id]["price"] = price  # 1. write the database first
    cache.delete(f"product:{product_id}")  # 2. then invalidate the key


def show(t, note=""):
    clock.now = t
    product, status = get_product("p1")
    print(f"t={t:>3}s price={product['price']} {status}{note}")


if __name__ == "__main__":
    show(0)
    show(5)
    show(10)
    update_price("p1", 15)
    show(20, " <- after update")
    show(400, " <- TTL expired")
    print("stats:", stats)

Browser ထဲမှာ run လို့ မရပါ

ဒီ code ဟာ AWS account အစစ်ပေါ်မှာ run ရမယ့် code ဖြစ်လို့ browser playground ထဲမှာ run လို့ မရပါ။ ကိုယ့် terminal (သို့) AWS CloudShell ထဲမှာ စမ်းပါ။

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Read pathcached = cache.get(key)

    Cache ကို အရင်ကြည့်ပါတယ်။ ရှိရင် HIT အဖြစ် database ကို လုံးဝ မထိဘဲ ပြန်ပေးပါတယ်။

  2. Fill on miss with jittered TTLcache.set(key, json.dumps(product), ex=ttl)

    Miss ဖြစ်ရင် database ကနေ ဖတ်ပြီး 300 စက္ကန့် ±10% TTL နဲ့ သိမ်းပါတယ်။ ဒါကြောင့် output မှာ 308s, 271s, 286s လို မတူတဲ့ TTL တွေ မြင်ရပါတယ်။

  3. Invalidate on writecache.delete(f"product:{product_id}")

    Price ပြောင်းတဲ့အခါ database ကို အရင်ရေးပြီး key ကို ဖျက်ပါတယ်။ t=20 မှာ ချက်ချင်း price 15 အသစ်ကို ပြန်ရတာ ဒါကြောင့်ပါ။

  4. Expiryif item is None or item[1] <= self.clock.now:

    t=400 မှာ entry ရဲ့ TTL (t=20 + 271s = 291) ကုန်သွားပြီမို့ miss ဖြစ်ပြီး database ကနေ ပြန်ဖြည့်ပါတယ်။

You should see
t=  0s price=12 MISS (cached for 308s)
t=  5s price=12 HIT
t= 10s price=12 HIT
t= 20s price=15 MISS (cached for 271s) <- after update
t=400s price=15 MISS (cached for 286s) <- TTL expired
stats: {'hit': 2, 'miss': 3, 'db_reads': 3}
Hot key expire ဖြစ်တဲ့အခါ stampede lock
  1. Hot key expires; 500 requests miss
  2. Each tries SET lock NX EX 10
  3. One request wins the lock
  4. Winner reads DB and refills the key
  5. Others wait briefly, re-read cache

Lock ရတဲ့ request

One database query, cache refilled

Lock မရတဲ့ request

Short sleep, then read the new value

Cache stampede (thundering herd) ကို ကာကွယ်ခြင်း

Hot key တစ်ခု expire ဖြစ်တဲ့ အချိန်မှာ request ရာနဲ့ချီက တစ်ပြိုင်နက် miss ဖြစ်ပြီး database ကို တူညီတဲ့ query တစ်ချိန်တည်း ပို့ကြပါတယ်။ Database နှေးသွားလေ cache ပြန်မဖြည့်နိုင်သေးတဲ့ အချိန် ကြာလေ၊ miss ပိုများလေ ဖြစ်ပြီး ပြန်ပြီး ပိုဆိုးလာပါတယ်။ Deploy ပြီးနောက် ဒါမှမဟုတ် cache node အသစ်မှာ (cold cache) ဒီလိုပဲ ဖြစ်တတ်ပါတယ်။

  • Jittered TTL: TTL ကို ±10% လောက် random လုပ်ပြီး တစ်ချိန်တည်း ဖြည့်ထားတဲ့ key တွေ တစ်ပြိုင်နက် expire မဖြစ်အောင် ဖြန့်ပါ။
  • Lock (single flight): SET lock:key value NX EX 10 နဲ့ request တစ်ခုတည်းကိုပဲ database ဖတ်ခွင့်ပေးပြီး ကျန်တာတွေကို ခဏစောင့်ပြီး cache ပြန်ဖတ်ခိုင်းပါ။ Lock ကို EX နဲ့ အမြဲ expire လုပ်ပါ၊ မဟုတ်ရင် worker crash ဖြစ်တာနဲ့ key က ထာဝရ lock ဖြစ်နေပါမယ်။
  • Early refresh: TTL မကုန်ခင် (ဥပမာ ၉၀% ရောက်ရင်) background ကနေ ပြန်ဖြည့်ပြီး hot key ကို ဘယ်တော့မှ အလွတ်မဖြစ်အောင် ထားပါ။
  • Cache warming: deploy ဒါမှမဟုတ် failover ပြီးရင် hot key တွေကို traffic မရောက်ခင် ကြိုဖြည့်ပါ။

Engine နဲ့ topology ရွေးချယ်ခြင်း

လိုအပ်ချက်Valkey / Redis OSSMemcached
Data structureHash, list, set, sorted set, streamString key-value သာ
Replication + failoverရ (replica, Multi-AZ)မရ — node ပျက်ရင် data ပျောက်
Persistence / backupSnapshot ရမရ
Scale ချဲ့ပုံCluster mode shard များNode ထပ်ထည့်၊ client က key တွေ ဖြန့်

Valkey က Redis license ပြောင်းပြီးနောက် Linux Foundation အောက်မှာ ဆက်တည်ဆောက်နေတဲ့ open-source fork ပါ၊ Redis OSS client နဲ့ command တွေနဲ့ compatible ဖြစ်ပြီး ElastiCache မှာ Redis OSS ထက် ဈေးသက်သာအောင် သတ်မှတ်ထားပါတယ်။ Project အသစ်တွေအတွက် များသောအားဖြင့် Valkey ကို ရွေးကြပါတယ်။ Memcached ကတော့ multi-threaded ဖြစ်ပြီး ရိုးရှင်းတဲ့ object cache အတွက် ကောင်းပေမဲ့ replication မရှိတာကို လက်ခံနိုင်မှ ရွေးပါ။

Node-based cluster မှာ cluster mode disabled ဆိုရင် shard တစ်ခု (primary တစ်ခု + replica ၅ ခုအထိ) ပဲ ရှိပြီး data အားလုံး node တစ်ခုရဲ့ memory ထဲ ဆံ့ရပါမယ်။ Cluster mode enabled က key space ကို shard အများကြီးပေါ် hash slot နဲ့ ခွဲပြီး write capacity နဲ့ memory ကို horizontal scale လုပ်ပါတယ်၊ ဒါပေမဲ့ client က cluster-aware ဖြစ်ရပြီး key အများကြီးပါတဲ့ command တွေက shard တစ်ခုတည်းမှာ ရှိတဲ့ key တွေနဲ့ပဲ အလုပ်လုပ်ပါတယ်။ Replica တွေနဲ့ Multi-AZ ဖွင့်ထားရင် primary ပျက်တဲ့အခါ replica ကို အလိုအလျောက် promote လုပ်ပါတယ်။

ElastiCache Serverless ကတော့ ဒီ topology ဆုံးဖြတ်ချက်တွေကို AWS ကို လွှဲပေးပြီး AZ အများကြီးမှာ data ကို replicate လုပ်ပါတယ်။ Data storage (GB-hour) နဲ့ ElastiCache Processing Unit (ECPU) အလိုက် ပေးရလို့ traffic မမှန်တဲ့ workload အတွက် ကောင်းပြီး load မြင့်ပြီး တည်ငြိမ်ရင် node-based cluster က ပိုသက်သာနိုင်ပါတယ်။

create-node-based.sh
# Cluster mode enabled: 2 shards x (1 primary + 1 replica), Multi-AZ failover
aws elasticache create-replication-group \
  --replication-group-id sessions \
  --replication-group-description "Session store, 2 shards" \
  --engine valkey \
  --cache-node-type cache.t4g.small \
  --cache-parameter-group-name default.valkey8.cluster.on \
  --num-node-groups 2 \
  --replicas-per-node-group 1 \
  --automatic-failover-enabled \
  --multi-az-enabled \
  --transit-encryption-enabled \
  --at-rest-encryption-enabled \
  --cache-subnet-group-name app-cache-subnets \
  --security-group-ids sg-0cac4e1a2b3c4d5e6
text
CLUSTER MODE ENABLED: 2 SHARDS, MULTI-AZ
----------------------------------------
        cluster-aware client (knows the slot map)
            |                         |
   slots 0-8191                slots 8192-16383
            v                         v
  +-------------------+     +-------------------+
  | shard 1           |     | shard 2           |
  | primary   (AZ-a)  |     | primary   (AZ-b)  |
  | replica   (AZ-b)  |     | replica   (AZ-a)  |
  +-------------------+     +-------------------+
  primary fails -> its replica is promoted automatically

Production မှာ

Production မှာ ဘယ်လိုသုံးကြလဲ

ပုံမှန် e-commerce team တစ်ခုက product catalog, price နဲ့ session data တွေကို Valkey cache တစ်ခုမှာ ထားပါတယ်။ Key တွေကို product:v3:p1 လို version prefix ပါအောင် နာမည်ပေးပါတယ် — cache ထဲက data format ပြောင်းတဲ့အခါ prefix ကို v4 ပြောင်းလိုက်ရုံနဲ့ key အဟောင်းတွေကို ဖတ်တော့မှာ မဟုတ်ဘဲ TTL နဲ့ အလိုလို ပျောက်သွားပါတယ်။

Cache ကို database နဲ့ AZ တူရာမှာ private subnet ထဲ ထားပြီး in-transit encryption ဖွင့်ထားပါတယ်။ Lambda ကနေ သုံးရင် function ကို VPC ထဲ ထည့်ရပြီး client ကို handler အပြင်ဘက်မှာ ဖန်တီးပါတယ်။ Team တွေက cache hit rate ကို 80-95% ကြားလောက် ရည်မှန်းကြပြီး hit rate ကျသွားတာက TTL တိုလွန်းတာ ဒါမှမဟုတ် memory မလောက်တာ ဖြစ်တတ်ပါတယ်။

  • CloudWatch: CacheHitRate, Evictions, CurrConnections, EngineCPUUtilization နဲ့ DatabaseMemoryUsagePercentage ကို alarm ထားပါ။
  • Failover စမ်းသပ်ခြင်း: test-failover နဲ့ primary ပြောင်းတာကို စမ်းပြီး client က reconnect လုပ်နိုင်လား စစ်ပါ။
  • Capacity: node-based cluster မှာ memory 25% လောက် overhead (replication buffer, snapshot) အတွက် ချန်ထားပါ။

အမှားများ

အဖြစ်များတဲ့ အမှားတွေ

TTL မပါဘဲ cache လုပ်ခြင်း

Invalidation code တွေက တစ်နေရာရာမှာ အမြဲ လွတ်တတ်ပါတယ် — admin tool, batch job, database ကို တိုက်ရိုက် ပြင်တာ စသဖြင့်။ TTL မပါရင် အဲဒီ stale data က ထာဝရ ကျန်နေပါမယ်။ Key တိုင်းကို TTL ထည့်ပါ၊ ပြောင်းခဲတဲ့ data ဆိုရင်တောင် နာရီပိုင်း ဒါမှမဟုတ် ရက်ပိုင်း TTL ထားပါ။

Cache ကို update လုပ်ပြီး delete မလုပ်ခြင်း

Write နှစ်ခု တစ်ပြိုင်နက် ဖြစ်ရင် database က write B ကို နောက်ဆုံး သိမ်းပေမဲ့ cache က write A ကို နောက်ဆုံး ရသွားနိုင်ပြီး မှားတဲ့ value က TTL ကုန်တဲ့အထိ ကျန်နေပါတယ်။ Key ကို delete လုပ်ရင် နောက် read က database ကနေ မှန်တဲ့ value ကို ပြန်ယူပါတယ်။

Cache ကို primary database အဖြစ် သုံးခြင်း

Eviction, node အစားထိုးတာ ဒါမှမဟုတ် asynchronous replication ကြောင့် failover အတွင်း write အချို့ ပျောက်နိုင်ပါတယ်။ Order, payment လို ပျောက်လို့မရတဲ့ data ကို ElastiCache ထဲမှာပဲ မထားပါနဲ့ — durable database ကို source of truth အဖြစ် ထားပါ။ (Durable in-memory database လိုရင် Amazon MemoryDB က သီးခြား service ပါ။)

Key အားလုံးကို TTL တစ်ခုတည်း ပေးခြင်း

Warm-up script က key ထောင်ချီကို တစ်ချိန်တည်း TTL 3600 နဲ့ ဖြည့်ရင် တစ်နာရီအကြာမှာ အားလုံး တစ်ပြိုင်နက် expire ဖြစ်ပြီး stampede ဖြစ်ပါတယ်။ Jitter ထည့်ပါ။

💰 Cost & Cleanup

Node-based cluster က node type အလိုက် node-hour နဲ့ ပေးရပြီး replica တိုင်းက node တစ်ခု ထပ်တိုးတာပါ (shard ၂ ခု × node ၂ ခု = node ၄ ခု)။ ElastiCache Serverless က သိမ်းထားတဲ့ data GB-hour နဲ့ ECPU အလိုက် ပေးရပြီး minimum data storage charge ရှိပါတယ်။ AZ ကြား data transfer လည်း ကုန်ကျနိုင်ပါတယ်။ Classic free tier မှာ micro node hour အကန့်အသတ်နဲ့ ပါတဲ့ account တွေ ရှိပေမဲ့ ကိုယ့် account ရဲ့ free tier စည်းမျဉ်းကို စစ်ပါ။ Lab ပြီးရင် cache တွေကို ချက်ချင်း ဖျက်ပါ။

စမ်းပြီးရင် ဖျက်ဖို့ command

cleanup.sh
aws elasticache delete-serverless-cache --serverless-cache-name product-cache

aws elasticache delete-replication-group \
  --replication-group-id sessions \
  --no-retain-primary-cluster

Mini challenge

Stampede lock ထည့်ပါ

Request ငါးခုက product:p1 ကို တစ်ပြိုင်နက် miss ဖြစ်ပါတယ်။ Lock တစ်ခု ထည့်ပြီး database ကို တစ်ကြိမ်ပဲ ဖတ်အောင် လုပ်ပါ။

  • Lock key က lock:product:<id> ဖြစ်ပြီး set(..., ex=10, nx=True) နဲ့ ယူပါ
  • Lock ရတဲ့ request တစ်ခုတည်းပဲ database ကို ဖတ်ပြီး cache ကို ပြန်ဖြည့်ပါ
  • Refill ပြီးရင် lock ကို ဖျက်ပါ၊ request ငါးခုလုံး cache ကနေ data ရရပါမယ်

ရလဒ်: lock winners: ['req-1']၊ served from cache: 5 of 5၊ db reads: 1 လို့ ထွက်ရပါမယ်။

အရိပ်အမြွက် ကြည့်ရန်

NX က key မရှိသေးမှ set လုပ်ပြီး ရှိပြီးသားဆိုရင် False ပြန်ပေးပါတယ်။ Request တိုင်းကို lock အရင် ယူခိုင်းပြီး True ရတဲ့ request ကိုပဲ refill လုပ်ခိုင်းပါ။

အဖြေ ကြည့်ရန်
stampede_lock.py
class InMemoryCache:
    """Same stand-in as the lesson example (no clock needed here)."""

    def __init__(self):
        self.data = {}

    def get(self, key):
        return self.data.get(key)

    def set(self, key, value, ex, nx=False):
        if nx and key in self.data:
            return False  # SET ... NX fails when the key already exists
        self.data[key] = value  # (expiry ignored in this short demo)
        return True

    def delete(self, key):
        self.data.pop(key, None)


cache = InMemoryCache()
DB = {"p1": "Mohinga kit"}
db_reads = 0


def try_lock(product_id, caller):
    # Valkey/Redis: SET lock:product:p1 req-1 NX EX 10
    return cache.set(f"lock:product:{product_id}", caller, ex=10, nx=True)


def refill(product_id):
    global db_reads
    db_reads += 1
    cache.set(f"product:{product_id}", DB[product_id], ex=300)
    cache.delete(f"lock:product:{product_id}")


if __name__ == "__main__":
    callers = ["req-1", "req-2", "req-3", "req-4", "req-5"]
    # All five miss at the same moment and race for the lock first.
    winners = [c for c in callers if try_lock("p1", c)]
    print("lock winners:", winners)
    for caller in winners:
        refill("p1")
    # The losers wait briefly, then simply re-read the cache.
    served = [cache.get("product:p1") for _ in callers]
    print("served from cache:", served.count("Mohinga kit"), "of", len(callers))
    print("db reads:", db_reads)

Quick Quiz 1 / 3

Cache-aside သုံးထားတဲ့ app မှာ product price ပြောင်းပါတယ်။ ဘယ်အစီအစဉ်က အလုံခြုံဆုံးလဲ။

Quick Quiz 2 / 3

Homepage ရဲ့ hot key တစ်ခု expire ဖြစ်တိုင်း database CPU က ၁၀၀% ထိ ခုန်တက်ပါတယ်။ ဘာက ဒီပြဿနာကို တိုက်ရိုက် ဖြေရှင်းလဲ။

Quick Quiz 3 / 3

Leaderboard အတွက် sorted set လိုပြီး primary ပျက်ရင် automatic failover လည်း လိုပါတယ်။ ElastiCache မှာ ဘာကို ရွေးမလဲ။

မှတ်ထားရမယ့် အချက်များ

  • Cache-aside က miss ဖြစ်မှ ဖြည့်ပြီး write-through က write တိုင်း update လုပ်ပါတယ်၊ အများစုက cache-aside နဲ့ write-time delete ကို တွဲသုံးကြပါတယ်။
  • Key တိုင်းကို TTL ပေးပြီး data ပြောင်းရင် database ကို အရင်ရေး၊ ပြီးမှ key ကို delete လုပ်ပါ။
  • Stampede ကို jittered TTL, lock (SET NX EX), early refresh နဲ့ ကာကွယ်ပါ။
  • Data structure, replication, failover လိုရင် Valkey/Redis OSS၊ ရိုးရှင်းတဲ့ object cache ဆိုရင် Memcached ကို ရွေးပါ။
  • Cluster mode က shard တွေပေါ် scale ချဲ့ပြီး Serverless က topology ကို AWS ကို လွှဲပေးပါတယ်၊ cache ကို source of truth အဖြစ် ဘယ်တော့မှ မသုံးပါနဲ့။

What is Amazon ElastiCache? — AWS Documentation

Caching strategies (ElastiCache) — AWS Documentation

Caching best practices — AWS Documentation

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

ElastiCache နဲ့ Caching Strategy များ | Thuta Learning