Trung BìnhDatabase iconDatabase

Khi nào nên dùng Redis làm cache?

Cache-aside là pattern phổ biến nhất; cache stampede giải quyết bằng mutex lock; maxmemory-policy allkeys-lru cho pure cache; target hit rate >80%.

  • Dùng Redis cache khi: data đọc nhiều hơn ghi, computation expensive (complex DB queries, API calls), cần reduce database load, data có thể stale trong thời gian ngắn.
  • Chiến lược: Cache-aside/Lazy loading (check cache → miss → fetch DB → write cache); Write-through (write cache + DB đồng thời — consistent nhưng write latency cao); Write-behind/Write-back (write cache → async write DB — nhanh nhưng risk data loss).
  • Cache stampede problem: nhiều requests hit cache cùng lúc khi cache expire, all go to DB — giải quyết bằng mutex lock (SET key value NX EX 30 để lock), hoặc probabilistic early expiration (expire sớm với xác suất nhỏ trước TTL thật).
  • Memory management: maxmemory-policy quan trọng — allkeys-lru (evict least-recently-used) cho cache, volatile-lru (chỉ evict keys có TTL), noeviction (trả error khi full — dùng cho session storage).
  • Monitoring: redis-cli INFO stats để xem hit rate, connected clients, memory usage; target cache hit rate >80% là healthy.

Xem toàn bộ Database cùng filter theo level & chủ đề con.

Mở danh sách Database