Question: What is the difference between Redis eviction policies and TTL?
Answer
In Redis, both the concept of eviction policies and Time to Live (TTL) play a crucial role in managing memory. However, they serve different purposes and function differently.
Time To Live (TTL)
TTL stands for Time to Live. In Redis, it's a way to set an expiry time on a key. After the specified time limit, the server will automatically delete the key. You can set this using the EXPIRE
command.
Here's an example:
SET mykey "Hello" EXPIRE mykey 10
In this example, the key 'mykey' will be automatically removed from Redis after 10 seconds.
Eviction Policies
On the other hand, eviction policies come into play when your Redis instance runs out of memory. An eviction policy determines which keys get removed to free up space. Redis supports multiple eviction policies that you can set based on your requirements, like 'allkeys-lru', 'volatile-lru', 'allkeys-random', etc.
For example, the 'allkeys-lru' policy will remove less recently used keys first, while 'volatile-lru' will only consider keys with an expiry set.
You can configure the eviction policy in your redis.conf file or dynamically using the CONFIG SET
command.
Example:
CONFIG SET maxmemory-policy allkeys-lru
In this example, we have set the eviction policy as 'allkeys-lru'.
So, TTL and eviction policies are not against each other. Instead, they work together - TTL sets the expiry time for individual keys, and eviction policies determine how Redis should act when it runs out of memory.
Was this content helpful?
Other Common Redis Questions (and Answers)
- What is the default port used by Redis?
- How to start Redis server?
- Is Redis persistent?
- How fast is Redis?
- How to install Redis on Mac?
- How to check if Redis is running?
- How to restart Redis?
- Does Redis persist data?
- How to install Redis on Ubuntu?
- How to stop Redis server?
- How to see Redis version?
- Does Redis have tables?
Free System Design on AWS E-Book
Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.
Switch & save up to 80%
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost