Caching strategies and cache invalidation

Master caching architectures, from cache-aside to write-behind. Learn how to handle cache stampedes, avalanches, and the hardest problem in computer science: cache invalidation.

intermediate12 min readBy CureBugs EditorialUpdated 5 Nov 2026

Caching is the secret weapon of scalable system design. At its core, caching is about storing copies of frequently accessed data in a temporary, high-speed storage layer so that future requests for that data can be served faster. If you are building a system that needs to scale from thousands to millions of users, throwing more database servers at the problem will eventually bankrupt you. Caching is how you survive.

What it is and why it matters

In modern software architecture, reading from a disk-backed database (like PostgreSQL or MySQL) is heavily constrained by disk I/O and complex query execution times. Even with SSDs, a complex SQL join might take 50 to 200 milliseconds.

By contrast, reading from an in-memory cache like Redis or Memcached takes less than a millisecond.

Why does this matter?

  1. Latency: Users expect web pages and APIs to load in under 200ms. Caching drops data retrieval times by orders of magnitude.
  2. Throughput: A single Redis instance can handle over 100,000 read operations per second. A standard relational database might start choking at 5,000 to 10,000 complex queries per second.
  3. Cost: Database compute and IOPS (Input/Output Operations Per Second) are expensive. Offloading 80% of your read traffic to a cheaper in-memory cache significantly reduces your AWS or GCP bill.

How it works

The most common caching architecture involves placing a distributed cache layer between your application servers and your primary database.

When a request comes in, the application first checks the cache. If the data is present, it's a Cache Hit. If it's missing, it's a Cache Miss, and the application must fetch the data from the slower primary database, optionally writing it back to the cache for future requests.

Caching Strategies

There is no one-size-fits-all approach to caching. The strategy you choose depends heavily on whether your system is read-heavy or write-heavy, and how tolerant your users are to stale data.

Read Strategies

1. Cache-Aside (Lazy Loading) The application is responsible for reading and writing to the cache. The cache does not interact with the database directly. If there is a miss, the application fetches from the DB and updates the cache. This is the most common strategy.

2. Read-Through The cache sits directly in front of the database. The application only talks to the cache. If there is a cache miss, the cache provider itself is responsible for fetching the data from the database, storing it, and returning it to the application.

Write Strategies

1. Write-Through When the application writes data, it writes to the cache and the database simultaneously (or the cache writes to the DB synchronously). The write is only considered successful when both are updated.

2. Write-Behind (Write-Back) The application writes data only to the cache and immediately returns a success response to the user. An asynchronous process later flushes these cached writes to the primary database in batches.

3. Write-Around The application writes data directly to the database, bypassing the cache entirely. The cache is only updated on a read miss.

Strategy Comparison

StrategyProsConsBest Use Case
Cache-AsideSimple to build, cache failures don't break the app (fallback to DB).Stale data is possible, app code is cluttered with cache logic.General purpose, read-heavy systems (e.g., user profiles).
Read-ThroughClean application code, transparent caching.Harder to set up, requires cache provider to support DB integration.Systems where you want strict separation of concerns.
Write-ThroughData is always consistent between cache and DB.Higher write latency since you must write to two places.Systems needing strong consistency (e.g., banking balances).
Write-BehindExtremely fast writes, high throughput, handles traffic spikes well.High risk of data loss if the cache crashes before flushing to DB.High-volume, low-criticality writes (e.g., YouTube view counters).
Write-AroundPrevents cache pollution with data that is written but rarely read.Read latency is high for newly written data.Archival systems, logging, or write-once-read-rarely data.

Code Example: Cache-Aside Pattern

Here is how you would implement the most common pattern, Cache-Aside, in a real application. Notice how we handle the cache miss and explicitly set a Time-To-Live (TTL) to ensure data doesn't stay stale forever.

import json

