I approach API performance by measuring first, then fixing the biggest bottlenecks across database, application and network layers. Measure - Track p95 and p99 latency, throughput and error rates per endpoint (Application Insights, OpenTelemetry, Prometheus). - Distributed tracing to see where time is spent: database, external calls or application code. - Load test realistic scenarios (k6, JMeter, Azure Load Testing) and profile CPU and memory (dotnet-trace, dotnet-counters). Database (usually the biggest win) - Proper indexes, efficient queries and projections (only needed columns), avoiding N+1 queries. - AsNoTracking for read-only EF Core queries; pagination for lists; keyset pagination for large datasets. - Connection pooling and short transactions. Caching - In-memory or distributed caching (IMemoryCache, Redis, HybridCache) for frequently read, rarely changing data, with clear invalidation. - HTTP caching (Cache-Control, ETags) and output caching for anonymous or shared responses. Async and resource usage - Async I/O end to end; no .Result or .Wait() (which cause thread-pool starvation). - Reuse HttpClient via IHttpClientFactory; avoid creating expensive objects per request. - Run independent downstream calls in parallel (Task.WhenAll). External dependencies - Timeouts, retries with backoff, circuit breakers and fallbacks so slow providers do not slow everything. - Move slow, non-urgent work (emails, reports, image processing) to background queues. Payload efficiency - Response compression (Brotli or gzip), smaller DTOs, avoiding over-fetching; System.Text.Json source generation for high-throughput serialization. Scalability and protection - Stateless services behind a load balancer with autoscaling; rate limiting to protect from abusive traffic. Code-level hot paths - Reduce allocations (avoid unnecessary LINQ, string concatenation and boxing in hot loops), and use Span<T> and pooling where profiling shows benefit. Example "Our product list endpoint averaged 1.8 seconds at peak. Tracing showed 120 SQL queries per request (N+1) and repeated calls to a pricing service. We switched to a single projected query with AsNoTracking, cached prices in Redis for five minutes, and added response compression. p95 latency dropped to 180 ms, and database CPU fell by about 40%." Always verify each change with metrics, because optimisations that are not measured can add complexity without benefit.
Ravindra Wadile · · 0 likes