📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Compare cache-aside, write-through and write-behind caching. How does each keep the cache and the database consistent, what goes wrong when a step fails, and when would you choose each in a .NET service?

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.

Mid-Level Theory Intermediate cache-aside caching consistency performance write-behind write-through

🎯 Key points

  • Cache-aside: app reads cache, loads from DB on miss and populates; on write, update DB then delete the key
  • Delete (invalidate) on write rather than update the cache, to avoid racing writers leaving stale values
  • Write-through: each write updates DB then cache in the same code path; reads after a write are warm and fast, writes slower
  • Write-through is not atomic: there is no transaction across SQL and Redis, so a failed cache set or racing writers can still leave stale data (use versions + TTL)
  • Write-behind: write to cache, persist to DB asynchronously; fast writes but data-loss window and eventual consistency
  • Failure between DB write and cache invalidation leaves stale data until TTL: the TTL is the safety net
  • Read-through is cache-aside with the loading inside the cache library (HybridCache GetOrCreateAsync)
  • Choose by read/write ratio, tolerance for staleness and tolerance for data loss

⏱ 30-second answer

  • Cache-aside (lazy loading): the app checks the cache, loads from the database on a miss and populates it; on a write it updates the database, then deletes the key. Simple and the default, but the first read after a change is slow and a failed delete leaves stale data until the TTL.
  • Write-through: every write goes to the database and the cache together, so reads are warm and consistent, at the cost of slower writes and caching data nobody reads.
  • Write-behind (write-back): writes land in the cache and are flushed to the database later, giving very fast writes but eventual consistency and a data-loss window if the cache fails.

I pick by read/write ratio, how much staleness is acceptable, and whether losing a write is ever acceptable.

🗣 Full answer (senior)

How I would answer this in an interview

"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 GetOrCreateAsync is 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."


The three strategies

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 modes

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

Production example

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%.

🔍 What the interviewer is checking

Checks that the candidate understands consistency and failure modes in caching, not just the definitions.

Green flags

  • Deletes rather than updates on write, and explains the race
  • Writes the database first
  • Treats the TTL as the staleness bound and mentions outbox for durable invalidation
  • Matches write-behind only to loss-tolerant data

Red flags

  • Thinks write-through is transactional
  • Uses write-behind for orders or payments
  • No TTL because of explicit invalidation

📚 Learn in depth

1. Cache-aside step by step

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.

2. The read-miss race

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.

3. Write-through mechanics

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.

4. Write-behind mechanics

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.

5. Making invalidation reliable

The DB commit and the cache delete are two systems with no shared transaction. Options, from simplest:

  1. Rely on TTL as the bound.
  2. Retry the delete with a short policy.
  3. Write an invalidation message to an outbox table in the same transaction; a relay publishes it and subscribers delete keys.
  4. Use change data capture from SQL Server to drive invalidation.

Try it yourself

  1. Write an integration test that runs two concurrent writers with update-the-cache and show the stale result; switch to delete and show it heals.
  2. Kill the process between SaveChangesAsync and RemoveAsync and observe staleness until TTL.
  3. Build a write-behind counter with Channel<T> and a BackgroundService that flushes every 5 seconds; measure SQL write count with Query Store.
  4. Measure first-read latency after a write for cache-aside vs write-through with k6.

💻 Code

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
        }
    }
}

⚠ Common mistakes

  • Mistake: Choosing a write strategy without measuring the read/write ratio. Why it is wrong: Write-through on write-heavy data caches values nobody reads and slows every write. Instead: Measure reads per write per key type (Application Insights or SQL Query Store), then choose.
  • Mistake: Micro-optimising cold paths with write-through. Why it is wrong: Rarely read data gains nothing from being pre-warmed. Instead: Use plain cache-aside or no cache.
  • Mistake: Updating the cache on write in cache-aside. Why it is wrong: Concurrent writers can leave the older value cached. Instead: Delete the key after the DB commit.
  • Mistake: Believing write-through is transactional. Why it is wrong: The database commit and the cache set are two separate operations; if the set fails or two writers interleave, the cache can hold an old value. Instead: Store a row version with the value, reject older writes, and keep a TTL.
  • Mistake: Writing the cache before the database. Why it is wrong: If the DB write fails, the cache serves data that never existed. Instead: Database first, cache second.
  • Mistake: No TTL because "we invalidate on write". Why it is wrong: A crash between commit and delete leaves stale data forever. Instead: Always keep a TTL as the safety net.
  • Mistake: Using write-behind for money, orders or anything you can't lose. Why it is wrong: A cache failure before flush loses committed-looking writes. Instead: Write to the database (or a durable queue) first.
  • Mistake: Write-behind entries with no TTL or with a TTL shorter than the flush interval. Why it is wrong: With no TTL, entries that fail to flush sit in Redis forever and memory grows; with a TTL shorter than the flush, Redis can evict or expire unflushed writes and they are silently lost. Instead: Keep unflushed data in a durable buffer (queue or persisted stream), set the cache TTL well above the flush interval, and alert on flush lag.
  • Mistake: Failing the user's write because the cache was unavailable. Why it is wrong: The cache is an optimisation; the DB write already succeeded. Instead: Log, rely on TTL, and alert.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions read-through or GetOrCreateAsync Why: Checks they can implement cache-aside with HybridCache and know its guarantees
    How to answer

    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).

    • Two levels: an in-process L1 (MemoryCache) and an optional L2, whatever IDistributedCache is registered (usually Redis).
    • Stampede protection: concurrent misses for the same key in one process share a single factory call.
    • Tags: entries can carry tags, and 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.

  2. When: Candidate mentions invalidating across instances Why: Checks they can propagate invalidation to several instances and a CDN
    How to answer

    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.

  3. When: Candidate mentions that the delete can fail after the commit Why: Checks they know the dual-write problem and the outbox or CDC fix
    How to answer

    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.

🛠 Real-world problems: how you handle them

Concurrent price updates leave the old price cached for hours
Situation
A retail pricing service used cache-aside with Redis but updated the cache on write instead of deleting it, with a [24-hour] TTL. A bulk import ran [8] parallel workers updating prices.
Signals
Customer complaints that checkout totals didn't match the product page; a reconciliation job flagged [~300] SKUs whose cached price differed from SQL; no errors in logs.
Investigation
Sampled mismatched SKUs and compared Redis values and timestamps with SQL `rowversion` and audit rows; Application Insights traces showed two workers updating the same SKU within milliseconds, with cache writes landing in the opposite order to DB commits.
Resolution
Immediate: flushed the affected keys with a script using `SCAN` and deleted them. Fix: switched writes to delete-after-commit, cut the TTL to [15 minutes], and stored the row version in the cached value so older writes are rejected on write-through paths.
Prevention
An integration test with concurrent writers asserting cache and DB agree; a nightly reconciliation sample with an alert on mismatches; a team guideline: database first, then delete, always with a 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.

↩ Usually asked after

More in Caching

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me