SkillPilotAI

Caching and performance

Caching in ASP.NET Core means serving repeated reads from memory, Redis or a stored response instead of the database. Done right it takes a 0.8 s endpoint down to a few milliseconds and cuts the DB load; done wrong it serves stale or wrong data.

61.1 Why is it used?

  • In the demo every GET /products/1 runs a 0.8 s DB query, even though product data does not change every second.
  • 1000 users at once means 1000 identical queries hitting the database.
  • The fix is cache-aside: check the cache first, go to the DB only on a miss, then store the result.
  • Cached responses plus ETags and compression also cut bandwidth and response size.
C#
var builder = WebApplication.CreateBuilder(args);builder.Services.AddSingleton<ProductRepo>();var app = builder.Build(); app.MapGet("/products/{id:int}",    async (int id, ProductRepo repo) =>    {        var product = await repo.FindAsync(id);        return product is null            ? Results.NotFound()            : Results.Ok(product);    }); app.Run();
Output
$ curl -i -w "\ntime: %{time_total}s\n" localhost:5061/products/1{"id":1,"name":"Mixer Grinder 1","price":209,"version":1}time: 0.808062s# server loginfo: ProductRepo[0]      DB query: product 1info: ProductRepo[0]      DB query: product 1

61.2 How it works

  • IMemoryCache: data in the app process memory. Fast, but empty after a restart and one copy per server.
  • HybridCache (.NET 9+, recommended today): L1 memory + L2 Redis (IDistributedCache), tags, and stampede protection.
  • Output caching: stores the whole HTTP response, so the endpoint code does not even run.
  • ETag: a version string for the resource; if the client sends the same value in If-None-Match the server returns 304 with no body.
  • Response compression: Brotli/Gzip shrink text responses such as JSON.
Where a request is served from
  1. 1.Output cache: whole response comes back (Age header), endpoint code does not run

  2. 2.ETag matches If-None-Match: only 304 Not Modified, no body

  3. 3.HybridCache L1: product found in app memory

  4. 4.HybridCache L2: product found in Redis (shared by all servers)

  5. 5.Database: only when every layer misses (0.8 s query)

  6. 6.Response compression (br/gzip) shrinks whatever goes out

Each layer that answers saves the work of every layer below it

61.3 IMemoryCache

  • Register with AddMemoryCache, inject IMemoryCache.
  • GetOrCreateAsync checks the key; the factory (DB query) runs only on a miss.
  • The key contains the id ($"product:{id}") so every product gets its own entry.
  • Always set an expiration (here 60 s absolute).
C#
builder.Services.AddMemoryCache();app.MapGet("/products/{id:int}", async (int id,    IMemoryCache cache, ProductRepo repo) =>{    var product = await cache.GetOrCreateAsync(        $"product:{id}", entry =>        {            entry.SetAbsoluteExpiration(                TimeSpan.FromSeconds(60));            return repo.FindAsync(id);        });    return product is null        ? Results.NotFound()        : Results.Ok(product);});
Output
$ curl -i -w "\ntime: %{time_total}s\n" localhost:5061/products/1HTTP/1.1 200 OK{"id":1,"name":"Mixer Grinder 1","price":209,"version":1}time: 0.006626s# server log: only one DB query

Result: the first call runs the DB query, the second comes back in about 6 ms.

61.4 HybridCache with Redis

  • Problem with IMemoryCache: lost on restart, and 3 servers keep 3 separate copies.
  • AddStackExchangeRedisCache connects Redis as the shared L2 cache; AddHybridCache adds the L1 + L2 cache.
  • Expiration (5 min) is for the Redis copy, LocalCacheExpiration (1 min) for the memory copy, so Redis shows a TTL near 300 s.
  • GetOrCreateAsync checks memory, then Redis, and runs the DB query only when both miss.
  • tags: ["products"] lets you remove a whole group of entries at once.
  • After an app restart product 2 comes from Redis without a DB query.
  • Stampede protection: 10 concurrent requests for a new key run the DB query only once.
