TechBuzzPro

Caching Strategies: Where Copies Live & Why Updates Go Stale

· 9 min read · Apps & Browsers

In this article
  1. What Is Caching and Why Do We Need It?
  2. Where Do Copies Live? The Main Cache Locations
  3. Why Do Updates Go Stale? The Root Causes
  4. Common Caching Strategies and How They Work
  5. How to Choose a Caching Strategy
  6. Common Problems and Pitfalls
  7. Costs and Trade-offs of Caching
  8. Alternatives to Caching
  9. Frequently Asked Questions

Caching strategies determine where copies of data are stored and how those copies are kept consistent with the original source. When a copy is updated in one place but not in another, the data becomes stale — a common problem in distributed systems. This article explains the main caching approaches, why staleness happens, and how to choose a strategy that balances performance with freshness.

What Is Caching and Why Do We Need It?

Caching is the practice of storing a copy of data in a faster or closer location than the original source. The goal is to reduce latency and network traffic by serving repeated requests from the cache instead of hitting the origin server or database every time. For example, a web browser stores images and scripts locally so that revisiting a page doesn't require downloading them again. Similarly, a CDN (Content Delivery Network) keeps copies of static assets in edge servers around the world, so users fetch them from a nearby location rather than a distant origin.

Caches are used at many levels: CPU caches, operating system page caches, DNS resolvers, HTTP caches, database query caches, and application-level caches like Redis or Memcached. Each level has its own trade-offs in terms of capacity, speed, and complexity. The core idea is always the same: trade some storage space for speed, and accept that the copy may not always be perfectly up-to-date.

Where Do Copies Live? The Main Cache Locations

Copies can live in several places, each with different characteristics:

  • Client-side caches – stored on the user's device (browser cache, mobile app cache). These are the closest to the user and the fastest, but they are also the hardest to invalidate because you don't control the client.
  • Edge caches (CDN) – stored in servers located at network edges, close to users geographically. They serve static and sometimes dynamic content, reducing load on the origin.
  • Reverse proxy caches – placed in front of an application server (e.g., Varnish, Nginx). They cache full responses or fragments to reduce server load.
  • In-memory caches (e.g., Redis, Memcached) – store key-value data in RAM for extremely fast access. Used for sessions, database query results, or computed values.
  • Database caches – some databases have built-in buffer pools or query caches that keep recently used data in memory.

The choice of where to put a cache depends on the data's volatility, the read-to-write ratio, and the acceptable staleness. For example, a product catalog that changes rarely might be cached aggressively at the edge, while a user's shopping cart must be nearly real-time and is better stored in a fast database or in-memory cache.

Why Do Updates Go Stale? The Root Causes

Staleness occurs when a cache copy is not updated after the original data changes. There are several reasons:

  • Time-based expiration (TTL) – the cache simply keeps the copy for a fixed period before checking for updates. This is simple but can serve outdated data until the TTL expires.
  • Lack of invalidation – the system doesn't notify the cache when the source changes. This happens when the cache is on a different server and the origin doesn't send a purge request.
  • Eventual consistency – in distributed databases, replicas may lag behind the primary. A cache reading from a replica might see an older version.
  • Race conditions – a write to the source and a cache update are not atomic. If the cache is updated before the source write commits, or vice versa, the cache might hold a value that was never the true state.
  • Partial updates – some caches store fragments or computed results. If the underlying data changes, the computed cache might not be recomputed unless explicitly triggered.

Staleness is often a trade-off: you can reduce it by shortening TTLs or implementing invalidation, but that increases load on the origin and reduces cache effectiveness.

Common Caching Strategies and How They Work

Several strategies exist to manage cache updates and staleness:

  • Cache-Aside (Lazy Loading) – the application checks the cache first; if missing, it fetches from the source, stores the result in the cache, and returns it. On writes, the application updates the source and invalidates the cache entry. This is simple and popular, but the first read after a write may be slow (cache miss).
  • Write-Through – the application writes to the cache and the source simultaneously (or the cache writes through to the source). This ensures the cache is always fresh, but adds latency to writes and can be wasteful if data is rarely read.
  • Write-Behind (Write-Back) – writes go to the cache first, and the cache asynchronously writes to the source later. This gives fast writes but risks data loss if the cache fails before the write is persisted.
  • Time-To-Live (TTL) – each cache entry has an expiration. After TTL, the entry is considered stale and is refreshed on the next read. This is a simple way to bound staleness.
  • Event-Driven Invalidation – when the source changes, it emits an event (e.g., a message queue) that triggers cache removal or update. This keeps staleness low but requires infrastructure.

Many systems combine these: use TTL as a safety net, and add invalidation for critical data. For example, a social media feed might use TTL of 5 minutes, but when a user posts, the system purges their feed cache immediately.

How to Choose a Caching Strategy

Choosing a strategy involves balancing freshness, performance, and complexity. Consider these factors:

  • Read-to-write ratio – if data is read often and written rarely, a long TTL or aggressive caching works well. If writes are frequent, you need faster invalidation.
  • Data volatility – how often does the data change? Stock prices change constantly; a user's profile changes rarely.
  • Acceptable staleness – can users see slightly old data? For a news article, a few minutes is fine; for a bank balance, it's not.
  • Consistency requirements – do you need strong consistency (always the latest) or is eventual consistency acceptable?
  • Infrastructure complexity – event-driven invalidation requires message brokers or pub/sub, which adds operational overhead.
  • Cost – caching reduces load on the origin, but adds storage and maintenance costs.

