Skip to content

What Is Caching? Cache Types and When to Use Each

A detailed explanation of caching: browser, page, object, opcode and CDN caching — how each type works, when to use it, how to set it up, and how to avoid stale-cache problems — with comparison tables and practical examples.

Performance and speedمنى السالم24 min read
Illustration of stacked cache layers with a fast arrow serving a browser window, representing types of caching
On this page

In this guide we break down each type of cache: how it works, where it is stored, when to use it and when to avoid it, and how to deal with its common problems. This article is part of the performance series and complements the broader guide Speed up your website, which ties all the speed factors together.

What is caching and why do we need it?

At its core, caching is a simple idea: instead of repeating expensive work, store its result somewhere faster and retrieve it. When a visitor requests a page, generating it may require running PHP code, executing database queries, assembling templates and then building the final HTML. That chain can take hundreds of milliseconds or more. If the same result will be shown to thousands of visitors, repeating all of that on every request is wasteful.

Caching solves two fundamental problems:

  • Reducing repeated work (computation): there is no need to rerun the same queries and processing thousands of times for the same result.
  • Reducing response time (latency): fetching a result from fast memory or from a geographically close server is much faster than building it from scratch or fetching it from a distant server.

The practical result is twofold: the visitor gets a faster page, and the server carries less load, so it can serve more visitors with the same resources. This compound effect is what makes caching the single most important performance lever for almost any site.

The principle of locality

Caching works because data access tends to repeat: the same content is requested over and over (temporal locality), and related data is requested together (spatial locality). The more often the same resource is requested, the more valuable it is to cache. That is why caching is very effective for relatively static public content (articles, informational pages, images) and less useful — sometimes even harmful — for personalized content that changes for each user.

How does caching work conceptually?

Every cache system revolves around a single life cycle:

  1. A request arrives: the system first looks in the cache for a stored result for this key (the cache key).
  2. Hit or miss: if a valid result is found, that is a "hit" and it is returned immediately. If not, that is a "miss," which requires generating the result from the source.
  3. Storage: on a miss, the result is computed and stored in the cache with a key and a validity period (TTL).
  4. Invalidation: when the source changes, the stored copy must be updated or deleted so it does not go stale.

The three most important concepts that control the behavior of any cache:

ConceptDescriptionWhy it matters
Cache keyThe identifier an item is stored and retrieved by (usually the URL + parameters)A wrong key mixes up users' content or prevents hits
Time to live (TTL)How long the copy remains valid before it is considered expiredToo short weakens the benefit; too long keeps outdated content
Invalidation (purge)When and how the old copy is deleted when the source changesThe hardest problem, and the source of most cache failures
Cache layers: where is the request caught?BrowserBrowserEdge / CDNEdgePage cachePageObject cacheObjectDatabaseOriginA hit at any layer ⟸ instant response without the full trip
Cache layers in order: the earlier the layer where the request hits (far right), the faster the response returns without reaching the database.

The hit rate is the most important measure of any cache's health: the share of requests served from the cache instead of the source. A cache with a 95% hit rate means only 5% of requests reached the origin server, which is a huge reduction in load.

What are the main types of caching on the web?

It is easy to confuse the types because they are all called "cache," but they work at different layers and solve different problems. The following table summarizes the big picture before we go into detail:

TypeWhere it runsWhat it storesWhat it reduces
Browser cacheThe visitor's deviceStatic files (CSS/JS/images)Repeat downloads and network time
Page cacheThe origin serverThe page's full HTMLGenerating the entire page
Object cacheServer memory (Redis/Memcached)Query and computation resultsDatabase load
Opcode cacheThe PHP engine on the serverCompiled bytecodeRe-interpreting code
Database cacheThe database engineRepeated results/data pagesDisk reads and querying
CDN / edge cacheGlobally distributed serversFiles and pages close to the visitorDistance to the origin server
DNS cacheThe resolver, browser and operating systemDomain-to-IP lookupsRepeated DNS queries

