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

The Trade-off between Consistency and Availability (CAP)

You will apply the CAP theorem to inform your cache configuration choices.

In this lesson, you will learn how to apply the CAP theorem—Consistency, Availability, and Partition Tolerance—to make informed decisions when configuring your Node.js caching layer.

The CAP theorem states that in a distributed system (like a cluster of Redis nodes), you can only guarantee two out of three properties during a network partition. Since a network failure (Partition) is inevitable in distributed infrastructure, you are effectively forced to choose between Consistency (C) and Availability (A) for your cache.

Consistency vs. Availability

  • Consistency (CP): You prioritize accurate data. If a node cannot confirm it has the latest value, it returns an error or blocks the request. This prevents stale data but increases latency or potential downtime during sync issues.
  • Availability (AP): You prioritize uptime. If a node is partitioned, it serves the last known value from its local memory, even if that data is outdated. This ensures the application remains responsive.

Application in Node.js

When configuring a distributed cache (like Redis Sentinel or Cluster), your choice depends on your feature requirements.

For a Financial Ledger, you would lean towards CP. You must ensure that updateAccountBalance operations are consistent across all nodes. If the network splits, it is safer to fail than to provide a stale balance.

For a Social Media Feed, you lean towards AP. Users prefer a slightly outdated "Like" count over an error message.

// Example: Pseudo-code for handling a Cache Miss during a Partition
async function getCachedProfile(userId) {
  try {
    return await cache.get(userId);
  } catch (err) {
    // If CP: return error to avoid serving stale data
    // If AP: fall back to a stale local read or primary DB to ensure uptime
    return await database.fetch(userId); 
  }
}

When building high-performance Node.js services, remember that "Consistency" isn't free. Tight consistency requires overhead for synchronization, which increases latency. Conversely, high availability through eventual consistency improves speed but requires robust logic to handle potential stale data reads within your application code.

Key Takeaway: Choose Consistency when accuracy is non-negotiable (e.g., payments), and choose Availability when low latency and constant uptime are more critical to the user experience.