Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Data Eviction in Redis

Introduction to Data Eviction

Data eviction in Redis refers to the process of removing data from memory when certain conditions are met, such as when the available memory is fully utilized. Redis uses various eviction policies to determine which data should be removed in order to free up space.

Eviction Policies

Redis offers several eviction policies to manage memory usage:

  • noeviction: Returns an error when the memory limit is reached and a write operation is attempted.
  • allkeys-lru: Evicts the least recently used (LRU) keys in the entire keyspace.
  • volatile-lru: Evicts the least recently used (LRU) keys with an expiry set.
  • allkeys-random: Randomly evicts keys in the entire keyspace.
  • volatile-random: Randomly evicts keys with an expiry set.
  • volatile-ttl: Evicts keys with the shortest time-to-live (TTL).

Configuring Eviction Policies

To configure the eviction policy in Redis, you can set the maxmemory-policy directive in the Redis configuration file (redis.conf) or use the CONFIG SET command.

Example: Set the eviction policy to allkeys-lru in redis.conf

maxmemory-policy allkeys-lru

Example: Set the eviction policy using the CONFIG SET command

CONFIG SET maxmemory-policy allkeys-lru

Setting Maxmemory

To enable eviction policies, you need to set a maximum memory limit using the maxmemory directive in the Redis configuration file or the CONFIG SET command.

Example: Set maxmemory to 100MB in redis.conf

maxmemory 100mb

Example: Set maxmemory using the CONFIG SET command

CONFIG SET maxmemory 100mb

Monitoring and Debugging

Redis provides several commands to monitor memory usage and eviction:

  • INFO memory: Provides statistics about Redis memory usage.
  • MEMORY STATS: Returns an array of memory-related metrics.
  • MEMORY USAGE : Estimates the memory usage of a key.

Example: Get Redis memory usage statistics

INFO memory
# Memory used_memory:1024000 used_memory_human:1000K ...

Example Scenario

Consider a scenario where you have limited memory available and want to ensure that the most recently used data remains in memory while older data is evicted.

  1. Set the maximum memory limit to 50MB:
  2. CONFIG SET maxmemory 50mb
  3. Set the eviction policy to allkeys-lru:
  4. CONFIG SET maxmemory-policy allkeys-lru
  5. Start adding data to Redis and observe the eviction process when the memory limit is reached.