The three main caching write strategies (cache-aside, write-through, write-behind), their consistency guarantees, failure modes and race conditions, and where read-through fits, with .NET examples.
I pick by read/write ratio, how much staleness is acceptable, and whether losing a write is ever acceptable.
"These are really three answers to one question: when the data changes, who updates the cache and when? With cache-aside the application owns everything. On a read it checks the cache, and on a miss it loads from SQL and puts the result in the cache with a TTL. On a write it updates the database and then deletes the cache key, so the next read reloads. In .NET, HybridCache's
GetOrCreateAsyncis the read side of that, which people sometimes call read-through because the loading sits inside the cache call.Write-through means every write updates both the database and the cache as part of the same operation, so readers always find a fresh, warm entry. It suits small, very read-heavy data like configuration or a product's price that is read thousands of times per write. Write-behind flips the order: the write goes to the cache, and a background process persists it to the database later, often batched. That makes writes very fast and absorbs bursts, think view counters or telemetry, but if the cache node dies before the flush you lose writes, and the database is behind.
The mistake I see is updating the cache on write instead of deleting the key. Two concurrent writers can finish in the opposite order to their database commits, and the cache ends up holding the older value with no expiry in sight. Deleting is idempotent and self-healing. I also never trust the invalidation step alone: if the process crashes after the database commit, the delete never happens, so the TTL is my upper bound on staleness. Where that bound must be tight, I publish the invalidation through an outbox so it survives a crash."
| Cache-aside | Write-through | Write-behind | |
|---|---|---|---|
| Who loads the cache | App, on miss | Write path | Write path |
| Read after write | Miss, then reload | Hit, fresh | Hit, fresh (in cache) |
| Write latency | DB + delete | DB + cache | Cache only |
| Consistency | Stale until delete or TTL | Strong-ish (two writes can still partly fail) | Eventual; DB lags |
| Data-loss risk | None (DB first) | None (DB first) | Yes, until flushed |
| Caches unread data | No | Yes | Yes |
| Typical .NET tool | HybridCache GetOrCreateAsync + RemoveAsync |
Service writes DB then SetAsync |
Channel/queue + background BackgroundService |
| Failure | Cache-aside | Write-through | Write-behind |
|---|---|---|---|
| Crash after DB commit | Stale until TTL | Stale until TTL | n/a |
| Cache down | Reads fall back to DB | Writes must not fail because of cache | Writes lost or blocked |
| Racing writers | Safe if you delete | Can store older value; use versions | Last flush wins |
A product-pricing service used write-through for prices (read ~5,000 times per write) and cache-aside for product descriptions. Moving prices from cache-aside to write-through removed the post-update latency spike, where p99 on the first reads after a bulk price import jumped to 900 ms, and kept p99 under 60 ms. View counts used write-behind with a 10-second flush, cutting SQL writes by about 95%.
Checks that the candidate understands consistency and failure modes in caching, not just the definitions.
Green flags
Red flags
READ: app -> cache.get(k) --hit--> return
\--miss--> db.query -> cache.set(k, v, ttl) -> return
WRITE: app -> db.update -> cache.delete(k)
Why delete, not set? Consider writers A and B:
A: db.update(v1) B: db.update(v2)
B: cache.set(v2)
A: cache.set(v1) <- cache now holds v1, DB holds v2
With delete, the worst case is an extra miss.
Even with delete there's a narrow race: reader R misses, reads v1 from the DB, writer W updates to v2 and deletes the key, then R writes v1 into the cache. Mitigations: short TTLs, versioned values (store a row version and refuse older writes), or a delayed second delete. In most business systems the TTL bound is acceptable.
The write path updates the DB, then sets the cache (DB first, so a cache failure never loses data). If the set fails, log it and delete the key or rely on the TTL. With multiple writers, include a version or rowversion so an older write can't overwrite a newer one.
write -> cache (and/or in-memory buffer) -> Channel<T> -> BackgroundService
-> batch every N items or T seconds -> bulk upsert to SQL
You need: durability for the buffer (Redis with persistence, or a queue like Azure Service Bus), idempotent upserts, back-pressure when SQL is slow, and a flush on graceful shutdown (StopAsync). It's an architectural commitment, not a cache setting.
The DB commit and the cache delete are two systems with no shared transaction. Options, from simplest:
SaveChangesAsync and RemoveAsync and observe staleness until TTL.Channel<T> and a BackgroundService that flushes every 5 seconds; measure SQL write count with Query Store.Cache-aside and write-through with HybridCache, plus a minimal write-behind buffer.
using System.Threading.Channels;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.Hosting;
namespace Pricing.Caching;
public sealed record Price(string Sku, decimal Amount, long Version);
public interface IPriceStore
{
Task<Price?> GetAsync(string sku, CancellationToken ct);
Task<Price> SaveAsync(string sku, decimal amount, CancellationToken ct); // returns new version
Task IncrementViewsAsync(IReadOnlyDictionary<string, int> counts, CancellationToken ct);
}
public sealed class PriceService(HybridCache cache, IPriceStore store)
{
private static string Key(string sku) => $"price:v1:{sku}";
// Cache-aside read (read-through via GetOrCreateAsync).
public ValueTask<Price?> GetAsync(string sku, CancellationToken ct) =>
cache.GetOrCreateAsync(Key(sku), (store, sku),
static async (s, token) => await s.store.GetAsync(s.sku, token),
cancellationToken: ct);
// Cache-aside write: DB first, then invalidate. TTL bounds staleness if the delete is lost.
public async Task UpdateWithInvalidateAsync(string sku, decimal amount, CancellationToken ct)
{
await store.SaveAsync(sku, amount, ct);
await cache.RemoveAsync(Key(sku), ct);
}
// Write-through: DB first, then put the fresh value so readers never miss.
public async Task UpdateWithWriteThroughAsync(string sku, decimal amount, CancellationToken ct)
{
var saved = await store.SaveAsync(sku, amount, ct);
await cache.SetAsync(Key(sku), saved, cancellationToken: ct);
}
}
// Write-behind: fast in-memory capture, batched persistence. Acceptable only for loss-tolerant data.
public sealed class ViewCounter(IPriceStore store) : BackgroundService
{
private readonly Channel<string> _views = Channel.CreateBounded<string>(
new BoundedChannelOptions(100_000) { FullMode = BoundedChannelFullMode.DropOldest });
public void Record(string sku) => _views.Writer.TryWrite(sku);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(10));
while (await timer.WaitForNextTickAsync(stoppingToken))
{
var batch = new Dictionary<string, int>();
while (_views.Reader.TryRead(out var sku))
batch[sku] = batch.GetValueOrDefault(sku) + 1;
if (batch.Count > 0)
await store.IncrementViewsAsync(batch, stoppingToken); // one round trip per flush
}
}
}
The senior framing is that every strategy is a choice about who pays for consistency: readers (cache-aside pays on the first miss), writers (write-through pays on every write), or durability (write-behind risks losing data). None gives you a transaction across the database and the cache, so I always define the staleness bound (the TTL) explicitly and, where it must be tight, make invalidation durable with an outbox.
| Strategy | When it fits | Cost | When not to |
|---|---|---|---|
| Cache-aside | Default; read-heavy data with tolerable brief staleness | Miss after every change; stale until delete/TTL | Data read immediately after write by many users |
| Write-through | Very read-heavy, small data that must be warm | Slower writes; caches unread data | Write-heavy or large datasets |
| Write-behind | High-rate, loss-tolerant writes (counters, telemetry) | Data-loss window; complex flush/back-pressure | Financial, order or audit data |
Measure: first-read latency after a write, stale-read rate (compare cached version to DB version in a sample), and SQL writes per second before and after.
HybridCache (Microsoft.Extensions.Caching.Hybrid, GA March 2025, works on .NET 8+) replaces hand-written cache-aside code with one call: GetOrCreateAsync(key, factory, options, tags, ct).
MemoryCache) and an optional L2, whatever IDistributedCache is registered (usually Redis).RemoveByTagAsync invalidates them as a group.I prove it by counting source calls and measuring p95 under a k6 load test before and after. The trade-off: protection and L1 invalidation are per process, so I keep L1 lifetimes short when data changes.
Use a shared output cache store (Redis) so EvictByTagAsync clears every instance, not just the one that handled the write. At the CDN, keep s-maxage short or purge by path through the CDN API (an Azure Front Door purge can take minutes). For data that must change quickly, avoid purging altogether: content-hash or versioned URLs (/catalogue?v=42) make the new version a new cache key, and ETags let clients revalidate cheaply with If-None-Match and get 304 when nothing changed. Decide the acceptable staleness per endpoint; stale-while-revalidate keeps responses fast while the edge refreshes, and the client should re-read after its own write so users see their change.
The commit and the delete are a dual write with no shared transaction, so a crash between them leaves stale data. Keep a TTL as the upper bound on staleness, then make invalidation durable with the transactional outbox pattern: write an invalidation message to an outbox table in the same transaction as the data change, and have a relay (a BackgroundService or Azure Functions) publish it, retrying until subscribers have deleted the keys. Deletes are idempotent, so at-least-once delivery is fine. Alternatives: change data capture on SQL Server driving deletes, domain events in an event-driven design, or versioned keys, where the change bumps a version so new reads use a new key and old entries simply age out under their TTL.
How to tell it (STAR)
**S:** At [company] customers saw one price on the product page and another at checkout after a bulk price import. **T:** I had to find why the cache disagreed with the database and stop it recurring. **A:** I compared cached values against SQL row versions and traced the import in Application Insights, and found parallel workers updating the cache in the opposite order to their database commits. I flushed the bad keys, changed writes to delete-after-commit with a shorter TTL, and added a concurrency test. **R:** Mismatches went from [~300 per import] to [zero over the next quarter], and the price-related support tickets stopped.
Last updated 23 Nov 2026.