A single request may pass through several layers: DNS resolves the address, the CDN serves the file from the edge, the HTML comes back from the page cache, and a dynamic fragment is retrieved from the object cache. They all cooperate, and each has its own configuration.

How does browser caching work, and what are its headers?

Browser caching stores static files on the visitor's own device, so the browser doesn't need to download them again on every visit. It is the cheapest type of cache and the closest to the user — the file is read from the local disk instead of over the network entirely.

It is controlled through HTTP headers that the server sends with the response. The most important are:

http
Cache-Control: public, max-age=31536000, immutable
ETag: "a1b2c3d4"
Expires: Wed, 11 Jun 2027 10:00:00 GMT
Last-Modified: Tue, 10 Jun 2026 08:30:00 GMT

The key headers explained:

HeaderFunctionPractical note
Cache-ControlThe main modern header for controlling cachingOverrides Expires and is always preferred
max-ageValidity period in seconds31536000 = a full year for static assets
public / privateAre intermediaries (CDNs) allowed to store it?Use private for personalized content
no-cacheMust revalidate with the server before useDoesn't mean "don't store" but "always revalidate"
no-storeStorage is completely forbiddenFor sensitive data only
immutableThe file will never change during the periodRemoves revalidation on refresh
ETagA content fingerprint for conditional validationThe server responds 304 if it hasn't changed
ExpiresAn absolute expiry date (legacy)A fallback for old browsers

Conditional validation and 304

Even after max-age expires, the browser doesn't always have to download the whole file again. The browser sends If-None-Match with the stored ETag value, and if the content hasn't changed, the server responds with 304 Not Modified and no response body. This saves bandwidth while guaranteeing freshness. Still, conditional validation is a full network round trip, so static assets are best given a long lifetime + immutable to avoid even that trip.

What is the difference between page caching and object caching?

These two types run on the origin server and have the biggest impact in content management systems such as WordPress. They are often confused, even though they are fundamentally different.

Page cache

The page cache stores the complete final HTML output after it is generated. On the first request for a page, the server runs all the code and queries and produces HTML, then saves that output. Subsequent requests are served straight from the saved copy without running almost any code. This has the strongest effect: it can take response time from 800 milliseconds to under roughly 50.

