Redis

We generally use Redis for our caching layer.

TODO - update to include any 3rd party recommendations

Maximum Memory

Setting the maxmemory directive in the Redis configuration file will limit the amount of memory that Redis can use.

This is useful for preventing Redis from using too much memory and starving other services of resources.

The default value is 0, which means that Redis will use as much memory as possible.

If the site is using large amounts of memory for caching, for instance, when we have sites with a lot of content, where each content page can potentially be cached, we may need to set this value.

A good baseline is to set this value to 40% of the total memory available on the server. This gives us a good amount left over for PHP and MySQL.

Note that you should look at how much memory is available on the server and how much you can afford to allocate to Redis.

Configuration

The configuration file is located at /etc/redis/redis.conf.

  1. Open the configuration file in your preferred text editor.
    sudo vim /etc/redis/redis.conf
    
  2. Find the maxmemory directive and set it to the desired value.
    • If the directive doesn't exist, find the commented out version of it, and add it below that.
  3. Save the file and exit the text editor.

Example

# 40% of 8GB is 3.2GB
maxmemory 3gb

Maximum Memory Policy

The maxmemory-policy directive in the Redis configuration file will determine what happens when Redis reaches the maxmemory limit.

If we're setting a maxmemory limit, we should also set a policy to determine what happens when this limit is reached, our recommended policy is allkeys-lru.

This will remove the least recently used keys from Redis when the maxmemory limit is reached.

Configuration

  1. Open the configuration file in your preferred text editor.
    sudo vim /etc/redis/redis.conf
    
  2. Find the maxmemory-policy directive and set it to the desired value.
    • If the directive doesn't exist, find the commented out version of it, and add it below that.
  3. Save the file and exit the text editor.

Example

maxmemory-policy allkeys-lru

Applying the changes without downtime

It is possible to apply configuration changes to Redis without downtime.

Instead of restarting the Redis service, we can use the CONFIG SET command to apply the changes.

  1. On your server, login to Redis
    redis-cli
    
  2. Apply the changes
    CONFIG SET maxmemory 3gb
    CONFIG SET maxmemory-policy allkeys-lru
    
  3. Verify the changes
    CONFIG GET maxmemory
    CONFIG GET maxmemory-policy
    

Applying changes with downtime

Restart the Redis service to apply the changes.

sudo systemctl restart redis