Skip to content

Multi-layer caching architecture — edge, page, object, database

How four cache tiers — CDN/edge, full-page, application object cache, database query cache — fit together. Request lifecycle, invalidation strategies, operational hazards.

Caching is hard not because the code is hard — every framework ships a cache helper — but because invalidation is hard. You can wire four layers of cache in front of an application in an afternoon. Keeping them coherent when an editor saves a draft, when a user logs in on a phone they have never used before, when one node in your cluster is purging and the other is not — that is the work, and it is the work nobody volunteers for. This article is the conceptual map of those four tiers: what each one does, where it sits in the request path, how it gets invalidated, and where the hazards live.

The right number of cache layers depends on traffic, content shape, and how much staleness the business can tolerate. A small marketing site might be fine with one — Cloudflare in front of nginx serving static HTML. A WordPress store at scale runs four or five layers, each catching a different miss pattern. The architecture below is what we operate on real production environments. It is not a checklist of layers you must add; it is the menu.

The four cache tiers

Every request that reaches an application traverses some subset of these layers. The interesting design choice is where you cut the request short.

  1. Edge / CDN cache. Points of presence around the world. Caches what is identical for many users — static assets, anonymous HTML, public API responses. Latency: 5-30 ms to the user.
  2. Reverse proxy / page cache. A cache that sits between the CDN and the application, inside the origin. nginx fastcgi_cache, Varnish, LiteSpeed LSCache. Caches full rendered HTML, with finer-grained invalidation than the CDN can offer. Latency: 1-5 ms once warm.
  3. Application object cache. Inside the application process or shared across instances. Redis, Memcached, in-process LRU. Caches structured data — query results, session blobs, computed values. Latency: 0.5-2 ms.
  4. Database query / result cache. Inside the database engine. PostgreSQL’s shared_buffers, InnoDB buffer pool, optional ProxySQL query cache. Caches hot pages and result sets. Latency: sub-millisecond when warm, single-digit milliseconds when cold but still in memory.

Each tier above the database absorbs work the layer below would otherwise do. The cumulative effect at warm equilibrium: the database sees maybe 1 % of the traffic the CDN sees, and even that 1 % is mostly index reads against pages already in the buffer pool.

Request lifecycle

Tier 1: Edge / CDN cache

The CDN is the cache closest to the user, geographically and by latency. It is also the cheapest layer to operate, because the points of presence are run by somebody else and you pay per gigabyte of egress. The vendors are interchangeable in concept: Cloudflare, Fastly, AWS CloudFront, Vercel Edge, Akamai. The mechanics differ — Cloudflare has cache rules and tiered cache, Fastly exposes VCL, CloudFront has behaviors — but the request flow is the same.

What goes here. Anything identical for many users. Static assets (CSS, JS, fonts, images) by default. Anonymous HTML for content sites — /, /blog/, /products/widget-x/ are the same for everyone not logged in. JSON API responses that depend only on URL and method. The win is the round-trip elimination: a user 8000 km from the origin sees a 200 ms TTFB collapse to 20 ms when the response comes from the local POP instead of crossing oceans.

TTL strategy. Three knobs matter. The max-age directive controls how long the browser caches. The s-maxage directive controls how long shared caches (the CDN) cache, often longer than max-age. stale-while-revalidate=60 lets the CDN serve a stale response for up to 60 seconds while refreshing in the background — invisible to the user, free latency win. stale-if-error=86400 lets the CDN serve stale content for a full day if origin is down. The right TTL is “as long as you can tolerate the staleness, minus the time it takes to manually purge.”

Cache key design. The default cache key is host + path. Vary on query strings selectively — ?page=2 matters, ?utm_source=twitter does not. Use the Vary response header sparingly — Vary: User-Agent is a hit-rate disaster because every user agent string is unique. Vary: Accept-Encoding is fine and expected. Cookies are the trap: any cookie in the request can be configured to fragment the cache key, and most CDNs will refuse to cache responses that have a Set-Cookie header by default. Strip cookies you do not need at the edge.

Purging. Cloudflare exposes purge by URL (any plan), purge by tag (Enterprise), purge by prefix and hostname (Enterprise), and the nuclear “purge everything” button. Tag-based purging is the discipline that scales — the application emits Cache-Tag: post-9381, category-shoes, and when the editor saves post 9381 the CMS fires one tag purge that clears every cached page tagged with post-9381 regardless of URL. Without tags, you either purge too narrowly (miss related pages) or too broadly (purge the whole zone, watch origin choke on the cold-cache traffic). See Cloudflare cache purge strategies for the operational detail.

Tier 2: Reverse proxy / page cache

