Memory Management: Keys, Expiration, and Eviction
9 min read
Memory Management: Keys, Expiration, and Eviction 🧠
Welcome to the cerebral cortex of Redis, where we'll explore how this in-memory data store manages its most precious resource: memory. Mismanaging memory in Redis is like trying to pour a gallon of water into a pint glass – eventually, things are going to get messy. This guide will walk you through the essential concepts of key expiration and eviction policies, ensuring your Redis instance runs like a well-oiled machine.
At its core, Redis holds all of your data in RAM. This is what makes it lightning-fast. However, RAM is a finite resource. If you keep adding data without a plan for removing the old, you'll eventually hit a wall. This is where memory management comes in. Redis provides two primary mechanisms for this: setting a "time to live" (TTL) on keys and defining eviction policies for when memory limits are reached.
1. Time to Live (TTL): Setting Expiration on Keys ⏳
The Problem: You're using Redis for caching API responses to speed up your application. But what happens when the underlying data changes? You don't want to serve stale data forever. Or perhaps you're storing user sessions that should automatically expire after a period of inactivity. Manually deleting these keys would be a tedious and error-prone process.
The Solution: Redis allows you to set an expiration time, or Time to Live (TTL), on a key. Once the TTL has passed, Redis will automatically delete the key. This is incredibly useful for managing temporary data like caches, sessions, and tokens.
Setting an Expiration
You can set an expiration on a key using the EXPIRE command, which takes the key name and the TTL in seconds as arguments.
Example:
Let's set a key user:123:session with some session data and make it expire in 300 seconds (5 minutes).
redis> SET user:123:session "some_session_data"
OK
redis> EXPIRE user:123:session 300
(integer) 1If the EXPIRE command is successful, it returns (integer) 1. If the key doesn't exist, it returns (integer) 0.
You can also set the expiration at the same time you create the key using the SET command with the EX option for seconds or PX for milliseconds.
Example:
redis> SET user:456:session "another_session" EX 60
OKThis creates the key and sets it to expire in 60 seconds.
Checking the Remaining Time
To see how much longer a key has before it expires, you can use the TTL command.
Example:
redis> TTL user:123:session
(integer) 290The command returns the remaining time in seconds.
If you need more precision, the PTTL command returns the remaining time in milliseconds.
Example:
redis> PTTL user:456:session
(integer) 59876Fun Fact: How does Redis delete expired keys? It uses a combination of "lazy deletion" and "active cleanup." When you try to access an expired key, Redis will notice it's expired and delete it then. Additionally, Redis periodically samples keys and deletes any that have expired. This approach is efficient and avoids the overhead of constantly monitoring every single key.
2. Making Keys Permanent or Checking Lifespans: PERSIST and TTL 🕰️
The Problem: You've set an expiration on a key, but now your application logic has changed, and you need that key to stick around indefinitely. Or, you need to programmatically check if a key has an expiration set at all.
The Solution: Redis provides the PERSIST command to remove the expiration from a key, making it permanent. The TTL command, as we've seen, can also tell you if a key has an associated expiration.
Making a Key Permanent
The PERSIST command is straightforward. It takes the key name as an argument and removes its associated timeout.
Example:
Let's say we have our user:123:session key with a TTL.
redis> TTL user:123:session
(integer) 150
redis> PERSIST user:123:session
(integer) 1
redis> TTL user:123:session
(integer) -1After PERSIST is called, the TTL command returns (integer) -1, which indicates that the key now has no expiration. If the key doesn't exist or doesn't have an expiry, PERSIST returns (integer) 0.
Understanding TTL Return Values
The TTL command provides valuable information about a key's lifespan based on its return value:
- A positive integer: The remaining time to live in seconds.
- -1: The key exists but has no associated expiration (it's persistent).
- -2: The key does not exist.
This allows your application to make intelligent decisions based on whether a key is about to expire or if it's a permanent piece of data.
3. Understanding Redis Memory Limits 📈
The Problem: As a responsible developer or operations engineer, you can't just let Redis consume all available memory on a server. Unchecked memory growth can lead to performance degradation of other services or even cause the server to become unresponsive.
The Solution: Redis allows you to configure a maximum memory limit. When this limit is reached, Redis will start taking action based on its configured eviction policy.
Configuring maxmemory
You can set the maxmemory directive in your redis.conf file or at runtime using the CONFIG SET command.
In redis.conf:
maxmemory 100mbAt runtime:
redis> CONFIG SET maxmemory 102400000
OKIt's generally a good practice to set a maxmemory limit to prevent Redis from consuming all of the system's RAM.
Monitoring Memory Usage
It's crucial to keep an eye on how much memory Redis is using. The INFO memory command provides a wealth of information about memory consumption.
Example:
redis> INFO memory
# Memory
used_memory:1007280
used_memory_human:983.67K
used_memory_rss:2002944
used_memory_rss_human:1.91M
...Some key metrics to watch are:
used_memory: The total number of bytes allocated by Redis.used_memory_human: A human-readable version ofused_memory.used_memory_rss: The Resident Set Size, which is the memory Redis has been allocated by the operating system.mem_fragmentation_ratio: The ratio ofused_memory_rsstoused_memory. A value greater than 1.5 might indicate significant memory fragmentation.
Industry Practice: In production environments, it's common to use monitoring tools like Prometheus and Grafana to track these metrics over time and set up alerts for when memory usage approaches the maxmemory limit.
4. Eviction Policies: How Redis Decides What to Delete (LRU vs LFU) 🗑️
The Problem: You've set a maxmemory limit, and your Redis instance is now full. A new write command comes in. What should Redis do? By default, it will return an error, preventing any new data from being written. This is often not the desired behavior, especially when using Redis as a cache.
The Solution: Redis offers several eviction policies that dictate which keys it should delete to make room for new data when the maxmemory limit is reached. The most commonly used and important to understand are Least Recently Used (LRU) and Least Frequently Used (LFU).
You can set the eviction policy in your redis.conf file or with CONFIG SET.
maxmemory-policy allkeys-lruThe "volatile" vs. "allkeys" Prefixes
Before diving into LRU and LFU, it's important to understand the prefixes:
volatile-*: These policies only consider keys that have an expiration set (a TTL). This is useful when you have a mix of cached data (with TTLs) and persistent data (without TTLs) in the same Redis instance.allkeys-*: These policies consider all keys for eviction, regardless of whether they have an expiration set. This is generally more memory-efficient as you don't need to set expires on keys just for them to be considered for eviction.
Least Recently Used (LRU)
The LRU policy evicts the keys that haven't been accessed for the longest time. The assumption is that if data hasn't been used recently, it's less likely to be needed soon.
volatile-lru: Evicts the least recently used keys from those with an expire set. This is the default policy for most Redis databases.allkeys-lru: Evicts the least recently used keys from all keys. This is a great general-purpose choice for caching.
Real-world Scenario: Imagine a news website's homepage. Articles that were just published or are trending are accessed frequently. Older articles that are no longer on the homepage are accessed less and less. An LRU policy would be effective here, keeping the fresh and popular articles in the cache while evicting the older ones.
Under the Hood: Redis uses an approximated LRU algorithm. Instead of maintaining a perfect, ordered list of all keys by access time (which would be memory-intensive), it samples a small number of keys and evicts the one that was least recently used among the sample.
Least Frequently Used (LFU)
Introduced in Redis 4.0, the LFU policy evicts the keys that have been accessed the fewest number of times. This can be more effective than LRU in scenarios where some data is consistently popular over time, even if it's not accessed as recently as other, less popular data.
volatile-lfu: Evicts the least frequently used keys from those with an expire set.allkeys-lfu: Evicts the least frequently used keys from all keys.
Real-world Scenario: Consider a product catalog for an e-commerce site. Some "bestseller" items are viewed constantly. Other items might get a burst of traffic from a short-lived marketing campaign but then become less popular. LFU would keep the consistent bestsellers in the cache, even if a new, briefly popular item was accessed more recently.
Interesting Fact: The LFU implementation in Redis is quite clever. It uses a probabilistic counter that only takes up a few bits per object to estimate access frequency and also incorporates a decay period, so the frequency of access diminishes over time. This allows the algorithm to adapt to changing access patterns.
Other Eviction Policies
While LRU and LFU are the most common, Redis offers other policies:
noeviction: The default policy. It doesn't evict any keys and returns an error on write operations when the memory limit is reached.volatile-ttl: Evicts the key with the shortest remaining time to live among keys with an expiration set.allkeys-random/volatile-random: Evicts a random key.
Industry Practice: For general caching use cases, allkeys-lru is often a good starting point. If you have a clear pattern of "hot" keys that are frequently accessed, allkeys-lfu might provide a better cache hit ratio. It's always best to monitor your cache hit rate and choose the policy that works best for your specific application's access patterns.
References
Challenge
You are the administrator for a Redis instance that serves as a cache for a busy web application. To ensure optimal performance and prevent memory exhaustion, you need to apply several memory management commands. Write the sequence of Redis commands to accomplish the following tasks in order:
A new user session has been created. Set the key
session:user:789with the string value{"last_login":"2023-10-27T10:00:00Z"}. This key should automatically expire after 20 minutes (1200 seconds). Use the single, most efficient command to set the key and its expiration time together.There is an existing key,
cache:api:popular_products, which was set without an expiration. To keep the data fresh, you need to add an expiration of 1 hour (3600 seconds) to this key.You have another key,
system:config:feature_flags, that was temporarily set with an expiration for testing purposes. The test is now complete, and this key must be made permanent. Write the command to remove its TTL.The server is configured with a
maxmemorylimit. To ensure that the cache effectively removes less relevant data when this limit is reached, you need to set the eviction policy. Configure the instance to evict keys that have been accessed the fewest times, considering only keys that have an expiration set.
Expected result
Your solution should consist of four distinct Redis commands, each on a new line, corresponding to the four tasks.
SET session:user:789 "{\"last_login\":\"2023-10-27T10:00:00Z\"}" EX 1200
EXPIRE cache:api:popular_products 3600
PERSIST system:config:feature_flags
CONFIG SET maxmemory-policy volatile-lfuExplanation:
SET ... EX 1200creates the key and sets its Time To Live (TTL) in a single atomic operation.EXPIREis used to add or update the TTL for a key that already exists.PERSISTremoves the existing expiration from a key, making it permanent until it is explicitly deleted.CONFIG SET maxmemory-policy volatile-lfusets the eviction policy. Thevolatile-lfupolicy evicts the least frequently used keys from the set of keys that have an expiration time (volatile).