Concept Flow - Cache invalidation strategies
Start: Data Cached
Check Cache Validity
Use Cache
Fetch Fresh Data
Update Cache
End
This flow shows how cache is checked for validity, used if valid, or invalidated and refreshed if not.
export async function getStaticProps() { const data = await fetchData() return { props: { data }, revalidate: 10, } }
| Step | Action | Cache State | Condition | Result |
|---|---|---|---|---|
| 1 | Initial build | Cache empty | No cache | Fetch data and cache it |
| 2 | Request at 5s | Cache valid | 5 < 10 seconds | Use cached data |
| 3 | Request at 12s | Cache expired | 12 > 10 seconds | Invalidate cache and fetch fresh data |
| 4 | Request at 15s | Cache valid | 3 seconds since last fetch < 10 | Use cached data |
| 5 | Request at 25s | Cache expired | 10 seconds since last fetch | Invalidate cache and fetch fresh data |
| 6 | End | Cache updated | N/A | Stop |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 | After Step 5 | Final |
|---|---|---|---|---|---|---|---|
| cacheTimestamp | null | 0s (build time) | 0s (still valid) | 12s (updated) | 12s (valid) | 25s (updated) | 25s |
| cacheData | null | data fetched | data reused | data refreshed | data reused | data refreshed | data refreshed |
Cache Invalidation Strategies in Next.js: - Use revalidate in getStaticProps to set cache lifetime. - Cache is valid until revalidate seconds pass. - After expiry, cache is invalidated and fresh data fetched. - This keeps data fresh without rebuilding every request. - Helps balance speed and data accuracy.