Optimising performance is critical for any high-traffic or feature-rich Drupal site. One of the most effective ways to improve responsiveness and reduce server load is by implementing a well-structured caching strategy.
While Drupal's built-in database caching may suffice for smaller or less complex sites, larger applications typically require more efficient solutions. Advanced cache backends like Redis, APCu, or Memcache can significantly enhance page load times by minimising repeated database queries and reducing latency across the application.
This blog walks through the most reliable caching options for modern Drupal environments, using current practices that apply across supported versions. You’ll find practical configuration examples and sample implementation code for each backend, providing a clear path to boost performance and deliver a smoother user experience.
Cache Backend fundamentals
Drupal stores cached data in “cache backends” – the physical mechanism (database, in-memory, or remote servers) where cached items reside. How cache items are stored, retrieved, and invalidated directly impacts performance, scalability, and resource consumption.
Key considerations:
- Setup complexity: Some backends work out-of-the-box (default database), whereas others like APCu, Redis, and Memcache may require additional configuration or infrastructure.
- Performance & scalability: In-memory systems deliver faster lookups and are well-suited for distributed environments.
- Data persistence: The database cache provides persistent storage, whereas advanced backends offer either optional persistence (Redis) or pure in-memory caching (APCu, Memcache). For example, APCu is ideal for fast lookup on a single server, but its data does not persist between server restarts.
For more details on the design and best practices of Drupal’s Cache API, refer to the official Drupal Cache API Documentation.
Core Backend options in Drupal
Drupal supports several caching solutions, each with its strengths:
- Database (default):
- Usage: Ideal for small sites or sites with moderate traffic.
- Persistence: Fully persistent as cache entries reside in the database.
- APCu:
- Usage: Best for single-server environments where an in-memory cache is desired for fast lookups.
- Persistence: Data does not persist across server restarts.
- Documentation: Drupal APCu Cache Module.
- Redis:
- Usage: Suited for medium to large-scale sites; its in-memory nature offers high-speed lookups with the possibility to scale horizontally by using clustering features.
- Persistence: Can be configured for optional disk persistence.
- Documentation: Redis Module for Drupal.
- Memcache:
- Usage: Often employed in distributed setups where caching is shared among multiple servers.
- Persistence: Purely in-memory, with a simpler data model compared to Redis.
- Documentation: Memcache Module for Drupal.
Many administrators observe that transitioning from the default database cache to an advanced backend can result in significant performance improvements, especially as traffic increases.
A practical use case: transitioning from database caching to an advanced backend
The scenario
Imagine a popular travel website that initially relies on Drupal’s default database caching. As the site grows, increasing traffic results in a heavier load on the database, slowing page responses and escalating resource consumption.
The goal
To reduce the load on the database and boost overall responsiveness, the site migrates to an advanced caching backend. For example, configuring Redis enables the site to serve cached content rapidly from memory while capitalising on its clustering features for scalability.
Considerations
- Infrastructure Readiness: Verify that your hosting environment supports the installation and configuration of advanced caching systems like APCu, Redis, or Memcache.
- Scalability: Both Redis and Memcache enhance performance under a distributed setup, a key factor for high-traffic sites.
- Cache Metadata Usage: Maintain the use of cache tags, contexts, and appropriate expiration settings to manage cache invalidation intelligently.
Sample implementation
Below is a practical sample implementation that demonstrates how to fetch data from a third-party API, cache it using Drupal’s Cache API, and then render the data with appropriate cache metadata. This example illustrates the concept behind transitioning from heavy database queries to utilising a fast cache backend.
/**
* Fetches weather data from a third-party API and caches the result.
*
* This function demonstrates a practical use case where an expensive API call
* is cached to reduce load on both the external API and the database.
*
* @param int $location_id
* The unique identifier for a location.
*
* @return array
* A render array containing the weather data and cache metadata.
*/
function mymodule_get_weather_data($location_id) {
// Create a unique cache ID based on the location.
$cid = 'mymodule:weather:' . $location_id;
// Load the default 'data' cache bin.
$cache = \Drupal::cache('data');
// Attempt to retrieve cached data.
if ($cache_item = $cache->get($cid)) {
// Cache hit: return the cached data along with render metadata.
return [
'#theme' => 'weather_display',
'#data' => $cache_item->data,
'#cache' => [
'tags' => ['weather:' . $location_id],
'max-age' => 1800,
],
];
}
// Cache miss: perform the API call to fetch weather data.
$api_url = "https://api.example.com/weather?location={$location_id}";
$response = file_get_contents($api_url);
// Decode the JSON response.
$weather_data = json_decode($response, TRUE);
// Define cache tags and set an expiration (max-age of 30 minutes).
$tags = ['weather:' . $location_id];
$max_age = 1800;
$expire = time() + $max_age;
// Store the fetched data in cache.
$cache->set($cid, $weather_data, $expire, $tags);
// Build and return the render array with cache metadata.
return [
'#theme' => 'weather_display',
'#data' => $weather_data,
'#cache' => [
'tags' => $tags,
'max-age' => $max_age,
],
];
}
Implementation flow explained:
- Cache ID generation:
A unique cache identifier ($cid) is generated by combining a module-specific prefix and the location ID. - Cache retrieval:
The function checks if data for the specified $cid exists in the ‘data’ cache bin. If found, it returns the cached data immediately, bypassing an external API call. - Data fetch and cache storage:
Upon a cache miss, the API is queried using file_get_contents(). The returned JSON is decoded, and the data is cached along with defined cache tags and an expiration time (max-age of 30 minutes). - Render array construction:
The function builds a render array that includes the weather data and cache metadata, allowing Drupal to manage cache variations intelligently.
For additional details on implementing caching strategies in Drupal, see the official Cache API documentation.
Configuration examples
Below are the precise configurations to include in your settings.php for each cache backend. These examples have been verified for code accuracy and are accompanied by links to relevant Drupal.org documentation.
Database Backend (default)
No additional module installation is needed for the default database caching. To explicitly set it, add the following to your settings.php:
// In settings.php, set the default cache backend to database.
$settings['cache']['default'] = 'cache.backend.database';
APCu Backend
Before configuring APCu, ensure the APCu PHP extension is installed and enabled on your server.
// In settings.php, configure APCu caching.
if (extension_loaded('apcu') && ini_get('apc.enabled')) {
// Use APCu as the default cache backend.
$settings['cache']['default'] = 'cache.backend.apcu';
// Optionally, assign APCu to specific cache bins.
$settings['cache']['bins']['render'] = 'cache.backend.apcu';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.apcu';
}
The Drupal APCu Cache Module provides further instructions and documentation.
Redis Backend
To use Redis, ensure the Redis PHP extension is installed and that the Redis module is added via Composer.
- Install Redis and the PHP Redis Extension:
- sudo apt-get install redis-server php-redis
sudo service redis-server restart
- Add the Drupal Redis Module via Composer:
- composer require drupal/redis
- Update your settings.php:
// In settings.php, configure Redis if the Redis extension and module are available.
if (extension_loaded('redis') && class_exists('Drupal\redis\ClientFactory')) {
// Define connection parameters.
$settings['redis.connection']['interface'] = 'PhpRedis';
$settings['redis.connection']['host'] = '127.0.0.1';
$settings['redis.connection']['port'] = 6379;
// Set Redis as the default cache backend.
$settings['cache']['default'] = 'cache.backend.redis';
// Optionally, exclude specific bins if required:
// $settings['cache']['bins']['bootstrap'] = 'cache.backend.chainedfast';
// Load Redis service definitions.
$settings['container_yamls'][] = 'modules/contrib/redis/example.services.yml';
}
For further configuration options, see the Redis Module for Drupal.
Memcache Backend
Memcache requires installing the Memcache server, enabling the PHP Memcache extension, and adding the corresponding Drupal module.
- Install Memcache and the PHP Memcache Extension:
- sudo apt-get install memcached php-memcache
sudo service memcached restart
- Add the Drupal Memcache Module via Composer:
- composer require drupal/memcache
- Configure Memcache in settings.php:
// In settings.php, configure Memcache if the extension and module are available.
if (extension_loaded('memcache') && class_exists('Drupal\memcache\MemcacheBackendFactory')) {
// Specify Memcache server settings.
$settings['memcache']['servers'] = ['127.0.0.1:11211' => 'default'];
$settings['memcache']['bins'] = ['default' => 'default'];
// Set Memcache as the default cache backend.
$settings['cache']['default'] = 'cache.backend.memcache';
// Load Memcache service definitions.
$settings['container_yamls'][] = 'modules/contrib/memcache/memcache.services.yml';
}
More details can be found in the Memcache Module for Drupal.
Making your decision
When choosing a cache backend for your Drupal site, consider the following:
- Traffic volume & growth:
Small sites might perform adequately with the default database caching, while increased traffic demands the speed and scalability of APCu, Redis, or Memcache. - Infrastructure capabilities:
Shared hosting may limit your caching options, whereas VPS or dedicated servers allow for more advanced setups. - Scalability & high availability:
Redis offers clustering and optional persistence; Memcache is effective in distributed environments. - Technical requirements:
Decide between persistent storage and purely in-memory caching based on your use case and the support for advanced features like cache tags.
Monitoring and validating your caching strategy
Once your caching backend is in place, continuous monitoring is essential:
- Using Drupal’s Cache Stats:
Some cache backends support a getStats() method for reviewing hit ratios and memory usage
// Example usage:
$cache = \Drupal::cache('render');
if (method_exists($cache, 'getStats')) {
$stats = $cache->getStats();
// Log or inspect $stats as needed.
}
- Application monitoring tools:
Tools like New Relic or Blackfire can help track performance and identify bottlenecks. - Native monitoring:
For Redis, run redis-cli info; for Memcache, use echo "stats" | nc localhost 11211 to gather insights.
For additional guidance, refer to the Drupal Cache API Documentation.
Series navigation
This article is part of our comprehensive series on Drupal caching:
- Introduction to Drupal Caching
- Understanding Drupal’s Cache API
- Choosing the Right Cache Backend for Your Drupal Site (You are here)
- Mastering Page and Block Caching in Drupal (Coming soon)
- Optimising Drupal Views and Forms with Caching (Coming soon)
- Entity and Render Caching for Drupal Performance (Coming soon)
- Building Custom Caching Services in Drupal (Coming soon)
- Implementing Custom Cache Bins for Specialised Needs (Coming soon)
- Advanced Drupal Cache Techniques (Coming soon)
- Drupal Caching Best Practices and Performance Monitoring (Coming soon)
In conclusion
Implementing an effective caching strategy in Drupal is not just a performance enhancement, it's essential for maintaining speed and reliability at scale. As your site grows in complexity or traffic volume, relying solely on default database caching can introduce bottlenecks. Solutions like APCu, Redis, and Memcache offer flexible, powerful alternatives tailored to different infrastructure needs.
By choosing the right backend and applying the configuration steps outlined in this guide, you can significantly reduce server load, improve response times, and deliver a more seamless experience to your users.
As with any performance optimization, continuous testing and monitoring are key. Stay aligned with Drupal’s official documentation to adapt your caching setup as technologies and best practices evolve.