Cloudflare Cache API in Workers
Programmatic edge caching with the Cache API — finer control than Cache-Control headers, free reads.
Why
The Cache API lets you cache arbitrary data (not just HTTP responses) at the edge for free. Reads are sub-ms and don't count against KV limits.
Ideal for caching API responses, computed results, and rendered HTML.
When
Use Cache API for API response caching, SSR HTML caching, and computed lookups. Avoid for data needing global consistency (use KV) or persistence across deploys (Cache is per-deploy).
How
Example
Common Problems
- ⚠Cache is per-datacenter not global — each edge POP caches independently, first request per POP misses
- ⚠Response consumed after return — must clone() before caching, body is one-shot
- ⚠Cache cleared on deploy — don't rely on Cache for persistence, use KV/R2
Best Practices
- ✓Use ctx.waitUntil for cache.put — don't block response on cache write
- ✓Vary cache key by auth role — cache different responses for admin vs user
- ✓Set max-age + swr — stale-while-revalidate keeps cache warm during revalidation
FAQ
What is Cloudflare Cache API in Workers and what problem does it solve?
Programmatic edge caching with the Cache API — finer control than Cache-Control headers, free reads. It lets developers deploy, store, and scale without self-managing infrastructure — a core reference for cloud service selection.
How do I get started with Cloudflare Cache API in Workers in 5 minutes?
Two steps to run it: (1) Get cache — const cache = caches.default (edge cache for current zone); (2) Put — cache.put(request, response) (response must have Cache-Control or TTL). Validate on the free tier first, then wire into production.
What is the #1 pitfall with Cloudflare Cache API in Workers?
The most frequent issue is: Cache is per-datacenter not global — each edge POP caches independently, first request per POP misses. Run a pre-launch checklist item by item, and add policy/config scanning in CI.
What are the best practices for Cloudflare Cache API in Workers?
Best practices for Cloudflare Cache API in Workers include: Use ctx.waitUntil for cache.put — don't block response on cache write; Vary cache key by auth role — cache different responses for admin vs user; Set max-age + swr — stale-while-revalidate keeps cache warm during revalidation. The first one — "Use ctx.waitUntil for cache.put — don't block response on cache write" — should be a team default baked into your IaC templates.
How do I control cost and avoid bill surprises with Cloudflare Cache API in Workers?
Three ways to prevent overspend: (1) tag every resource with env/team and enable billing alarms; (2) set budget thresholds to trigger Slack/email alerts; (3) review idle resources in Cost Explorer regularly and clean them up. Most Cloudflare Cache API in Workers options offer a free tier — validate within free quota before scaling.