Every time a dynamic page is accessed, WordPress sends queries to the database to retrieve site settings, as well as information about posts, users, and other data needed to generate HTML. Moreover, a significant portion of this data remains virtually unchanged between queries. Therefore, instead of querying MySQL or MariaDB every time, WordPress can retrieve pre-processed data from RAM using Redis - an ultra-fast key-value NoSQL database that stores data in the server’s RAM (RAM).
This type of caching is particularly useful for WooCommerce online stores, large news sites, and websites with a large number of logged-in users, where standard HTML page caching has limited applicability.
In this article, we’ll explore how object caching works in WordPress, how to install and configure Redis on a Linux server, connect it to your site, and test its effectiveness.
How WordPress Object Caching Works
WordPress has its own object caching mechanism (Object Cache), which is used by both the CMS core and its plugins. For example, if several functions request the same user data while a page is being rendered, WordPress can store the result of the first request in the cache and reuse it.
However, by default, this cache exists only for the duration of the current PHP request. As soon as the server finishes processing the request, the cached data is lost, and the process repeats the next time the site is accessed.
Redis allows you to set up a persistent object cache, in which data is preserved between individual PHP requests. WordPress writes objects to Redis, from where they can subsequently be retrieved by other PHP-FPM processes serving site visitors.
It’s important to understand that Redis does not replace MySQL or MariaDB. The database remains the primary storage for information, and the contents of the object cache are regenerated as needed.
Object caching should also not be confused with other WordPress optimization mechanisms, such as:
- Page Cache, which stores pre-rendered HTML pages, allowing PHP code to be skipped entirely in some cases;
- OPcache, which stores compiled PHP bytecode, eliminating the need for the interpreter to recompile scripts;
- Object Cache, which stores data that the application works with during PHP code execution.
All three of these mechanisms can be used simultaneously, as they reduce the load on the server at different stages of HTTP request processing.
Installing Redis on the Server
Let’s walk through the setup using the example of a VPS running Ubuntu 24.04 LTS or Debian 12/13, on which WordPress is already running. To execute the commands, you’ll need SSH access to the server and root privileges or the ability to use `sudo`.
In this case, Redis, the web server, PHP, and the database will all be located on the same server, so there’s no need to open additional public ports.
First, let’s update the list of available packages and install Redis along with the PHP extension for working with it:
sudo apt update sudo apt install redis-server php-redis
The php-redis extension, also known as PhpRedis, allows PHP to interact with Redis via a native client. If multiple versions of PHP are installed on the server or third-party repositories are used, make sure the extension is installed for the specific version of PHP that powers WordPress.
Enable Redis to start automatically when the operating system boots:
sudo systemctl enable --now redis-server
Check the service status and Redis availability:
sudo systemctl status redis-server redis-cli ping
If Redis is running and accepting connections without additional authentication, the server will respond to the PING command with PONG.
You can check for the PHP extension using the following command:
php -m | grep -i '^redis$'
However, this command checks the PHP CLI, whose configuration may differ from that of PHP-FPM.
If the website runs via PHP-FPM, you’ll need to restart the corresponding service after installing the extension. For example, for PHP 8.3:
sudo systemctl restart php8.3-fpm
In Ubuntu 24.04, the default version is PHP 8.3; in Debian 12, it is PHP 8.2; and in Debian 13, it is PHP 8.4. If you’re using Apache with the mod_php module, you’ll need to restart Apache instead of PHP-FPM. On a live server, of course, you should perform the restart during a period of minimal load.
Configuring Redis for Object Caching
When installed from the default Ubuntu and Debian repositories, the Redis configuration file is located at /etc/redis/redis.conf. However, before making any changes to it, it’s a good idea to save a backup:
sudo cp -a /etc/redis/redis.conf /etc/redis/redis.conf.bak
Now open the file in a text editor:
sudo nano /etc/redis/redis.conf
Since Redis is used exclusively for WordPress caching in our case, it makes sense to change some of the default configuration settings.
Restricting Network Access
Redis should not be accessible from the Internet. Furthermore, if PHP and Redis are running on the same server, there is no need to allow connections even from the local network.
Let’s check the following settings:
bind 127.0.0.1 protected-mode yes port 6379
With this configuration, Redis will accept TCP connections only via the local interface.
However, restricting access via bind does not protect Redis from other applications running on the same server. Therefore, on servers hosting websites belonging to different owners, you must additionally configure authentication and isolation for Redis instances.
Limiting RAM Usage
Since Redis stores data primarily in RAM, without limiting its usage, a growing cache may begin to compete for resources with MySQL and PHP-FPM.
Let’s start by allocating 256 MB for the object cache:
maxmemory 256mb maxmemory-policy allkeys-lru
The maxmemory parameter defines the threshold at which Redis begins to apply a data eviction policy. However, the actual memory consumption by the Redis process may exceed the specified value due to internal structures, buffers, and memory allocation characteristics.
The allkeys-lru policy allows Redis to free up space by removing keys that haven’t been accessed in a long time. The algorithm is approximate, but for the WordPress object cache, it is generally sufficient.
As an alternative, you can use allkeys-lfu, where Redis takes into account the frequency of key accesses.
As for the amount of memory itself, there is no one-size-fits-all recommendation. For a small website, 64–128 MB may be sufficient, whereas a large online store may require hundreds of megabytes or several gigabytes. It’s best to determine the appropriate amount based on statistics from the live website.
Disabling Cache Writing to Disk
Redis supports two main mechanisms for long-term data storage: periodic creation of state snapshots (RDB) and operation logging (AOF).
If Redis is used exclusively as a WordPress object cache, there is usually no need to save its contents to disk, since WordPress will gradually rebuild the cache after the service restarts.
To disable both mechanisms, set the following parameters:
save "" appendonly no
Of course, this configuration is only acceptable if the Redis instance is not used by other applications to store data that cannot be lost upon a restart.
After making the changes, restart the service:
sudo systemctl restart redis-server sudo systemctl status redis-server
Verify that Redis is listening on the port only on the local interface:
sudo ss -lntp | grep ':6379'
You can verify that the memory settings have taken effect directly via the Redis CLI:
redis-cli CONFIG GET maxmemory redis-cli CONFIG GET maxmemory-policy
For the configuration shown above, the expected value of maxmemory is 268435456 bytes, and the eviction policy is allkeys-lru.
Connecting Redis to WordPress
To integrate Redis with WordPress, we’ll use the free Redis Object Cache plugin, which supports PhpRedis, Predis, and Relay clients and also allows you to track cache usage statistics.
Before installing, check to see if the site is already using another persistent object caching mechanism. The reason is that WordPress loads the external object cache implementation from the file wp-content/object-cache.php, so it’s not possible to use multiple independent implementations of this type of caching at the same time. If the file already exists, you should first determine which plugin it belongs to and properly disable the previous implementation.
In the WordPress admin panel, go to the "Plugins" section, find Redis Object Cache, install it, and activate it.
Then open the wp-config.php file - after saving a backup copy outside the site’s public directory - and add the following settings:
define('WP_REDIS_HOST', '127.0.0.1');
define('WP_REDIS_PORT', 6379);
define('WP_REDIS_CLIENT', 'phpredis');
define('WP_REDIS_DATABASE', 0);
define('WP_REDIS_PREFIX', 'mysite:');
define('WP_REDIS_TIMEOUT', 1);
define('WP_REDIS_READ_TIMEOUT', 1);
This block must be placed before the wp-settings.php file is included. If any of the listed constants are already present in the configuration, simply change their values.
The WP_REDIS_PREFIX parameter specifies the prefix for the keys under which WordPress will store data in Redis, and WP_REDIS_DATABASE defines the number of the logical database being used. The value mysite: should be replaced with your site’s unique identifier.
After saving the configuration, go to the "Settings" > "Redis" section in the admin panel and click the "Enable Object Cache" button. The plugin will create the object-cache.php file in the wp-content directory, after which WordPress will begin using Redis as external storage for the object cache.
If WP-CLI is installed on the server, you can install the plugin and enable caching directly from the command line using the following commands:
wp plugin install redis-cache --activate wp redis enable wp redis status
These commands should be run from the WordPress root directory as the system user who owns the site files.
It is not necessary to separately set the WP_CACHE constant to true for Redis Object Cache to work. This constant is used by other WordPress caching mechanisms and does not, by itself, activate the persistent object cache.
Using Redis for Multiple WordPress Sites
If multiple WordPress sites are hosted on a single VPS, technically they can all use a single Redis instance. However, in this case, you must prevent key conflicts and account for the specifics of cache clearing.
For example, for the first site, you can specify the following in wp-config.php:
define('WP_REDIS_DATABASE', 0);
define('WP_REDIS_PREFIX', 'site1:');
And for the second one:
define('WP_REDIS_DATABASE', 1);
define('WP_REDIS_PREFIX', 'site2:');
This way, each site will use its own logical database and a unique key prefix.
However, Redis logical databases do not have separate RAM limits, and the data eviction policy applies to the entire server instance. This means that a heavily trafficked online store could evict the cache of a less-trafficked site from memory.
Furthermore, separation by database number does not provide full isolation from a security standpoint. Therefore, if the websites belong to different clients or differ significantly in terms of load characteristics, it is preferable to run separate Redis instances for them with their own memory and access settings.
How to Check Redis Performance in WordPress
The "Connected" status in the Redis Object Cache settings indicates that WordPress has successfully connected to Redis. However, the mere presence of a connection does not, in itself, indicate the effectiveness of caching.
To start, open a few pages of the site that are processed by PHP, and then view the Redis statistics using the command:
redis-cli INFO stats
Among other metrics, we’ll be interested in the following:
keyspace_hits- the number of successful requests to existing keys;keyspace_misses- the number of requests to non-existent keys;evicted_keys- the number of keys evicted due to insufficient allocated memory;expired_keys -the number of keys removed after their expiration time.
The ratio of successful requests to the total number of hits and misses is called the Cache Hit Ratio and is calculated using the formula:
Hit Ratio = \frac{hits}{hits + misses} \times 100\%
For example, if Redis recorded 9,000 hits and 1,000 misses, the Cache Hit Ratio would be 90%.
Since these counters apply to the entire Redis instance and are accumulated from the moment the instance starts or the statistics are reset, it is better to compare changes in their values over a specific period to assess caching efficiency.
You can view RAM usage using the following command:
redis-cli INFO memory
Of particular interest here are the parameters used_memory_human, used_memory_rss_human, and maxmemory_human. These allow you to compare the amount of memory allocated to Redis by its memory allocator, the actual size of the process’s resident memory, and the set limit.
If the value of evicted_keys continues to increase while the percentage of successful cache hits decreases, there is reason to reconsider the allocated memory size or the key eviction policy. However, data eviction itself is a normal part of cache operation and does not indicate a Redis malfunction.
How to Measure WordPress Performance Gains
To assess the actual benefits of Redis, you can use the Query Monitor plugin, which allows you to view the number of SQL queries, their execution times, and other page-processing metrics.
It is advisable to take several measurements before enabling Redis and repeat them once the object cache has filled with data. When doing so, you must compare the same pages under identical conditions, eliminating the influence of cached HTML.
It also makes sense to evaluate changes in TTFB (Time to First Byte), CPU load, and MySQL or MariaDB activity.
Redis typically has the greatest impact when WordPress regularly makes a large number of repetitive database queries. However, if the main cause of the site’s slow performance is unoptimized PHP code, heavy SQL queries whose results aren’t cached, or calls to third-party APIs, installing Redis may have virtually no effect on page load times.
What to Do If Redis Stops Working
If WordPress reports a connection error after enabling object caching, you should first check the status of the Redis service and its log:
sudo systemctl status redis-server sudo journalctl -u redis-server -n 50 --no-pager redis-cli ping
If Redis is running but WordPress cannot connect to it, check the settings in wp-config.php, verify that the PhpRedis extension is enabled in your PHP-FPM configuration, and review the authentication settings if authentication was enabled.
To temporarily disable the Redis Object Cache without uninstalling the plugin, add the following line to wp-config.php:
define('WP_REDIS_DISABLED', true);
WordPress will revert to its default object caching mechanism. Once the issue is resolved, you can remove this constant or set it to false.
As for periodically clearing Redis, you should not schedule it unless absolutely necessary. WordPress automatically updates and removes the relevant objects from the cache when data changes, and Redis frees up memory according to the configured eviction policy.
Furthermore, completely clearing the cache on a heavily trafficked site can lead to a sharp increase in the number of requests to MySQL, since all PHP processes will have to retrieve data from the database again.
A properly configured object cache should operate virtually transparently to the site administrator. It is sufficient to periodically monitor RAM usage, hit and miss statistics, and database load in order to adjust the Redis configuration as needed.