Skip to content

Lesson 2 of 3

Caching at every layer

2 min

The fastest request is the one your server never has to compute. Caching works at several layers, each with a different job.

Browser cache

Static files with versioned names can be cached for a year:

location ~* \.(css|js|woff2|png|jpg|webp|avif)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
}

CDN

A CDN keeps copies of your files close to visitors. For a site serving the Gulf and Egypt from one region, it removes most of the distance.

Page cache

For pages that look the same to every visitor (home page, blog posts), store the finished HTML. WordPress cache plugins or Nginx's fastcgi_cache can serve thousands of requests per second this way.

Never page-cache anything personal: carts, account pages, checkout.

Object cache

Redis keeps the results of expensive database queries in memory. It helps most on dynamic pages that can't be page-cached.

Opcode cache

Make sure OPcache is enabled for PHP. It's free speed: compiled code stays in memory instead of being re-parsed on every request.

The hard part of caching is invalidation. Decide up front how each cache is cleared when content changes.