The user wants a "sitewide caching policy."
This is a broad request that requires specific, actionable rules across several key areas of web caching:
- CDN TTL Heuristics: How long should content live at the edge?
- ETag / Last-Modified: Handling validation.
- Stale-while-revalidate (SWR): Optimizing performance vs. freshness.
- SEO Constraints: ensuring crawlability and indexability aren't harmed.
Target Audience/Context: Likely a web architect, backend engineer, or DevOps engineer looking for a standard blueprint for a dynamic website (e.g., an e-commerce site, a blog, or a SaaS platform).
Key Principles to keep in mind:
- Granularity: A "one-size-fits-all" TTL is bad. I need to segment by content type (Static assets, HTML, API/Data).
- Performance vs. Freshness: The eternal trade-off.
- Cache Hierarchies: Browser -> CDN -> Origin.
- SEO: Specific requirements for Googlebot and social media scrapers.
Drafting the Policy - Section by Section:
1. CDN TTL Heuristics (The "Hold" Times)
- Static Assets (JS, CSS, Images, Fonts): These should be immutable if versioned (e.g.,
app.123.js). If not versioned, long TTL.
- Rule:
Cache-Control: public, max-age=31536000, immutable.
- HTML (The pages): This is the trickiest part. If we cache too long, updates are invisible. If too short, the origin dies under load.
- Standard: Short TTL (0-60s) or "Must-Revalidate".
- Strategy: Use SWR here (more on that later).
- API/JSON: Usually private or short-lived.
- Public data (e.g., product catalog): Minutes to hours.
- Private data (user profile):
private, no-store or private, max-age=0.
2. ETag / Last-Modified (The Validation)
- Why: To save bandwidth. If the content hasn't changed, send a 304.
- ETag: Better for dynamic content or precise changes. Should be a hash of the content.
- Last-Modified: Good enough for files or things with timestamps.
- Policy: Generate strong ETags for HTML/APIs. Use file timestamps for static assets.
3. Stale-while-revalidate (SWR) & Stale-if-error
- The "Magic" Header:
Cache-Control: max-age=10, stale-while-revalidate=59.
- Logic: Serve the old content instantly while refreshing the cache in the background.
- Application: Essential for HTML pages to maintain high TTFB (Time To First Byte) while keeping content reasonably fresh. Also great for API endpoints that are read-heavy.
4. SEO Constraints
- Googlebot: Renders JS but prefers fast HTML. Caching helps Core Web Vitals (CWV).
- Risk: Serving personalized content to the public cache (Leakage). Or serving the "Sign In" page to Googlebot because the cache captured a redirect.
- Vary Header:
Vary: User-Agent (bad for CDN efficiency usually, but necessary sometimes) or Vary: Accept-Encoding.
- Mobile:
Vary: Accept-CH or distinct mobile URLs vs responsive.
- Sitemaps/Robots: Must be fresh.
Structure of the Response:
I will structure this as a formal "Blueprint" or "Design Document."
- Phase 1: Asset Classification (The Strategy): Grouping content types.
- Phase 2: The Header Configuration (The Tactic): Specific
Cache-Control strings.
- Phase 3: Validation & Invalidation: ETags and Purging.
- Phase 4: SEO & Bot Handling: Special rules.
- Phase 5: Summary Table: Quick reference.
Refining the Heuristics:
- Tiers:
- Tier 1: Fingerprinted Statics. (1 year, immutable).
- Tier 2: Unversioned Statics. (Images uploaded by users, etc.). 1 day - 1 month.
- Tier 3: Dynamic HTML (Public). Short TTL + SWR. (e.g., 10s TTL, 1 hour SWR).
- Tier 4: Dynamic HTML (Private). No-store.
SEO Specifics:
- Googlebot acts like a user. If you cache redirect rules (301/302), you can break SEO.
Vary: Cookie is crucial for authenticated sessions so the CDN doesn't serve a "Welcome User" page to a guest (or vice versa, though usually private cache handles this). actually, for CDNs, Vary: Cookie usually effectively disables caching for that URL unless the CDN is cookie-aware. Better strategy: Bypass cache if Cookie exists.
Self-Correction/Review during drafting:
- Correction: Don't just say "Use ETag." Mention how. Weak vs Strong ETags.
- Clarification: Distinguish between Browser Cache (Client) and CDN Cache (Edge). The policy usually dictates how the CDN talks to the Browser, and how the CDN talks to the Origin.
- Constraint Check: The prompt asks for "Sitewide." I need to make sure I cover the edge cases like 404s and 301s. 404s should have a short TTL (what if the page is created?). 301s should have a long TTL (permanence).
Final Polish:
Make the headers easy to copy-paste. Use bold text for emphasis. Ensure the distinction between s-maxage (CDN) and max-age (Browser) is clear.
Let's build the response based on these thoughts.
- Static Assets: Immutable.
- HTML: SWR is the hero here.
- APIs:
s-maxage for shared cache, max-age for browser.
- Invalidation: Surrogate keys are better than just URL purging.
Let's write it out.
Designing a sitewide caching policy requires balancing three competing forces: Performance (TTFB), Freshness (data accuracy), and Efficiency (origin load/SEO).
Below is a comprehensive blueprint for a modern caching architecture, segmented by resource type.
1. The Core Strategy: "Tiered Freshness"
We do not apply one rule to the whole site. We divide the site into four resource tiers:
- Immutable Assets: JS/CSS/Image fingerprints.
- Dynamic Content: HTML pages, APIs.
- Semi-Static Content: Blog posts, Product listings.
- Edge Logic: Redirects, Error pages.
2. CDN TTL Heuristics (Time-to-Live)
This dictates how long the CDN holds the content before asking the origin for a new copy.
A. Immutable Assets (The "Forever" Cache)
- Target:
main.a1b2c3.js, logo.png, style.css?v=1.2.
- Policy:
Cache-Control: public, max-age=31536000, immutable
- Heuristic:
- If the filename contains a hash (e.g.,
[name].[contenthash].js) or a query string version parameter, cache for 1 year.
- Why: These files never change. If you update code, you change the filename. The browser/CDN never needs to check the server.
B. Dynamic HTML (The "Stale-While-Revalidate" Cache)
- Target: Homepage, Product Detail Pages (PDP), Category Pages.
- Policy:
Cache-Control: public, s-maxage=60, max-age=0, stale-while-revalidate=86400
- Heuristic:
s-maxage=60: The CDN serves the cached page for 60 seconds. If a user requests it after 60s, the CDN triggers a background fetch from the origin.
stale-while-revalidate: Even if the content is 1 second "old," the CDN serves the stale version instantly while refreshing the cache in the background. This ensures users never wait for the origin server to render HTML.
- Note: For highly volatile data (stock tickers), reduce
s-maxage to 1 or 0.
C. Edge Logic (Redirects & Errors)
- Target: 301 Redirects, 404 Pages.
- Policy:
Cache-Control: public, max-age=300
- Heuristic:
- Redirects: Cache 301s for a short time (e.g., 5 mins). If you accidentally create a redirect loop, caching it for 1 year breaks the URL permanently.
- 404s: Cache 404s briefly. If a user requests a non-existent image, you don't want that request hitting your database 100 times a second.
3. ETag & Last-Modified Rules (Validation)
TTLs eventually expire. When they do, we use validators to save bandwidth.
-
ETag (Entity Tag):
- Rule: Enable for HTML and JSON responses only.
- Generation: The ETag should be a hash of the content (e.g., MD5 or SHA-256 of the response body).
- Heuristic: If the content changes by one byte, the ETag changes.
- Outcome: When the CDN expires (e.g., after 60s), it sends a
If-None-Match header to the origin. If the content hasn't changed, the origin sends a 304 Not Modified (0 bytes transferred), saving significant processing time.
-
Last-Modified:
- Rule: Use for Static Assets and Large Files (PDFs, Videos).
- Heuristic: Calculating an ETag for a 2GB video file is CPU expensive.
Last-Modified relies on the file system timestamp, which is "free" computationally.
- Outcome:
If-Modified-Since header checks if the file was touched.
4. SEO Constraints & Handling
Caching is dangerous for SEO if done incorrectly. Googlebot expects fast loads, but accurate content.
A. The Vary Header (The SEO Killer)
- Constraint: Google crawls mostly with a US desktop User-Agent, but also crawls as Mobile and from different geos.
- Rule: Avoid
Vary: User-Agent unless absolutely necessary.
- If you serve different HTML to Mobile vs. Desktop, you risk "Cloaking" (showing different content to Googlebot vs users) if your CDN caches the Desktop version and serves it to the Mobile bot.
- Solution: Use Dynamic Rendering or Responsive Design so the HTML is identical for all agents. If you must vary by device, ensure your CDN creates separate cache "buckets" for Mobile and Desktop explicitly.
B. Canonical Tags & Cache Segmentation
- Constraint: If your site serves content via CDN (e.g.,
cdn.example.com) but the canonical is www.example.com.
- Rule: The CDN cache key must ignore the
Host header if it serves multiple domains pointing to the same origin, OR strictly segregate them.
C. Sitemaps & Robots.txt
- Policy:
Cache-Control: public, max-age=3600
- Reason: These change rarely. However, do not cache
noindex tags in headers for long periods. If you accidentally deploy a noindex sitewide and it gets cached for 24 hours, Google will de-index your site.
5. Implementation Summary Table
| Resource Type | Cache-Control Strategy | ETag / Last-Mod | Notes |
|---|
| Fingerprinted JS/CSS | public, max-age=31536000, immutable | Disable | Never check. Rely on filename change. |
| User Uploads (Images) | public, max-age=2592000 (30 days) | Last-Mod | Long cache. Invalidate via CDN API if replaced. |
| HTML (Homepage/PLP) | public, s-maxage=60, stale-while-revalidate=86400 | ETag (Strong) | Instant load, background refresh. |
| API (JSON) | private, max-age=0, must-revalidate OR s-maxage=10 | ETag (Weak) | "Private" if user-specific. Short TTL if public. |
| Redirects (301) | public, max-age=300 | Disable | Short TTL to prevent "infinite redirect" disasters. |
6. The "Stale-While-Revalidate" Flow (The Hero)
This is the most critical directive for modern performance.
- Request 1 (User A): CDN has no cache. Requests from Origin. Origin sends HTML +
Cache-Control: s-maxage=10, stale-while-revalidate=60.
- Request 2 (User B - 5s later): CDN has cache. Serves immediately (Latency: ~10ms).
- Request 3 (User C - 15s later): The content is "stale" (older than 10s).
- Without SWR: CDN waits for Origin to generate new HTML (Latency: ~500ms). User waits.
- With SWR: CDN serves the stale HTML to User C immediately (Latency: ~10ms). Simultaneously, the CDN sends a background request to the Origin to refresh the cache for the next user.
7. SEO Checklist Before Go-Live
- Surrogate Keys: Ensure your CDN supports cache tagging (Surrogate Keys). If you update a product price, you must be able to purge only that specific HTML page, not the entire site cache.
- No
Vary: Cookie: Most CDNs do not cache responses that Vary: Cookie. If your HTML depends on a login state (e.g., "Hello John"), you must either:
- Cache a generic version ("Hello User") and personalize via JavaScript (Client-side).
- Or set the HTML to
private (Do not cache in CDN).