my alt

Setting Up FastCGI Page Cache and APCu Object Cache on Your WordPress Website

Enhance your WordPress website’s performance with FastCGI Page Cache and APCu Object Cache. This guide covers setup steps, necessary nginx configuration edits, and the benefits and risks of these caching mechanisms.

Enhancing your WordPress website’s performance can be achieved through various caching mechanisms. In this post, we’ll explore how to set up FastCGI Page Cache and APCu Object Cache on a WordPress website. We’ll also look at the necessary edits to your nginx configuration files and discuss the advantages and potential risks of these implementations.

FastCGI Page Cache helps reduce server load and improve response times by caching dynamic content. APCu Object Cache stores PHP objects in memory, speeding up repeated database queries. Let’s dive into the setup.

Editing nginx Configuration Files for FastCGI Page Cache

To enable FastCGI Page Cache, you need to edit your nginx configuration files. Here are the steps:

Main nginx Configuration

Add the following lines to your main nginx configuration file (usually located at /etc/nginx/nginx.conf):

# Add FastCGI cache path configuration
fastcgi_cache_path /var/www/html/wp-content/cache/fastcgi levels=1:2 keys_zone=WORDPRESS:100m max_size=10g inactive=24h use_temp_path=off;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;

These lines define the path for storing cached files, set the cache key, and configure nginx to ignore certain headers when caching.

Site-Specific nginx Configuration

Next, update your site-specific nginx configuration file (typically found in /etc/nginx/sites-available/your-site.conf).

First, at the server root block level:

set $skip_cache 0;

if ($request_method = POST) {
    set $skip_cache 1;
}
if ($query_string != "") {
    set $skip_cache 1;
}

