Technology Sharing

Redis data expiration and elimination strategy

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Redis data expiration and elimination strategy

Expiration Policy

Timed expiration

In settingskey​'s expiration time,key​Create a timer and let the timerkeyWhen the expiration time comes, the key is deleted. When the expiration time comes, it will be cleared immediately. This strategy can clear expired data immediately, which is very memory-friendly, but it will take up a lot ofCPU​Resources are used to process expired data, which affects the response time and throughput of the cache.

Lazy expiration

Only when visiting akey​, it will determine whether the key has expired, and clear it if it expires. This strategy can maximize the savingsCPU​Resources, but very memory-unfriendly. In extreme cases, a large number of expiredkey​It is not accessed again and will not be cleared, taking up a lot of memory.

Periodic expiration

At regular intervals, a certain number of databases will be scanned.expiresA certain number ofkey​, and clear the expiredkeyThis strategy is a compromise between the first two. By adjusting the time interval of the scheduled scan and the time limit of each scan, it can be used in different situations.CPU​Achieve the optimal balance between memory resources.

Elimination strategy

Redis's memory elimination strategy refers to how to apply for new memory when Redis's cache memory is insufficient.

  • noeviction​:When the memory is insufficient to accommodate the newly written data, the new write operation will report an error.
  • allkeys-lru​: When the memory is insufficient to accommodate newly written data, remove the least recently used key in the key space
  • allkeys-random​:When the memory is insufficient to accommodate newly written data, a key is randomly removed from the key space.
  • volatile-lru​:When the memory is insufficient to accommodate newly written data, remove the least recently used key in the key space with an expiration time set.
  • volatile-random​:When the memory is insufficient to accommodate newly written data, a key is randomly removed from the key space with an expiration time set.
  • volatile-ttl​:When the memory is insufficient to accommodate newly written data, in the key space with an expiration time set, keys with earlier expiration times are removed first.

Summarize

Expiration strategy selection

Lazy deletion and periodic deletion combination mode.

Elimination strategy selection

allkeys-lru