def get_user_profile(user_id, cache, db):
    cache_key = f"user:{user_id}"
    
    # 1. Try fetching from cache
    cached_data = cache.get(cache_key)
    if cached_data:
        return json.loads(cached_data)
        
    # 2. Cache miss: fetch from database
    user_profile = db.query("SELECT * FROM users WHERE id = ?", user_id)
    
    if user_profile:
        # 3. Write to cache with a 1-hour TTL
        cache.set(cache_key, json.dumps(user_profile), ex=3600)
        
    return user_profile

Cache Invalidation and Eviction

Phil Karlton famously said, "There are only two hard things in Computer Science: cache invalidation and naming things."

When data changes in the database, the cache becomes stale. Cache invalidation is the process of removing or updating this stale data. If you get this wrong, users will see old prices on an e-commerce site or deleted messages in a chat app.

Invalidation Techniques

  1. Active Invalidation: When the application updates the database, it explicitly deletes (DEL) or updates the key in the cache.
  2. Passive Invalidation (TTL): Every key is given a Time-To-Live. After the TTL expires, the cache automatically deletes the key. The next request will trigger a cache miss and fetch fresh data.
  3. Change Data Capture (CDC): Tools like Debezium tail the database transaction logs (e.g., MySQL binlog). When a row changes, Debezium publishes an event to Kafka, and a separate consumer updates the cache. This decouples cache invalidation from application logic.

Eviction Policies

Caches have limited memory. What happens when Redis reaches its max memory limit? It must evict older keys to make room for new ones. Common policies include:

  • LRU (Least Recently Used): Evicts the keys that haven't been accessed for the longest time. This is the most popular and effective policy for web applications.
  • LFU (Least Frequently Used): Evicts keys with the lowest access count. Great if you have a clear set of "hot" items.
  • FIFO (First In, First Out): Evicts the oldest keys based on creation time, regardless of how often they are accessed.

Trade-offs and Failure Modes

In a system design interview, knowing how caches fail is what separates mid-level engineers from senior engineers.

1. Cache Penetration

The Problem: Malicious users or bugs repeatedly query for a key that does not exist in the database (e.g., user_id = -1). Because it's not in the DB, it never gets cached. Every request results in a cache miss and hits the database, potentially bringing the DB down. The Fix:

  • Cache Null Values: If a DB query returns empty, cache the empty result with a short TTL.
  • Bloom Filters: Place a Bloom filter in front of the cache. It can tell you with 100% certainty if an item does not exist, saving a database trip.

2. Cache Avalanche

The Problem: You deploy a new feature and cache 100,000 items at the exact same time with a TTL of 1 hour. Exactly one hour later, all 100,000 keys expire simultaneously. The next wave of requests results in massive cache misses, sending a tsunami of queries to the database and crashing it. The Fix: Add Jitter to your TTLs. Instead of exactly 3600 seconds, set the TTL to 3600 + random(0, 300) seconds. This spreads the expirations out over a 5-minute window.

3. Cache Stampede (Thundering Herd)

The Problem: A highly popular key (e.g., the live score of an India vs Pakistan cricket match) expires. In the millisecond it takes for the first request to fetch the new score from the DB and update the cache, 10,000 other requests arrive. They all see a cache miss and all 10,000 hit the database simultaneously to compute the same value. The Fix:

  • Mutex / Distributed Locks: When a cache miss occurs, the application must acquire a lock for that specific key before querying the DB. The other 9,999 requests wait for the lock, and by the time they get it, the cache is already populated.
  • Probabilistic Early Expiration (PERF): A background thread artificially recomputes and updates the cache before the actual TTL expires.

How it shows up in real systems

  • Twitter Timeline: Generating a timeline requires complex joins across users, followers, and tweets. Twitter uses massive Redis clusters to cache pre-computed timelines for active users. This is a form of Write-Behind/Push model.
  • Flash Sales (e.g., Flipkart Big Billion Days): Inventory counts are cached in Redis. When a user buys an item, the inventory is decremented in Redis using atomic operations (DECR), and the actual database is updated asynchronously to handle the massive write throughput.
  • Content Delivery Networks (CDNs): CDNs like Cloudflare are essentially globally distributed caches for static assets (images, JS, CSS) placed geographically closer to the user.

