Volume 7 · Chapter 5 — Advanced .NET Engineering, Performance & Production Excellence

High-Performance APIs

Goutham Mayaluri 8 min read .NETC#Performance

5.1 Introduction

A high-performance API sustains high request volume at low, predictable latency while using resources efficiently. In ASP.NET Core this comes from understanding the request pipeline, choosing the right hosting and serialization options, and applying caching, compression, and connection management deliberately. The goal is not just raw speed but consistent tail latency under load, which is what users and SLOs actually experience.

5.2 The Request Pipeline and Middleware

Every request flows through an ordered chain of middleware before reaching an endpoint. Because each component runs on every request, ordering and efficiency matter: put short-circuiting concerns (auth failures, rate-limit rejections, cached responses) early so expensive work is skipped, and keep middleware lightweight and async.

sequenceDiagram
  autonumber
  participant C as Client
  participant K as Kestrel
  participant MW as Middleware Pipeline
  participant EP as Endpoint
  C->>K: HTTP request
  K->>MW: exception handler -> HSTS -> auth -> rate limit -> output cache
  alt rejected early (401 / 429 / cache hit)
      MW-->>C: short-circuit response (no endpoint work)
  else passes
      MW->>EP: routed to handler
      EP-->>MW: result
      MW-->>C: response (compressed)
  end

5.3 Minimal APIs and Endpoint Efficiency

Minimal APIs reduce per-request overhead compared to the full MVC filter pipeline and are well suited to high-throughput microservices. Combined with typed results and source-generated serialization, they keep the hot path lean.


var app = builder.Build();

app.MapGet("/accounts/{id:guid}/balance", async (Guid id, IBalanceQuery q, CancellationToken ct) =>
{
    var balance = await q.GetAsync(id, ct);
    return balance is null ? Results.NotFound() : Results.Ok(balance);
})
.CacheOutput(p => p.Expire(TimeSpan.FromSeconds(5)))   // output caching
.RequireRateLimiting("per-user");

app.Run();

5.4 Serialization Performance

Serialization is often a hidden hot spot.System.Text.Jsonis fast and low-allocation, and its source generator removes reflection at runtime, improving throughput and enabling trimming/AOT. Keep DTOs lean, avoid serializing fields clients do not use, and reuse serializer options.


// Source-generated serialization: no runtime reflection, AOT-friendly.
[JsonSerializable(typeof(BalanceDto))]
public partial class ApiJsonContext : JsonSerializerContext { }

builder.Services.ConfigureHttpJsonOptions(o =>
    o.SerializerOptions.TypeInfoResolverChain.Insert(0, ApiJsonContext.Default));

5.5 Response Compression and HTTP/2-3

Compression (Brotli, then Gzip) shrinks payloads and cuts transfer time for text-heavy responses, at a small CPU cost - measure the trade-off for your payloads. HTTP/2 multiplexes many requests over one connection, reducing head-of-line blocking; HTTP/3 (QUIC) improves further on lossy networks. Kestrel supports all three.

5.6 gRPC for Service-to-Service

For internal, high-frequency service-to-service calls, gRPC over HTTP/2 with Protobuf binary serialization offers lower latency and smaller payloads than JSON over HTTP/1.1, plus strongly typed contracts and streaming. Use it between services; keep REST/JSON at the public edge for broad client compatibility.

5.7 API Caching Layers

ASP.NET Core offers output caching (cache the whole response), response caching (HTTP cache headers), and application caching (IMemoryCache/Redis for data). Layer them: output-cache stable GET responses, cache expensive data lookups, and use ETags so clients can revalidate cheaply.

5.8 Rate Limiting and Connection Management

The built-in rate limiter (fixed window, sliding window, token bucket, concurrency) protects the service from overload and enforces fair use. Equally important is reusingHttpClientviaIHttpClientFactory- creating a newHttpClientper call exhausts sockets (SocketExceptionunder load), while the factory pools and recycles handlers correctly.


builder.Services.AddRateLimiter(o => o.AddSlidingWindowLimiter("per-user", w =>
{
    w.PermitLimit = 100; w.Window = TimeSpan.FromMinutes(1); w.SegmentsPerWindow = 6;
}));

// Reuse pooled handlers - never 'new HttpClient()' per request.
builder.Services.AddHttpClient<LedgerClient>(c => c.BaseAddress = new(ledgerUrl));
Senior Interview Question

How do you improve ASP.NET Core API performance?

