Caching


Caching is a technique to store frequently accessed data in a temporary storage area (the cache) closer to the application, reducing data retrieval latency and improving overall performance. When a user requests data, the application first checks the cache. If the data is found (a cache hit), it’s served directly from the cache, which is much faster than fetching from the original source (e.g., a database or a remote server). If the data isn’t found (a cache miss), the application fetches it from the source, stores it in the cache for future requests, and then serves it to the user.

Different Caching Strategies:

// Simple in-memory caching example using a Map
const cache = new Map();

function getCachedData(key) {
  if (cache.has(key)) {
    console.log("Cache hit!");
    return cache.get(key);
  } else {
    console.log("Cache miss!");
    const data = fetchDataFromSource(key); // Replace with actual data fetching logic
    cache.set(key, data);
    return data;
  }
}


// Simulate fetching data from a slow source
function fetchDataFromSource(key) {
    console.log("Fetching data from source...");
    // Simulate a 1-second delay to demonstrate caching benefits
    return new Promise(resolve => {
        setTimeout(() => {
            resolve({ id: key, value: `Data for ${key}` });
        }, 1000);
    });
}



async function testCache() {
    console.log(await getCachedData(1));
    console.log(await getCachedData(1)); // This should be a cache hit
    console.log(await getCachedData(2)); // Cache miss
    console.log(await getCachedData(2)); // Cache hit
}
testCache();


Cache Invalidation:

Considerations:

By strategically implementing caching, web applications can significantly improve performance, reduce server load, and provide a faster, more responsive user experience.