Skip to main content

Welcome to a Grasp lesson

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

Lesson 45

Caching Patterns and Trade-offs

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

Hello! Welcome to your lesson on caching patterns.

In our previous lesson, we explored consensus protocols like Raft and Paxos. We learned that their primary purpose is to maintain a strongly consistent, replicated state machine—a single source of truth—even when servers fail. Now, we'll turn our attention to a complementary problem: how to improve system performance and reduce load on that source of truth by creating fast, local copies of data. This is the world of caching.

Today's lesson focuses on a critical aspect of system design and a frequent topic in Staff-level interviews. We'll address the learning outcome: Compare and contrast core caching patterns (e.g., cache-aside, read-through, write-through) and their trade-offs.

By the end of this lesson, you'll be able to articulate not just what these patterns are, but more importantly, when to use each one, justifying your decision based on requirements for latency, data consistency, and system complexity.

1. The "Why" and "Where" of Caching

Before diving into specific patterns, it's essential to solidify the fundamentals. Caching is fundamentally about trading a small amount of fast, expensive storage (like RAM) for significant gains in speed and a reduction in load on slower, cheaper storage (like SSDs or HDDs).

We'll start with a video from a Meta Staff Engineer that provides an excellent overview of caching's role in system design interviews.

Caching in System Design Interviews w/ Meta Staff Engineer

This video, 'Caching in System Design Interviews', begins by explaining the motivation for caching and then explores the different layers in a system where a cache can be placed. This context is crucial for making informed design decisions.

Watch from 00:48 to 07:54. Pay close attention to: The order-of-magnitude difference between memory and disk access speeds. The four primary locations for caching: external (e.g., Redis), in-process, CDN, and client-side. The trade-offs associated with each location, especially the shared nature of external caches versus the speed of in-process caches.

To summarize the key locations for caching discussed in the video:

  • External Cache (e.g., Redis, Memcached): A separate service dedicated to caching. It's shared by all application servers, which is great for data consistency across your service fleet, but introduces network latency for every cache access. This is the most common pattern discussed in interviews.
  • In-Process Cache: The cache lives within the application's memory space. This is extremely fast as it avoids network calls, but the cache is not shared between different application instances, leading to potential inconsistencies and duplicated data. It's best for very hot, small pieces of data like configuration flags.
  • Content Delivery Network (CDN): A geographically distributed cache for static assets (images, videos, JS/CSS files). It optimizes for network latency by serving content from a location physically closer to the user.
  • Client-Side Cache: Data is stored on the user's device (e.g., browser cache, local storage). This offers the best performance for the user but gives you the least control over data freshness and cache invalidation.

For the rest of this lesson, we will focus primarily on external application caches, as this is where the choice of read/write patterns has the most significant architectural impact.


2. The Core Caching Patterns: A Deep Dive

Now we get to the heart of the matter: how does your application interact with the cache and the database? The specific sequence of read and write operations defines the caching pattern. We will explore the four most important patterns.

The same video provides a concise explanation of these patterns.

Caching in System Design Interviews w/ Meta Staff Engineer

Let's continue with the 'Caching in System Design Interviews' video. The next section breaks down the four main cache architectures.

Watch from 08:43 to 15:00. Focus on understanding the data flow for each of the four patterns: Cache-Aside (or Lazy Loading) Write-Through Write-Behind (or Write-Back) Read-Through \nNotice how the responsibility shifts between the application and the cache in each pattern.

Let's break down these patterns one by one, focusing on the trade-offs that are critical for a Staff-level discussion.

Cache-Aside (Lazy Loading)

This is the most common pattern and your default choice in an interview unless specific requirements dictate otherwise. The application logic is responsible for managing both the cache and the database.

  • Read Path:
    1. Application tries to read data from the cache.
    2. Cache Hit: Data is found and returned.
    3. Cache Miss: Application reads data from the database, writes it to the cache, and then returns it.
  • Write Path:
    1. Application writes directly to the database.
    2. Application invalidates (deletes) the corresponding entry in the cache.
A Guide to Caching Strategies
A visual representation of the Cache-Aside pattern. The left side shows the read path with a cache miss, and the right side shows the write path, where the application updates the database and invalidates the cache. Source: Alex Xu's "System Design Interview – An Insider's Guide".

Trade-offs:

  • Pros:
    • Resilient: The cache can be down, and the application will still function, albeit more slowly, by hitting the database directly.
    • Relevant Data: Only data that is actually requested is cached, keeping the cache from being filled with "cold" data.
  • Cons:
    • Higher Latency on Miss: A cache miss results in three distinct operations: cache read, database read, and cache write.
    • Data Inconsistency: There's a window of time between the database write and the cache invalidation where the cache can hold stale data. If another client reads from the cache during this window, it will get the old value.

Write-Through

In this pattern, writes go through the cache, which then synchronously writes to the database.

  • Read Path: Typically combined with Cache-Aside or Read-Through. The application reads from the cache.
  • Write Path:
    1. Application writes data to the cache.
    2. The cache synchronously writes the same data to the database.
    3. The operation is considered complete only after both the cache and database are updated.

