Getting Redis Eviction Policy in PHP (Detailed Guide w/ Code Examples)

Use Case(s)

The maxmemory-policy configuration setting in Redis determines what happens when the maximum memory limit has been reached. The eviction policy can be set to various levels such as noeviction, allkeys-lru, volatile-lru, allkeys-random, volatile-random, volatile-ttl. This can be particularly useful in managing your cache, by choosing how to handle overflow whether you're running a time-sensitive operation or looking for resource optimization.

Code Examples

To get the current eviction policy with PHP and Redis, we use the config method provided by the Redis PHP extension. Here's an example:

$redis = new Redis(); $redis->connect('', 6379); $evictionPolicy = $redis->config('GET', 'maxmemory-policy'); print_r($evictionPolicy);

In this code, we create a new Redis instance, connect to it, and then use the config method with GET command and maxmemory-policy argument to retrieve the current eviction policy.

Best Practices

It's important to understand each eviction policy before implementing it in your application. For instance, if your Redis setup contains important data that should not be lost, using noeviction would be a safer choice. On the other hand, if your application requires more fresh data and can tolerate losing older data, allkeys-lru (Least Recently Used) or volatile-lru could be an appropriate choice.

Common Mistakes

One common mistake is not considering the eviction policy when setting up Redis for your application. This can lead to unexpected data loss when the memory limit is reached. Make sure to provide an appropriate value for maxmemory-policy based on your application's needs.


Q: What happens if I don't set an eviction policy in Redis?

A: If you don't explicitly set an eviction policy, Redis will prevent any new writes until memory becomes available after removing some old data.

Q: Can I change the eviction policy at runtime?

A: Yes, Redis allows changing the maxmemory-policy configuration at runtime using the CONFIG SET command.

Was this content helpful?

Start building today

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