Custom PHP

PHP Caching Strategies That Hold Up in Production

PHP caching strategies store generated data so repeated requests avoid expensive work: full-page caches serve ready HTML, fragment caches save template parts, object caches keep database results in Redis or Memcached, and HTTP caching lets browsers and proxies reuse responses. In my builds I pair each layer with an explicit invalidation rule, because a stale cache is worse than no cache.

By Saif Al Jahanwebdev-saif.com

The four caching layers and what each one stores

Developers often treat caching as one switch. It is four distinct layers, and each one stores a different representation of your data. Full-page caching stores the finished HTML response for a URL. Fragment caching stores a rendered widget, sidebar or template partial. Object caching stores the result of a database query or API call in memory. HTTP caching stores the response at the browser, CDN or reverse proxy. I map every performance problem to one of these layers before changing code, because caching the wrong layer hides symptoms without removing the expensive work. Each layer also needs its own invalidation rule, and the rules get stricter as cached content moves closer to the user.

  • Page cache: complete HTML for one URL, served without booting PHP
  • Fragment cache: a single template partial, menu or product block
  • Object cache: query rows, API payloads and computed values in RAM
  • HTTP cache: response headers consumed by browsers, CDNs and proxies

Full-page caching: serve HTML without running PHP

Full-page caching is the biggest single win for anonymous traffic. The first request renders the page and writes the output to disk or to a fast key-value store; later requests skip template rendering and database queries entirely. In plain PHP I capture output with ob_start() and write the buffer to a versioned file key, checking filemtime() against a TTL before serving it. In WordPress I prefer a server-level page cache such as Nginx fastcgi_cache or a CDN edge over a plugin, because it responds before PHP starts. The hard part is not storing the page, it is knowing when to delete it: published content, comment changes and cart state must all trigger a targeted purge.

  • Cache only anonymous, non-personalised responses
  • Key by URL path, query string and relevant cookies or headers
  • Set a TTL, but purge on publish and edit events
  • Bypass the cache for checkout, cart and logged-in sessions

Fragment caching for the parts that move

Sometimes most of a page is stable and one block changes often. Recaching the whole page on every update is wasteful; fragment caching lets you keep the stable HTML and refresh only the moving piece. I wrap the expensive partial in an output buffer, build a key from its arguments, and store the result with a short TTL. In WordPress the transients API or wp_cache_set() with a named group does the same job. Fragments are also useful for third-party API calls that are slow but tolerant of slightly old data. The key discipline is naming: a fragment key must include every input that can change its output, or you will serve the menu from yesterday with current prices.

  • Cache the partial, not the whole response, when one block changes often
  • Include every variable in the cache key: IDs, locale, currency, user role
  • Use short TTLs for data that changes without a triggering hook
  • Keep fragments small enough that regenerating one is cheap

Object caching with Redis or Memcached

Object caching keeps the results of expensive operations in memory so repeated PHP requests do not recompute them. In plain PHP that means Predis or the phpredis extension with keys like user:42:profile and an explicit expiry. In WordPress, a persistent object cache drop-in named object-cache.php lets wp_cache_get(), wp_cache_set() and wp_cache_delete() survive between requests instead of resetting on every page load. This is the layer that helps most with repeated queries, term lookups and remote API responses. I avoid storing whole objects with embedded state; cache flat, serialisable arrays and read them through a small wrapper that owns the key format and the TTL, so invalidation stays in one place.

  • Use wp_cache_get() and wp_cache_set() with a dedicated group per data type
  • Store flat arrays, not objects with behaviour or open resources
  • Give every key an expiry, even if it is generous
  • Centralise key building so one delete call can purge a family of keys

HTTP caching headers and the reverse proxy

