.NET › Caching (In-Memory, Distributed & Redis)

What is cache-aside (lazy loading) pattern, and how does it compare to write-through caching?

Intermediate

Answer

Cache-aside (the most common pattern) has the application check the cache first, and on a miss, load from the data source and populate the cache for next time -- the cache is only ever updated reactively on read misses. Write-through caching instead updates the cache synchronously every time data is written to the underlying store, guaranteeing the cache is never stale for writes that went through this path, at the cost of added write latency and more complex write-path code.
// Cache-aside (most common)
public async Task<Product> GetProductAsync(int id) {
    var cached = await _cache.GetAsync(id);
    if (cached != null) return cached;
    var product = await _db.GetProductAsync(id);
    await _cache.SetAsync(id, product);
    return product;
}

// Write-through: cache updated on every write, not just read-miss
public async Task UpdateProductAsync(Product product) {
    await _db.UpdateAsync(product);
    await _cache.SetAsync(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 ledger system uses write-through caching to guarantee the cache never briefly shows stale balance data after a transaction.

Common 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?