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]>
924 lines
39 KiB
HTML
924 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-cdn-edge-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-cdn-edge-caching.md">
|
|
|
|
<link rel="icon" href="/favicon.svg">
|
|
<link rel="canonical" href="https://hanzoskills.com/caching-cdn-edge-caching">
|
|
</head>
|
|
<!-- Reading this with a machine? Every page here is also plain markdown.
|
|
This one: https://hanzoskills.com/caching-cdn-edge-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-cdn-edge-caching</h1><p class="lede">CDN and edge cache optimization with Cloudflare, Fastly, and CloudFront for global performance and reduced origin load</p><h1>CDN Edge 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>Delivering content globally with low latency</li><li>Reducing origin server load and bandwidth costs</li><li>Implementing edge caching with Cloudflare, Fastly, or CloudFront</li><li>Optimizing TTFB (Time To First Byte) performance</li><li>Configuring cache purging and invalidation at scale</li><li>Setting up geo-caching and regional optimization</li><li>Debugging CDN cache behavior and hit rates</li></ul>
|
|
<p><strong>Prerequisites</strong>: <code>http-caching.md</code>, <code>caching-fundamentals.md</code>, basic CDN knowledge</p>
|
|
<p><strong>Related Skills</strong>: <code>cache-invalidation-strategies.md</code>, <code>cloudflare-workers.md</code>, <code>frontend-performance.md</code></p>
|
|
<hr>
|
|
<h2>Core Concepts</h2>
|
|
<h3>CDN Architecture</h3>
|
|
<pre><code>User Request → Edge Server (PoP) → Origin Shield → Origin Server
|
|
(10-50ms) (cache check) (optional) (100-500ms)
|
|
|
|
Edge Cache Hierarchy:
|
|
1. Edge PoP (Point of Presence) - 200+ locations globally
|
|
2. Origin Shield (optional) - Regional cache tier
|
|
3. Origin Server - Your application/storage</code></pre>
|
|
<h3>Performance Impact (2024 Data)</h3>
|
|
<pre><code class="lang-python">from dataclasses import dataclass
|
|
|
|
@dataclass
|
|
class CDNPerformanceMetrics:
|
|
"""Real-world CDN performance improvements"""
|
|
|
|
# TTFB improvements with edge caching
|
|
without_cdn = {
|
|
"average_ttfb": "402ms",
|
|
"p95_ttfb": "800ms",
|
|
"origin_requests": "100%"
|
|
}
|
|
|
|
with_cdn = {
|
|
"average_ttfb": "207ms", # 49% improvement
|
|
"p95_ttfb": "350ms", # 56% improvement
|
|
"cache_hit_rate": "85-95%",
|
|
"origin_requests": "5-15%"
|
|
}
|
|
|
|
# Case study: Optimized edge TTL
|
|
edge_ttl_optimization = {
|
|
"before": "Edge TTL: 1 hour",
|
|
"after": "Edge TTL: 1 week",
|
|
"result": "Long-tail content cached, 70% TTFB reduction (500ms → 150ms)"
|
|
}
|
|
|
|
# Netflix 2022 optimization
|
|
netflix_case_study = {
|
|
"change": "Mixed invalidation + expiration approach",
|
|
"cpu_reduction": "30%",
|
|
"cache_efficiency": "Maintained data freshness"
|
|
}</code></pre>
|
|
<hr>
|
|
<h2>Cloudflare Edge Caching</h2>
|
|
<h3>1. Cache Rules</h3>
|
|
<p><strong>Concept</strong>: Control caching behavior based on URL patterns, file types, conditions</p>
|
|
<pre><code class="lang-javascript">// Cloudflare Workers example
|
|
export default {
|
|
async fetch(request, env, ctx) {
|
|
const url = new URL(request.url);
|
|
|
|
// Define cache behavior by path
|
|
let cacheControl;
|
|
|
|
if (url.pathname.match(/\.(js|css|png|jpg|svg)$/)) {
|
|
// Static assets - long cache
|
|
cacheControl = 'public, max-age=31536000, immutable';
|
|
} else if (url.pathname.startsWith('/api/')) {
|
|
// API responses - short cache
|
|
cacheControl = 'public, max-age=300, s-maxage=600';
|
|
} else if (url.pathname.endsWith('.html')) {
|
|
// HTML - always revalidate
|
|
cacheControl = 'public, max-age=0, must-revalidate';
|
|
} else {
|
|
// Default
|
|
cacheControl = 'public, max-age=3600';
|
|
}
|
|
|
|
// Fetch from origin
|
|
const response = await fetch(request);
|
|
|
|
// Clone response and add cache header
|
|
const newResponse = new Response(response.body, response);
|
|
newResponse.headers.set('Cache-Control', cacheControl);
|
|
|
|
return newResponse;
|
|
}
|
|
};</code></pre>
|
|
<h3>2. Edge TTL Configuration</h3>
|
|
<pre><code class="lang-python">class CloudflareEdgeTTL:
|
|
"""Cloudflare Edge TTL best practices (2024)"""
|
|
|
|
@staticmethod
|
|
def dynamic_content():
|
|
"""
|
|
Dynamic content with short Edge TTL
|
|
|
|
Ensures content freshness for frequently updated data
|
|
"""
|
|
return {
|
|
"edge_ttl": "1-4 hours",
|
|
"browser_ttl": "5 minutes",
|
|
"use_case": "News feeds, dashboards",
|
|
"headers": "Cache-Control: public, max-age=300, s-maxage=3600"
|
|
}
|
|
|
|
@staticmethod
|
|
def static_content():
|
|
"""
|
|
Static content with long Edge TTL
|
|
|
|
2024 optimization: 1 week is sweet spot
|
|
"""
|
|
return {
|
|
"edge_ttl": "1 week (604800s)",
|
|
"browser_ttl": "1 hour",
|
|
"use_case": "Images, fonts, versioned assets",
|
|
"headers": "Cache-Control: public, max-age=3600, s-maxage=604800",
|
|
"benefit": "Long-tail content cached at edge"
|
|
}
|
|
|
|
@staticmethod
|
|
def api_responses():
|
|
"""
|
|
API responses with balanced TTL
|
|
|
|
Longer edge cache than browser for shared caching
|
|
"""
|
|
return {
|
|
"edge_ttl": "10 minutes",
|
|
"browser_ttl": "1 minute",
|
|
"use_case": "Public APIs, product catalogs",
|
|
"headers": "Cache-Control: public, max-age=60, s-maxage=600"
|
|
}
|
|
|
|
# Cloudflare Page Rules (Dashboard configuration)
|
|
"""
|
|
URL Pattern: example.com/static/*
|
|
Settings:
|
|
- Cache Level: Cache Everything
|
|
- Edge Cache TTL: 1 week
|
|
- Browser Cache TTL: 1 hour
|
|
|
|
URL Pattern: example.com/api/*
|
|
Settings:
|
|
- Cache Level: Cache Everything
|
|
- Edge Cache TTL: 10 minutes
|
|
- Browser Cache TTL: 1 minute
|
|
- Bypass Cache on Cookie: yes
|
|
"""</code></pre>
|
|
<h3>3. Tiered Cache</h3>
|
|
<p><strong>Concept</strong>: Multi-tier caching to reduce origin requests</p>
|
|
<pre><code class="lang-python">class CloudflareTieredCache:
|
|
"""
|
|
Tiered Cache optimization (included with all plans)
|
|
|
|
Flow: Edge PoP → Regional Tier → Origin
|
|
"""
|
|
|
|
benefits = {
|
|
"reduced_origin_load": "Upper-tier PoPs cache for lower-tier",
|
|
"improved_hit_rate": "Regional cache serves multiple edge locations",
|
|
"lower_bandwidth": "Fewer origin fetches",
|
|
"automatic": "No configuration needed (enabled by default)"
|
|
}
|
|
|
|
# How it works
|
|
"""
|
|
1. User in Asia requests /image.jpg
|
|
2. Asia PoP checks local cache (MISS)
|
|
3. Asia PoP checks regional tier (Singapore)
|
|
4. Regional tier has cached copy (HIT)
|
|
5. Regional tier serves to Asia PoP
|
|
6. Asia PoP caches and serves to user
|
|
|
|
Next request from Japan:
|
|
- Japan PoP → Singapore regional → Cached! (no origin)
|
|
"""</code></pre>
|
|
<h3>4. Bypass Cache on Cookie</h3>
|
|
<pre><code class="lang-javascript">// Cloudflare Worker: Bypass cache for authenticated users
|
|
export default {
|
|
async fetch(request, env, ctx) {
|
|
const url = new URL(request.url);
|
|
|
|
// Check for session cookie
|
|
const cookies = request.headers.get('Cookie') || '';
|
|
const hasSessionCookie = cookies.includes('session_id=');
|
|
|
|
if (hasSessionCookie) {
|
|
// Bypass cache for authenticated users
|
|
const response = await fetch(request, {
|
|
cf: { cacheEverything: false }
|
|
});
|
|
|
|
const newResponse = new Response(response.body, response);
|
|
newResponse.headers.set('Cache-Control', 'private, no-cache');
|
|
return newResponse;
|
|
}
|
|
|
|
// Cache for anonymous users
|
|
const response = await fetch(request, {
|
|
cf: {
|
|
cacheEverything: true,
|
|
cacheTtl: 3600
|
|
}
|
|
});
|
|
|
|
return response;
|
|
}
|
|
};</code></pre>
|
|
<hr>
|
|
<h2>Fastly Edge Caching</h2>
|
|
<h3>1. VCL (Varnish Configuration Language)</h3>
|
|
<pre><code class="lang-vcl"># Fastly VCL example
|
|
sub vcl_recv {
|
|
# Skip cache for authenticated requests
|
|
if (req.http.Cookie ~ "session_id") {
|
|
return(pass);
|
|
}
|
|
|
|
# Normalize URL for better cache hit rate
|
|
if (req.url ~ "\?$") {
|
|
set req.url = regsub(req.url, "\?$", "");
|
|
}
|
|
|
|
# Set cache key
|
|
set req.hash += req.url;
|
|
set req.hash += req.http.host;
|
|
}
|
|
|
|
sub vcl_fetch {
|
|
# Override cache TTL based on content type
|
|
if (beresp.http.Content-Type ~ "image/") {
|
|
set beresp.ttl = 7d; # 1 week for images
|
|
set beresp.http.Cache-Control = "public, max-age=604800";
|
|
}
|
|
|
|
if (beresp.http.Content-Type ~ "application/json") {
|
|
set beresp.ttl = 5m; # 5 minutes for JSON APIs
|
|
set beresp.http.Cache-Control = "public, max-age=300";
|
|
}
|
|
|
|
return(deliver);
|
|
}
|
|
|
|
sub vcl_deliver {
|
|
# Add cache status header for debugging
|
|
if (obj.hits > 0) {
|
|
set resp.http.X-Cache = "HIT";
|
|
set resp.http.X-Cache-Hits = obj.hits;
|
|
} else {
|
|
set resp.http.X-Cache = "MISS";
|
|
}
|
|
}</code></pre>
|
|
<h3>2. Surrogate Keys (Cache Tags)</h3>
|
|
<p><strong>Concept</strong>: Tag-based cache invalidation for granular control</p>
|
|
<pre><code class="lang-python">class FastlySurrogateKeys:
|
|
"""Surrogate key patterns for efficient purging"""
|
|
|
|
@staticmethod
|
|
def set_surrogate_keys(product_id: int, category_id: int) -> str:
|
|
"""
|
|
Set multiple surrogate keys for flexible invalidation
|
|
|
|
Pattern: entity-type:id
|
|
"""
|
|
keys = [
|
|
f"product:{product_id}",
|
|
f"category:{category_id}",
|
|
"product-listing",
|
|
f"v1" # API version
|
|
]
|
|
return " ".join(keys)
|
|
|
|
# Flask example
|
|
@staticmethod
|
|
def flask_example():
|
|
"""
|
|
from flask import Response
|
|
|
|
@app.route('/api/product/<int:product_id>')
|
|
def get_product(product_id):
|
|
product = get_product_from_db(product_id)
|
|
|
|
# Set surrogate keys
|
|
keys = FastlySurrogateKeys.set_surrogate_keys(
|
|
product_id, product['category_id']
|
|
)
|
|
|
|
response = Response(json.dumps(product))
|
|
response.headers['Surrogate-Key'] = keys
|
|
response.headers['Cache-Control'] = 'public, max-age=3600'
|
|
|
|
return response
|
|
"""
|
|
|
|
@staticmethod
|
|
def purge_by_key(api_key: str, service_id: str, surrogate_key: str):
|
|
"""
|
|
Purge cache by surrogate key via Fastly API
|
|
|
|
Benefits:
|
|
- Purge all products in category: "category:123"
|
|
- Purge specific product: "product:456"
|
|
- Purge all product listings: "product-listing"
|
|
"""
|
|
import requests
|
|
|
|
url = f"https://api.fastly.com/service/{service_id}/purge/{surrogate_key}"
|
|
headers = {
|
|
"Fastly-Key": api_key,
|
|
"Accept": "application/json"
|
|
}
|
|
|
|
response = requests.post(url, headers=headers)
|
|
return response.json()
|
|
|
|
# Usage
|
|
"""
|
|
# When product 456 is updated:
|
|
purge_by_key(api_key, service_id, "product:456")
|
|
|
|
# When category 123 changes:
|
|
purge_by_key(api_key, service_id, "category:123")
|
|
# Invalidates all products in that category
|
|
"""</code></pre>
|
|
<h3>3. Soft Purge vs Instant Purge</h3>
|
|
<pre><code class="lang-python">class FastlyPurgeStrategies:
|
|
"""Purge strategies for different scenarios"""
|
|
|
|
@staticmethod
|
|
def instant_purge():
|
|
"""
|
|
Hard purge: Immediately remove from cache
|
|
|
|
Use when: Critical updates, security issues
|
|
Downside: All requests hit origin (stampede risk)
|
|
"""
|
|
return {
|
|
"method": "POST /purge/{url}",
|
|
"behavior": "Remove immediately, next request hits origin",
|
|
"use_case": "Breaking news, security patches"
|
|
}
|
|
|
|
@staticmethod
|
|
def soft_purge():
|
|
"""
|
|
Soft purge: Mark stale, serve while revalidating
|
|
|
|
Use when: Normal updates, performance critical
|
|
Benefit: No origin stampede, smooth updates
|
|
"""
|
|
return {
|
|
"method": "POST /purge/{url} with Fastly-Soft-Purge: 1",
|
|
"behavior": "Mark stale, serve stale while revalidating",
|
|
"use_case": "Product updates, content changes"
|
|
}
|
|
|
|
# Implementation
|
|
import requests
|
|
|
|
def soft_purge_url(api_key: str, url: str):
|
|
"""Soft purge specific URL"""
|
|
headers = {
|
|
"Fastly-Key": api_key,
|
|
"Fastly-Soft-Purge": "1"
|
|
}
|
|
response = requests.post(f"https://api.fastly.com/purge/{url}", headers=headers)
|
|
return response.json()</code></pre>
|
|
<hr>
|
|
<h2>CloudFront Caching</h2>
|
|
<h3>1. Cache Behaviors</h3>
|
|
<pre><code class="lang-python">class CloudFrontCacheBehaviors:
|
|
"""AWS CloudFront cache configuration"""
|
|
|
|
@staticmethod
|
|
def static_assets_behavior():
|
|
"""Cache behavior for static assets"""
|
|
return {
|
|
"path_pattern": "/static/*",
|
|
"viewer_protocol_policy": "redirect-to-https",
|
|
"cache_policy": {
|
|
"min_ttl": 86400, # 1 day
|
|
"default_ttl": 2592000, # 30 days
|
|
"max_ttl": 31536000 # 1 year
|
|
},
|
|
"compress": True,
|
|
"allowed_methods": ["GET", "HEAD"],
|
|
}
|
|
|
|
@staticmethod
|
|
def api_behavior():
|
|
"""Cache behavior for API endpoints"""
|
|
return {
|
|
"path_pattern": "/api/*",
|
|
"viewer_protocol_policy": "https-only",
|
|
"cache_policy": {
|
|
"min_ttl": 0,
|
|
"default_ttl": 300, # 5 minutes
|
|
"max_ttl": 3600 # 1 hour
|
|
},
|
|
"origin_request_policy": "AllViewer",
|
|
"cache_based_on": ["query_strings", "headers"]
|
|
}
|
|
|
|
# Terraform configuration
|
|
"""
|
|
resource "aws_cloudfront_distribution" "main" {
|
|
enabled = true
|
|
|
|
origin {
|
|
domain_name = "origin.example.com"
|
|
origin_id = "primary"
|
|
}
|
|
|
|
# Static assets
|
|
ordered_cache_behavior {
|
|
path_pattern = "/static/*"
|
|
target_origin_id = "primary"
|
|
|
|
min_ttl = 86400
|
|
default_ttl = 2592000
|
|
max_ttl = 31536000
|
|
|
|
compress = true
|
|
|
|
allowed_methods = ["GET", "HEAD"]
|
|
cached_methods = ["GET", "HEAD"]
|
|
|
|
forwarded_values {
|
|
query_string = false
|
|
cookies {
|
|
forward = "none"
|
|
}
|
|
}
|
|
|
|
viewer_protocol_policy = "redirect-to-https"
|
|
}
|
|
|
|
# API endpoints
|
|
ordered_cache_behavior {
|
|
path_pattern = "/api/*"
|
|
target_origin_id = "primary"
|
|
|
|
min_ttl = 0
|
|
default_ttl = 300
|
|
max_ttl = 3600
|
|
|
|
allowed_methods = ["GET", "HEAD", "OPTIONS", "PUT", "POST", "PATCH", "DELETE"]
|
|
cached_methods = ["GET", "HEAD"]
|
|
|
|
forwarded_values {
|
|
query_string = true
|
|
headers = ["Authorization", "Accept"]
|
|
cookies {
|
|
forward = "all"
|
|
}
|
|
}
|
|
|
|
viewer_protocol_policy = "https-only"
|
|
}
|
|
}
|
|
"""</code></pre>
|
|
<h3>2. Lambda@Edge for Dynamic Caching</h3>
|
|
<pre><code class="lang-javascript">// Lambda@Edge: Viewer Request
|
|
exports.handler = async (event) => {
|
|
const request = event.Records[0].cf.request;
|
|
const headers = request.headers;
|
|
|
|
// Normalize URL for better cache hit rate
|
|
if (request.querystring) {
|
|
// Sort query parameters
|
|
const params = new URLSearchParams(request.querystring);
|
|
const sortedParams = new URLSearchParams([...params.entries()].sort());
|
|
request.querystring = sortedParams.toString();
|
|
}
|
|
|
|
// Add cache key based on device type
|
|
const userAgent = headers['user-agent'][0].value.toLowerCase();
|
|
const deviceType = /mobile/i.test(userAgent) ? 'mobile' : 'desktop';
|
|
headers['x-device-type'] = [{ value: deviceType }];
|
|
|
|
return request;
|
|
};
|
|
|
|
// Lambda@Edge: Origin Response
|
|
exports.handler = async (event) => {
|
|
const response = event.Records[0].cf.response;
|
|
|
|
// Set cache headers based on content type
|
|
const contentType = response.headers['content-type']?.[0]?.value || '';
|
|
|
|
if (contentType.includes('image/')) {
|
|
response.headers['cache-control'] = [{
|
|
value: 'public, max-age=31536000, immutable'
|
|
}];
|
|
} else if (contentType.includes('application/json')) {
|
|
response.headers['cache-control'] = [{
|
|
value: 'public, max-age=300'
|
|
}];
|
|
}
|
|
|
|
return response;
|
|
};</code></pre>
|
|
<hr>
|
|
<h2>Cache Warming Strategies</h2>
|
|
<pre><code class="lang-python">import asyncio
|
|
import aiohttp
|
|
from typing import List
|
|
|
|
class CacheWarming:
|
|
"""Proactive cache warming for deployments"""
|
|
|
|
@staticmethod
|
|
async def warm_urls(urls: List[str], headers: dict = None):
|
|
"""
|
|
Warm cache by requesting URLs
|
|
|
|
Use after: Deployments, cache purges, invalidations
|
|
"""
|
|
if headers is None:
|
|
headers = {"User-Agent": "Cache-Warmer/1.0"}
|
|
|
|
async with aiohttp.ClientSession() as session:
|
|
tasks = []
|
|
for url in urls:
|
|
tasks.append(session.get(url, headers=headers))
|
|
|
|
responses = await asyncio.gather(*tasks, return_exceptions=True)
|
|
|
|
results = []
|
|
for url, response in zip(urls, responses):
|
|
if isinstance(response, Exception):
|
|
results.append({"url": url, "status": "error", "error": str(response)})
|
|
else:
|
|
results.append({
|
|
"url": url,
|
|
"status": response.status,
|
|
"cache_status": response.headers.get("X-Cache", "unknown")
|
|
})
|
|
|
|
return results
|
|
|
|
@staticmethod
|
|
def generate_warm_urls(sitemap_url: str) -> List[str]:
|
|
"""
|
|
Generate URLs to warm from sitemap
|
|
|
|
Prioritize high-traffic pages
|
|
"""
|
|
import requests
|
|
from xml.etree import ElementTree
|
|
|
|
response = requests.get(sitemap_url)
|
|
root = ElementTree.fromstring(response.content)
|
|
|
|
urls = []
|
|
for url_element in root.findall('.//{http://www.sitemaps.org/schemas/sitemap/0.9}loc'):
|
|
urls.append(url_element.text)
|
|
|
|
return urls
|
|
|
|
# Usage
|
|
async def warm_cache_after_deployment():
|
|
"""Warm cache after deployment"""
|
|
important_urls = [
|
|
"https://example.com/",
|
|
"https://example.com/products",
|
|
"https://example.com/api/featured",
|
|
]
|
|
|
|
results = await CacheWarming.warm_urls(important_urls)
|
|
|
|
for result in results:
|
|
print(f"{result['url']}: {result['status']} - {result.get('cache_status')}")
|
|
|
|
# Run warming
|
|
# asyncio.run(warm_cache_after_deployment())</code></pre>
|
|
<hr>
|
|
<h2>Geo-Caching and Regional Optimization</h2>
|
|
<pre><code class="lang-python">class GeoCaching:
|
|
"""Geographic caching strategies"""
|
|
|
|
@staticmethod
|
|
def geo_specific_content():
|
|
"""
|
|
Serve different content by region
|
|
|
|
Use Vary header or separate cache keys
|
|
"""
|
|
return {
|
|
"approach_1_vary_header": {
|
|
"header": "Vary: Cloudflare-IPCountry",
|
|
"behavior": "Separate cache per country",
|
|
"use_case": "I18n content"
|
|
},
|
|
"approach_2_dynamic_routing": {
|
|
"method": "Cloudflare Workers geo-routing",
|
|
"benefit": "Custom logic per region",
|
|
"use_case": "Complex regional rules"
|
|
}
|
|
}
|
|
|
|
# Cloudflare Workers geo-routing
|
|
"""
|
|
export default {
|
|
async fetch(request, env) {
|
|
const country = request.cf.country;
|
|
|
|
// Route to regional buckets
|
|
let cacheKey;
|
|
if (['US', 'CA', 'MX'].includes(country)) {
|
|
cacheKey = `https://cdn.example.com/na/${request.url}`;
|
|
} else if (['GB', 'FR', 'DE'].includes(country)) {
|
|
cacheKey = `https://cdn.example.com/eu/${request.url}`;
|
|
} else {
|
|
cacheKey = `https://cdn.example.com/global/${request.url}`;
|
|
}
|
|
|
|
// Fetch with regional cache key
|
|
return fetch(cacheKey, request);
|
|
}
|
|
};
|
|
"""</code></pre>
|
|
<hr>
|
|
<h2>Debugging and Monitoring</h2>
|
|
<pre><code class="lang-python">class CDNCacheDebugging:
|
|
"""Tools for debugging CDN cache behavior"""
|
|
|
|
@staticmethod
|
|
def check_cache_status():
|
|
"""
|
|
Interpret cache status headers
|
|
|
|
Common headers:
|
|
- X-Cache: HIT/MISS
|
|
- CF-Cache-Status: Cloudflare status
|
|
- X-Cache-Hits: Number of hits
|
|
- Age: Time in cache (seconds)
|
|
"""
|
|
return {
|
|
"cloudflare": {
|
|
"HIT": "Served from Cloudflare cache",
|
|
"MISS": "Not in cache, fetched from origin",
|
|
"EXPIRED": "Cached but TTL expired, revalidating",
|
|
"STALE": "Serving stale content",
|
|
"BYPASS": "Cache bypassed",
|
|
"DYNAMIC": "Uncacheable (dynamic content)"
|
|
},
|
|
"fastly": {
|
|
"HIT": "Served from Fastly cache",
|
|
"MISS": "Origin fetch",
|
|
"PASS": "Bypassed cache"
|
|
}
|
|
}
|
|
|
|
# curl debugging
|
|
"""
|
|
# Check cache status
|
|
curl -I https://example.com/api/data
|
|
|
|
# Relevant headers:
|
|
# CF-Cache-Status: HIT
|
|
# Age: 120
|
|
# Cache-Control: public, max-age=3600
|
|
"""
|
|
|
|
# Python debugging
|
|
import requests
|
|
|
|
def debug_cdn_cache(url: str):
|
|
"""Debug CDN cache behavior"""
|
|
response = requests.get(url)
|
|
|
|
return {
|
|
"url": url,
|
|
"status": response.status_code,
|
|
"cache_control": response.headers.get("Cache-Control"),
|
|
"cf_cache_status": response.headers.get("CF-Cache-Status"),
|
|
"x_cache": response.headers.get("X-Cache"),
|
|
"age": response.headers.get("Age"),
|
|
"etag": response.headers.get("ETag"),
|
|
}
|
|
|
|
# Monitor cache hit rate
|
|
def calculate_hit_rate(total_requests: int, cache_hits: int) -> float:
|
|
"""Calculate cache hit rate percentage"""
|
|
return (cache_hits / total_requests) * 100 if total_requests > 0 else 0</code></pre>
|
|
<hr>
|
|
<h2>Quick Reference</h2>
|
|
<h3>CDN Selection Guide</h3>
|
|
<p>| Feature | Cloudflare | Fastly | CloudFront | |---------|-----------|--------|------------| | <strong>Ease of Use</strong> | Excellent | Moderate | Good | | <strong>Free Tier</strong> | Yes (generous) | No | Yes (limited) | | <strong>Purge API</strong> | Yes | Excellent (surrogate keys) | Yes | | <strong>Edge Compute</strong> | Workers | Compute@Edge | Lambda@Edge | | <strong>Cache TTL Control</strong> | Page Rules, Workers | VCL | Behaviors | | <strong>Best For</strong> | General sites | High-performance APIs | AWS ecosystem |</p>
|
|
<h3>Cache Optimization Checklist</h3>
|
|
<ul><li>[ ] Set appropriate Edge TTL (1 week for static, minutes for dynamic)</li><li>[ ] Configure browser Cache-Control headers</li><li>[ ] Enable compression (gzip/brotli)</li><li>[ ] Implement cache warming for critical pages</li><li>[ ] Set up cache purging/invalidation</li><li>[ ] Monitor cache hit rates (target: 85%+)</li><li>[ ] Use Tiered Cache (Cloudflare) or Origin Shield</li><li>[ ] Test cache behavior with curl/browser tools</li></ul>
|
|
<hr>
|
|
<h2>Related Skills</h2>
|
|
<p><strong>Next Steps</strong>:</p>
|
|
<ul><li><code>cache-invalidation-strategies.md</code> → Purging and invalidation patterns</li><li><code>cache-performance-monitoring.md</code> → Measuring CDN effectiveness</li><li><code>cloudflare-workers.md</code> → Edge compute integration</li></ul>
|
|
<p><strong>Foundations</strong>:</p>
|
|
<ul><li><code>http-caching.md</code> → Browser and HTTP caching</li><li><code>caching-fundamentals.md</code> → Core caching concepts</li></ul>
|
|
<hr>
|
|
<h2>Summary</h2>
|
|
<p>CDN edge caching dramatically improves global performance and reduces origin load:</p>
|
|
<ul><li><strong>Cloudflare</strong>: Easy setup, generous free tier, Tiered Cache, Workers for custom logic</li><li><strong>Fastly</strong>: VCL power, surrogate keys for granular purging, instant/soft purge</li><li><strong>CloudFront</strong>: AWS integration, Lambda@Edge, robust cache behaviors</li><li><strong>Performance</strong>: 49-80% TTFB improvements, 85-95% cache hit rates</li></ul>
|
|
<p><strong>Key takeaways</strong>:</p>
|
|
<ol><li>Use long Edge TTL (1 week) for static content</li><li>Implement Tiered Cache to reduce origin requests</li><li>Use surrogate keys (Fastly) or tags for granular invalidation</li><li>Monitor cache hit rates and optimize for 85%+ hits</li><li>Warm cache after deployments and purges</li></ol>
|
|
<p><strong>Next</strong>: Move to <code>redis-caching-patterns.md</code> for application-level caching.</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-cdn-edge-caching.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
|
|
</footer>
|
|
</div></body></html> |