0
0
Astroframework~8 mins

Caching API responses in Astro - Performance & Optimization

Choose your learning style9 modes available
Performance: Caching API responses
HIGH IMPACT
Caching API responses improves page load speed by reducing network requests and speeds up rendering by serving stored data quickly.
Fetching data for a page that rarely changes
Astro
import { cache } from 'astro:cache';
const data = await cache(async () => {
  const response = await fetch('https://api.example.com/data');
  return await response.json();
}, { ttl: 3600 });
return data;
Caches the API response for 1 hour, serving stored data instantly on repeat visits.
📈 Performance GainReduces network requests to zero during cache lifetime, cutting load blocking by 200-500ms
Fetching data for a page that rarely changes
Astro
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
Fetches fresh data on every page load causing repeated network delays and slower rendering.
📉 Performance CostBlocks rendering for 200-500ms per request depending on network speed
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
No caching, fetch on every loadMinimal1 per data updateModerate due to delayed content[X] Bad
Caching API responses with TTLMinimal1 on cache missLow due to instant data[OK] Good
Rendering Pipeline
Without caching, the browser waits for the network response before rendering content, delaying Style Calculation and Layout. With caching, data is available immediately, allowing faster Style Calculation and Layout.
Network
Style Calculation
Layout
Paint
⚠️ BottleneckNetwork latency delays initial data availability, blocking rendering
Core Web Vital Affected
LCP
Caching API responses improves page load speed by reducing network requests and speeds up rendering by serving stored data quickly.
Optimization Tips
1Cache API responses to reduce network latency and speed up page load.
2Set a reasonable TTL to balance freshness and performance.
3Use Astro's built-in cache utilities to simplify caching implementation.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of caching API responses in Astro?
ATriggers more reflows during rendering
BIncreases bundle size significantly
CReduces network requests and speeds up page load
DBlocks rendering longer due to cache checks
DevTools: Network
How to check: Open DevTools > Network tab, reload page, observe API request timing and frequency. Then enable caching and reload again to see reduced or no requests.
What to look for: Fewer or no repeated API requests and faster document load times indicate effective caching.