A common approach is to start with TTL-based caching, measure staleness, and then add invalidation for the most critical paths. For example, an e-commerce site might cache product pages for 10 minutes, but invalidate the cart cache immediately on any cart change.

Common Problems and Pitfalls

Even with a good strategy, caching can introduce issues:

  • Cache stampede – when a popular cache entry expires and many requests hit the origin simultaneously. Solution: use request coalescing or a lock.
  • Cache poisoning – if a cache stores a corrupted or malicious response, it can serve it to many users. Validate data before caching.
  • Thundering herd – similar to stampede, but for writes: many clients updating the same key at once, causing contention.
  • Stale data in long-lived connections – WebSocket or server-sent events might keep a connection open, and the client may not re-fetch the cache.
  • Cache invalidation is hard – the old adage “there are only two hard things in computer science: cache invalidation and naming things” is true. Invalidation requires knowing all cache locations and notifying them all.

Another common mistake is assuming that a cache is always consistent. For example, a CDN might serve a stale JavaScript file after a new deployment because the cache wasn't purged. This is why many sites use versioned filenames (e.g., app.12345.js) to force cache misses on new releases.

Costs and Trade-offs of Caching

Caching is not free. The main costs are:

  • Storage – caches consume RAM or disk. In-memory caches are expensive per GB.
  • Complexity – adding a cache layer means more components to operate, monitor, and debug.
  • Staleness risk – the less often you refresh, the more stale the data can be, which can lead to user-facing errors or inconsistencies.
  • Operational overhead – invalidation mechanisms, monitoring cache hit rates, and handling cache failures all require effort.

On the other hand, the benefits often outweigh the costs: reduced latency, lower bandwidth usage, and less load on databases and origin servers. A well-tuned cache can handle a large percentage of read traffic without hitting the origin, improving scalability and user experience.

Alternatives to Caching

Sometimes caching is not the right solution. Alternatives include:

  • Database indexing and query optimization – if reads are slow, fixing the database might be better than adding a cache.
  • Read replicas – distribute read load across multiple database replicas, each with its own copy of the data. This is a form of caching but at the database level.
  • Content pre-generation – generate static files in advance (e.g., a static site generator) instead of caching dynamic responses.
  • Streaming or push updates – instead of clients polling for changes, push updates via WebSockets or server-sent events, reducing the need for caching.
  • Data denormalization – store redundant data in a form that avoids expensive joins, reducing the need for computed caches.

In practice, most large systems use a combination of these: a CDN for static assets, an in-memory cache for hot data, and database replicas for read scaling. The key is to understand the data's access patterns and choose the right tool for each layer.

Frequently Asked Questions

What is the difference between cache invalidation and cache expiration?

Cache invalidation is an explicit action that removes or updates a cache entry when the source changes, often triggered by an event or a write operation. Cache expiration is a time-based mechanism where entries are considered stale after a TTL and are refreshed on the next access. Invalidation aims to keep data fresh immediately, while expiration bounds staleness by time.

How do CDNs handle cache invalidation?

CDNs typically support cache purging via an API or control panel. You can purge a specific URL, a directory, or the entire cache. Some CDNs also support cache tags, allowing you to invalidate all objects with a certain tag (e.g., all product pages). Purging is immediate but can be expensive if done frequently, so many sites rely on TTLs and only purge on major updates.

What is a cache stampede and how do you prevent it?

A cache stampede occurs when a popular cache entry expires and many concurrent requests miss the cache, all hitting the origin simultaneously, causing a spike in load. To prevent it, you can use request coalescing (only one request fetches from the origin, others wait), a lock or mutex, or a longer TTL with background refresh. Another technique is to use a “stale-while-revalidate” pattern, where the stale entry is served while a background job refreshes the cache.

Is it better to use a short TTL or event-driven invalidation?

It depends on how critical freshness is and how often the data changes. If data changes rarely, a short TTL (e.g., 1 minute) is simple and sufficient. If data changes frequently and staleness is unacceptable (e.g., a user's session), event-driven invalidation is better because it updates the cache immediately after a write. However, event-driven invalidation requires more infrastructure, such as a message queue or pub/sub system.

What is the “stale-while-revalidate” caching strategy?

Stale-while-revalidate is a strategy where the cache serves the stale (old) version of the data immediately, while asynchronously fetching the fresh version from the origin. Once the fresh version is retrieved, it replaces the stale entry. This gives users low latency and reduces the chance of a stampede, but the user might see slightly outdated data for a short period. It's commonly used in HTTP caching and CDNs.

Can caching cause data loss?

Yes, especially with write-behind caching. If the cache writes to the source asynchronously and the cache server crashes before the write is flushed, that data can be lost. To mitigate this, you can use write-through caching (which is slower but safer) or add durability mechanisms, such as persisting the write queue to disk. For read-only caches, data loss is not an issue, but stale data can be served.