mirror of
https://github.com/hanzoai/skills.git
synced 2026-11-19 00:47:36 +00:00
hanzoskills.com/llms.txt now opens with the install line, the API reference index and the company index, so an agent that lands on any one of the three can find the rest. robots.txt claimed 537 documents while llms.txt counts 920. The number is gone from robots.txt; llms.txt derives it. public/ is regenerated from scripts/site.py, which it had fallen behind: the copy-prompt menu and agent bar were in the generator and not in the committed pages. tests/site.mjs passes against the result. Co-authored-by: Hanzo Dev <[email protected]>
879 lines
39 KiB
HTML
879 lines
39 KiB
HTML
<!doctype html>
|
|
<html lang="en"><head>
|
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>caching-http-caching</title>
|
|
<meta name="color-scheme" content="dark">
|
|
<style>
|
|
/* Committed to one visual world: a dark instrument panel. No light variant —
|
|
the dot field and the hairline rules only read on black, and a naive
|
|
inversion would wash both out. Every colour is painted explicitly so the page
|
|
never borrows a host background. */
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
|
|
|
|
:root{
|
|
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
|
|
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
|
|
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
|
|
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
|
|
--font-zen-pixel-square:'Zen Pixel Square',monospace;
|
|
--mono:var(--font-zen-mono);
|
|
--sans:var(--font-zen-sans);
|
|
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
|
|
--r:999px; --r-soft:14px;
|
|
}
|
|
*{box-sizing:border-box}
|
|
html{-webkit-text-size-adjust:100%}
|
|
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
|
|
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
|
|
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
|
|
|
|
/* The dot field. A halftone made of one repeating radial-gradient, faded out
|
|
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
|
|
/* No overflow clip here: the dot field is inset to the box already, and a clip
|
|
would cut off the copy-prompt menu. */
|
|
.hero{position:relative;border-bottom:1px solid var(--line)}
|
|
.hero::before{content:"";position:absolute;inset:0;
|
|
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
|
|
background-size:7px 7px;
|
|
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
pointer-events:none}
|
|
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
|
|
|
|
nav{border-bottom:1px solid var(--line)}
|
|
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
|
|
justify-content:space-between;align-items:center;gap:1rem}
|
|
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--ink);text-decoration:none;
|
|
display:inline-flex;align-items:center;gap:.6rem}
|
|
.brand i{font-style:normal;color:var(--faint)}
|
|
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
|
|
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--soft);text-decoration:none}
|
|
nav a.up:hover{color:var(--ink)}
|
|
|
|
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
|
|
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
|
|
h1 em{font-style:normal;color:var(--faint)}
|
|
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
|
|
|
|
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
|
|
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
|
|
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
|
|
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
|
|
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
|
|
line-height:1.2;font-weight:400}
|
|
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
|
|
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
|
|
.btn.solid:hover{background:#d8d8d4}
|
|
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
|
|
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
|
|
|
|
/* Copy-prompt selector. Each row copies the prompt for its own target. */
|
|
.copy{position:relative;display:inline-flex}
|
|
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
|
|
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
|
|
padding:.4rem;display:flex;flex-direction:column;
|
|
box-shadow:0 12px 32px rgba(0,0,0,.75)}
|
|
.menu[hidden]{display:none}
|
|
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
|
|
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
|
|
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
|
|
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
|
|
white-space:nowrap}
|
|
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
|
|
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
|
|
.mi:hover .mark{color:var(--ink)}
|
|
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
|
|
letter-spacing:.1em;text-transform:uppercase}
|
|
|
|
/* Works-with bar: one scrolling row, name and mark per agent. */
|
|
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
|
|
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
|
|
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
|
|
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
|
|
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
|
|
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
|
|
display:flex;align-items:center}
|
|
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
|
|
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
|
|
-webkit-overflow-scrolling:touch;
|
|
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
|
|
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
|
|
.bar::-webkit-scrollbar{display:none}
|
|
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
|
|
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
|
|
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
|
|
text-decoration:none;background:var(--ground)}
|
|
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
|
|
.agent .mark{width:.95rem;height:.95rem}
|
|
|
|
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
|
|
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
|
|
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
|
|
p{margin:0 0 1rem;max-width:70ch}
|
|
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
|
|
li{margin:.22rem 0}
|
|
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
|
|
text-decoration-color:var(--line-hi)}
|
|
a:hover{text-decoration-color:var(--ink)}
|
|
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
|
|
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
|
|
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
|
|
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
|
|
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
|
|
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
|
|
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
|
|
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
|
|
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
|
|
display:block;overflow-x:auto}
|
|
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
|
|
|
|
.curl{display:block;background:var(--panel);border:1px solid var(--line);
|
|
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
|
|
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
|
|
white-space:pre;line-height:1.9}
|
|
.curl b{color:var(--ink);font-weight:400}
|
|
.curl i{font-style:normal;color:var(--faint)}
|
|
|
|
/* index */
|
|
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
|
|
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
|
|
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
|
|
#q:focus{outline:none;border-color:var(--soft)}
|
|
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
|
|
text-transform:uppercase;margin:0 0 2rem}
|
|
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
|
|
padding-bottom:.45rem}
|
|
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
|
|
border-radius:var(--r-soft);text-decoration:none}
|
|
.row:hover{background:#0a0a0a}
|
|
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
|
|
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
|
|
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
|
|
color:var(--faint);font-size:.85rem}
|
|
footer a{color:var(--soft)}
|
|
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
|
|
margin:0 0 2rem;font-size:.85rem}
|
|
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
|
|
border-bottom:1px solid var(--line);padding-bottom:.4rem}
|
|
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
|
|
.fmap a:hover{text-decoration:underline}
|
|
.fmap div{color:var(--faint);line-height:1.5}
|
|
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
|
|
|
|
@media (max-width:640px){
|
|
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
|
|
.btns{gap:.5rem}
|
|
.btn{padding:.75rem 1.15rem;font-size:.68rem}
|
|
.copy,.copy .btn{width:100%;justify-content:center}
|
|
.menu{left:0;right:0;min-width:0}
|
|
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
|
|
.strip b{border-right:0;padding-right:0}
|
|
.bar{width:100%}
|
|
}
|
|
</style>
|
|
<link rel="alternate" type="text/markdown" href="/caching-http-caching.md">
|
|
|
|
<link rel="icon" href="/favicon.svg">
|
|
<link rel="canonical" href="https://hanzoskills.com/caching-http-caching">
|
|
</head>
|
|
<!-- Reading this with a machine? Every page here is also plain markdown.
|
|
This one: https://hanzoskills.com/caching-http-caching.md
|
|
Index: https://hanzoskills.com/llms.txt
|
|
Corpus: https://hanzoskills.com/all.md
|
|
Append .md to any path for the markdown twin. -->
|
|
<body>
|
|
<nav><div class="in">
|
|
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
|
|
<a class="up" href="/">All skills</a>
|
|
</div></nav>
|
|
|
|
<div class="wrap">
|
|
<h1>caching-http-caching</h1><p class="lede">Browser and HTTP cache layer optimization using cache headers, conditional requests, and validation strategies</p><h1>HTTP Caching</h1>
|
|
<p><strong>Last Updated</strong>: 2025-10-25</p>
|
|
<h2>When to Use This Skill</h2>
|
|
<p><strong>Activate when</strong>:</p>
|
|
<ul><li>Optimizing web application performance</li><li>Reducing server load and bandwidth costs</li><li>Implementing proper cache headers for static assets</li><li>Debugging browser caching issues</li><li>Designing API caching strategies</li><li>Implementing conditional requests (ETags, Last-Modified)</li><li>Configuring CDN caching behavior</li></ul>
|
|
<p><strong>Prerequisites</strong>: <code>caching-fundamentals.md</code>, basic HTTP knowledge</p>
|
|
<p><strong>Related Skills</strong>: <code>cdn-edge-caching.md</code>, <code>service-worker-caching.md</code>, <code>frontend-performance.md</code></p>
|
|
<hr>
|
|
<h2>Core Concepts</h2>
|
|
<h3>HTTP Cache Flow</h3>
|
|
<pre><code>Browser Request
|
|
↓
|
|
1. Check browser cache
|
|
↓
|
|
2. Is cached? Is fresh?
|
|
├─ Yes (HIT) → Return from cache
|
|
├─ Expired → Revalidate with server
|
|
└─ No (MISS) → Request from server
|
|
↓
|
|
3. Server response with cache headers
|
|
↓
|
|
4. Store in cache (if cacheable)
|
|
↓
|
|
5. Return to application</code></pre>
|
|
<h3>Cache Headers Overview</h3>
|
|
<pre><code class="lang-python">from dataclasses import dataclass
|
|
from typing import Optional
|
|
from datetime import datetime, timedelta
|
|
|
|
@dataclass
|
|
class HTTPCacheHeaders:
|
|
"""HTTP caching headers reference"""
|
|
|
|
# Modern (HTTP/1.1)
|
|
cache_control: str # Primary caching directive
|
|
etag: Optional[str] = None # Entity tag for validation
|
|
last_modified: Optional[str] = None # Last modification time
|
|
|
|
# Legacy (HTTP/1.0)
|
|
expires: Optional[str] = None # Absolute expiration time
|
|
pragma: Optional[str] = None # Legacy no-cache
|
|
|
|
# Additional
|
|
vary: Optional[str] = None # Vary cache by headers
|
|
age: Optional[int] = None # Time in cache (seconds)
|
|
|
|
class CacheDirectives:
|
|
"""Cache-Control directive meanings"""
|
|
|
|
DIRECTIVES = {
|
|
# Cacheability
|
|
"public": "Cacheable by any cache (browsers, CDNs)",
|
|
"private": "Cacheable by browser only, not CDNs",
|
|
"no-cache": "Must revalidate before use (NOT 'don't cache')",
|
|
"no-store": "Don't cache at all (sensitive data)",
|
|
|
|
# Expiration
|
|
"max-age=<seconds>": "Fresh for N seconds from response time",
|
|
"s-maxage=<seconds>": "Shared cache (CDN) max age, overrides max-age",
|
|
"stale-while-revalidate=<seconds>": "Serve stale while updating",
|
|
"stale-if-error=<seconds>": "Serve stale if origin errors",
|
|
|
|
# Revalidation
|
|
"must-revalidate": "Must not serve stale without revalidation",
|
|
"proxy-revalidate": "Shared caches must revalidate",
|
|
"immutable": "Never revalidate (content won't change)",
|
|
}</code></pre>
|
|
<hr>
|
|
<h2>Cache-Control Header</h2>
|
|
<h3>Basic Examples</h3>
|
|
<pre><code class="lang-python">class CacheControlExamples:
|
|
"""Common Cache-Control configurations"""
|
|
|
|
@staticmethod
|
|
def static_assets():
|
|
"""
|
|
Static assets with fingerprinting (e.g., app.abc123.js)
|
|
|
|
Pattern: Long cache with immutable
|
|
"""
|
|
return {
|
|
"header": "Cache-Control",
|
|
"value": "public, max-age=31536000, immutable",
|
|
"explanation": "Cache for 1 year, never revalidate",
|
|
"use_for": ["JS/CSS with hash", "Versioned images"]
|
|
}
|
|
|
|
@staticmethod
|
|
def html_pages():
|
|
"""
|
|
HTML pages (dynamic content)
|
|
|
|
Pattern: No caching or short TTL with revalidation
|
|
"""
|
|
return {
|
|
"header": "Cache-Control",
|
|
"value": "public, max-age=0, must-revalidate",
|
|
"explanation": "Always revalidate before serving",
|
|
"use_for": ["HTML pages", "API HTML responses"]
|
|
}
|
|
|
|
@staticmethod
|
|
def api_responses():
|
|
"""
|
|
API responses (read-heavy endpoints)
|
|
|
|
Pattern: Short TTL with private caching
|
|
"""
|
|
return {
|
|
"header": "Cache-Control",
|
|
"value": "private, max-age=300",
|
|
"explanation": "Cache in browser for 5 minutes",
|
|
"use_for": ["User-specific API data", "Dashboard APIs"]
|
|
}
|
|
|
|
@staticmethod
|
|
def cdn_assets():
|
|
"""
|
|
CDN-delivered assets
|
|
|
|
Pattern: Long browser cache, longer CDN cache
|
|
"""
|
|
return {
|
|
"header": "Cache-Control",
|
|
"value": "public, max-age=3600, s-maxage=86400",
|
|
"explanation": "Browser: 1 hour, CDN: 24 hours",
|
|
"use_for": ["Images", "Fonts", "Public assets"]
|
|
}
|
|
|
|
@staticmethod
|
|
def no_caching():
|
|
"""
|
|
Sensitive or always-fresh data
|
|
|
|
Pattern: Complete cache prevention
|
|
"""
|
|
return {
|
|
"header": "Cache-Control",
|
|
"value": "no-store, no-cache, must-revalidate, private",
|
|
"explanation": "Never cache, always fetch fresh",
|
|
"use_for": ["Sensitive data", "Real-time data"]
|
|
}
|
|
|
|
@staticmethod
|
|
def stale_while_revalidate():
|
|
"""
|
|
Serve stale content while updating (2024 pattern)
|
|
|
|
Pattern: Balance freshness and performance
|
|
"""
|
|
return {
|
|
"header": "Cache-Control",
|
|
"value": "public, max-age=60, stale-while-revalidate=300",
|
|
"explanation": "Serve stale for 5min while revalidating",
|
|
"use_for": ["News feeds", "Social media timelines"]
|
|
}
|
|
|
|
# Implementation examples
|
|
def set_cache_headers_flask():
|
|
"""Flask example"""
|
|
from flask import make_response
|
|
|
|
@app.route('/api/data')
|
|
def api_data():
|
|
response = make_response({"data": "value"})
|
|
response.headers['Cache-Control'] = 'private, max-age=300'
|
|
return response
|
|
|
|
def set_cache_headers_express():
|
|
"""Express.js example"""
|
|
# JavaScript
|
|
"""
|
|
app.get('/api/data', (req, res) => {
|
|
res.set('Cache-Control', 'private, max-age=300');
|
|
res.json({ data: 'value' });
|
|
});
|
|
"""
|
|
|
|
def set_cache_headers_fastapi():
|
|
"""FastAPI example"""
|
|
from fastapi import Response
|
|
|
|
@app.get("/api/data")
|
|
async def api_data(response: Response):
|
|
response.headers["Cache-Control"] = "private, max-age=300"
|
|
return {"data": "value"}</code></pre>
|
|
<h3>Modern Directives (2024)</h3>
|
|
<pre><code class="lang-python">class ModernCacheDirectives:
|
|
"""2024 caching best practices"""
|
|
|
|
@staticmethod
|
|
def immutable_pattern():
|
|
"""
|
|
Immutable directive (Chrome 54+, Firefox 49+)
|
|
|
|
Prevents revalidation even on reload
|
|
"""
|
|
return {
|
|
"header": "Cache-Control: public, max-age=31536000, immutable",
|
|
"benefit": "No revalidation on refresh (F5)",
|
|
"use_case": "Fingerprinted assets (app.[hash].js)",
|
|
"support": "All modern browsers (2024)"
|
|
}
|
|
|
|
@staticmethod
|
|
def stale_while_revalidate_pattern():
|
|
"""
|
|
Serve stale while updating in background
|
|
|
|
Chrome 75+, Firefox 68+
|
|
"""
|
|
return {
|
|
"header": "Cache-Control: max-age=60, stale-while-revalidate=86400",
|
|
"behavior": [
|
|
"< 60s: Serve from cache (fresh)",
|
|
"60s - 24h: Serve stale, revalidate async",
|
|
"> 24h: Block until revalidated"
|
|
],
|
|
"benefit": "Instant responses + background updates",
|
|
"support": "Chrome, Firefox, Safari 16+"
|
|
}
|
|
|
|
@staticmethod
|
|
def stale_if_error_pattern():
|
|
"""
|
|
Serve stale on server errors
|
|
|
|
Resilience pattern for high availability
|
|
"""
|
|
return {
|
|
"header": "Cache-Control: max-age=3600, stale-if-error=86400",
|
|
"behavior": "Serve stale up to 24h if origin returns 5xx",
|
|
"benefit": "Graceful degradation during outages",
|
|
"use_case": "Critical APIs, high-availability content"
|
|
}</code></pre>
|
|
<hr>
|
|
<h2>Conditional Requests</h2>
|
|
<h3>ETag (Entity Tag)</h3>
|
|
<p><strong>Concept</strong>: Hash/version of content for validation</p>
|
|
<pre><code class="lang-python">import hashlib
|
|
from typing import Optional
|
|
|
|
class ETagHandler:
|
|
"""ETag generation and validation"""
|
|
|
|
@staticmethod
|
|
def generate_etag(content: str) -> str:
|
|
"""
|
|
Generate ETag from content
|
|
|
|
Strong ETag: byte-for-byte match required
|
|
Weak ETag: semantic equivalence (W/"...")
|
|
"""
|
|
# Strong ETag
|
|
hash_value = hashlib.sha256(content.encode()).hexdigest()[:16]
|
|
return f'"{hash_value}"'
|
|
|
|
@staticmethod
|
|
def generate_weak_etag(content: str) -> str:
|
|
"""
|
|
Weak ETag for semantic equivalence
|
|
|
|
Use when minor differences acceptable (whitespace, formatting)
|
|
"""
|
|
hash_value = hashlib.sha256(content.encode()).hexdigest()[:16]
|
|
return f'W/"{hash_value}"'
|
|
|
|
@staticmethod
|
|
def validate_etag(request_etag: str, current_etag: str) -> bool:
|
|
"""Check if ETags match"""
|
|
# Strip W/ prefix for weak comparison
|
|
req = request_etag.replace('W/', '')
|
|
cur = current_etag.replace('W/', '')
|
|
return req == cur
|
|
|
|
# Flask implementation
|
|
def etag_example_flask():
|
|
from flask import Flask, request, make_response
|
|
|
|
app = Flask(__name__)
|
|
|
|
@app.route('/api/data')
|
|
def api_data():
|
|
content = get_current_data() # {"data": "value"}
|
|
content_str = json.dumps(content, sort_keys=True)
|
|
|
|
# Generate ETag
|
|
etag = ETagHandler.generate_etag(content_str)
|
|
|
|
# Check If-None-Match header
|
|
if_none_match = request.headers.get('If-None-Match')
|
|
|
|
if if_none_match == etag:
|
|
# Content unchanged - return 304 Not Modified
|
|
response = make_response('', 304)
|
|
response.headers['ETag'] = etag
|
|
return response
|
|
|
|
# Content changed - return 200 with data
|
|
response = make_response(content)
|
|
response.headers['ETag'] = etag
|
|
response.headers['Cache-Control'] = 'private, max-age=300'
|
|
return response
|
|
|
|
# FastAPI implementation
|
|
from fastapi import FastAPI, Request, Response, status
|
|
from fastapi.responses import JSONResponse
|
|
|
|
app = FastAPI()
|
|
|
|
@app.get("/api/data")
|
|
async def api_data(request: Request):
|
|
content = {"data": "value"}
|
|
content_str = json.dumps(content, sort_keys=True)
|
|
|
|
# Generate ETag
|
|
etag = ETagHandler.generate_etag(content_str)
|
|
|
|
# Check If-None-Match
|
|
if_none_match = request.headers.get("if-none-match")
|
|
|
|
if if_none_match == etag:
|
|
# Not modified
|
|
return Response(status_code=status.HTTP_304_NOT_MODIFIED, headers={"ETag": etag})
|
|
|
|
# Return data with ETag
|
|
return JSONResponse(
|
|
content=content,
|
|
headers={
|
|
"ETag": etag,
|
|
"Cache-Control": "private, max-age=300"
|
|
}
|
|
)</code></pre>
|
|
<h3>Last-Modified / If-Modified-Since</h3>
|
|
<pre><code class="lang-python">from datetime import datetime
|
|
from email.utils import formatdate, parsedate_to_datetime
|
|
|
|
class LastModifiedHandler:
|
|
"""Last-Modified header handling"""
|
|
|
|
@staticmethod
|
|
def format_http_date(dt: datetime) -> str:
|
|
"""Convert datetime to HTTP date format"""
|
|
# HTTP date: Wed, 21 Oct 2015 07:28:00 GMT
|
|
return formatdate(dt.timestamp(), usegmt=True)
|
|
|
|
@staticmethod
|
|
def parse_http_date(date_str: str) -> datetime:
|
|
"""Parse HTTP date string to datetime"""
|
|
return parsedate_to_datetime(date_str)
|
|
|
|
@staticmethod
|
|
def is_modified_since(last_modified: datetime, if_modified_since: Optional[str]) -> bool:
|
|
"""
|
|
Check if content was modified since given time
|
|
|
|
Returns: True if modified (send full response)
|
|
"""
|
|
if not if_modified_since:
|
|
return True # No conditional request
|
|
|
|
try:
|
|
client_time = LastModifiedHandler.parse_http_date(if_modified_since)
|
|
# Compare (truncate to seconds, HTTP dates have 1s precision)
|
|
return last_modified.timestamp() > client_time.timestamp()
|
|
except Exception:
|
|
return True # Parse error, send full response
|
|
|
|
# Flask example
|
|
@app.route('/api/document/<int:doc_id>')
|
|
def get_document(doc_id):
|
|
doc = get_document_from_db(doc_id) # Returns {content, updated_at}
|
|
|
|
last_modified = doc['updated_at']
|
|
last_modified_str = LastModifiedHandler.format_http_date(last_modified)
|
|
|
|
# Check If-Modified-Since
|
|
if_modified_since = request.headers.get('If-Modified-Since')
|
|
|
|
if not LastModifiedHandler.is_modified_since(last_modified, if_modified_since):
|
|
# Not modified
|
|
response = make_response('', 304)
|
|
response.headers['Last-Modified'] = last_modified_str
|
|
return response
|
|
|
|
# Modified - return full document
|
|
response = make_response(doc['content'])
|
|
response.headers['Last-Modified'] = last_modified_str
|
|
response.headers['Cache-Control'] = 'private, max-age=300'
|
|
return response</code></pre>
|
|
<hr>
|
|
<h2>Vary Header</h2>
|
|
<p><strong>Purpose</strong>: Vary cache by request headers (e.g., Accept-Encoding, User-Agent)</p>
|
|
<pre><code class="lang-python">class VaryHeaderExamples:
|
|
"""Vary header patterns"""
|
|
|
|
@staticmethod
|
|
def vary_by_encoding():
|
|
"""
|
|
Vary by Accept-Encoding
|
|
|
|
Cache separate versions for gzip, br, etc.
|
|
"""
|
|
return {
|
|
"header": "Vary: Accept-Encoding",
|
|
"use_case": "Compressed responses",
|
|
"example": "Same content, different compression"
|
|
}
|
|
|
|
@staticmethod
|
|
def vary_by_auth():
|
|
"""
|
|
Vary by Authorization
|
|
|
|
Prevent caching of authenticated content
|
|
"""
|
|
return {
|
|
"header": "Vary: Authorization",
|
|
"use_case": "User-specific content",
|
|
"warning": "Often better to use Cache-Control: private"
|
|
}
|
|
|
|
@staticmethod
|
|
def vary_by_multiple():
|
|
"""
|
|
Vary by multiple headers
|
|
|
|
Cache multiplied by combinations
|
|
"""
|
|
return {
|
|
"header": "Vary: Accept-Encoding, Accept-Language",
|
|
"use_case": "i18n content with compression",
|
|
"warning": "Cache fragmentation (many variants)"
|
|
}
|
|
|
|
# Implementation
|
|
@app.route('/api/content')
|
|
def get_content():
|
|
accept_encoding = request.headers.get('Accept-Encoding', '')
|
|
accept_language = request.headers.get('Accept-Language', 'en')
|
|
|
|
# Generate appropriate content
|
|
content = get_localized_content(accept_language)
|
|
|
|
response = make_response(content)
|
|
response.headers['Vary'] = 'Accept-Encoding, Accept-Language'
|
|
response.headers['Cache-Control'] = 'public, max-age=3600'
|
|
|
|
return response</code></pre>
|
|
<hr>
|
|
<h2>Cache Busting Strategies</h2>
|
|
<h3>1. Fingerprinting / Hashing</h3>
|
|
<p><strong>Best Practice</strong>: Include content hash in filename</p>
|
|
<pre><code class="lang-python">import hashlib
|
|
import os
|
|
|
|
class CacheBusting:
|
|
"""Cache busting strategies"""
|
|
|
|
@staticmethod
|
|
def fingerprint_filename(filepath: str) -> str:
|
|
"""
|
|
Add content hash to filename
|
|
|
|
Example: app.js → app.a1b2c3d4.js
|
|
"""
|
|
with open(filepath, 'rb') as f:
|
|
content = f.read()
|
|
|
|
# Generate hash
|
|
hash_value = hashlib.md5(content).hexdigest()[:8]
|
|
|
|
# Insert hash before extension
|
|
name, ext = os.path.splitext(filepath)
|
|
return f"{name}.{hash_value}{ext}"
|
|
|
|
@staticmethod
|
|
def query_string_versioning(url: str, version: str) -> str:
|
|
"""
|
|
Add version query parameter
|
|
|
|
Less ideal (some caches ignore query params)
|
|
"""
|
|
separator = '&' if '?' in url else '?'
|
|
return f"{url}{separator}v={version}"
|
|
|
|
# Build tool integration (example)
|
|
"""
|
|
# Webpack/Vite automatically handles this:
|
|
|
|
// webpack.config.js
|
|
module.exports = {
|
|
output: {
|
|
filename: '[name].[contenthash].js',
|
|
},
|
|
};
|
|
|
|
// Results in: main.a1b2c3d4.js
|
|
// HTML references updated automatically
|
|
"""
|
|
|
|
# HTML generation
|
|
def generate_asset_url(asset_path: str, version: Optional[str] = None) -> str:
|
|
"""
|
|
Generate versioned asset URL
|
|
|
|
Development: /static/app.js
|
|
Production: /static/app.a1b2c3d4.js
|
|
"""
|
|
if os.environ.get('ENV') == 'production':
|
|
return CacheBusting.fingerprint_filename(asset_path)
|
|
else:
|
|
return asset_path</code></pre>
|
|
<h3>2. Immutable Assets</h3>
|
|
<pre><code class="lang-html"><!-- Immutable pattern with long cache -->
|
|
<link rel="stylesheet" href="/static/app.a1b2c3d4.css">
|
|
<!-- Server sends: Cache-Control: public, max-age=31536000, immutable -->
|
|
|
|
<!-- Non-fingerprinted assets: short cache -->
|
|
<link rel="stylesheet" href="/static/app.css">
|
|
<!-- Server sends: Cache-Control: public, max-age=300 --></code></pre>
|
|
<hr>
|
|
<h2>Testing Cache Headers</h2>
|
|
<h3>Using curl</h3>
|
|
<pre><code class="lang-bash"># Check response headers
|
|
curl -I https://example.com/api/data
|
|
|
|
# Check with If-None-Match (ETag validation)
|
|
curl -H "If-None-Match: \"abc123\"" -I https://example.com/api/data
|
|
|
|
# Check with If-Modified-Since
|
|
curl -H "If-Modified-Since: Wed, 21 Oct 2015 07:28:00 GMT" -I \
|
|
https://example.com/api/data
|
|
|
|
# Verbose output
|
|
curl -v https://example.com/api/data</code></pre>
|
|
<h3>Browser DevTools</h3>
|
|
<pre><code class="lang-javascript">// Chrome DevTools Network tab:
|
|
// 1. Open DevTools (F12)
|
|
// 2. Network tab
|
|
// 3. Disable cache checkbox (for testing)
|
|
// 4. Look at "Size" column:
|
|
// - "(disk cache)" = from disk cache
|
|
// - "(memory cache)" = from memory cache
|
|
// - "304 Not Modified" = conditional request successful
|
|
// - File size = fresh request
|
|
|
|
// Inspect headers
|
|
fetch('/api/data')
|
|
.then(response => {
|
|
console.log('Cache-Control:', response.headers.get('cache-control'));
|
|
console.log('ETag:', response.headers.get('etag'));
|
|
console.log('Age:', response.headers.get('age'));
|
|
});</code></pre>
|
|
<hr>
|
|
<h2>Patterns</h2>
|
|
<h3>Pattern 1: Static Asset Pipeline</h3>
|
|
<pre><code class="lang-python">class StaticAssetCaching:
|
|
"""Optimal caching for static assets"""
|
|
|
|
@staticmethod
|
|
def configure_asset_caching():
|
|
"""
|
|
Different strategies for different asset types
|
|
"""
|
|
return {
|
|
"fingerprinted_assets": {
|
|
"pattern": "*.{hash}.{js,css,png,jpg}",
|
|
"cache_control": "public, max-age=31536000, immutable",
|
|
"explanation": "Content-addressed, never changes"
|
|
},
|
|
"fonts": {
|
|
"pattern": "*.{woff,woff2,ttf}",
|
|
"cache_control": "public, max-age=31536000, immutable",
|
|
"explanation": "Fonts rarely change"
|
|
},
|
|
"images_without_hash": {
|
|
"pattern": "*.{png,jpg,svg}",
|
|
"cache_control": "public, max-age=2592000", # 30 days
|
|
"explanation": "Long but not immutable"
|
|
},
|
|
"html": {
|
|
"pattern": "*.html",
|
|
"cache_control": "public, max-age=0, must-revalidate",
|
|
"explanation": "Always check for updates"
|
|
}
|
|
}
|
|
|
|
# Nginx configuration
|
|
"""
|
|
# Fingerprinted assets
|
|
location ~* \.[\da-f]{8}\.(js|css)$ {
|
|
add_header Cache-Control "public, max-age=31536000, immutable";
|
|
}
|
|
|
|
# Fonts
|
|
location ~* \.(woff|woff2|ttf)$ {
|
|
add_header Cache-Control "public, max-age=31536000, immutable";
|
|
}
|
|
|
|
# HTML
|
|
location ~* \.html$ {
|
|
add_header Cache-Control "public, max-age=0, must-revalidate";
|
|
}
|
|
"""</code></pre>
|
|
<hr>
|
|
<h2>Anti-Patterns</h2>
|
|
<h3>❌ No Cache Headers</h3>
|
|
<pre><code class="lang-python"># WRONG: Missing cache headers
|
|
@app.route('/api/data')
|
|
def api_data():
|
|
return {"data": "value"}
|
|
# Browser uses heuristic caching (unpredictable)
|
|
|
|
# CORRECT: Explicit cache headers
|
|
@app.route('/api/data')
|
|
def api_data():
|
|
response = make_response({"data": "value"})
|
|
response.headers['Cache-Control'] = 'private, max-age=300'
|
|
return response</code></pre>
|
|
<h3>❌ Confusing no-cache and no-store</h3>
|
|
<pre><code class="lang-python"># WRONG: Using no-cache to prevent caching
|
|
response.headers['Cache-Control'] = 'no-cache'
|
|
# "no-cache" means "revalidate before use", NOT "don't cache"
|
|
|
|
# CORRECT: Use no-store to prevent caching
|
|
response.headers['Cache-Control'] = 'no-store'</code></pre>
|
|
<h3>❌ Caching Personalized Content</h3>
|
|
<pre><code class="lang-python"># WRONG: Public cache for user-specific data
|
|
@app.route('/api/user/profile')
|
|
def user_profile():
|
|
response = make_response(get_user_data())
|
|
response.headers['Cache-Control'] = 'public, max-age=3600'
|
|
# CDN will cache and serve to wrong users!
|
|
return response
|
|
|
|
# CORRECT: Private cache only
|
|
@app.route('/api/user/profile')
|
|
def user_profile():
|
|
response = make_response(get_user_data())
|
|
response.headers['Cache-Control'] = 'private, max-age=300'
|
|
return response</code></pre>
|
|
<hr>
|
|
<h2>Quick Reference</h2>
|
|
<h3>Cache-Control Directives</h3>
|
|
<p>| Directive | Meaning | Use Case | |-----------|---------|----------| | public | Any cache can store | Static assets, public APIs | | private | Browser only, no CDN | User-specific data | | no-cache | Revalidate before use | HTML, frequently updated | | no-store | Don't cache | Sensitive data | | max-age=N | Fresh for N seconds | All cacheable content | | s-maxage=N | CDN max age | CDN-delivered content | | immutable | Never revalidate | Fingerprinted assets | | stale-while-revalidate=N | Serve stale while updating | Balance freshness/performance |</p>
|
|
<h3>Status Codes</h3>
|
|
<p>| Code | Meaning | Use Case | |------|---------|----------| | 200 OK | Full response | Normal response | | 304 Not Modified | Content unchanged | Successful conditional request | | 412 Precondition Failed | Condition not met | Failed conditional request |</p>
|
|
<hr>
|
|
<h2>Related Skills</h2>
|
|
<p><strong>Next Steps</strong>:</p>
|
|
<ul><li><code>cdn-edge-caching.md</code> → CDN configuration and optimization</li><li><code>service-worker-caching.md</code> → Progressive Web App caching</li><li><code>cache-performance-monitoring.md</code> → Measuring cache effectiveness</li></ul>
|
|
<p><strong>Foundations</strong>:</p>
|
|
<ul><li><code>caching-fundamentals.md</code> → Core caching concepts</li><li><code>frontend-performance.md</code> → Overall web performance</li></ul>
|
|
<hr>
|
|
<h2>Summary</h2>
|
|
<p>HTTP caching optimizes web performance through browser and intermediate caches:</p>
|
|
<ul><li><strong>Cache-Control</strong>: Modern directive for caching behavior (public, private, max-age, immutable)</li><li><strong>Conditional Requests</strong>: ETags and Last-Modified for validation</li><li><strong>Vary</strong>: Cache variations based on request headers</li><li><strong>Cache Busting</strong>: Fingerprinting for immutable assets</li></ul>
|
|
<p><strong>Key takeaways</strong>:</p>
|
|
<ol><li>Use Cache-Control (not Expires) for modern caching</li><li>Fingerprint assets for long-term caching with immutable</li><li>Implement ETags for efficient revalidation</li><li>Use private for user-specific, public for shared content</li><li>Test cache behavior with curl and browser DevTools</li></ol>
|
|
<p><strong>Next</strong>: Move to <code>cdn-edge-caching.md</code> for CDN optimization.</p>
|
|
<footer>
|
|
<div class="fmap">
|
|
<div><b>Build</b>
|
|
<a href="https://hanzo.app">hanzo.app</a> app builder
|
|
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
|
|
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
|
|
<div><b>Run</b>
|
|
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
|
|
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
|
|
<div><b>Account</b>
|
|
<a href="https://hanzo.id">hanzo.id</a> sign in
|
|
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
|
|
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
|
|
<div><b>Company</b>
|
|
<a href="https://hanzo.ai">hanzo.ai</a> canonical
|
|
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
|
|
</div>
|
|
<div class="fend"><a href="/caching-http-caching.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
|
|
</footer>
|
|
</div></body></html> |