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
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
- Redis will be unable to write any new keys/values and will error.
- The lack of available memory will cause your server to start swapping
(assuming you have a swap file or partition configured).
- The system will slow to a crawl and services may become unresponsive.
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
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
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:
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:
volatile-lru– evict the least recently used key with an expiration.
allkeys-lru– evict the least recently used key, expiration or not.
volatile-lfu– evict the least frequently used key with an expiration.
allkeys-lfu– evict the least frequently used key, expiration or not.
volatile-random– evict a random key with an expiration.
allkeys-random– evict a random key, expiration or not.
volatile-ttl– evict the key with the closest expiration.
noeviction– do nothing, let the server burn.