I work down the request path with measurement at each step. I keep the middleware pipeline lean and order it so rejections and cache hits short-circuit before expensive work; use Minimal APIs and source-generated JSON to cut per-request overhead and allocations; enable output/response caching for stable GETs and application caching for expensive data; apply compression where payloads justify it; and ensure database access is efficient (projection, indexing, AsNoTracking). I reuseHttpClientvia the factory, enable HTTP/2-3, and add rate limiting to protect tail latency under load. Throughout, I validate with load tests and traces rather than assuming, because the real bottleneck is usually downstream, not the framework.

Senior Interview Question

Why is creating a new HttpClient per request a problem, and what is the fix?

Eachnew HttpClient()creates a new connection handler, and disposing it leaves the underlying socket in TIME_WAIT for a while. Under load you exhaust available sockets and start gettingSocketExceptions, and you also lose DNS-change awareness if you cache a single static client forever. The fix isIHttpClientFactory(typed or named clients), which pools and rotates handlers, respects DNS TTLs, and integrates resilience policies. It gives you connection reuse without the socket-exhaustion or stale-DNS pitfalls of the naive approaches.

Senior Interview Question

When would you choose gRPC over REST/JSON?

For internal service-to-service communication that is high-frequency or latency-sensitive, gRPC’s HTTP/2 transport and Protobuf binary encoding give smaller payloads, lower latency, strongly typed contracts, and first-class streaming. It shines in a microservice mesh. I keep REST/JSON at the public edge and for browser clients, where broad compatibility, human-readability, and caching infrastructure matter more, and where gRPC’s tooling and browser support are weaker (gRPC-Web notwithstanding). The decision is audience and call pattern: internal and chatty leans gRPC, public and heterogeneous leans REST.

Senior Interview Question

What is the difference between output caching, response caching, and in-memory caching?

Output caching stores the fully rendered server response and serves it directly on subsequent matching requests, controlled entirely server-side - great for expensive but stable GET endpoints. Response caching sets HTTP cache headers so clients and intermediary proxies/CDNs can cache, moving the cache closer to the user but depending on their honoring the headers. In-memory (application) caching stores arbitrary data objects inside the process for your code to reuse, unrelated to HTTP. They compose: application caching speeds up data access, output caching skips whole responses, and response headers let the CDN offload traffic entirely.

Principal Engineer Question

How do you design an API to hold p99 latency steady as traffic grows 10x?

Steady tail latency under growth comes from removing shared bottlenecks and adding backpressure, not from tuning one endpoint. I make instances stateless so they scale horizontally behind a load balancer, and push session/state to Redis. I protect the tail with rate limiting and bounded concurrency so overload sheds load gracefully instead of collapsing, and I wrap downstream calls with timeouts and circuit breakers so one slow dependency cannot inflate p99 everywhere. I offload what I can to caches and CDNs (output caching, ETags) so most traffic never reaches the origin, and I make the database scale via read replicas or a CQRS read model since it is the usual limit. Finally I validate with load tests at target scale and watch p99, not just averages, because averages hide the pain. The architecture, not micro-optimization, is what keeps the tail flat at 10x.

Principal Engineer Question

A downstream service is intermittently slow and it is inflating your API's tail latency. How do you contain it?

This is temporal coupling leaking a dependency’s problems into my SLO. I contain it with the resilience toolkit: a tight per-call timeout so a slow response cannot hold a request (and a thread) for long, a circuit breaker that trips on sustained failure to stop hammering the sick dependency and fail fast, and a bulkhead so calls to that dependency use an isolated resource pool and cannot starve the rest of the API. Where the business allows, I add a fallback (cached or degraded response) so the user still gets something. If the interaction does not truly need to be synchronous, I convert it to async messaging so the dependency’s latency no longer sits in the request path. The principle is that my API’s tail latency must not be hostage to a dependency’s worst day.

5.9 Banking Enterprise Scenario

A bank’s customer API must sustain a tenfold traffic increase during payday peaks. The team runs stateless instances behind a load balancer with session state in Redis, uses Minimal APIs with source-generated JSON, and output-caches stable reference-data endpoints. Internal calls to the ledger and fraud services use gRPC and pooledHttpClients wrapped in timeout and circuit-breaker policies, with a sliding-window rate limiter guarding the edge. Load tests at target scale confirm p99 stays within SLO, and when the fraud service degrades one evening, the circuit breaker and a cached risk fallback keep the API responsive.

Chapter Revision Notes

  • Keep the middleware pipeline lean and order it to short-circuit early.
  • Minimal APIs + source-generated JSON reduce per-request overhead and allocations.
  • Reuse HttpClient via IHttpClientFactory to avoid socket exhaustion.
  • Layer caching (output, response headers/CDN, application data).
  • Use gRPC internally; REST/JSON at the public edge.
  • Protect tail latency with rate limiting, timeouts, and circuit breakers.