Learn Nginx · 10/13

Server-Side Caching for Speed

8 min read

Hello there, future Nginx guru! 🧙‍♂️

Welcome to the guide on Server-Side Caching. Let's be honest, nobody likes a slow website. If your site takes more than a few seconds to load, users will click away faster than you can say "reverse proxy." This is where caching swoops in to save the day.

The Problem: Imagine your server is a world-class chef. Every time a customer (a user request) asks for a popular dish (your homepage), the chef has to run to the pantry, chop the vegetables, cook the meal from scratch, and serve it. This is fine for a few customers, but when a hundred people order the same dish at once, the chef gets overwhelmed, and the kitchen (your server) slows to a crawl.

The Solution: Server-side caching is like telling the chef to pre-cook several portions of that popular dish and keep them on a warming tray. When a new order comes in, they can serve it instantly. Nginx acts as that very efficient kitchen assistant, serving pre-made responses directly from its "warming tray" (the cache) without bothering the busy chef (your backend application) for every single request. This drastically reduces server load and makes your website fly.

Ready to speed things up? Let's dive in.


1. Introduction to Microcaching for High Traffic 🏎️

The Problem: Your website just hit the front page of a major news aggregator! Hooray! But wait... your server is now smoking, and the site is barely loading. Even with some caching, the sheer volume of requests for your dynamic homepage is crushing your backend.

The Solution: Microcaching. This is a powerful technique where you cache dynamic content, but only for a very short time—think 1 to 10 seconds.

It sounds a bit crazy, right? What good is a 1-second cache?

Here's the magic: If you get 500 requests per second for your homepage, without microcaching, your backend has to generate the page 500 times. With a 1-second microcache, Nginx handles the first request, sends it to your backend, caches the result, and then serves that same cached result to the other 499 users who requested it within that second. Your backend load just dropped by 99.8%! This technique is a lifesaver for handling massive traffic spikes while keeping content fresh.

A Minimalist Configuration Example:

Here’s how you could set up a 1-second cache for a proxied backend.

nginx
# This part goes in your http block
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m;

server {
    # ... other server config ...

    location / {
        proxy_cache my_cache;
        proxy_cache_valid 200 1s; # Cache successful responses for 1 second
        proxy_pass http://my_backend_app;

        # This header is your best friend for debugging
        add_header X-Cache-Status $upstream_cache_status;
    }
}

This simple setup tells Nginx to cache successful responses for just one second, which is enough to absorb huge traffic surges.


2. Accelerating Dynamic Apps: Configuring FastCGI Cache ⚡

The Problem: Your web application, likely written in PHP, Python, or Ruby, is the bottleneck. It connects to a database, runs complex logic, and renders templates for every single request. This is slow and resource-intensive.

The Solution: fastcgi_cache. This is a specialized cache designed to store the final HTML output generated by your application server (like PHP-FPM). Instead of running the entire PHP process for every visitor, Nginx can just serve the pre-generated page directly from its cache.

Think of Nginx as a helpful librarian. Instead of running to the vast, complex archives (your PHP application and database) for a popular book every single time, the librarian keeps a copy at the front desk (the FastCGI cache).

Hands-On Configuration:

Setting this up involves two main steps.

Step 1: Define the Cache Zone (in your nginx.conf http block)

You need to tell Nginx where to store the cache files and how to manage them.

nginx
# /etc/nginx/nginx.conf

http {
    # ... other http settings ...

    # Defines the cache storage
    fastcgi_cache_path /var/cache/nginx/fastcgi_cache levels=1:2 keys_zone=PHPCACHE:100m inactive=60m max_size=1g;
    fastcgi_cache_key "$scheme$request_method$host$request_uri";
}

Let's quickly break down the fastcgi_cache_path directive:

  • /var/cache/nginx/fastcgi_cache: The directory on your server where cached files will be stored.
  • levels=1:2: Creates a two-level directory structure to keep the cache organized and prevent performance issues with too many files in one folder.
  • keys_zone=PHPCACHE:100m: Creates a shared memory zone named PHPCACHE with 100MB of space to store the cache keys and metadata. This is crucial for fast lookups. A 10MB zone can hold about 80,000 keys.
  • inactive=60m: If a cached file isn't accessed for 60 minutes, it gets removed, regardless of its freshness.
  • max_size=1g: Sets the maximum size of the cache on disk to 1 gigabyte.

