How to set Redis max memory usage

Josh Sherman
2 min read
Servers NoSQL

Redis is one of my favorite data stores. The multitude of data types makes it flexible enough to serve as a simple caching layer (replacing Memcached) or as a full-blown RDBMS replacement if you’re willing to jump through a few hoops.

Because Redis is an in-memory data store, it’s limited by the amount of RAM (memory) available on your system. Even if you’re diligent about expiring data regularly, you always run the risk of too many items being stuffed into Redis before the oldest items have expired and fallen off.

What happens when you run out of memory? A number of things will start to happen:

While this caveat is default behavior, it’s easy enough to reconfigure Redis to only occupy a certain amount of memory.

First, you’ll need to edit your redis.conf file, which is typically found in /etc/redis:

su -c "vim /etc/redis/redis.conf"

Once you’re in there, you will need to jump to the MEMORY MANAGEMENT section. Under that section there are two settings that we’ll want to edit.

The first is maxmemory which sets the upper limit on how much RAM Redis can take up. When Redis gets close to this value, the server’s eviction policy will kick in.

The default eviction policy is a lack of one. Find the setting maxmemory-policy, which is set to noeviction. You’ll want to change this setting as well to the policy that fits your needs.

For me, that setting is volatile-lfu which will evict the least frequently used key that has an expiration date set.

When you put it all together, your settings will look something like this:

maxmemory 512000000
maxmemory-policy volatile-lfu

Obviously, you’ll want to set the maxmemory to a value that’s less than the amount of memory you have available on your server. If evicting the least frequently used key that has an expiration date isn’t your cup of tea, you can use one of these values:

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

Related Articles