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

Write-Through Caching Strategies

You will ensure consistency by updating the cache and the primary database in a single transaction-like flow.

In this lesson, you will learn how to maintain perfect data consistency by ensuring your cache and database are updated simultaneously during write operations.

Understanding Write-Through Caching

Up until now, you have likely used the Cache-Aside pattern, where your application manually checks the cache and then fetches from the database if the data is missing. While effective for reads, this can lead to stale data if the underlying database is updated without clearing the cache.

A Write-Through strategy flips this logic. Instead of updating the database and hoping the cache eventually invalidates, the application treats the cache and the primary database as a single logical unit. When you perform a write, the application updates the database and the cache in one transaction-like flow before returning a success response to the client.

Implementation Logic

The goal is to ensure the cache is always a mirror of the most recent database state. By wrapping these operations, you ensure that any subsequent read request—no matter how soon it arrives—always hits the updated value in the cache.

async function updateUserSettings(userId, newSettings) {
  // 1. Update the primary database
  const updatedUser = await db.users.update(userId, newSettings);

  // 2. Immediately update the cache to match the DB
  // This ensures the cache is never stale
  await redis.set(`user:${userId}:settings`, JSON.stringify(updatedUser));

  return updatedUser;
}

Why Use This?

The primary advantage of this approach is strong consistency. Because the cache is updated synchronously with the write, you eliminate the "window of staleness" that often plagues complex systems. If your Node.js application relies on real-time configuration or user state, Write-Through provides a guarantee that the data retrieved from the cache is as accurate as the data stored in the database.

However, keep in mind that this adds latency to your write operations, as the user must wait for both the database and the cache to acknowledge the write. This strategy is best suited for read-heavy applications where the cost of a slightly slower write is outweighed by the performance gain and reliability of guaranteed cache hits.

Key Takeaway: Write-Through caching forces the cache and database to stay in sync by updating both synchronously, ensuring that reads always retrieve the most current version of your data.