Stale-while-revalidate Strategy
Code snippet showing how to implement the stale-while-revalidate strategy, where we respond with the cached data and fetch the latest data in the background for future requests.
// This function simulates retrieving data from a cache
function getFromCache(key) {
// Implementation of cache retrieval, e.g., using localStorage
return localStorage.getItem(key);
}
// This function simulates updating the cache with new data
function updateCache(key, value) {
// Implementation of cache update, e.g., using localStorage
localStorage.setItem(key, value);
}
// This function fetches the latest data from the server
async function fetchLatestData(url, key) {
try {
const response = await fetch(url);
const data = await response.json();
updateCache(key, JSON.stringify(data));
} catch (error) {
console.error('Error fetching data:', error);
}
}
// Stale-while-revalidate implementation
async function fetchData(url, key) {
const staleData = getFromCache(key);
if (staleData) {
// Respond with stale data immediately
console.log('Responding with stale data:', JSON.parse(staleData));
// Fetch latest data in the background for future requests
fetchLatestData(url, key);
} else {
// If no data in cache, wait for fresh data
await fetchLatestData(url, key);
return fetchData(url, key); // Retry fetching after cache is updated
}
}
The snippet above implements the stale-while-revalidate strategy using a simulated cache system (e.g., localStorage). It first tries to respond with cached data if available, and then fetches the latest data from the server in the background, updating the cache for future requests. If the cache is empty, it will fetch fresh data, update the cache, and retry the retrieval process.