Step 2: Apply the Cache to your PHP Location Block (in your site's config)

Now, tell Nginx to actually use the cache for PHP requests.

nginx
# /etc/nginx/sites-available/your-site.com

server {
    # ... server config ...

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock; # Path to your PHP-FPM socket

        # --- Caching directives start here ---
        fastcgi_cache PHPCACHE; # Use the cache zone we defined earlier
        fastcgi_cache_valid 200 60m; # Cache successful (200 OK) responses for 60 minutes
        fastcgi_cache_valid 404 5m;  # Cache "Not Found" pages for 5 minutes

        # This lets you see if the cache is working
        add_header X-Cache-Status $upstream_cache_status;
    }
}

After adding this and reloading Nginx, the X-Cache-Status header in your browser's developer tools will show MISS on the first visit, and HIT on subsequent visits!


3. Caching Downstream: Setting up Proxy Cache 📮

The Problem: Your main Nginx server doesn't run the application itself. Instead, it acts as a "reverse proxy," forwarding requests to other backend servers (maybe a Node.js API, a Java application, or even another web server). Hitting these backend services for every request is inefficient.

The Solution: proxy_cache. This is a general-purpose cache for storing responses from any backend server Nginx is proxying requests to. It's conceptually identical to fastcgi_cache, but uses different directives.

The setup is remarkably similar, which is great because you're already familiar with the concepts!

Hands-On Configuration:

Step 1: Define the proxy_cache_path (in your http block)

nginx
# /etc/nginx/nginx.conf

http {
    # ...

    proxy_cache_path /var/cache/nginx/proxy_cache levels=1:2 keys_zone=PROXYCACHE:100m inactive=60m max_size=1g;
}

Notice how this is almost identical to the FastCGI setup? The parameters mean the same thing.

Step 2: Apply the Cache in your location Block

nginx
# /etc/nginx/sites-available/your-api-gateway.com

server {
    # ...

    location /api/v1/users {
        proxy_pass http://user_service_backend;

        # --- Caching directives ---
        proxy_cache PROXYCACHE;
        proxy_cache_valid 200 10m; # Cache successful API responses for 10 minutes
        proxy_cache_key "$scheme$request_method$host$request_uri";

        # The essential debug header
        add_header X-Proxy-Cache $upstream_cache_status;
    }
}

The $upstream_cache_status variable will show values like HIT, MISS, EXPIRED, or BYPASS, giving you clear insight into what the cache is doing.


4. Cache Control: Rules for Bypassing and Purging Content 🕹️

Caching is fantastic, but it's not a one-size-fits-all solution. Sometimes you need more control.

The Problem:

  1. How do you prevent caching on pages that must always be live, like a shopping cart, a checkout page, or a user's admin dashboard?
  2. You just published a critical update to an article. How do you force the cache to clear now instead of waiting for it to expire?

The Solution: Bypassing and Purging.