HTTP caching pushes reuse outside PHP entirely. A response with Cache-Control: public, max-age=3600 can be served by the browser, a CDN edge or a Varnish instance without touching your server. I use s-maxage for shared caches when the browser should hold a shorter value, and ETag or Last-Modified so a conditional request returns 304 Not Modified when nothing changed. The Vary header matters as much as the TTL: Vary: Accept-Encoding is standard, while Vary: Cookie is often the reason a page cache appears broken. In PHP I set headers early with header() and make sure no session_start() or prior output has disabled caching. This layer most directly improves TTFB and the Core Web Vitals that depend on it.

  • Cache-Control: public, max-age for public pages and static assets
  • s-maxage to give proxies a longer lifetime than browsers
  • ETag or Last-Modified for 304 revalidation
  • Vary on the request headers that actually change the response

Invalidation rules that do not serve stale content

Every cached value is a bet that the source will not change before the TTL expires. Invalidation is how you close that bet. I use three rules: time-based expiry as a safety net, event-based purges on saves and deletes, and versioned keys when content changes in ways no hook observes. In WordPress I hook save_post, updated_term_meta and WooCommerce stock-change actions to wp_cache_delete() the specific keys, never wp_cache_flush(), which empties everything and causes a thundering herd on the next request. For tag-based purging I keep a small map from tag to key list so one product update removes exactly its fragments. If a purge cannot be guaranteed, I shorten the TTL rather than pretend the cache is correct.

  • TTL is a backstop, not an invalidation strategy by itself
  • Purge the exact keys on save, delete and status-change hooks
  • Use versioned keys, such as post ID plus modified timestamp, for silent changes
  • Never call wp_cache_flush() on a busy site

Stampedes, measurement and a safe rollout

Caching introduces failure modes that do not exist without it. A cache stampede happens when a popular key expires and dozens of requests all regenerate it at once; I avoid that with a short mutex lock, soft expiry that serves slightly stale data while one request refreshes, or a jittered TTL so keys do not expire together. I also verify a cache is working rather than assuming it: response headers, a hit or miss counter, and a before and after comparison of TTFB on a throttled connection tell you more than a hunch. I roll out one layer at a time, measure p95 response time, and keep a documented kill switch. On custom PHP projects for webdev-saif.com I treat invalidation as part of the build, not an afterthought someone debugs at 2am.

Frequently asked questions

What are the four main PHP caching strategies?

The four main PHP caching strategies are full-page caching, which stores the finished HTML; fragment caching, which stores individual template parts; object caching, which keeps query and API results in Redis or Memcached; and HTTP caching, which lets browsers and proxies reuse responses. Each layer needs its own key design and invalidation rule. In practice I start with page caching for anonymous traffic, then add object and fragment caching where one slow block or query still dominates response time.

What is the difference between page caching and object caching?

Page caching stores the final HTML for a whole URL and can serve it without running PHP at all. Object caching stores smaller pieces of data, such as a query result, a term lookup or an API payload, in memory and still runs PHP to assemble the page. Use page caching for anonymous pages that rarely change per visitor, and object caching for repeated work shared across many pages. They solve different problems and work best together.

How do I invalidate a cache when content changes?

Invalidate a cache by deleting the exact keys affected by a change, triggered from the hook that knows about it. In WordPress that means calling wp_cache_delete() on save_post or a WooCommerce stock-change action rather than flushing the whole cache. Pair event purges with a TTL safety net and versioned keys for changes no hook fires. If you cannot guarantee a purge, shorten the TTL instead of shipping stale content.

Should I use Redis or Memcached for object caching?

For most PHP and WordPress builds Redis is the easier choice: it supports richer data structures, optional persistence and key scanning, and it is well supported by persistent object cache drop-ins. Memcached is simpler and very fast for pure key-value string storage under high concurrency. Pick Redis when you need tag-style purges or sorted sets; pick Memcached when you only need straight get and set speed. Either beats having no persistent cache.

Can caching break a WooCommerce store?

Yes, caching cart, checkout and account pages can expose one shopper session to another. I bypass page and HTTP caching for any response that depends on a session or cookie, keep fragment caches keyed by user role or cart ID, and set Cache-Control: private, no-store on checkout routes. Product and category pages are safe to cache aggressively; personalised areas are not. Test with two logged-in sessions before launch.

Written by Saif Al Jahan, webdev-saif.com · Mymensingh, Bangladesh. Last updated .