C#
builder.Services.AddStackExchangeRedisCache(o =>    o.Configuration = "localhost:6379"); builder.Services.AddHybridCache(o =>    o.DefaultEntryOptions = new()    {        Expiration = TimeSpan.FromMinutes(5),        LocalCacheExpiration =            TimeSpan.FromMinutes(1)    });
Output
$ docker exec c61-redis redis-cli KEYS '*'product:2$ docker exec c61-redis redis-cli TTL product:2298
C#
app.MapGet("/products/{id:int}", async (int id,    HybridCache cache, ProductRepo repo,    CancellationToken ct) =>{    var product = await cache.GetOrCreateAsync(        $"product:{id}",        async t => await repo.FindAsync(id, t),        tags: ["products"],        cancellationToken: ct);    return product is null        ? Results.NotFound()        : Results.Ok(product);});
Output
$ for i in $(seq 1 10); do    curl -s -o /dev/null localhost:5061/products/3 &  done; wait# server loginfo: ProductRepo[0]      DB query: product 3

61.5 Output caching

  • AddOutputCache in services, UseOutputCache in the pipeline, CacheOutput on the endpoint.
  • Here: 60 s expiration and the products tag on the list endpoint.
  • First call takes about 1 s; the second comes back in 5 ms with an Age header (response is 3 s old).