Bypassing the Cache (Don't Cache This!)

You can tell Nginx to skip the cache for specific requests. A very common industry practice is to bypass the cache for logged-in users to ensure they always see their personalized content.

This is typically done by checking for the presence of a specific cookie (like a session cookie).

Example: Bypass Cache for Logged-in WordPress Users

nginx
server {
    # ...
    set $skip_cache 0;

    # If the request has a wordpress_logged_in cookie, set the variable to 1
    if ($http_cookie ~* "wordpress_logged_in") {
        set $skip_cache 1;
    }

    # ...

    location ~ \.php$ {
        # ... your normal fastcgi_pass directives ...

        # The bypass directive checks our variable. If it's not "0", it bypasses the cache.
        fastcgi_cache_bypass $skip_cache;
        fastcgi_no_cache $skip_cache;

        # ... your other fastcgi_cache directives ...
        add_header X-Cache-Status $upstream_cache_status;
    }
}

With this rule, any user who is logged into WordPress will BYPASS the cache, while anonymous visitors will get served from the HIT or MISS cache.

Purging the Cache (Delete This Now!)

Purging means actively deleting a specific item (or a group of items) from the cache. This is more direct than waiting for expiration.

The most robust way to do this is with the proxy_cache_purge directive, which may require installing an extra Nginx module depending on your setup.

Example: Setting up a Purge Location

This configuration allows you to send a special PURGE request to an endpoint to clear its cache. For security, we'll restrict it to only be accessible from the server itself (127.0.0.1).

nginx
# In your http block
proxy_cache_path /var/cache/nginx/proxy_cache ... keys_zone=PROXYCACHE:100m ...;

# In your server block
server {
    # ...

    location ~ /purge(/.*) {
        # Allow purge requests only from localhost
        allow 127.0.0.1;
        deny all;

        # The magic happens here
        proxy_cache_purge PROXYCACHE "$scheme$request_method$host$1";
    }
}

To purge the cache for https://example.com/my-article, you would run this command from your server:

bash
curl -X PURGE "https://example.com/purge/my-article"

Nginx will respond with a 204 No Content to indicate success. You can also use a wildcard * to purge everything under a certain path.

A simpler, though more brutal, method is to just delete the cache files directly from the server.

bash
sudo rm -rf /var/cache/nginx/proxy_cache/*

This clears the entire cache zone. It's effective but less precise.


📚 References for Extra Reading

Challenge

You are a DevOps engineer responsible for optimizing a high-traffic WordPress website. The site serves dynamic content via PHP-FPM and also relies on an external Node.js API for weather data.

Your task is to write the http block and the relevant parts of a server block for an Nginx configuration that implements a multi-layered caching strategy based on the following requirements:

  1. FastCGI Cache Setup:

    • Define a cache path at /var/nginx/cache/php for a cache zone named php_cache.
    • The zone should have a memory size of 10m.
    • Configure it with levels=1:2, an inactive timeout of 60 minutes, and a maximum disk size of 1GB.
  2. Proxy Cache Setup:

    • Define a cache path at /var/nginx/cache/api for a cache zone named api_cache.
    • The zone should have a memory size of 5m.
    • Configure it with levels=1:2, an inactive timeout of 30 minutes, and a maximum disk size of 250MB.
  3. Server Configuration:

    • PHP Location Block (~ \.php$):
      • Apply the php_cache.
      • Set the default cache validity for successful responses (200 status code) to 30 minutes.
      • Implement a cache bypass for logged-in users. The bypass should be triggered if the cookie variable $cookie_wordpress_logged_in is not empty.
    • API Location Block (/api/weather):
      • This location proxies requests to a backend server.
      • Apply the api_cache.
      • Cache successful responses for 10 minutes.
    • Homepage Microcaching (location = /):
      • This location also handles PHP files.
      • Apply the php_cache.
      • Override the default cache validity. Set it to cache successful responses for only 2 seconds to handle traffic spikes.
    • Debugging: Add the X-Cache-Status header to all responses served from this server to help debug cache hits and misses.

Expected result

Your final configuration should be a valid Nginx snippet that correctly implements all the specified caching rules.

  • The http block must contain two directives: fastcgi_cache_path and proxy_cache_path.
    • fastcgi_cache_path is configured for /var/nginx/cache/php, with levels=1:2, keys_zone=php_cache:10m, inactive=60m, and max_size=1g.
    • proxy_cache_path is configured for /var/nginx/cache/api, with levels=1:2, keys_zone=api_cache:5m, inactive=30m, and max_size=250m.
  • Inside the server block:
    • The add_header X-Cache-Status $upstream_cache_status; directive must be present.
    • The location = / block must contain fastcgi_cache php_cache; and fastcgi_cache_valid 200 2s;.
    • The location /api/weather block must contain proxy_cache api_cache; and proxy_cache_valid 200 10m;.
    • The location ~ \.php$ block must contain fastcgi_cache php_cache;, fastcgi_cache_bypass $cookie_wordpress_logged_in;, and fastcgi_cache_valid 200 30m;.
nginx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.