Reducing TTFB in WordPress by Implementing Redis Object Caching
Table of Contents
High TTFB in WordPress environments is often a direct result of excessive database queries executed during the PHP initialization phase.
While page caching serves static files to anonymous visitors, dynamic requests—such as WooCommerce cart updates or logged-in user sessions—bypass these files entirely. These requests force WordPress to query the MySQL database for options, user metadata, and taxonomy terms every single time. Redis acts as a persistent memory layer that stores the results of these expensive queries. This mechanism prevents the server from hitting the disk for data that has already been retrieved.
Implementing this layer reduces the time PHP spends waiting for the database to return results. You will notice a significant decrease in the Time to First Byte metric, especially on pages with complex query structures.
Reducing Database Latency with In-Memory Storage
The core of this optimization lies in the WP_Object_Cache class, which WordPress uses to store data internally during a single page load.
By default, this cache is non-persistent and is discarded as soon as the PHP process finishes. Redis transforms this transient storage into a persistent one by moving the data to an external RAM-based service. When a function calls get_option(), WordPress first checks the Redis store before even attempting to connect to MySQL. If the data exists in Redis, it is returned in microseconds, bypassing the entire SQL execution and parsing pipeline.
This approach is particularly effective for large wp_options tables where autoloaded data can exceed several megabytes. Persistent object caching is the only way to scale the WordPress backend without increasing server CPU cores.
When the database query takes more than 0.5s, the bottleneck is usually disk I/O or poorly indexed tables.
Redis bypasses these issues by keeping the most frequently accessed data in volatile memory. If you are running a high-traffic WooCommerce store, this architectural change is not optional. Backend response times improve because the database is no longer the primary source of truth for every request. You will see the server load average drop as the number of active MySQL threads decreases.
You must install the php-redis extension and a Redis server instance before modifying any WordPress files. Ensure your environment supports the PHPRedis extension for better performance over the Predis library.
Configuring the Redis Drop-in for WordPress
Use the following configuration in your wp-config.php file to establish the connection between the application and the Redis service.
define('WP_CACHE', true);
define('WP_REDIS_HOST', '127.0.0.1');
define('WP_REDIS_PORT', 6379);
define('WP_REDIS_DATABASE', 0);
define('WP_REDIS_TIMEOUT', 1);
define('WP_REDIS_READ_TIMEOUT', 1);
define('WP_CACHE_KEY_SALT', 'unique_site_prefix_');
Setting a WP_CACHE_KEY_SALT is a critical step for servers hosting multiple WordPress installations to prevent cross-site data leakage. Without a unique salt, one site might retrieve the options or user data of another site sharing the same Redis database. This configuration ensures that PHP connects to the Redis daemon with a strict timeout of one second. If the Redis service fails to respond within this window, the application will fallback to standard database queries, preventing a total site outage.
After defining these constants, you must place the object-cache.php drop-in file into the wp-content directory. This file acts as the bridge that overrides the default WordPress cache functions with Redis-specific commands.
Validating the Connection
Verify the status of the cache by running the redis-cli info command on your server terminal.
Look specifically for the db0:keys=... line, which indicates that WordPress is successfully writing data to the Redis keyspace. If the key count remains at zero, check your firewall settings to ensure port 6379 is accessible locally. Use the MONITOR command to see the real-time flow of GET and SET operations as you browse your site. This live feed confirms that the object-cache.php drop-in is functioning correctly.
A common bottleneck occurs when the wp_options table grows due to poorly coded plugins that store large arrays in a single row. Each time WordPress loads, it fetches all autoloaded options, which can consume significant memory and CPU time if the database resides on a slow disk.
Optimizing Redis Memory Management and Eviction
Efficient cache management requires understanding the eviction policy configured in the redis.conf file.
When the allocated memory limit is reached, Redis must decide which keys to delete to make room for new data. The allkeys-lru policy is generally preferred for WordPress environments as it removes the least recently used keys regardless of their expiration time. This ensures that frequently accessed metadata and options remain in memory, preventing a sudden spike in TTFB. You can monitor memory usage in real-time by executing the INFO memory command within the Redis CLI.
Refined memory limits prevent the service from crashing under heavy load. Use the following commands to check hit rates and memory consumption.
# Check Redis hit rate
redis-cli info stats | grep -E "keyspace_hits|keyspace_misses"
# Check memory usage
redis-cli info memory | grep "used_memory_human"
A keyspace hit rate below 80% suggests that your cache is either too small or the data is expiring too quickly.
You can adjust the default TTL for transients to keep data in memory longer, provided you have sufficient RAM available. If the hit rate is low, the CPU must work harder to re-process queries, negating the benefits of the cache. Scaling the memory allocated to Redis is often cheaper than upgrading your database server. High hit rates directly correlate with lower TTFB values and better user experience for authenticated users.
Redis is a single-threaded service, which means a single slow command can block the entire queue. Avoid using the KEYS * command on production environments, as it scans the entire database and can cause latency spikes.
Measuring the Impact on Backend Response Times
Objective performance testing is required to validate the effectiveness of the object cache.
Use a tool like curl to measure the response time for a logged-in user session, which bypasses the page cache. Run the command curl -o /dev/null -s -w "%{time_starttransfer}n" https://yourdomain.com multiple times to establish a baseline. You should see the start-transfer time drop by 150ms to 300ms after Redis is enabled. This improvement is most visible in the WordPress dashboard (/wp-admin/), where page loads become significantly snappier.
If the TTFB remains unchanged, the bottleneck may lie in the PHP execution itself rather than the database. Use a profiler like Xdebug or Query Monitor to identify specific functions that are consuming excessive resources.
Monitoring Hits via Code
You can inject cache statistics directly into the page source for immediate verification.
// Add this to your functions.php to monitor cache hits in the footer
add_action('wp_footer', function() {
global $wp_object_cache;
if (is_object($wp_object_cache)) {
echo "<!-- Redis Hits: {$wp_object_cache->cache_hits} | Misses: {$wp_object_cache->cache_misses} -->";
}
}, 999);
This snippet injects the cache statistics into the HTML source code for easy debugging. You can inspect the source to see exactly how many database queries were saved by the Redis layer. If the hit count is significantly higher than the miss count, the configuration is successful. Sites with heavy use of the Metadata API or the Options API will see the largest gains.
This simple observation allows you to prove the ROI of the technical implementation to stakeholders. Maintaining a clean Redis instance is a mandatory task for any serious technical lead or developer.
Comparing Redis to Memcached reveals why Redis is the superior choice for modern WordPress stacks.
While Memcached is a simple key-value store, Redis supports complex data types and provides built-in persistence options. This means if the Redis service restarts, you can configure it to reload the cache from disk rather than starting with an empty set. For WordPress, the ability to handle larger data sets and the efficiency of the PHPRedis extension provide a clear performance advantage. Most managed WordPress hosts have shifted to Redis as the default object caching solution for this reason.
If you are managing your own VPS, the memory overhead of Redis is negligible compared to the speed gains it provides. Object caching is the foundation of a high-performance WordPress stack.
Moving the data layer into RAM eliminates the most common cause of high TTFB. This setup ensures that the server remains responsive even as the database size grows over time.
Related Articles
If you enjoyed reading this, then please explore our other articles below:
More Articles
If you enjoyed reading this, then please explore our other articles below:




2019-2026 ©