Trade-offs:

  • Pros:
    • Strong Consistency: Data in the cache is never stale relative to the database after a write. Reads that follow a write are guaranteed to get the fresh data.
    • Simpler Application Logic: The application doesn't have to manage writing to two places.
  • Cons:
    • High Write Latency: The write operation must wait for both the cache write and the database write to complete, making it the slowest write pattern.
    • Cache Pollution: Every write goes to the cache, even if the data is rarely read again, potentially evicting more useful data.
    • Requires Specialized Library: Standard caches like Redis don't support this out of the box. You typically need a provider library or framework that orchestrates the write to the database.

Write-Behind (or Write-Back)

This pattern is similar to Write-Through, but the write to the database is asynchronous.

  • Read Path: Same as Write-Through (Cache-Aside or Read-Through).
  • Write Path:
    1. Application writes data to the cache.
    2. The application immediately gets an acknowledgment.
    3. The cache asynchronously writes the data to the database in the background, often in batches.

Trade-offs:

  • Pros:
    • Very Low Write Latency: Writes are extremely fast because the application only waits for the in-memory cache write.
    • High Write Throughput: Excellent for write-heavy workloads as it can absorb bursts and batch writes to the DB.
  • Cons:
    • Risk of Data Loss: If the cache fails before the data is persisted to the database, those writes are permanently lost. This is a significant risk.
    • Eventual Consistency: There is a period of inconsistency between the cache and the database until the asynchronous write completes.

Read-Through

The cache itself is responsible for reading from the database. The application only ever interacts with the cache.

  • Read Path:
    1. Application asks the cache for data.
    2. Cache Hit: Data is returned.
    3. Cache Miss: The cache itself fetches the data from the database, stores it, and then returns it to the application.
  • Write Path: Typically combined with Write-Through or Write-Behind.

Trade-offs:

  • Pros:
    • Clean Application Code: The application's data access logic is simplified; it just talks to the cache, abstracting the database away.
  • Cons:
    • Requires Specialized Library: Like Write-Through, this requires a cache provider that can be configured to connect to and query your database.
    • Less Flexible: The cache data model is often tied more closely to the database schema.

3. A Staff-Level Comparison: Choosing the Right Pattern

In a Staff+ interview, simply listing the patterns isn't enough. The real test is articulating the trade-offs and choosing the right tool for the job. Here's a comparative summary:

Pattern Write Latency Read-after-Write Consistency Data Loss Risk Implementation Complexity Best For
Cache-Aside Low (DB write only) Eventual Low Moderate (in application) Read-heavy workloads, general purpose. The default choice.
Write-Through High Strong Low High (requires library) Workloads needing strong consistency (e.g., bank ledgers, inventory).
Write-Behind Very Low Eventual High High (requires library) Write-heavy workloads where some data loss is acceptable (e.g., metrics, analytics).
Read-Through N/A (Depends on write pattern) (Depends on write pattern) High (requires library) Abstracting data sources; often seen with CDNs.

This table provides a great cheat sheet for mapping system requirements to the right caching strategy.

Caching Strategies by Scenario
This table connects common system design scenarios, such as the need for strong consistency or handling read-heavy workloads, to the most appropriate caching strategies. Source: Gaurav Sen

Example Justification:

  • Interviewer: "We're designing a social media feed. How would you cache the posts?"
  • Your thought process: A feed is read-heavy. It's okay if a new post appears with a slight delay (eventual consistency). Strong consistency isn't required. Data loss is unacceptable.
  • Your answer: "I would use a Cache-Aside pattern. When a user requests their feed, we'll first check Redis. If it's a miss, we'll query the database to assemble the feed, store it in Redis with a TTL of, say, 60 seconds, and return it. When a user creates a new post, we'll write it to the database and then send invalidation signals for the cached feeds of their followers. This approach is well-suited for a read-heavy system where eventual consistency is acceptable. Write-Through would introduce unnecessary write latency, and Write-Behind carries an unacceptable risk of losing new posts."

Conclusion

Understanding these core caching patterns and their associated trade-offs is fundamental to designing performant and resilient distributed systems.

Key Takeaways:

  • Four Core Patterns: Cache-Aside, Write-Through, Write-Behind, and Read-Through are the primary ways applications interact with caches and databases.
  • Responsibility Matters: The key differentiator is whether the application or the cache is responsible for communicating with the database.
  • Cache-Aside is the Default: It offers a good balance of performance, simplicity, and fault tolerance, making it the go-to pattern for many read-heavy systems.
  • Trade-offs are Paramount: The choice of pattern is a trade-off between write latency, data consistency, and risk of data loss. Your ability to articulate these trade-offs demonstrates senior-level thinking.
    • Need strong consistency? Tolerate high write latency with Write-Through.
    • Need low write latency? Accept the risk of data loss with Write-Behind.

Preview of the Next Lesson:
We've touched upon the problem of stale data and cache invalidation. In our next lesson, we will perform a deep dive on this topic, which is famously one of the "two hard things in computer science." We will analyze cache invalidation strategies (e.g., TTL-based, write-based) and their impact on data consistency.