Speed Up Your Worker with Cache API (5 Lines of Code)
Published: (December 29, 2025 at 05:05 AM EST)
1 min read
Source: Dev.to
Source: Dev.to
Using the Cache API in 5 Lines
export default {
async fetch(request) {
const cache = caches.default;
let response = await cache.match(request);
if (!response) {
response = await fetch(request);
response = new Response(response.body, response);
response.headers.set('Cache-Control', 'max-age=3600');
await cache.put(request, response.clone());
}
return response;
}
};
Performance Impact
- Before caching: every request hits the origin (200‑500 ms latency, high CPU usage).
- After caching: cached requests return in <10 ms, with a typical hit rate of 70‑90 % and minimal CPU usage.
- Example on my API:
- P50 latency: 450 ms → 15 ms
- P95 latency: 800 ms → 25 ms
- Cache hit rate: 85 %
Best Practices
- Cache only
GETrequests. - Set an appropriate TTL (e.g.,
max-age=3600for 1 hour) – avoid caching forever. - Use distinct cache keys for different variants (query parameters, headers, etc.).
- Invalidate or update the cache when underlying data changes.
Additional Resources
For more performance patterns, see the full guide: https://appybot.gumroad.com/l/oatoe