Trung BìnhRedis iconRedis

Key expiration và eviction policy trong Redis: các policy là gì và khi nào dùng?

Key expiration: dùng EXPIRE key seconds, PEXPIRE key milliseconds, hoặc SET key value EX seconds để tự động xóa key sau khoảng thời gian.

  • Redis kiểm tra expiry theo hai cách: lazy expiration (kiểm tra khi access key) và active expiration (background job mỗi 100ms xóa random sample 20 key trong set expired keys).
  • Eviction policy được áp dụng khi Redis đạt maxmemory: noeviction (reject write khi full), allkeys-lru (xóa key ít dùng nhất gần đây trong toàn bộ keyspace), volatile-lru (chỉ xóa key có TTL ít dùng nhất), allkeys-lfu (xóa key ít dùng nhất theo frequency — Redis 4.0+), volatile-ttl (xóa key có TTL ngắn nhất), allkeys-random.
  • Cache dùng allkeys-lru hoặc allkeys-lfu; session store dùng volatile-lru; data không thể mất dùng noeviction.
  • Nên set maxmemory-policy phù hợp và monitor evicted_keys metric.

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

Mở danh sách Redis