Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 46

Cache Invalidation Strategies and Data Consistency

This lesson is built with resources from youtube.com, engineering.fb.com and 1 more site.

Hello! Welcome back to our series on Distributed Systems Building Blocks.

In the previous lesson, we contrasted the core caching patterns—Cache-Aside, Write-Through, Write-Behind, and Read-Through. We established that Cache-Aside is the most common pattern, but it introduces a window of inconsistency between the database and the cache. This brings us to one of the famously "two hard things in computer science": cache invalidation.

Today's lesson directly addresses this challenge, focusing on the learning outcome: Analyze cache invalidation strategies (e.g., TTL-based, write-based) and their impact on data consistency.

For a Staff-level interview, simply knowing the patterns isn't enough. The expectation is a deep understanding of consistency trade-offs, race conditions, and how to operate caching systems at scale. This lesson will equip you with that depth, moving from fundamental strategies to the advanced problems faced by companies like Meta.

1. The Core Problem: Cache Inconsistency

When data is written to your database, the copy of that data in your cache becomes stale. Cache inconsistency is the state where the cache holds this stale data, and a client reading from the cache receives an outdated value.

To see how this plays out, let's watch a short segment from the video we used in the last lesson.

Caching in System Design Interviews w/ Meta Staff Engineer

This clip from 'Caching in System Design Interviews' provides a clear, concrete example of how cache inconsistency occurs and introduces the two primary strategies to combat it: invalidating on write and using short TTLs.

Watch from 20:10 to 22:55. Focus on the sequence of events that leads to a user seeing a stale profile picture. Pay attention to the distinction between solutions that prioritize consistency (invalidate on write) versus those that accept some staleness (short TTLs).

The video highlights a crucial point: the "correct" solution depends entirely on your product requirements. Is it acceptable for a user to see an old profile picture for five minutes? If so, eventual consistency is fine. If not, you need a more active approach.

While a stale profile picture might be a minor issue, cache inconsistency can have severe consequences. To understand the stakes, let's look at why a company like Meta invests so heavily in this area.

Cache made consistent - Engineering at Meta

This article from Meta Engineering, 'Cache made consistent,' explains why cache consistency is a critical problem, not just a theoretical one. It provides a powerful example of how inconsistency can lead to a 'split-brain' scenario.

Read the section titled 'Why do we care about cache consistency at all?'. The example about shuffling a user's primary message store in TAO demonstrates how cache inconsistency can be indistinguishable from data loss from a user's perspective.

As you can see, failing to manage cache consistency can lead to fragmented data and a broken user experience. Now, let's dive into the strategies for preventing this.


2. Cache Invalidation Strategies

There are two primary families of invalidation strategies: passive (time-based) and active (event-based).

Cache Invalidation Strategies
A visual comparison of write-based invalidation, read-based invalidation (part of the cache-aside pattern), and TTL-based invalidation. Source: The Pragmatic Engineer Newsletter

Strategy 1: Time-To-Live (TTL) Based Invalidation

This is the simplest invalidation strategy. When you write an item to the cache, you attach an expiration time, or TTL. The cache is responsible for automatically evicting the item once the TTL expires.

  • How it works: SET user:123 '{"name":"Alex"}' EX 300 (Set key user:123 with a TTL of 300 seconds).
  • Impact on Consistency: Guarantees eventual consistency. The data will be stale for, at most, the duration of the TTL.
  • Trade-offs:
    • Pros:
      • Very simple to implement; requires no extra application logic for invalidation.
      • Protects the database from stale data persisting indefinitely in the cache.
    • Cons:
      • Data is guaranteed to be stale for some period. The shorter the TTL, the less stale the data, but the lower the cache hit rate.
      • Can cause a "thundering herd" or "cache stampede" if many clients request a popular, expired key simultaneously.

When to use TTL: It's a great fit for data where freshness isn't critical and some staleness is acceptable. Examples include social media feeds, user recommendations, or product catalogs that update infrequently. You are trading strong consistency for simplicity and performance.

Strategy 2: Write-Based (Active) Invalidation

This strategy involves actively removing an item from the cache when its source-of-truth is updated. This is the "invalidation" step we discussed in the Cache-Aside pattern.

The process is:

  1. Application receives a request to update data (e.g., UPDATE users SET name = 'Bob' WHERE id = 123).
  2. Application writes the change to the database.
  3. Application sends a command to the cache to invalidate the corresponding data.

There's a key decision here: should the application update the new value in the cache, or simply delete it?

A foundational paper and talk from Facebook on scaling Memcache provides a clear answer.

NSDI '13 - Scaling Memcache at Facebook

This talk from NSDI '13, 'Scaling Memcache at Facebook', explains their look-aside caching architecture. It directly addresses the question of whether to update or delete on write.

Watch from 04:35 to 05:01. Listen for the justification of why they prefer delete (invalidation) over set (updating) on the write path.

The key reason, as mentioned in the video, is that deletes are idempotent. If an invalidation message is delayed or sent multiple times due to retries, the outcome is the same: the key is gone. An update operation, however, is not idempotent. A late-arriving update could potentially overwrite a more recent value, leading to inconsistency. Therefore, the standard practice is: write to DB, then DELETE from cache.