Its drawback is that it is "all or nothing": if a page contains even one personalized part (the user's name, the shopping cart), it cannot be stored as is for everyone. The solution is to exclude these pages, or to use fragmentation techniques such as ESI, or to inject the personalized parts via JavaScript after the page loads.

Object cache

The object cache stores expensive partial results in fast memory such as Redis or Memcached: the result of a complex query, settings, a list of categories, API results. Instead of going to the database every time, the result is retrieved from memory by key. This is useful for dynamic pages that cannot be cached as a full page but repeat the same internal queries.

DimensionPage cacheObject cache
What is storedThe page's full HTMLPartial query/computation results
LocationServer disk/memoryRedis / Memcached
Best forStatic public pagesDynamic and personalized pages
Speed impactThe largest (bypasses PHP entirely)Moderate (relieves the database)
Handling personalizationPoor (needs exclusions)Excellent (stores only the parts)

The practical rule: use the page cache for public content and the object cache to speed up the dynamic parts that cannot be cached as a page. They work together; neither replaces the other. For a deeper look at applying these two types to WordPress specifically, see Speed up WordPress.

How does opcode caching (OPcache) work?

PHP code is written as text, and it must be parsed and compiled into bytecode before it runs on every request. OPcache stores the compiled bytecode in shared memory, so the PHP engine skips the parsing and compilation step on subsequent requests and jumps straight to execution.

Its effect is large and silent: it doesn't change the page output but speeds up generating it, often cutting PHP processing time noticeably without any change to the code. It is fundamentally different from the previous types because it stores compiled code, not data or output.

SettingTypical valueFunction
opcache.enable1Enables OPcache
opcache.memory_consumption128–256 (MB)Amount of memory allocated to bytecode
opcache.max_accelerated_files10000+Number of files that can be cached
opcache.validate_timestamps1 development / 0 productionDoes it check whether files changed?
opcache.revalidate_freq2–60 (seconds)How often files are rechecked

In production, turning off validate_timestamps gives maximum performance, but it means any code change won't be picked up until the OPcache memory is cleared manually or PHP is restarted — a common point of failure after a deployment.

OPcache is a server-level setting, which is why you may not control it on shared hosting, while you have full control over it on a VPS or managed hosting. Serious hosting providers enable it by default with suitable production settings. For the difference in server control between these environments, see Shared vs. VPS vs. managed hosting.

How does a CDN cache serve content from the edge?

A content delivery network (CDN) distributes copies of your files — and sometimes full HTML pages — to servers spread around the world called points of presence (PoPs). When a visitor requests a resource, it is served from the nearest geographic point instead of the distant origin server, cutting the round-trip time from hundreds of milliseconds to tens.

Edge caching works on the same principles as any cache, but with a geographic dimension: on a miss at an edge node, the node fetches the resource from the origin once, stores it, and then serves it locally to every visitor in that region. For static assets this is an almost free performance gain; for HTML it requires careful configuration to avoid caching personalized content.

FeatureBenefit
Geographic distributionLower latency for distant visitors
Origin offloadThe origin server handles far fewer requests
Absorbing traffic peaksHandles waves of visitors without straining the origin
Built-in protectionAbsorbs part of overload attacks

A CDN complements server-side caching and does not replace it: the page cache speeds up content generation at the origin, and the CDN speeds up its delivery to the visitor. You will find a detailed explanation of how a CDN works in What is a CDN.

Cache headers and CDNs

A CDN mostly respects the same Cache-Control headers, with one important distinction: s-maxage sets the cache lifetime for shared intermediaries (such as a CDN) separately from max-age for the browser:

http
Cache-Control: public, max-age=0, s-maxage=3600

This example means: don't rely on the browser cache (max-age=0), but allow the CDN to cache the page for an hour (s-maxage=3600). It is a useful pattern for HTML pages you want to serve from the edge while keeping the ability to invalidate them centrally when content is updated.

How do you choose a cache TTL for each asset type?

Choosing a TTL is a balance between freshness and performance: a longer lifetime means better performance and less load, but it raises the chance of showing outdated content. The golden rule: tie the lifetime to how often the content changes.

Asset typeSuggested TTLStrategy
CSS / JS (with hash)One year (max-age=31536000, immutable)Bust the cache by changing the file name
Static images and fontsA month – a yearLong, because they rarely change
HTML for an article pageMinutes – hoursShort + invalidation on update
Frequently changing home pageMinutesShort, because it updates often
Public API responsesSeconds – minutesDepends on how time-sensitive the data is
Personalized content/cartDon't cache (no-store/private)Differs for every user

Cache busting with a hash

The secret to giving static assets a full-year lifetime without fear of stale content is embedding a fingerprint (hash) in the file name: app.4f8a2c.js. When the file changes, the hash changes and the name becomes completely new (app.9b1e7d.js), so the browser treats it as a different resource and downloads it immediately. The old copy stays in the cache, but nobody requests it. This way you combine the longest possible cache with an instant update when something changes. Modern build tools generate these fingerprints automatically.

This pattern doesn't apply to the HTML itself (the page URL is fixed and carries no hash), which is why the HTML lifetime stays short and relies on explicit invalidation when content is updated.

Why is cache invalidation one of the hardest problems?

A famous computer science saying holds that "the two hardest problems are naming things and cache invalidation." The reason is that invalidation requires knowing exactly when a stored copy became outdated, across multiple layers, without over-invalidating (which wastes the benefit) or under-invalidating (which keeps stale content).

The main invalidation methods:

MethodHow it worksWhen to use it
TTL expiryThe copy expires automatically after a set periodFor content expected to change periodically
Explicit invalidation (purge)Deleting a specific key as soon as it changesWhen editing/publishing content
Tag-based invalidationDeleting everything that carries a given tagTo invalidate a related group in one go
Full invalidation (flush)Emptying the entire cacheA last resort; causes a wave of misses

The best practice is event-driven invalidation: when you publish an article, invalidate only the article page and its related pages (the home page, the category page, the RSS feed), not the whole cache. Frequent full invalidation keeps emptying the cache, so you lose its benefit and expose the server to load surges (a cache stampede) as everything is rebuilt at once.

Event-driven invalidation (selective purge)Event: article editedArticle pagePurged and refreshedHome pagePurged and refreshedCategory pagePurged and refreshedThe other cached pages stay as they are — no full rebuild
Event-driven invalidation: a content update invalidates only its related pages (selectively) and leaves the rest of the cache intact.

When should you not use caching?

Caching is a powerful tool, but it isn't always appropriate. The rule: don't cache what differs for each user or what must be real-time.

Examples of content that shouldn't be cached as a full page:

  • Dashboards and accounts: each user sees their own data.
  • The shopping cart and checkout page: they change constantly and are sensitive.
  • Pages that require login: a cached copy can leak one user's data to another — a real security risk.
  • Search results and personal filters: endless combinations and a low hit rate.
  • Financial data or real-time stock levels: freshness matters more than performance.

For personalized content, the solution isn't to disable caching but to choose the right layer: use the object cache for expensive shared parts, inject the personalized parts after load, and set Cache-Control: private or no-store on sensitive responses so no shared intermediary stores them.

How does caching differ across hosting environments?

How much control you have over caching depends heavily on the type of hosting, because some layers need server-level permissions that aren't available in every environment.

EnvironmentBrowser cachePage cacheObject cacheOPcache / server level
Shared hostingAvailable (headers)Usually via a pluginLimited/sometimes unavailableManaged by the provider, little control
VPSFull controlFull controlRedis/Memcached, installed by youFull control over settings
Managed hostingPreconfiguredBuilt in and optimizedUsually enabled (Redis)Optimized by the provider
LiteSpeed / advanced serverBuilt inFast server-level cachingIntegratedOptimized by default

On shared hosting, you usually rely on caching plugins because server permissions are limited, and object caching may not be available. On a VPS you control everything, but the setup is your responsibility. Managed hosting and advanced servers such as LiteSpeed offer server-level caching that is faster than plugin-based caching, because it runs before PHP even loads.

The key point: server-level caching (LiteSpeed Cache, Nginx FastCGI Cache) is usually faster and more efficient than caching inside the application, because it intercepts the request early. Whether this layer is available depends on the hosting environment you choose.

Which tools and plugins suit each environment?

Environment / platformCommon caching toolType it covers
WordPress (general)WP Super Cache, W3 Total CachePage + browser + object cache
WordPress + LiteSpeedLiteSpeed CacheServer + page + object cache
Object cacheRedis Object Cache, MemcachedObject cache
NginxFastCGI Cache / proxy_cacheServer-level page cache
Custom applicationRedis / VarnishObject / reverse-proxy page cache
CDN layerCloudflare, Fastly, etc.Edge cache

Expert tip: never combine more than one page caching plugin. Running two plugins that manage the page cache at the same time causes conflicts, corrupted files and unpredictable behavior. Pick one comprehensive tool per layer, and keep the object cache (Redis) separate from the page cache, with no conflict.

Common mistakes

These mistakes come up again and again; they strip caching of its value or cause failures:

  • A long TTL on HTML with no invalidation: content stays stale for days. Keep HTML short-lived with invalidation on update.
  • A short TTL on static assets: wasteful, since files are downloaded again for no reason. Use one year + a hash for static assets.
  • Caching logged-in users' pages: risks leaking data between users. Exclude these pages explicitly.
  • no-cache instead of no-store: no-cache means "revalidate," not "don't store"; for sensitive data, use no-store.
  • Forgetting hash-based cache busting: CSS/JS updates don't reach visitors. Use fingerprints in file names.
  • Running two page caching plugins: conflicts and corrupted files. Only one tool per layer.
  • Not clearing OPcache after a deployment: the new code doesn't run. Revalidate or clear OPcache on deploy.
  • A wrong or missing Vary: different versions get mixed up (such as compressed and uncompressed). Set Vary precisely.

Cache problems and their fixes

When you run into strange behavior, this diagnostic table links the symptom to the cause and the fix:

ProblemLikely causeFix
Stale cacheLong TTL or invalidation didn't happenInvalidate the copy explicitly or shorten the TTL
Content doesn't update after editingPage/CDN cache wasn't invalidatedClear the page cache and purge the CDN
Design changes don't appearBrowser cache holding old CSS/JSUse hashes in file names
One user's page shown to another userA personalized page cached by mistakeExclude login pages, set private
New code doesn't work after deploymentOPcache holds the old bytecodeClear OPcache / restart PHP-FPM
Conflict after installing a caching pluginTwo page caching plugins at onceKeep only one and remove the other
Periodic waves of slownessMass cache expiry (stampede)Use staggered invalidation and rebuild locks

Stale content

The most common complaint: "I edited the content, but visitors still see the old version." Trace the layers starting from the one closest to the visitor: clear the browser cache (or try a private window), clear the page cache on the server, then purge the CDN. Usually one of the layers wasn't invalidated. The root-cause fix is to tie publishing to automatic invalidation of every affected layer.

Caching logged-in users' pages

If a user sees another user's data, the cause is usually a personalized page cached as a public copy. Make sure your caching plugin/layer excludes pages that carry a login cookie, and that personalized responses carry Cache-Control: private. This isn't a performance problem but a privacy hole that must be fixed immediately.

Two conflicting caching plugins

Installing two page caching plugins at once (such as running a general caching plugin on top of LiteSpeed's server-level cache) causes duplication and conflicts. The rule: only one page cache layer. If your server offers its own server-level cache, use the caching plugin that is compatible with it and disable any other page cache, while keeping the object cache (Redis) active separately.

Conclusion

Caching isn't a single switch but a system of cooperating layers: the browser cache brings files closer to the visitor, the page cache skips HTML generation, the object cache relieves the database, OPcache speeds up code execution, and the CDN brings content geographically closer. Each layer solves a specific problem, and the right setup combines them without conflict.

Start with the high-impact basics: correct cache headers for static assets (one year + a hash), a page cache for public content, and a CDN in front of your site. Then add object caching and server-level OPcache if your environment allows them. And remember that the hardest part is always invalidation: tie it to events, invalidate precisely rather than wholesale, and exclude personalized content. That way you get lasting speed without stale-content surprises. All of this is part of a broader picture you will find in the guide Speed up your website.

Frequently asked questions

What is the difference between page caching and browser caching? Page caching runs on the server and stores the final HTML so it can be served to every visitor without being regenerated. Browser caching runs on the visitor's device and stores static files (CSS/JS/images) so they are not downloaded again on later visits. The first reduces the server's workload; the second reduces network traffic for that same visitor.

Does a CDN replace server-side caching? No, they complement each other. Server-side caching (page/object) speeds up content generation at the origin, while a CDN speeds up delivery to the visitor from the nearest geographic point. The best performance comes from running both together: content generated quickly at the origin and distributed quickly from the edge.

What is a good cache hit rate? There is no absolute value, but in general, the closer the hit rate gets to 90% or higher, the better the cache is working for static assets and public content. A low rate may mean the TTL is too short, personalized content is being cached to no benefit, or cache keys are fragmented more than necessary.

Why don't my changes show up even though I saved them? Usually because one of the cache layers was not invalidated after the update. Trace the layers starting from the nearest: the browser cache, then the page cache on the server, then the CDN. Try a private browsing window to rule out the browser cache, then clear the page cache and purge the CDN.

Can pages that require login be cached? Not as a full public page, because that could leak one user's data to another. Exclude these pages from the page cache, set Cache-Control: private, and use object caching only for the expensive shared parts. Personalized parts are injected after load or fetched dynamically.

What is the difference between no-cache and no-store? no-cache does not mean "don't store"; it means the browser must revalidate with the server before using the stored copy. no-store prevents storage entirely and is used for sensitive data that must not be saved anywhere.

How long should images, CSS and JS files be cached? Static assets that carry a fingerprint (hash) in their file name can be cached for a full year with immutable, because any change produces a new name that busts the cache automatically. HTML, on the other hand, stays short-lived (minutes to hours) and relies on explicit invalidation when content is updated.

Do I need object caching (Redis) for a small site? Not always. Small public sites benefit more from page caching, which skips processing entirely. Object caching becomes important for dynamic sites with expensive repeated queries, or for pages that cannot be cached as a full page. Start with page caching and add Redis when you need it.

Does running two caching plugins improve performance? No, it usually hurts it. Two plugins managing the page cache at the same time conflict with each other, producing corrupted files and unpredictable behavior. Use a single comprehensive page caching tool; object caching (Redis) can run alongside it separately without conflict.

Sources

Frequently asked questions

What is the difference between page caching and browser caching?

Page caching runs on the server and stores the final HTML so it can be served to every visitor without being regenerated. Browser caching runs on the visitor's device and stores static files (CSS/JS/images) so they are not downloaded again on later visits. The first reduces the server's workload; the second reduces network traffic for that same visitor.

Does a CDN replace server-side caching?

No, they complement each other. Server-side caching (page/object) speeds up content generation at the origin, while a CDN speeds up delivery to the visitor from the nearest geographic point. The best performance comes from running both together: content generated quickly at the origin and distributed quickly from the edge.

What is a good cache hit rate?

There is no absolute value, but in general, the closer the hit rate gets to 90% or higher, the better the cache is working for static assets and public content. A low rate may mean the TTL is too short, personalized content is being cached to no benefit, or cache keys are fragmented more than necessary.

Why don't my changes show up even though I saved them?

Usually because one of the cache layers was not invalidated after the update. Trace the layers starting from the nearest: the browser cache, then the page cache on the server, then the CDN. Try a private browsing window to rule out the browser cache, then clear the page cache and purge the CDN.

Can pages that require login be cached?

Not as a full public page, because that could leak one user's data to another. Exclude these pages from the page cache, set Cache-Control: private, and use object caching only for the expensive shared parts. Personalized parts are injected after load or fetched dynamically.

What is the difference between no-cache and no-store?

no-cache does not mean "don't store"; it means the browser must revalidate with the server before using the stored copy. no-store prevents storage entirely and is used for sensitive data that must not be saved anywhere.

How long should images, CSS and JS files be cached?

Static assets that carry a fingerprint (hash) in their file name can be cached for a full year with immutable, because any change produces a new name that busts the cache automatically. HTML, on the other hand, stays short-lived (minutes to hours) and relies on explicit invalidation when content is updated.

Do I need object caching (Redis) for a small site?

Not always. Small public sites benefit more from page caching, which skips processing entirely. Object caching becomes important for dynamic sites with expensive repeated queries, or for pages that cannot be cached as a full page. Start with page caching and add Redis when you need it.

Does running two caching plugins improve performance?

No, it usually hurts it. Two plugins managing the page cache at the same time conflict with each other, producing corrupted files and unpredictable behavior. Use a single comprehensive page caching tool; object caching (Redis) can run alongside it separately without conflict.