DataC# · TypeScript

Cache-Aside

The application checks the cache first, loads from the database on a miss, stores the result with a TTL, and invalidates it on writes.

On this page
  1. Problem
  2. Context
  3. Solution
  4. Implementation
  5. Trade-offs
  6. Alternatives
  7. Anti-patterns
  8. Related lessons
  9. Interview questions

Problem

Read-heavy workloads hit the database with the same queries over and over: the product page, the user profile, the configuration that changes once a week. Each read costs a network round trip, query planning and disk or buffer-pool access, and the database becomes the bottleneck long before the application servers do.

Adding read replicas helps but is expensive and still slower than memory. The data that matters most is usually a small hot set, and keeping it close to the application could absorb most of the read traffic.

Context

Use this pattern when:

  • Reads vastly outnumber writes, and a small fraction of keys receives most of the traffic.
  • Slightly stale data is acceptable for a bounded period (seconds to minutes).
  • The cache (Redis, Memcached, in-process memory) has no built-in knowledge of the database.
  • The system must keep working, more slowly, if the cache is empty or unavailable.

Solution

The application owns the caching logic. On a read it looks up the key in the cache. On a hit it returns the cached value. On a miss it reads from the database, writes the result into the cache with a time to live, and returns it. The cache only ever holds data that someone asked for, so it fills with the hot set naturally.

On a write, the application updates the database first and then deletes the cache entry, rather than writing the new value into it. Deleting is idempotent and avoids races where two concurrent writers leave the cache holding the older value. The next read repopulates the entry from the database.

The TTL is the safety net: if an invalidation is lost, the stale entry still expires. Popular keys need protection against stampedes, where many requests miss at once after expiry and all hit the database; a per-key lock, request coalescing or early probabilistic refresh solves this.

How it works, step by step

  1. 1Read: GET the key from the cache; return the value on a hit.
  2. 2On a miss, load the value from the database.
  3. 3SET the value in the cache with a TTL (plus a little random jitter), then return it.
  4. 4Write: update the database, then DELETE the cache key.
  5. 5Treat cache errors as misses so a cache outage degrades performance, not correctness.

Implementation

In .NET the read path fits IDistributedCache (backed by Redis); in Node the same logic uses a Redis client. Both examples coalesce concurrent misses within one process to limit stampedes.

C#Cache-aside with IDistributedCache
using System.Collections.Concurrent;
using System.Text.Json;
using Microsoft.Extensions.Caching.Distributed;

public sealed record Product(string Id, string Name, decimal Price);

public sealed class ProductService(IDistributedCache cache, IProductRepository db)
{
    private static readonly ConcurrentDictionary<string, SemaphoreSlim> Locks = new();

    public async Task<Product?> GetAsync(string id, CancellationToken ct)
    {
        var key = $"product:{id}";
        var cached = await TryGetAsync(key, ct);
        if (cached is not null) return JsonSerializer.Deserialize<Product>(cached);

        // Only one request per key per instance goes to the database.
        var gate = Locks.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));
        await gate.WaitAsync(ct);
        try
        {
            cached = await TryGetAsync(key, ct);
            if (cached is not null) return JsonSerializer.Deserialize<Product>(cached);

            var product = await db.FindAsync(id, ct);
            if (product is null) return null;

            var ttl = TimeSpan.FromMinutes(10) + TimeSpan.FromSeconds(Random.Shared.Next(0, 60));
            await cache.SetStringAsync(key, JsonSerializer.Serialize(product),
                new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = ttl }, ct);
            return product;
        }
        finally
        {
            gate.Release();
        }
    }

    public async Task UpdatePriceAsync(string id, decimal price, CancellationToken ct)
    {
        await db.UpdatePriceAsync(id, price, ct);   // 1. source of truth first
        await cache.RemoveAsync($"product:{id}", ct); // 2. then invalidate
    }

    private async Task<string?> TryGetAsync(string key, CancellationToken ct)
    {
        try { return await cache.GetStringAsync(key, ct); }
        catch (Exception) { return null; } // cache down: behave as a miss
    }
}

public interface IProductRepository
{
    Task<Product?> FindAsync(string id, CancellationToken ct);
    Task UpdatePriceAsync(string id, decimal price, CancellationToken ct);
}

.NET 9 adds HybridCache, which combines an in-memory and a distributed layer and includes stampede protection; the hand-rolled version above shows what it does for you.

