Course contentsShow
← Node.js
Lesson 1321 of 1,98012. Caching Strategies and Application SpeedFree lesson

Implementing Cache-Aside Patterns

You will build the standard workflow of checking the cache, querying the database on a miss, and updating the cache.

In this lesson, you will learn how to implement the cache-aside pattern to reduce database load and speed up data retrieval in your Node.js applications.

The Cache-Aside Workflow

The cache-aside pattern (also known as "lazy loading") keeps your application logic simple by treating the cache as an optional shortcut. Instead of forcing data into the cache ahead of time, the application attempts to retrieve it from the cache first. If the data is absent—a "cache miss"—the application performs the "heavy lifting" by querying the database, then populates the cache for future requests.

This strategy ensures that your cache only stores data that is actually being requested, rather than wasting memory on rarely accessed records.

Implementing the Pattern

In a typical Node.js setup using an abstraction like Redis, your data retrieval function should follow this three-step logic:

  1. Check the cache: Attempt to get the data using a unique key (e.g., user:123).
  2. Handle the miss: If the result is null, query your primary database.
  3. Update the cache: Store the database result in the cache so the next request is a "cache hit."
async function getUser(userId) {
  const cacheKey = `user:${userId}`;

  // 1. Check the cache
  const cachedData = await cache.get(cacheKey);
  if (cachedData) {
    return JSON.parse(cachedData);
  }

  // 2. Cache miss: Query the database
  const user = await db.users.findById(userId);

  // 3. Update the cache for next time
  if (user) {
    await cache.set(cacheKey, JSON.stringify(user));
  }

  return user;
}

Why this matters

By placing this pattern around your database queries, you shield your primary data store from redundant read operations. Because you are checking the cache before reaching out to the disk-based database, the application responds much faster once the "warm-up" phase is complete. This pattern is particularly powerful for read-heavy workloads where the cost of a database query significantly outweighs the overhead of an in-memory cache lookup.

Key Takeaway: The cache-aside pattern optimizes performance by treating the database as the source of truth and the cache as a lazy-loading buffer that only stores data on demand.