Caching
Cache ช่วยลด latency และลด load บน database โดยเก็บข้อมูลที่ถูกอ่านบ่อยไว้ใน memory หรือ layer ที่เร็วกว่า แต่ต้องออกแบบ TTL และ invalidation ให้ดี
Cache hit, cache miss และ TTL
- Cache hit: ข้อมูลอยู่ใน cache และตอบกลับได้เร็ว
- Cache miss: ข้อมูลไม่อยู่ใน cache ต้องไปอ่านจาก database/origin
- TTL: เวลาที่ข้อมูลอยู่ใน cache ก่อนหมดอายุ
Amazon ElastiCache
Amazon ElastiCache เป็น managed in-memory caching service รองรับ engines เช่น Redis OSS, Valkey และ Memcached ใช้สำหรับ session store, query result cache, leaderboard, rate limiting หรือ pub/sub pattern บางกรณี
Cache-aside pattern
1. Application reads key from cache
2. If cache hit -> return value
3. If cache miss -> read database
4. Store result in cache with TTL
5. Return value
Invalidation
Cache invalidation คือการทำให้ข้อมูลเก่าใน cache ถูกลบหรือหมดอายุเมื่อ source of truth เปลี่ยน ถ้า TTL ยาวเกิน ผู้ใช้อาจเห็นข้อมูลเก่า ถ้า TTL สั้นเกิน cache hit rate ต่ำและ database ยังรับ load สูง
Common mistakes
- Cache sensitive data โดยไม่กำหนด encryption/access control ให้เหมาะสม
- ใช้ cache เป็น source of truth ทั้งที่ข้อมูลหายได้
- ตั้ง TTL โดยเดา ไม่วัด cache hit rate และ stale data tolerance
- ไม่มี fallback เมื่อ cache unavailable
Review questions
- Cache hit และ cache miss ต่างกันอย่างไร?
- TTL ที่ยาวเกินไปมีความเสี่ยงอะไร?
- ทำไม cache ไม่ควรเป็น source of truth ของข้อมูลสำคัญ?
Sources: What is Amazon ElastiCache?