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/api.md
1# Cache Reserve API23## Workers Integration45```6┌────────────────────────────────────────────────────────────────┐7│ CRITICAL: Workers Cache API ≠ Cache Reserve │8│ │9│ • Workers caches.default / cache.put() → edge cache ONLY │10│ • Cache Reserve → zone-level setting, automatic, no per-req │11│ • You CANNOT selectively write to Cache Reserve from Workers │12│ • Cache Reserve works with standard fetch(), not cache.put() │13└────────────────────────────────────────────────────────────────┘14```1516Cache Reserve is a **zone-level configuration**, not a per-request API. It works automatically when enabled for the zone:1718### Standard Fetch (Recommended)1920```typescript21// Cache Reserve works automatically via standard fetch22export default {23async fetch(request: Request, env: Env): Promise<Response> {24// Standard fetch uses Cache Reserve automatically25return await fetch(request);26}27};28```2930### Cache API Limitations3132**IMPORTANT**: `cache.put()` is **NOT compatible** with Cache Reserve or Tiered Cache.3334```typescript35// ❌ WRONG: cache.put() bypasses Cache Reserve36const cache = caches.default;37let response = await cache.match(request);38if (!response) {39response = await fetch(request);40await cache.put(request, response.clone()); // Bypasses Cache Reserve!41}4243// ✅ CORRECT: Use standard fetch for Cache Reserve compatibility44return await fetch(request);4546// ✅ CORRECT: Use Cache API only for custom cache namespaces47const customCache = await caches.open('my-custom-cache');48let response = await customCache.match(request);49if (!response) {50response = await fetch(request);51await customCache.put(request, response.clone()); // Custom cache OK52}53```5455## Purging and Cache Management5657### Purge by URL (Instant)5859```typescript60// Purge specific URL from Cache Reserve immediately61const purgeCacheReserveByURL = async (62zoneId: string,63apiToken: string,64urls: string[]65) => {66const response = await fetch(67`https://api.cloudflare.com/client/v4/zones/${zoneId}/purge_cache`,68{69method: 'POST',70headers: {71'Authorization': `Bearer ${apiToken}`,72'Content-Type': 'application/json',73},74body: JSON.stringify({ files: urls })75}76);77return await response.json();78};7980// Example usage81await purgeCacheReserveByURL('zone123', 'token456', [82'https://example.com/image.jpg',83'https://example.com/video.mp4'84]);85```8687### Purge by Tag/Host/Prefix (Revalidation)8889```typescript90// Purge by cache tag - forces revalidation, not immediate removal91await fetch(92`https://api.cloudflare.com/client/v4/zones/${zoneId}/purge_cache`,93{94method: 'POST',95headers: { 'Authorization': `Bearer ${apiToken}`, 'Content-Type': 'application/json' },96body: JSON.stringify({ tags: ['tag1', 'tag2'] })97}98);99```100101**Purge behavior:**102- **By URL**: Immediate removal from Cache Reserve + edge cache103- **By tag/host/prefix**: Revalidation only, assets remain in storage (costs continue)104105### Clear All Cache Reserve Data106107```typescript108// Requires Cache Reserve OFF first109await fetch(110`https://api.cloudflare.com/client/v4/zones/${zoneId}/cache/cache_reserve_clear`,111{ method: 'POST', headers: { 'Authorization': `Bearer ${apiToken}` } }112);113114// Check status: GET same endpoint returns { state: "In-progress" | "Completed" }115```116117**Process**: Disable Cache Reserve → Call clear endpoint → Wait up to 24hr → Re-enable118119## Monitoring and Analytics120121### Dashboard Analytics122123Navigate to **Caching > Cache Reserve** to view:124125- **Egress Savings**: Total bytes served from Cache Reserve vs origin egress cost saved126- **Requests Served**: Cache Reserve hits vs misses breakdown127- **Storage Used**: Current GB stored in Cache Reserve (billed monthly)128- **Operations**: Class A (writes) and Class B (reads) operation counts129- **Cost Tracking**: Estimated monthly costs based on current usage130131### Logpush Integration132133```typescript134// Logpush field: CacheReserveUsed (boolean) - filter for Cache Reserve hits135// Query Cache Reserve hits in analytics136const logpushQuery = `137SELECT138ClientRequestHost,139COUNT(*) as requests,140SUM(EdgeResponseBytes) as bytes_served,141COUNT(CASE WHEN CacheReserveUsed = true THEN 1 END) as cache_reserve_hits,142COUNT(CASE WHEN CacheReserveUsed = false THEN 1 END) as cache_reserve_misses143FROM http_requests144WHERE Timestamp >= NOW() - INTERVAL '24 hours'145GROUP BY ClientRequestHost146ORDER BY requests DESC147`;148149// Filter only Cache Reserve hits150const crHitsQuery = `151SELECT ClientRequestHost, COUNT(*) as requests, SUM(EdgeResponseBytes) as bytes152FROM http_requests153WHERE CacheReserveUsed = true AND Timestamp >= NOW() - INTERVAL '7 days'154GROUP BY ClientRequestHost155ORDER BY bytes DESC156`;157```158159### GraphQL Analytics160161```graphql162query CacheReserveAnalytics($zoneTag: string, $since: string, $until: string) {163viewer {164zones(filter: { zoneTag: $zoneTag }) {165httpRequests1dGroups(166filter: { datetime_geq: $since, datetime_leq: $until }167limit: 1000168) {169dimensions { date }170sum {171cachedBytes172cachedRequests173bytes174requests175}176}177}178}179}180```181182## Pricing183184```typescript185// Storage: $0.015/GB-month | Class A (writes): $4.50/M | Class B (reads): $0.36/M186// Cache miss: 1A + 1B | Cache hit: 1B | Assets >1GB: proportionally more ops187```188189## See Also190191- [README](./README.md) - Overview and core concepts192- [Configuration](./configuration.md) - Setup and Cache Rules193- [Patterns](./patterns.md) - Best practices and optimization194- [Gotchas](./gotchas.md) - Common issues and troubleshooting195