Advertisement
Advanced ASP.NET Core, Caching

How would you implement cache-aside versus write-through caching patterns for a frequently-read, occasionally-written resource?

Short answer

Cache-aside (most common) checks the cache first and, on a miss, loads from the data source and populates the cache reactively -- appropriate for read-heavy workloads.

Save ASP.NET Core mock interview
Advertisement
AModel answer
Cache-aside (most common) checks the cache first and, on a miss, loads from the data source and populates the cache reactively -- appropriate for read-heavy workloads. Write-through caching instead updates the cache synchronously on every write, guaranteeing the cache is never stale for writes that went through that path, at the cost of added write latency and more complex write-path code -- the right choice depends on whether staleness-until-next-read (cache-aside) or guaranteed freshness (write-through) matters more for the specific resource.
// Cache-aside (most common)
public async Task<Product> GetProductAsync(int id) {
    var cached = await _cache.GetAsync<Product>($"product-{id}");
    if (cached is not null) return cached;
    var product = await _db.GetProductAsync(id);
    await _cache.SetAsync($"product-{id}", product);
    return product;
}

// Write-through: update cache immediately on write
public async Task UpdateProductAsync(Product product) {
    await _db.UpdateAsync(product);
    await _cache.SetAsync($"product-{product.Id}", product);  // cache updated immediately
}
Real-world example
A read-heavy product catalog uses cache-aside since reads vastly outnumber writes, while a financial account balance endpoint uses write-through caching to guarantee the cache never briefly shows stale balance data after a transaction.
Likely follow-ups
  • What is write-behind (write-back) caching and when is it appropriate?
  • How does cache-aside handle the stampede problem differently than write-through?
Related topics