When the CDN misses, the request lands at the origin. The reverse proxy in front of the application is the next chance to short-circuit. nginx’s fastcgi_cache and proxy_cache directives, Varnish, LiteSpeed’s LSCache module are the popular options. They cache the full rendered HTML at the origin level, before the request gets to PHP-FPM, Node, or whatever runs the application.

The question is whether you need this tier at all when the CDN is in front of you. Three cases where it pays:

  • The CDN cannot match your purge granularity. Without Enterprise Cloudflare you do not have tag purges. A LiteSpeed cache plugin emits per-post purges via the LSCache API as soon as a WordPress editor saves. The CDN above can be a few seconds behind without consequence; the origin cache is always fresh.
  • Logged-in users bypass the CDN but should still be fast. The CDN passes through requests with session cookies. The page cache at the origin can have a separate “vary on logged-in status” key and serve a different (still cached) variant.
  • Origin compute is the bottleneck. A page cache at origin saves PHP-FPM worker time. On a busy WordPress install, a warm LSCache HIT serves in under 1 ms with no PHP execution; a MISS spawns a PHP worker and may take 500 ms or more.

Granular invalidation is the reason this tier exists. Configure the application to issue a PURGE against the local cache on every write — when a post is saved, when a comment is posted, when an admin updates a setting. The CDN above gets a tag purge fired in parallel. Both layers stay coherent.

Logged-in user bypass is the standard configuration. The cache reads a session cookie; if present, the request bypasses the cache and goes straight to the application. Get this wrong and you serve user A’s account page to user B — a “vary on cookie name only” rule, not “vary on cookie value,” is the discipline.

Tier 3: Application object cache

Below the page cache, inside the application, is the object cache. Redis or Memcached, sometimes a per-process in-memory LRU layered on top. This is the cache that holds the structured fragments the application would otherwise rebuild from the database every request — query results, user sessions, computed configuration, the result of an expensive function call.

Per-request and persistent objects. Inside a single request, an in-process cache prevents the same query running twice (the “user 42’s profile” lookup that three different functions all need). Across requests, Redis or Memcached holds objects long enough to amortize the cost of computing them. WordPress wp-cache groups, Rails fragment cache, Django low-level cache API — every framework has a wrapper.

Cache stampede protection. A popular cache entry expires. A thousand requests arrive in the next 50 ms. Each one sees the miss, runs the expensive computation, and writes to the cache. The database is hit a thousand times for the same query that should have been one. This is the thundering herd / dogpile problem. The two fixes that work: request coalescing (only one process recomputes; the others wait on a mutex) and probabilistic early expiration (some fraction of reads to an entry close to expiry are treated as misses, so one writer refreshes the entry before everyone else sees the cliff).

Tag-based invalidation. Redis does not support tags natively. Tag invalidation is built on top with two patterns: a Lua script that maintains a tag → set-of-keys map and deletes all keys for a tag on invalidation, or the simpler approach of including a version number in every cache key and bumping the version (lazy invalidation — old keys age out via TTL). The version-bump approach is easier to reason about and what we default to.

Memory pressure and eviction. Redis has a maxmemory-policy. allkeys-lru evicts the least-recently-used key regardless of whether it had a TTL — appropriate for a pure cache instance. volatile-lru only evicts keys with a TTL set, leaving TTL-less keys alone — appropriate when you mix cache and persistent state in the same Redis. noeviction makes writes fail when memory is full — appropriate for Redis as a queue store, never for a cache.

Tier 4: Database query / result cache

Below the application is the database, and the database has its own caches. The naming is inconsistent across vendors.

PostgreSQL shared_buffers is a block cache. Postgres reads disk pages (8 KB blocks) into shared memory; subsequent reads of the same page hit memory. Set to roughly 25 % of system RAM as a starting point. Past 40 % the law of diminishing returns kicks in because the OS page cache also caches the same data. Postgres also runs a planner cache for prepared statements and a small per-backend cache of catalog lookups.

InnoDB buffer pool is MySQL’s equivalent. Same idea: a pool of pages in memory, configured via innodb_buffer_pool_size. The recommendation is 50-80 % of system RAM on dedicated database servers. The buffer pool covers index pages, data pages, and the undo and insert buffers. A small buffer pool on a large dataset means constant disk reads; a properly sized pool keeps the working set in memory.

MySQL query cache is deprecated. The legacy MySQL query cache (the one keyed by the literal SQL text) is removed in MySQL 8.0 and was widely disabled before that. It serializes writes by acquiring a global lock to invalidate cached entries, which on a write-heavy workload destroys throughput. If you find a project enabling it, you have found a project running MySQL 5.7 or earlier. The right cache layer for read-heavy MySQL is ProxySQL or an external cache in Tier 3.

