Memcached

In-memory caching system ที่ใช้ Slab Allocation แก้ปัญหา memory fragmentation — เรียบง่ายกว่า Redis แต่ multi-threaded throughput สูง

Slab Allocation — แก้ Memory Fragmentation

ปัญหา

ถ้า allocate/free แบบ random size → memory แตกเป็นช่องเล็ก ๆ → item ใหม่ใส่ไม่ลง

วิธีแก้

  • แบ่ง memory เป็น slab classes ขนาดต่างกัน (72B, 144B, …, 1MB)
  • แต่ละ slab class มี chunks ขนาดคงที่
  • store item ขนาด N bytes → ไปอยู่ slab class ที่ chunk size >= N
  • ไม่มี external fragmentation (แต่อาจมี internal fragmentation บ้าง)

Redis vs Memcached

ด้านRedisMemcached
Data structuresหลายแบบ (List, Set, Hash, Sorted Set, Stream)แค่ string
PersistenceRDB + AOFไม่มี (pure cache)
ThreadingSingle-threaded (mostly)Multi-threaded
Memory mgmtjemallocSlab allocator
EvictionLRU, LFU, TTL-basedLRU
ReplicationMaster/replica + clusterไม่มี (client-side sharding)

เมื่อไหร่ควรใช้ Memcached

  • ต้องการ pure cache ไม่ต้อง persistence
  • ต้องการ multi-threaded throughput สูง
  • Data เป็นแค่ key-value string ธรรมดา

เมื่อไหร่ควรใช้ Redis แทน

  • ต้องการ data structures (List, Set, Hash, Sorted Set)
  • ต้องการ persistence (RDB/AOF)
  • ต้องการ pub/sub messaging
  • ต้องการ replication + clustering

Key Points

  • Memcached ใช้ Slab Allocation แก้ memory fragmentation — ไม่มี external fragmentation
  • Multi-threaded → throughput สูงกว่า Redis ที่เป็น single-threaded
  • แต่ features น้อยกว่า Redis มาก — แค่ key-value string
  • ไม่มี persistence — pure cache, data หายเมื่อ restart
  • ไม่มี replication built-in — ต้อง sharding ฝั่ง client
  • Redis — ทางเลือกที่มี features มากกว่า
  • Connection Pooling — connection management สำหรับ cache layer
  • Database Replication — Memcached ไม่มี replication ต่างจาก Redis