الانتقال إلى المحتوى
Software ArchitectureSystem Design· 7 دقائق للقراءة

A Cache Is Not Just a Faster Copy: Staleness, Invalidation and Cache-Aside Races

Every cache is a second copy that can drift from the database. Decide how stale each value may be, and keep old copies from overwriting new ones.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

A merchant raises a product's price from 80 to 100 and saves. The admin screen shows 100. For the next five minutes, some shoppers still see 80 on the product page, then pay 100 at checkout, which reads the database. The team checks the code: every save removes the product's cache key, exactly as the cache-aside pattern says. The stale price showed up anyway, and only under real traffic.

The common misconception

The belief: adding a cache is a pure performance win. It returns the same data, just faster, so it can't change what users see.

It's a reasonable belief. Microsoft's caching guidance opens with the upside: "Caching can dramatically improve performance, scalability, and availability." For data that rarely changes, it really is close to free. In development, with one user clicking one page at a time, the cache never serves anything wrong, and invalidation code that removes the key on every save looks complete.

Engineers have long known better, though. Martin Fowler's bliki keeps a favorite saying attributed to Phil Karlton: "There are only two hard things in Computer Science: cache invalidation and naming things."

What actually happens

A cache is a snapshot

Microsoft's guidance puts it plainly: "Think of a cache as a snapshot of the original data at some point in the past." From the moment a value is cached, the database can move on without it. A bounds how long a stale copy can live, and choosing it is a trade: "If you make it too short, objects expire too quickly and you reduce the benefits of using the cache. If you make the period too long, you risk the data becoming stale."

Every server holds its own copy

An in-memory cache such as IMemoryCache is private to one process. With several instances behind a load balancer, "each application instance has its own independent cache that holds its own copy of the data", and the same query on two instances can return different results. A save handled by server A removes A's entry only; server B keeps serving its copy until it expires. A shared cache such as Redis removes that particular problem, but not the next one.

Invalidate on write still leaves windows

says: read from the cache, load from the database on a miss and store the result, and on a write update the database and then remove the cached entry. Microsoft is honest about what that buys: "The Cache-Aside pattern doesn't guarantee consistency between the data store and the cache." Even in the right order, "Between the write and the next read, a reader can experience a cache miss or briefly see stale data."

The race: an old value written back

The window can last for the whole TTL. Here is the behind the price bug:

  1. A shopper's request misses the cache and loads the product: price 80.
  2. Before that request stores it, the merchant's save commits price 100.
  3. The save removes the cache key. Nothing is cached yet, so there's nothing to remove.
  4. The shopper's request finishes and stores 80. The database says 100; the cache says 80 until the entry expires.

Facebook's memcache paper calls this a stale set: "A stale set occurs when a web server sets a value in memcache that does not reflect the latest value that should be cached. This can occur when concurrent updates to memcache get reordered." Nothing in the cache-aside code prevents it, because the read and the write-back aren't one step.

The fix: let the newer version win

C# Products.cs
public sealed class Products(IMemoryCache cache, IProductStore db){    public async Task<Product?> GetAsync(int id)    {        if (cache.TryGetValue(id, out Product? hit)) return hit;        var p = await db.LoadAsync(id);     // 1. miss: loads price 80        if (p is not null)                  // 4. writes back the old 80            cache.Set(id, p, TimeSpan.FromMinutes(5));        return p;    }    public async Task SetPriceAsync(int id, decimal price)    {        await db.SavePriceAsync(id, price); // 2. commits 100        cache.Remove(id);                   // 3. nothing cached yet    }}// The database says 100; the cache says 80 for the next 5 minutes

Every product row carries a version that increases on each save, and both sides now offer their copy instead of blindly setting or removing it. The writer stores the version it just saved, the reader stores the version it loaded, and whichever is newer stays, in either order. The shopper's late 80 (version 1) arrives after the merchant's 100 (version 2) and is rejected. Offering the same version twice changes nothing, so the operation stays safe to repeat; Facebook chose deletes over updates for that reason and closed the race with leases instead.

The trade-offs are real. The writer must know the new version, usually from a version column the database maintains. One lock serializes every cache write in the process, which suits low write volumes. If memory pressure evicts the newer entry before the old one arrives, the window opens again, which is why the TTL stays. And across servers a process lock means nothing: with Redis the compare must happen in the cache itself, for example with the WATCH/MULTI/EXEC transactions Microsoft describes, which Redis discards "If any watched key changes before the transaction starts".

StrategyWhat readers may seeCost
TTL onlyOld values for up to the TTL after a changeMore misses when the TTL is short
Invalidate on writeBrief stale reads, plus the write-back raceSimple write path
Write-throughThe new value right after a successful writeHigher write latency, more coordination
Version-guarded writesOld copies can't replace newer onesVersions and an atomic compare in the cache
No cacheAlways the current valueEvery read hits the database

How to apply it in your project

  1. List what you cache and how stale it may beFor each cached value, write down who reads it and how old it may safely be. That number becomes its TTL.
  2. Check every path that changes the dataMake sure each write updates the database before touching the cache, and find writers that bypass your code, such as jobs, other services or manual fixes.
  3. Close the race where staleness hurtsFor values where an old copy causes real damage, add a version and let only newer versions into the cache, with the compare done atomically.
  4. Read critical values from the sourceKeep decisions that move money or stock on the database, and keep a TTL on every cache entry as the last line of defense.

Key takeaways

  • A cache is a second copy of your data; staleness is its normal state, bounded only by expiry and invalidation.
  • Each server's in-memory cache is its own copy, so a write on one server doesn't reach the others.
  • Cache-aside has a race: a slow reader can write an old value back after the writer removed the key.
  • Version-guarded writes let the newer copy win in either order, at the cost of versions and an atomic compare.
  • Give every cached value a staleness budget and a TTL, and read critical values from the source.

📚 المصادر

  1. Caching guidance — Azure Architecture Center, Microsoft Learn
  2. Cache-Aside pattern — Azure Architecture Center, Microsoft Learn
  3. Scaling Memcache at Facebook — Nishtala et al., NSDI 2013
  4. TwoHardThings — Martin Fowler, bliki

التعليقات (0)