ProxySQL sits between the application and MySQL. It supports a result-set cache: a SELECT statement is hashed, the result is cached for a configurable TTL, and subsequent identical SELECTs return from ProxySQL without touching the database. Useful for read-heavy workloads where the same queries repeat. Invalidation is by TTL only — ProxySQL does not see writes, so a stale read window equal to the TTL is the cost. Configure TTLs in milliseconds, not minutes.

Cross-tier concerns

The four tiers do not exist in isolation. The seams between them are where most of the operational pain lives.

Cache key design. The temptation is to vary on everything that might matter — user ID, locale, currency, theme, A/B test variant, device class. Every dimension multiplies the cache key cardinality. Five users times three locales times two currencies times three themes = 90 distinct cache entries for what was originally one page. The hit rate collapses. The discipline is to vary only on dimensions that materially change the response, push variation as far down the stack as possible (render the page anonymously and have client-side JS personalize it), and use Vary headers only when the response actually differs.

Invalidation patterns. Four broad patterns. Write-through: on every database write, the application updates the cache immediately. Most coherent, most write-amplification. Write-behind: writes go to the cache; the cache flushes to the database asynchronously. Fastest writes, weakest durability. Lazy / TTL-based: cache entries expire naturally; reads miss after expiry and refresh. Simplest. Explicit purge: on certain events (publish, save, admin change), the application fires explicit purges to every affected cache. Most surgical. Real systems mix all four — TTL on the CDN, explicit purge on the page cache, write-through on the object cache, lazy expiration on derived computed values.

The dogpile / thundering herd. When a hot entry expires, every concurrent request sees the miss simultaneously and races to recompute. The database goes to 100 % CPU for a few seconds. Mitigations: request coalescing inside the application (one mutex per cache key, only one refresh in flight), probabilistic early expiration, locked recomputation with stale-while-revalidate so other requests get the stale value during the refresh. See cache stampede mitigation for the patterns.

Cache poisoning. Web Cache Deception is the canonical attack: /account/profile/foo.css is treated as a static asset by a naive cache rule, the application returns the logged-in profile HTML, the CDN caches it under the path containing .css, and the next user requesting that URL gets the first user’s profile. Header smuggling — sending an unkeyed header that origin uses to differentiate responses — produces the same effect. The defense is strict cache-key composition (only key on what is rendered into the response), normalization (strip unknown query params), and content-type validation (do not cache a text/html response under a .css extension).

Stale content tolerance. The business question that should drive TTLs: what is the actual cost of 60 seconds of stale content? On a marketing page, zero — nobody notices. On a news homepage during a breaking story, large — the front page lagging by a minute is a meaningful product failure. On a stock ticker, fatal — even one second is wrong data. Set TTLs accordingly. The default of “as long as we can get away with” is usually correct, but be honest about what “get away with” means for each surface.

When each tier is overkill

A small site does not need four cache layers. A solo founder’s portfolio gets twelve visitors a day; the database is bored. Adding Redis adds a service to monitor, a memory limit to manage, a connection pool to size — all for caching results that are already coming back in 5 ms.

The honest test for each tier: does it have a measurable hit rate above 30 %, and is its absence causing a measurable problem? An object cache with a 10 % hit rate is not paying its operational rent. A page cache in front of an application that responds in 50 ms uncached is solving a problem nobody has. Cache tiers are operational debt; only carry the ones that pay.

The progression that fits most sites: start with the CDN (the cheapest, biggest hit-rate layer). Add an object cache when database load becomes meaningful and the access pattern is read-heavy. Add a page cache at origin only when CDN bypasses (logged-in users, cookie-bearing requests) become a meaningful share of traffic. Database query caching tunes itself via shared_buffers / buffer pool sizing — that one is free.

When Stack Harbor manages this for you

Caching architecture is a deliverable inside Managed Operations — we design the layers, measure the hit rates, write the purge rules, and own the operational runbook. For WordPress at scale, enterprise WordPress operations bundles LiteSpeed Cache, Redis object cache, and Cloudflare cache rules into a single managed stack. For cPanel-hosted WordPress sites, cPanel/WHM Management covers the LSCache layer plus origin tuning. The PaaS-hosted variant lives under Cloud PaaS, where the cache layers are containerized and scale horizontally with the application.

Senior engineers design the cache topology and review the invalidation paths. Day-to-day cache health (hit rates, eviction rates, memory pressure) is monitored automatically; deviations are picked up by the support desk. The phone is reserved for the account manager — for technical work, the ticket queue is the channel that gets engineering attention.

See also