Interview Questions

1. How do you handle a cache stampede (thundering herd)?

Model Answer: I would use a distributed lock (like Redis Redlock). On a cache miss, a thread must acquire the lock for that specific key. Only the thread holding the lock queries the database and updates the cache. Other threads poll the cache again after a short delay. Alternatively, for extremely hot keys, I would use a background worker to refresh the cache asynchronously before the TTL expires.

2. What is the difference between Memcached and Redis?

Model Answer: Memcached is a simple, volatile, multi-threaded key-value store designed purely for string caching. Redis is single-threaded (historically) but offers rich data structures (Hashes, Sets, Sorted Sets, Bitmaps), persistence to disk, replication, and pub/sub capabilities. Today, Redis is the industry standard for almost all new system designs.

3. How do you guarantee absolute consistency between the cache and the database?

Model Answer: Absolute (strong) consistency is extremely difficult and usually defeats the performance benefits of caching. If forced, I would use a Write-Through cache combined with distributed transactions (Two-Phase Commit). However, in practice, we usually aim for eventual consistency using Change Data Capture (CDC) tools like Debezium to tail the DB logs and update the cache, ensuring the cache is never more than a few milliseconds behind.

4. When would you choose Write-Behind over Write-Through?

Model Answer: I would choose Write-Behind for systems with massive write volumes where data loss of a few seconds is acceptable, such as aggregating YouTube video views or collecting IoT sensor telemetry. I would choose Write-Through for critical data like financial transactions where we cannot risk losing the data if the cache node crashes before flushing to the DB.

5. How do you size a cache?

Model Answer: I calculate the size of a single cached object (e.g., a JSON user profile is ~1KB). Then I estimate the number of active items we need to keep in memory (e.g., 1 million Daily Active Users). $1KB \times 1,000,000 = 1GB$. I would then add a 20-30% buffer for Redis overhead and future growth, leading to a required cache size of roughly 1.3GB. I would configure an LRU eviction policy to handle any overflow.

6. What happens if the cache goes down entirely?

Model Answer: If the cache goes down in a Cache-Aside pattern, all traffic falls back to the primary database. This usually causes an immediate database crash due to the sudden spike in load. To mitigate this, I would implement circuit breakers in the application to fail fast and shed load, and ensure the cache is deployed as a highly available cluster with replication and automatic failover.

Common Mistakes in Interviews

  • Forgetting to mention TTLs: Interviewers will dock points if you design a cache without an expiration strategy. Data changes, and without a TTL, your system will serve stale data forever.
  • Caching everything: Caching is expensive. RAM costs significantly more per gigabyte than SSD storage. Only cache frequently accessed, read-heavy data.
  • Ignoring the "Hot Key" problem: If a single key (like a viral celebrity post) gets millions of hits, it will overwhelm the single Redis node holding that key (due to consistent hashing). The solution is to add a local in-memory cache (like Guava or Caffeine in Java) on the application servers themselves to absorb the localized spike.

Mock interview

Can you explain it when someone pushes back?

Interviewers rarely ask for a definition. They ask why you'd pick this over that, and what breaks at ten times the load. A mock round finds those gaps before the real one does.

  • A question on your own project, then a design problem
  • The interviewer probes the parts you skim over
  • A scored report that quotes your answers and says what to fix
Start a mock design round Voice or text. Pause whenever you need to.

Applying somewhere? Start with the company filled in

Go deeper elsewhere

The best material we've found on these topics.

Practise this

Reading builds understanding. Practice makes it stick.

Keep reading

All articles
Case studies•intermediate

Design a distributed rate limiter

10 min read
System design•intermediate

Rate limiting algorithms explained

14 min read
Case studies•intermediate

Design a URL shortener

11 min read