Distributed Caching with Redis in .NET: What We Invalidate Explicitly and What We Let Expire
When a .NET microservice adds a distributed caching layer with Redis, the first question gets settled quickly: how to read. Almost always with cache-aside, where the service checks Redis first and, on a miss, falls back to the database and writes the result back into the cache. The question that almost never gets the same care is the reverse one: when should a key be removed explicitly because the underlying data changed, and when is it fine to leave it alone and let the TTL do the work. Made without a consistent rule, that decision is exactly what produces the "I'm seeing stale data" reports that end up as a support ticket with no clear cause.
Two patterns, two different promises
Cache-aside is the default pattern because it is the simplest to implement and the one that tolerates a Redis outage best: if the cache goes down, the service keeps working against the database, just slower.
public async Task<ProductoDto> ObtenerProductoAsync(int id)
{
var clave = $"producto:{id}";
var cacheado = await _cache.GetStringAsync(clave);
if (cacheado is not null)
return JsonSerializer.Deserialize<ProductoDto>(cacheado)!;
var producto = await _db.Productos.FindAsync(id);
if (producto is null) return null;
var dto = ProductoDto.DesdeEntidad(producto);
await _cache.SetStringAsync(clave, JsonSerializer.Serialize(dto),
new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) });
return dto;
}
Cache-aside's promise is "eventually correct within the TTL window": if nobody invalidates the key, the data can be stale for up to ten minutes. For many data types that window is acceptable, and it is not worth complicating the write path just to close it.
Write-through makes the opposite promise: the cache should never hold stale data, because every write to the database updates the cache in the same flow, before the operation is confirmed to the caller.
public async Task ActualizarPrecioAsync(int productoId, decimal nuevoPrecio)
{
var producto = await _db.Productos.FindAsync(productoId);
producto.Precio = nuevoPrecio;
await _db.SaveChangesAsync();
var dto = ProductoDto.DesdeEntidad(producto);
await _cache.SetStringAsync($"producto:{productoId}", JsonSerializer.Serialize(dto),
new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) });
}
The cost of write-through is that every write now depends on the write to Redis also succeeding, or at least on an explicit decision about what to do if it fails. Neither pattern is better in the abstract: they solve different consistency problems, and mixing them without a per-data-type rule is exactly what produces inconsistencies nobody can later explain.
The rule we use to decide, key by key
The rule is not technical, it is a business one: how expensive is it, for this specific piece of data, for someone to see a stale version during the TTL window? For a product catalog where prices change a few times a day, a ten-minute TTL with no explicit invalidation is a small, acceptable risk window: plain cache-aside, no changes to the write path.
For a product price a salesperson just corrected after spotting a loading error, waiting ten minutes for the TTL to expire has a real cost: sales going out at the wrong price during that window. There, explicit invalidation after the write is not optional.
public async Task CorregirPrecioAsync(int productoId, decimal nuevoPrecio)
{
var producto = await _db.Productos.FindAsync(productoId);
producto.Precio = nuevoPrecio;
await _db.SaveChangesAsync();
await _cache.RemoveAsync($"producto:{productoId}");
}
Deleting the key instead of overwriting it with the new value is deliberate: the next read will recompute it from the database through the normal cache-aside path, instead of duplicating the same serialization logic that already exists on the read side inside the write path. It is one fewer failure mode to keep in sync, at the cost of one extra line of code.
The full rule we apply, data type by data type, is this: if the business cost of seeing a stale value during the TTL is low and predictable, we let it expire on its own. If that cost is high, unpredictable, or tied to a one-off human action like a price correction, we invalidate explicitly in the same flow as the write that changed it. What we never do is decide this for the convenience of the code at the moment of writing it: the question is always about the data, never about how much extra work the invalidation call takes to write.
What breaks when the two rules mix without a clear owner
The typical incident does not show up when a service uses pure cache-aside, nor when it uses pure write-through. It shows up when both coexist on the same key, written by different teams or flows, with no one clearly owning that key's consistency.
A real case of this pattern: the catalog service wrote prices with explicit invalidation, as in the example above. A bulk inventory import process, maintained by a different team, updated the Productos table directly through a batch-loading tool, bypassing the application code entirely, and therefore never calling RemoveAsync. The result was that, after every import, the cache kept serving pre-import prices for the rest of the active TTL, while the database already had the correct value. The symptom in production did not point at the cache at all: it looked like the import "hadn't taken effect," because nobody was comparing Redis directly against the database.
The underlying problem was not the TTL or the chosen pattern, it was that the key producto:{id} had two writers with different invalidation rules, neither aware of the other. Any writer that touches cached data — including batch processes, migration scripts, or scheduled jobs — has to invalidate the same key the application code invalidates, or the TTL silently becomes the only real guarantee, without anyone having decided that on purpose.
What didn't work the first time
The first attempt to fix that case was shortening the TTL on product keys to one minute, on the assumption that the inconsistency window would become irrelevant without having to touch the import process. It didn't work: with a catalog of several thousand frequently queried products, a one-minute TTL meant most reads went straight back to the database instead of the cache, because keys were expiring almost as fast as they filled up. We ended up with the worst of both options: the inconsistency during that one-minute window was still there, and we had also lost most of the benefit of having a cache in the first place.
What worked was setting the TTL back to a sensible value for the read pattern and, in parallel, adding an explicit invalidation call to the batch import process for every product it modified, using the exact same key the application code uses. Invalidation cannot be solved by shortening the TTL enough that the problem stops being noticeable — that only changes how often it happens, not whether it happens.
What we check before calling a caching layer done
Before considering a distributed caching layer finished, we list explicitly, for each cached data type, whether its invalidation is pure TTL or explicit invalidation after a write, and we write that decision down in the code or the service documentation, not only in the head of whoever implemented it. We review every possible write path for that data, including batch processes, migration scripts, and scheduled jobs that bypass the normal application code, because any one of them that skips invalidating the shared cache turns the TTL into the only real control, without anyone having chosen that on purpose. And we verify that, whenever two different services or processes can write the same underlying data, there is a single invalidation point for that key, instead of every writer reimplementing its own idea of when the cache should be cleared.