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.
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();$ 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 161.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.
- Step 1
1.Output cache: whole response comes back (Age header), endpoint code does not run
- Step 2
2.ETag matches If-None-Match: only 304 Not Modified, no body
- Step 3
3.HybridCache L1: product found in app memory
- Step 4
4.HybridCache L2: product found in Redis (shared by all servers)
- Step 5
5.Database: only when every layer misses (0.8 s query)
- Step 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).
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);});$ 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 queryResult: 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.
builder.Services.AddStackExchangeRedisCache(o => o.Configuration = "localhost:6379"); builder.Services.AddHybridCache(o => o.DefaultEntryOptions = new() { Expiration = TimeSpan.FromMinutes(5), LocalCacheExpiration = TimeSpan.FromMinutes(1) });$ docker exec c61-redis redis-cli KEYS '*'product:2$ docker exec c61-redis redis-cli TTL product:2298app.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);});$ 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 361.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).
builder.Services.AddOutputCache(); // ...app.UseOutputCache(); app.MapGet("/products", (ProductRepo repo, CancellationToken ct) => repo.AllAsync(ct)) .CacheOutput(p => p .Expire(TimeSpan.FromSeconds(60)) .Tag("products"));$ 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.005128s61.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.
$ 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)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();});$ 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- Step 1
1.PUT /products/1/price?price=249 updates the DB
- Step 2
2.cache.RemoveAsync("product:1") clears the HybridCache entry
- Step 3
3.Without more work the output cache still serves the old list (price 209)
- Step 4
4.store.EvictByTagAsync("products") removes every response tagged products
- Step 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.
// 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);$ 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.
builder.Services.AddResponseCompression(o =>{ o.EnableForHttps = true; o.Providers.Add<BrotliCompressionProvider>(); o.Providers.Add<GzipCompressionProvider>();}); // ...app.UseResponseCompression();app.UseOutputCache();$ 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 bytes61.9 Comparison: caching tools in ASP.NET Core
| Tool | What it stores | Where | Use it when |
|---|---|---|---|
| IMemoryCache | Data (objects) | App memory of one server | Single server; lost on restart |
| HybridCache (.NET 9+) | Data, L1 memory + L2 Redis | Memory + IDistributedCache | Multiple servers; gives stampede protection and tags |
| Output caching | Whole HTTP response | Server (output cache store) | Same response for many users; tag eviction |
| ETag + 304 | Nothing on server; version in header | Client keeps the body | Client already has the data; save bandwidth |
| [ResponseCache] | Nothing on server | Only sets Cache-Control | Browser/CDN caching (older code) |
| Response compression | Not a cache | On the wire | Large 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.
// 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.