01เลือก Data Type ให้ตรงโจทย์

String / Hash

Cache object, counter หรือ field-value ที่แก้บาง field ได้

Set / Sorted Set

สมาชิกไม่ซ้ำ, ranking, score และ range query

Stream

Append-only entries, consumer groups และ event processing

อย่าจำแค่ Big-O ของ command ต้องคิดขนาดสมาชิกด้วย เช่นคำสั่ง O(N) บน key ที่เล็กอาจรับได้ แต่ key ใหญ่มากจะ block event loop ของ Redis และเพิ่ม network payload ควรกำหนด key naming, cardinality และ maximum size ตั้งแต่ต้น

02Cache-aside และ Cache Stampede

Cache-aside ให้อ่าน cache ก่อน หาก miss จึงอ่าน database แล้วเขียน cache กลับ จุดยากคือ invalidation: หลัง update ต้องลบหรือแก้ cache อย่างไร และยอม stale data ได้นานเท่าไร

policy-cache.ts
async function getPolicy(id: string) {
  const key = `policy:${id}`
  const cached = await redis.get(key)
  if (cached) return JSON.parse(cached)

  const policy = await db.policy.findById(id)

  // TTL มี jitter ลดโอกาส key จำนวนมากหมดพร้อมกัน
  const ttl = 300 + Math.floor(Math.random() * 60)
  await redis.set(key, JSON.stringify(policy), { EX: ttl })

  return policy
}
  • ใช้ TTL พร้อม jitter ป้องกัน key จำนวนมากหมดพร้อมกัน
  • ใช้ request coalescing หรือ lock สั้น ๆ เมื่อ cache miss ของ hot key
  • ทำ negative caching ชั่วคราวสำหรับ not-found ที่ถูกยิงซ้ำ
  • วัด hit ratio, evictions, memory fragmentation และ latency ไม่ใช่แค่ uptime

03Eviction และ Persistence

กำหนด `maxmemory` และ eviction policy ให้ตรง workload: `allkeys-lru` เหมาะกับ cache ทั่วไปที่บาง key ถูกใช้บ่อย, `allkeys-lfu` เก็บ key ที่ถูกใช้ถี่ ส่วน `noeviction` คืน error เมื่อ memory เต็มและเหมาะเมื่อการลบ key อัตโนมัติยอมรับไม่ได้

RDB เป็น snapshot กู้เร็วแต่เสียข้อมูลหลัง snapshot ได้ ส่วน AOF บันทึก write operation ทนทานกว่าแต่ใช้ I/O และ recovery มากกว่า การใช้ Redis เป็น source of truth ต้องออกแบบ persistence, replication และ backup จริง ไม่ใช่เชื่อว่า in-memory เท่ากับข้อมูลชั่วคราวเสมอ

04Distributed Lock อย่างระมัดระวัง

Lock พื้นฐานใช้ `SET key token NX PX ttl` และปลดด้วย script ที่ตรวจ token ก่อนลบ เพื่อไม่ลบ lock ของเจ้าของใหม่ แต่ TTL อาจหมดขณะงานยังทำอยู่ จึงต้องคิด lease renewal, fencing token และผลกระทบเมื่อ network partition

อ่านเอกสารทางการ: Redis Key Eviction