Trade-offs:

  • Pros:
    • Can significantly reduce the window of staleness compared to TTL.
  • Cons:
    • More complex application logic; the application is now responsible for invalidation.
    • Introduces race conditions (which we'll cover next).
    • What if the invalidation command fails? The cache will now hold stale data indefinitely (or until the TTL, if you use both).

Strategy 3: Event-Driven Invalidation (Pub/Sub)

In a distributed or microservices architecture, the service that writes to the database may not be the same one that reads from it. How does the writing service tell all the reading services to invalidate their caches?

This is where an event-driven approach using a message broker (like Kafka, RabbitMQ, or even Redis Pub/Sub) becomes essential.

Distributed Cache Invalidation at Scale
A high-level diagram showing how a pub/sub broker can be used to distribute invalidation events to multiple listeners in a microservices architecture. Source: vinay.georgiatech on Medium

The flow is:

  1. The Writer Service updates the database.
  2. After the DB write is confirmed, it publishes an invalidation event (e.g., { "key": "product:456" }) to a topic on the message broker.
  3. Multiple Reader Services subscribe to this topic. When they receive the event, they invalidate the key from their respective caches.

This pattern is extremely powerful for decoupling services in a large-scale system. You can read more about its implementation details in the "Event-Based Invalidation" section of the article "A Deep Dive into Caching Strategies" (LINK).


3. Staff-Level Depth: Race Conditions and Consistency at Scale

Knowing the strategies is expected. A Staff-level discussion requires you to anticipate and solve the complex failure modes that arise in distributed systems.

The "Stale Set" Race Condition

Consider this sequence of events in a cache-aside system with active invalidation:

  1. Request 1: Reads key K, finds it's not in the cache (a miss).
  2. Request 1: Starts fetching the value V1 for key K from the database.
  3. Request 2: Updates the value of K to V2 in the database.
  4. Request 2: Invalidates key K from the cache.
  5. Request 1: Finishes fetching V1 from the database and, to be helpful, writes K=V1 back into the cache.

Result: The cache now permanently holds the stale value V1, even though the database holds V2. This is a classic and dangerous race condition.

How do you solve this? The same Facebook talk offers an elegant solution: leases.

NSDI '13 - Scaling Memcache at Facebook

Continuing with the 'Scaling Memcache at Facebook' video, this section explains the stale set problem and introduces 'leases' as a mechanism to prevent it.

Watch from 05:01 to 06:20. Focus on how a lease ID, obtained on a cache miss, acts as a token to prevent a stale write. This is conceptually similar to a 'compare-and-set' or 'load-link/store-conditional' operation.

By using a lease, the stale write from Request 1 would be rejected by the cache because the lease token it holds was invalidated by the write from Request 2. This is a powerful technique to bring up in an interview as it demonstrates a deep understanding of concurrency control in caching.

Consistency in Geo-Distributed Systems

The problem gets even harder when you have multiple data centers. Imagine a master database in one region and read replicas in others. There's a replication lag between the master and replicas.

This creates another race condition:

  1. A write for key K goes to the master DB in us-east-1.
  2. The write service sends an invalidation for K to the local cache in eu-west-1.
  3. A read request in eu-west-1 gets a cache miss for K.
  4. The read service fetches K from the local DB replica in eu-west-1. But the change from the master hasn't replicated yet!
  5. The read service gets the old value and writes it back into the cache.

The Facebook team solved this with a mechanism called "remote markers," which you can explore by watching from 13:50 to 15:00 in the same LINK video. The key takeaway is that geo-distribution adds replication lag as another source of inconsistency that your design must account for.

Observability: You Can't Fix What You Can't See

How do you even know if your cache is inconsistent? At Meta's scale, even rare race conditions happen constantly. They built dedicated tooling to solve this.

Cache made consistent - Engineering at Meta

The final reading from 'Cache made consistent' discusses Meta's solution to a critical problem: how to measure and debug cache inconsistencies at scale. This is a masterclass in observability for distributed systems.

Read the sections 'Reliable consistency observability', 'Consistency tracing', and 'A real bug we found and fixed this year'. Focus on the concepts: Polaris: A service that acts like a client to measure client-observable inconsistencies without false positives. Consistency Tracing: A stateful tracing library that logs cache mutations only during the small window where race conditions are likely, avoiding the overhead of logging everything. \nThis demonstrates the level of operational rigor required for large-scale caching.


Conclusion

In this lesson, we moved from the "what" of caching patterns to the "how" and "why" of cache invalidation, a topic rich with the kind of trade-offs and complex problems you'll face in a Staff-level interview.

Key Takeaways:

  • Invalidation is a spectrum: Strategies range from the simple, eventually-consistent TTL-based approach to the more complex but timely write-based active invalidation.
  • Deletes are idempotent: When implementing active invalidation, prefer deleting the key over updating it to avoid race conditions from reordered or retried operations.
  • Microservices favor events: Use a pub/sub model to decouple services and broadcast invalidation events in a distributed architecture.
  • Discuss the hard problems: For a Staff+ role, show you've thought about race conditions (like stale sets and their solution with leases) and the challenges of observability at scale (like Meta's Polaris and Consistency Tracing).

Preview of the Next Lesson:

We've focused on keeping a single cache or cluster consistent. But what happens when your data becomes too large to fit on a single cache server? How do you distribute the load and data across a fleet of cache nodes? In our next lesson, we will explain and apply consistent hashing for data partitioning and load balancing, the fundamental algorithm that makes large-scale distributed caches possible.