C#
builder.Services.AddOutputCache(); // ...app.UseOutputCache(); app.MapGet("/products",    (ProductRepo repo, CancellationToken ct) =>        repo.AllAsync(ct))   .CacheOutput(p => p       .Expire(TimeSpan.FromSeconds(60))       .Tag("products"));
Output
$ curl -i -w "\ntime: %{time_total}s\n" localhost:5061/productsHTTP/1.1 200 OKContent-Length: 11705Age: 3[{"id":1,"name":"Mixer Grinder 1","price":209,...time: 0.005128s

61.6 Invalidation: RemoveAsync and EvictByTagAsync

  • Checkpoint from the video: change product 1 price to 249, then GET /products. You still see 209.
  • Reason: RemoveAsync cleared only the HybridCache entry; the output cache kept its own copy of the list.
  • Fix: inject IOutputCacheStore and call EvictByTagAsync("products") after the update.
Output
$ curl -i -X PUT "localhost:5061/products/1/price?price=249"HTTP/1.1 204 No Content$ curl -s localhost:5061/products[{"id":1,"name":"Mixer Grinder 1","price":209,...# Age: 3  (stale list)
C#
app.MapPut("/products/{id:int}/price",    async (int id, decimal price,    ProductRepo repo, HybridCache cache,    IOutputCacheStore store,    CancellationToken ct) =>{    if (!repo.UpdatePrice(id, price))        return Results.NotFound();     await cache.RemoveAsync($"product:{id}", ct);    await store.EvictByTagAsync("products", ct);    return Results.NoContent();});
Output
$ curl -i -X PUT "localhost:5061/products/1/price?price=249"HTTP/1.1 204 No Content$ curl -i -w "\ntime: %{time_total}s\n" localhost:5061/productsHTTP/1.1 200 OK[{"id":1,"name":"Mixer Grinder 1","price":249,...time: 0.818889s
Price update and invalidation
  1. 1.PUT /products/1/price?price=249 updates the DB

  2. 2.cache.RemoveAsync("product:1") clears the HybridCache entry

  3. 3.Without more work the output cache still serves the old list (price 209)

  4. 4.store.EvictByTagAsync("products") removes every response tagged products

  5. 5.Next GET /products runs a fresh DB query and shows 249

61.7 ETag and 304 Not Modified

  • The ETag is built from the product version ("v2") and sent as a response header.
  • The client sends it back in If-None-Match; on a match the server returns 304 without a body.
  • When the price changes the version becomes v3, so the old ETag no longer matches and fresh data (200) comes back.
C#
// product comes from HybridCache (as before)if (product is null) return Results.NotFound(); var etag = $"\"v{product.Version}\"";http.Response.Headers.ETag = etag; if (http.Request.Headers.IfNoneMatch == etag)    return Results.StatusCode(304); return Results.Ok(product);
Output
$ curl -i localhost:5061/products/1HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8ETag: "v2"{"id":1,"name":"Mixer Grinder 1","price":249,"version":2} $ curl -i -H 'If-None-Match: "v2"' localhost:5061/products/1HTTP/1.1 304 Not ModifiedServer: KestrelETag: "v2" # after PUT price=279$ curl -i -H 'If-None-Match: "v2"' localhost:5061/products/1HTTP/1.1 200 OKETag: "v3"{"id":1,"name":"Mixer Grinder 1","price":279,"version":3}

61.8 Response compression

  • EnableForHttps = true, because compression is off by default over HTTPS.
  • Add Brotli and Gzip providers; UseResponseCompression goes before UseOutputCache.
  • The products list went from 11705 bytes to 1505 bytes with Accept-Encoding: br.
C#
builder.Services.AddResponseCompression(o =>{    o.EnableForHttps = true;    o.Providers.Add<BrotliCompressionProvider>();    o.Providers.Add<GzipCompressionProvider>();}); // ...app.UseResponseCompression();app.UseOutputCache();
Output
$ curl -s -D - -o /dev/null -H "Accept-Encoding: br" \    -w "size: %{size_download} bytes\n" localhost:5061/productsHTTP/1.1 200 OKContent-Encoding: brVary: Accept-Encodingsize: 1505 bytes

61.9 Comparison: caching tools in ASP.NET Core

ToolWhat it storesWhereUse it when
IMemoryCacheData (objects)App memory of one serverSingle server; lost on restart
HybridCache (.NET 9+)Data, L1 memory + L2 RedisMemory + IDistributedCacheMultiple servers; gives stampede protection and tags
Output cachingWhole HTTP responseServer (output cache store)Same response for many users; tag eviction
ETag + 304Nothing on server; version in headerClient keeps the bodyClient already has the data; save bandwidth
[ResponseCache]Nothing on serverOnly sets Cache-ControlBrowser/CDN caching (older code)
Response compressionNot a cacheOn the wireLarge text/JSON responses

61.10 Common mistakes

  • Cache key without the id: after product 1, a request for product 2 also returns the Mixer Grinder. The key must contain every value that changes the result.
  • No expiration on an entry: data can stay stale forever.
  • Clearing only one cache layer on update: the output cache keeps serving the old list.
  • Thinking [ResponseCache] caches on the server: it only sets Cache-Control for browsers/CDNs; server-side needs output caching.
  • Using a cache to hide a slow query: fix the query and index first, because every miss still runs it.
  • IMemoryCache on several servers: each server has its own, inconsistent copy.
C#
// Wrong: no id in the key, everyone gets product 1var product = await cache.GetOrCreateAsync(    "product", entry => { /* ... */ return repo.FindAsync(id); });// GET /products/2 -> {"id":1,"name":"Mixer Grinder 1",...} // Right: one entry per productvar product = await cache.GetOrCreateAsync(    $"product:{id}", entry => { /* ... */ return repo.FindAsync(id); });// GET /products/2 -> {"id":2,"name":"Steel Bottle 2",...}

61.11 Interview tips

  • "I use HybridCache for cache-aside: it combines memory and Redis and gives stampede protection."
  • Whole responses: output caching with tags, invalidated with EvictByTagAsync when data changes.
  • On GET return 304 with ETags; keep response compression on for large JSON.
  • Always mention invalidation and that you measure and fix slow queries before adding a cache.
  • Know that [ResponseCache] only sets headers; it is not a server cache.