Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Cloudflare platform skill covering Workers, D1, R2, KV, AI, Durable Objects, and security.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/cache-reserve/patterns.md
1# Cache Reserve Patterns23## Best Practices45### 1. Always Enable Tiered Cache67```typescript8// Cache Reserve is designed for use WITH Tiered Cache9const configuration = {10tieredCache: 'enabled', // Required for optimal performance11cacheReserve: 'enabled', // Works best with Tiered Cache1213hierarchy: [14'Lower-Tier Cache (visitor)',15'Upper-Tier Cache (origin region)',16'Cache Reserve (persistent)',17'Origin'18]19};20```2122### 2. Set Appropriate Cache-Control Headers2324```typescript25// Origin response headers for Cache Reserve eligibility26const originHeaders = {27'Cache-Control': 'public, max-age=86400', // 24hr (minimum 10hr)28'Content-Length': '1024000', // Required29'Cache-Tag': 'images,product-123', // Optional: purging30'ETag': '"abc123"', // Optional: revalidation31// Avoid: 'Set-Cookie' and 'Vary: *' prevent caching32};33```3435### 3. Use Cache Rules for Fine-Grained Control3637```typescript38// Different TTLs for different content types39const cacheRules = [40{41description: 'Long-term cache for immutable assets',42expression: '(http.request.uri.path matches "^/static/.*\\.[a-f0-9]{8}\\.")',43action_parameters: {44cache_reserve: { eligible: true },45edge_ttl: { mode: 'override_origin', default: 2592000 }, // 30 days46cache: true47}48},49{50description: 'Moderate cache for regular images',51expression: '(http.request.uri.path matches "\\.(jpg|png|webp)$")',52action_parameters: {53cache_reserve: { eligible: true },54edge_ttl: { mode: 'override_origin', default: 86400 }, // 24 hours55cache: true56}57},58{59description: 'Exclude API from Cache Reserve',60expression: '(http.request.uri.path matches "^/api/")',61action_parameters: { cache_reserve: { eligible: false }, cache: false }62}63];64```6566### 4. Making Assets Cache Reserve Eligible from Workers6768**Note**: This modifies response headers to meet eligibility criteria but does NOT directly control Cache Reserve storage (which is zone-level automatic).6970```typescript71export default {72async fetch(request: Request, env: Env): Promise<Response> {73const response = await fetch(request);74if (!response.ok) return response;7576const headers = new Headers(response.headers);77headers.set('Cache-Control', 'public, max-age=36000'); // 10hr minimum78headers.delete('Set-Cookie'); // Blocks caching7980// Ensure Content-Length present81if (!headers.has('Content-Length')) {82const blob = await response.blob();83headers.set('Content-Length', blob.size.toString());84return new Response(blob, { status: response.status, headers });85}8687return new Response(response.body, { status: response.status, headers });88}89};90```9192### 5. Hostname Best Practices9394Use Worker's hostname for efficient caching - avoid overriding hostname unnecessarily.9596## Architecture Patterns9798### Multi-Tier Caching + Immutable Assets99100```typescript101// Optimal: L1 (visitor) → L2 (region) → L3 (Cache Reserve) → Origin102export default {103async fetch(request: Request, env: Env): Promise<Response> {104const url = new URL(request.url);105const isImmutable = /\.[a-f0-9]{8,}\.(js|css|jpg|png|woff2)$/.test(url.pathname);106const response = await fetch(request);107108if (isImmutable) {109const headers = new Headers(response.headers);110headers.set('Cache-Control', 'public, max-age=31536000, immutable');111return new Response(response.body, { status: response.status, headers });112}113return response;114}115};116```117118## Cost Optimization119120### Cost Calculator121122```typescript123interface CacheReserveEstimate {124avgAssetSizeGB: number;125uniqueAssets: number;126monthlyReads: number;127monthlyWrites: number;128originEgressCostPerGB: number; // e.g., AWS: $0.09/GB129}130131function estimateMonthlyCost(input: CacheReserveEstimate) {132// Cache Reserve pricing133const storageCostPerGBMonth = 0.015;134const classAPerMillion = 4.50; // writes135const classBPerMillion = 0.36; // reads136137// Calculate Cache Reserve costs138const totalStorageGB = input.avgAssetSizeGB * input.uniqueAssets;139const storageCost = totalStorageGB * storageCostPerGBMonth;140const writeCost = (input.monthlyWrites / 1_000_000) * classAPerMillion;141const readCost = (input.monthlyReads / 1_000_000) * classBPerMillion;142143const cacheReserveCost = storageCost + writeCost + readCost;144145// Calculate origin egress cost (what you'd pay without Cache Reserve)146const totalTrafficGB = (input.monthlyReads * input.avgAssetSizeGB);147const originEgressCost = totalTrafficGB * input.originEgressCostPerGB;148149// Savings calculation150const savings = originEgressCost - cacheReserveCost;151const savingsPercent = ((savings / originEgressCost) * 100).toFixed(1);152153return {154cacheReserveCost: `$${cacheReserveCost.toFixed(2)}`,155originEgressCost: `$${originEgressCost.toFixed(2)}`,156monthlySavings: `$${savings.toFixed(2)}`,157savingsPercent: `${savingsPercent}%`,158breakdown: {159storage: `$${storageCost.toFixed(2)}`,160writes: `$${writeCost.toFixed(2)}`,161reads: `$${readCost.toFixed(2)}`,162}163};164}165166// Example: Media library167const mediaLibrary = estimateMonthlyCost({168avgAssetSizeGB: 0.005, // 5MB images169uniqueAssets: 10_000,170monthlyReads: 5_000_000,171monthlyWrites: 50_000,172originEgressCostPerGB: 0.09, // AWS S3173});174175console.log(mediaLibrary);176// {177// cacheReserveCost: "$9.98",178// originEgressCost: "$25.00",179// monthlySavings: "$15.02",180// savingsPercent: "60.1%",181// breakdown: { storage: "$0.75", writes: "$0.23", reads: "$9.00" }182// }183```184185### Optimization Guidelines186187- **Set appropriate TTLs**: 10hr minimum, 24hr+ optimal for stable content, 30d max cautiously188- **Cache high-value stable assets**: Images, media, fonts, archives, documentation189- **Exclude frequently changing**: APIs, user-specific content, real-time data190- **Compression note**: Cache Reserve fetches uncompressed from origin, serves compressed to visitors - factor in origin egress costs191192## See Also193194- [README](./README.md) - Overview and core concepts195- [Configuration](./configuration.md) - Setup and Cache Rules196- [API Reference](./api.md) - Purging and monitoring197- [Gotchas](./gotchas.md) - Common issues and troubleshooting198