TypeScriptCache-aside with Redis and in-flight coalescing
import { createClient } from 'redis';

type Product = { id: string; name: string; price: number };

const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

const inFlight = new Map<string, Promise<Product | null>>();
const TTL_SECONDS = 600;

export async function getProduct(id: string, db: { find(id: string): Promise<Product | null> }): Promise<Product | null> {
  const key = 'product:' + id;

  const cached = await redis.get(key).catch(() => null); // cache errors count as misses
  if (cached) return JSON.parse(cached) as Product;

  // Concurrent misses for the same key share one database read.
  const pending = inFlight.get(key);
  if (pending) return pending;

  const load = (async () => {
    try {
      const product = await db.find(id);
      if (product) {
        const ttl = TTL_SECONDS + Math.floor(Math.random() * 60);
        await redis.set(key, JSON.stringify(product), { EX: ttl }).catch(() => undefined);
      }
      return product;
    } finally {
      inFlight.delete(key);
    }
  })();
  inFlight.set(key, load);
  return load;
}

export async function updatePrice(id: string, price: number, db: { updatePrice(id: string, price: number): Promise<void> }) {
  await db.updatePrice(id, price);
  await redis.del('product:' + id);
}

Coalescing works per process. Across many instances, a short Redis lock (SET key NX PX) or serving slightly stale data while one worker refreshes protects the database from fleet-wide stampedes.

In production

  • Delete on write rather than update: two concurrent writers updating the cache can leave the older value in place.
  • Always set a TTL; it bounds staleness when an invalidation is missed and lets cold keys age out.
  • Add jitter to TTLs so keys written together do not all expire in the same second.
  • Consider caching "not found" results briefly to stop repeated lookups of missing keys from reaching the database.
  • Monitor hit ratio, latency and evictions; a falling hit ratio usually means the cache is too small or keys are too fine-grained.

Trade-offs

Benefits

  • Large reduction in database load and read latency for hot data.
  • Simple to add to existing code paths; the cache needs no database integration.
  • Resilient: if the cache fails, reads fall through to the database.
  • The cache holds only data that is actually requested.

Costs

  • Reads can return stale data until invalidation or TTL expiry.
  • Every miss costs three round trips (cache, database, cache write), so cold starts are slower than no cache at all.
  • Invalidation logic lives in application code and is easy to forget on a new write path.
  • Popular keys expiring can cause stampedes without extra protection.

Alternatives

Read-through cache
The cache library loads missing values itself through a configured loader, keeping application code simpler at the cost of coupling to the cache provider.
Write-through cache
Writes go to the cache and the database together, so reads are always warm, but every write pays both costs and rarely read data fills the cache.
Write-behind cache
Writes go to the cache and are flushed to the database asynchronously; very fast writes, but data can be lost if the cache fails before flushing.
Read replicas or materialised views
Scale reads inside the database layer when staleness must be tightly controlled or queries are too varied to cache by key.

Anti-patterns

Caching without a TTL
One missed invalidation leaves wrong data in the cache indefinitely.
Updating the cache before the database
If the database write then fails, the cache serves a value that never existed in the source of truth.
Treating the cache as the source of truth
Caches evict under memory pressure and lose data on restart; anything that must survive belongs in the database.
Synchronised expiry of hot keys
Identical TTLs set at startup make many keys expire together, sending a burst of misses to the database.

Interview questions

Why delete the cache entry on write instead of updating it?

If two writers update the database and then the cache, their cache writes can arrive in the opposite order, leaving the older value cached indefinitely. Deleting is idempotent and order-independent: the next read loads the current value from the database.

What is a cache stampede and how do you prevent it?

When a popular key expires, many concurrent requests miss simultaneously and all query the database. Prevent it with request coalescing or a per-key lock so one request reloads the value, by serving stale data while refreshing in the background, or by refreshing probabilistically before expiry.

How do you choose a TTL?

From the business tolerance for staleness and the cost of a miss. Prices or stock levels may need seconds; product descriptions can live for hours. Shorter TTLs reduce staleness but lower the hit ratio and raise database load.

Your cache cluster restarts. What happens to the database and how do you prepare?

The hit ratio drops to zero and every read reaches the database, which may not have capacity for full traffic. Prepare with stampede protection, rate limiting to the database, warming the hottest keys and capacity planning that accounts for a cold cache.