if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|^/feed/*|/tag/.*/feed/*|index.php|/.*sitemap.*.(xml|xsl)") {
    set $skip_cache 1;
}

if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {
    set $skip_cache 1;
}

Then, the at the PHP location level:

fastcgi_split_path_info ^(.+.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_intercept_errors off;
fastcgi_buffer_size 16k;
fastcgi_buffers 4 16k;
fastcgi_connect_timeout 600;
fastcgi_send_timeout 600;
fastcgi_read_timeout 600;
# FastCGI caching settings
fastcgi_cache WORDPRESS;
fastcgi_cache_valid 200 301 302 24h;
fastcgi_cache_min_uses 1;
fastcgi_cache_lock on;
fastcgi_cache_use_stale error timeout updating invalid_header http_500 http_503;
fastcgi_cache_bypass $skip_cache;
fastcgi_no_cache $skip_cache;
fastcgi_cache_valid 404 1m;
add_header X-FastCGI-Cache $upstream_cache_status;
add_header Cache-Control "public, max-age=86400";

These settings manage how nginx handles caching for different requests and ensure that certain requests bypass the cache, such as POST requests, requests with query strings, and logged-in users. You may want to edit the expiration times, here set to 24 hours, which is enough for any website that does produce new content in a larger timeframe.

FastCGI is now actively caching your content. To verify that caching is working correctly, you can check the cache directory on your server. Navigate to the cache path you defined earlier, typically /var/www/html/wp-content/cache/fastcgi. You should see folders being created and updated in this directory. The size of this directory will grow as more content is cached, indicating that the cache is storing your dynamic content.

Monitoring Cache Activity

You can control and monitor FastCGI cache activity through various means:

1. Check Cache Directory: Periodically check the /var/www/html/wp-content/cache/fastcgi directory. If you see files being generated and updated, it means FastCGI is caching your pages.

2. Cache Status Headers: Look at the HTTP response headers to see if a request was served from the cache. For instance, use browser developer tools or command-line tools like curl to inspect headers. You should see a header like X-FastCGI-Cache: HIT if the content was served from the cache, or X-FastCGI-Cache: MISS if it was not. You can also preform simple curl -I your-domain.com in a terminal to see if the cache was a HIT or MISS.

How does FastCGI Page Cache actually work?

When a request is made to your WordPress site, nginx checks the FastCGI cache first. If a cached version of the requested page exists and is still valid, nginx serves this cached content directly, bypassing PHP execution and database queries. This significantly reduces the load on your server and speeds up response times. If the cache does not have the requested page, nginx processes the request normally, generates the content, and stores it in the cache for future requests.

This allows your site to factually be as fast as a static HTML website. What FastCGI does not do is balance your content across the web: this is known as CDN and is impossible with only one server. You can combine FastCGI (and other cache mechanisms) with CDNs of course, such as CloudFlare, however we do not recommend this for privacy reasons: FastCGI will be “owned by you”, whereas a CDN will distribute your Data across several servers that are not under your control. Further, most CDN services collect data abut your visitors.

Implementing APCu Object Cache

APCu Object Cache can significantly speed up your WordPress site by caching database query results. To implement APCu, follow these steps:

1. Install the APCu extension for PHP.
2. Add the object-cache.php file from the TukuToi APCu Cache Drop In Plugin to your /wp-content directory. Alternatively you can use any other APCu WordPress Cache file – there are numerous from simple to very complex implementations out there.

APCu Backend Stats Page

The TukuToi APCu Cache Drop In Plugin includes a small backend stats page to monitor your cache. This is already included in the above-mentioned file and you do not need to do any further work to use it. It is available under the Tools menu > Cache Stats. Again, there are numerous implementations of APCu Cache Stats out there, so feel free to choose another one if you need a more comprehensive statistics page.

How APCu Object Cache Works

The APCu (Alternative PHP Cache User) Object Cache works by storing the results of database queries in the server’s memory. Here’s a more detailed breakdown of how it functions:

1. Database Query Execution: When a page on your WordPress site is loaded, it often requires multiple database queries to retrieve the necessary data. Without a caching mechanism, these queries are executed every time a page is loaded, which can be resource-intensive.

2. Caching Query Results: With APCu Object Cache, the first time a query is executed, its result is stored in memory (RAM). This means that subsequent requests for the same data can be served directly from memory, significantly speeding up the response time.

3. Retrieving from Cache: On subsequent page loads, instead of executing the same database query again, WordPress will retrieve the result from the APCu cache. This reduces the load on the database server and speeds up the overall page load time.

4. Cache Expiration: Cached data is stored for a specified period. When the cache expires, the next request will fetch fresh data from the database and store it in the cache again. You can configure the expiration settings to balance between data freshness and performance.

5. APCu Stats Page: The backend stats page provided by the TukuToi APCu Cache repository gives you insights into the performance of your cache. You can see the number of cache hits and misses, the amount of memory used, and other relevant statistics. This helps you monitor and optimize your caching strategy.

Clearing Caches

To manage and clear caches, you can use the TukuToi Clear Cache MU Plugin. This tool provides an easy way to clear both FastCGI and APCu caches in one simple page, which you can find under Tools > Cache Controls.

Clearing caches can be necessary in scenarios where you make significant changes to your site content or structure, and you want these changes to be reflected immediately. The Clear Cache MU Plugin ensures that you can efficiently manage your cache without having to manually delete cached files or data.

We wrote more comprehensively about how to install MU Plugins, and what WordPress MU Plugins are in previous posts.

By implementing and monitoring APCu Object Cache and using tools like the Clear Cache MU Plugin, you can ensure that your WordPress site remains fast and responsive, even as it grows in complexity and traffic.

Advantages and Risks of FastCGI & APCu Cache

Advantages:

  1. Improved Performance: Both FastCGI and APCu caches reduce server load and response times.
  2. Reduced Latency: Cached content is delivered faster, improving user experience.
  3. Scalability: Efficient caching allows your site to handle more traffic.

Risks:

  1. Stale Content: Cached content may not always be up-to-date. Proper cache invalidation is crucial.
  2. Configuration Complexity: Incorrect configuration can lead to cache bypass or errors.
  3. Resource Usage: Caching mechanisms consume disk space and memory. Monitor resource usage to prevent issues.
  4. Weirdness: Yes, things can get weird. Caches can sometimes cause unexpected behavior, such as WordPress Transients no longer being stored in the database but continuing to work because they are cached in memory now. This is not a misconfiguration; it’s an expected but “strange” outcome of how caching mechanisms like APCu work. Such behavior can be confusing and may make debugging more challenging. Regular monitoring and understanding of how your caching system interacts with WordPress is crucial to manage these oddities effectively.

Bringing Your WordPress Site to the Next Level

By setting up FastCGI Page Cache and APCu Object Cache, you can significantly enhance your WordPress site’s performance. Properly configured caching reduces server load, decreases response times, and improves the overall user experience. Remember to monitor your caches and clear them as needed using tools like the TukuToi Clear Cache repository.

Happy caching!


Related Articles

Based on our Cosine Similarity Analysis
Setting Up FastCGI Page Cache and APCu Object Cache on Your WordPress Website

How to make a WordPress Site Faster?

Are you facing issues with your WordPress site speed? Discover essential tips and plugins to make your WordPress site faster and improve user experience.

Read more

Setting Up FastCGI Page Cache and APCu Object Cache on Your WordPress Website

Creating a MU Plugin to Modernize the WordPress Caption Shortcode

Discover how to create a Must-Use (MU) plugin to enhance WordPress caption shortcodes using modern image formats like WebP for improved performance and faster loading times.

Read more