Lesson 25 / 26
Performance Habits
Apply async I/O, response caching and compression and measure before optimising.
Measure first
Most slow APIs are slow because of the database or a remote call, not C#. Fix N+1 queries, add indexes, use async everywhere, and only then consider caching. Guessing without measuring wastes time.
Output caching and compression
Cache a read-heavy, rarely changing endpoint for 30 seconds and compress responses. Never cache user-specific data under a shared key.
builder.Services.AddOutputCache();
builder.Services.AddResponseCompression();
var app = builder.Build();
app.UseResponseCompression();
app.UseOutputCache();
app.MapGet("/catalog", () => Catalog.LoadAll())
.CacheOutput(p => p.Expire(TimeSpan.FromSeconds(30)));Use health checks
Map app.MapHealthChecks("/healthz") so load balancers and Kubernetes can tell whether your app is alive. Add structured logging and metrics (OpenTelemetry) so you can see problems before users report them.
Quick check: What should you do before adding caching to a slow endpoint?
- Rewrite it in another language
- Turn off logging
- Add more middleware
- Measure to find the real bottleneck
Answer
Measure to find the real bottleneck — Profiling or query logs usually show the real cause, such as an N+1 query, which caching would only hide.