Question: What is the difference between Redis eviction policies and TTL?


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.


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?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.