A code review of an ASP.NET Core endpoint and API client covering per-call HttpClient, sync-over-async, sequential N+1 downstream calls, missing timeouts and cancellation, and over-fetching by returning the entity graph, with a ranked rewrite.
I rank findings by what hurts production first:
.Result blocks ThreadPool threads (sync-over-async → starvation), and new HttpClient() per call churns sockets until socket or SNAT exhaustion.The rewrite uses typed clients via IHttpClientFactory with the standard resilience handler, async all the way, independent calls in parallel with Task.WhenAll, a batch endpoint for products, and an AsNoTracking projection to a DTO. I'd prove it with a load test: p95, dependency count and response size before and after.
"I'd read it top to bottom once, then rank what I find by how it fails in production. The two things that take a service down come first:
.Resulton an async call inside a request handler, andnew HttpClient()per call. The first blocks a ThreadPool thread for the whole downstream call; under load the pool can't inject threads fast enough and every request slows down, which is ThreadPool starvation. The second creates a new connection pool per call, so every call pays TCP and TLS and leaves a socket in TIME_WAIT, which ends in socket or SNAT port exhaustion. Right after those, returning the entity graph is a privacy problem: it serialises the customer's date of birth and the product's cost price to the browser, which under the Privacy Act is the kind of thing that turns into a notifiable breach.For example, at [company] I reviewed [an order-details endpoint] very like this one. It made [1 + 2N] sequential calls per request, [41 for a typical 20-line order], each blocking a thread. I asked for typed clients with
IHttpClientFactoryand the standard resilience handler, async all the way with the cancellation token passed through, the customer and shipping calls in parallel withTask.WhenAll, a batchGET /products?ids=instead of one call per line, and anAsNoTrackingprojection to a response DTO. [In the load test p95 went from 2.4 s to 180 ms, dependency calls per request from 41 to 3, and the response from 380 KB to 6 KB.]The mistake I see in reviews is leading with style comments, or approving because 'it works on my machine'. A senior review ranks findings by impact and attaches evidence or a test for the blocking ones."
app.MapGet("/orders/{id:int}", (int id, ShopDb db) =>
{
var order = db.Orders // 1
.Include(o => o.Lines).ThenInclude(l => l.Product)
.Include(o => o.Customer)
.First(o => o.Id == id); // 2
var http = new HttpClient(); // 3
var customer = http.GetFromJsonAsync<CustomerInfo>(
$"https://customers.internal/customers/{order.CustomerId}").Result; // 4
foreach (var line in order.Lines) // 5
{
line.Product.Stock = http.GetFromJsonAsync<int>(
$"https://inventory.internal/stock/{line.ProductId}").Result; // 6
}
order.Shipping = http.GetFromJsonAsync<ShippingInfo>(
$"https://shipping.internal/orders/{id}").Result; // 7
return order; // 8
});
| # | Severity | Line | Problem | Fix |
|---|---|---|---|---|
| 1 | Stall | 4, 6, 7 | .Result blocks ThreadPool threads; synchronous EF query (2) too |
Async handler, await, CancellationToken |
| 2 | Stall | 3 | new HttpClient() per request: new pool, handshakes, TIME_WAIT, never disposed |
Typed clients via IHttpClientFactory |
| 3 | Security/privacy | 8, 1 | Entity graph serialised: customer PII, product cost, internal fields; cycles; tracked entities mutated with remote data | AsNoTracking projection to a DTO |
| 4 | Latency | 5–6 | One inventory call per line, sequential: N+1 across services | Batch endpoint, chunked |
| 5 | Latency | 4, 7 | Independent calls run in sequence | Task.WhenAll |
| 6 | Reliability | 3–7 | No timeouts, retries or circuit breaker; default 100 s timeout | AddStandardResilienceHandler |
| 7 | Correctness | 2 | First throws for unknown ids → 500 instead of 404 |
FirstOrDefaultAsync + Results.NotFound() |
| 8 | Diagnostics | all | No logging of dependency failures; hard-coded URLs | Typed clients with configured base addresses, OpenTelemetry |
| 9 | Design | all | Orchestration logic in the endpoint | A query handler/service; endpoint stays thin |
See the code example: typed clients with resilience, a handler that runs the database query and the independent calls concurrently, one batch inventory call, and a DTO.
Microsoft.CodeAnalysis.BannedApiAnalyzers) for new HttpClient() outside the composition root; add "no entities in responses" to the PR checklist.After the rewrite, the endpoint's p95 at [200 requests/s] fell from 2.4 s to 180 ms, ThreadPool queue length stayed near zero instead of climbing into the hundreds, and the response shrank from 380 KB to 6 KB.
Checks whether the candidate can review code for production performance and safety risks, rank findings by impact, and propose a correct modern rewrite with guard rails.
Green flags
Task.WhenAll and a batch call in the rewriteRed flags
new HttpClient() in using and calls it fixedrequest thread --> GetFromJsonAsync(...).Result
| thread blocked, waiting on I/O
| completion needs a ThreadPool thread to run the continuation
under load: all threads blocked -> continuations queue -> hill climbing adds ~1-2 threads/s
-> latency climbs for every endpoint, CPU stays low
dotnet-counters shows it as threadpool-queue-length rising and threadpool-thread-count creeping up while CPU is low. A dump shows many threads in Task.Wait/GetResult.
Each new HttpClient() brings a new SocketsHttpHandler and connection pool. With no reuse, every call opens TCP + TLS and closes, leaving TIME_WAIT sockets (60–120 s). At 200 requests/s × 22 calls that's thousands of connections per second, far beyond ephemeral port and Azure SNAT limits. Not disposing the client also leaks the handler until GC.
Include chains load columns the client never shows; serialisation and payload size grow with the graph.Order → Customer → Orders throws or bloats with ReferenceHandler.Preserve.line.Product.Stock = ...) risks writing it back if SaveChanges is called later in the scope.before: DB -> customer -> stock(1) -> stock(2) ... stock(20) -> shipping = 22 sequential calls
after: DB -> [customer | stock(batch of 20) | shipping] in parallel = 1 + max(3 calls)
Latency becomes the slowest of three calls instead of the sum of 22, and downstream load drops from 22 to 3 requests.
There are three layers, and the rewrite uses all of them:
client disconnects / gateway gives up
-> HttpContext.RequestAborted (bound to the CancellationToken parameter in Minimal APIs)
-> passed to EF Core (ToListAsync(ct)) and every HttpClient call
-> resilience pipeline: total timeout (30 s default) and per-attempt timeout (10 s default)
CancellationToken parameter in a Minimal API handler is bound to HttpContext.RequestAborted. Passing it down stops SQL queries and downstream calls when the caller has gone, so abandoned work doesn't keep consuming threads and connections.AddStandardResilienceHandler configures a total request timeout and a per-attempt timeout (tunable through HttpStandardResilienceOptions). Set them below the caller's budget: if the BFF gives up at 2 s, a 10 s per-attempt timeout downstream is wasted work.using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(TimeSpan.FromMilliseconds(300));
try { recommendations = await recs.GetAsync(id, cts.Token); }
catch (OperationCanceledException) when (!ct.IsCancellationRequested) { recommendations = []; } // our timeout, not the caller's
AddRequestTimeouts + .WithRequestTimeout(...)) sets a server-side budget per endpoint and cancels the request token when it is exceeded.OperationCanceledException when the caller cancelled; let it end the request.Select into anonymous types or DTOs is not tracked, so AsNoTracking matters mostly for entity queries, but keeping it makes intent clear.Contains over a parameter list (used by the stock batch endpoint) is translated to padded scalar parameters by default in EF Core 10, instead of EF Core 8–9's single OPENJSON parameter; re-check plans after upgrading.EF.CompileAsyncQuery removes per-call query compilation overhead; measure first, because EF's query cache already helps.Include chains in read endpoints; projection generates a narrower SQL statement and avoids cartesian explosion.HttpClient built on a fake HttpMessageHandler that records requests. Assert that a 20-line order makes exactly one stock call with 20 IDs, that a 404 from shipping yields a null status, and that cancellation propagates.WebApplicationFactory<Program> with the downstream clients replaced, and Testcontainers for SQL Server, asserting the JSON shape contains no PII fields (a snapshot test of the response contract).dotnet-counters: ThreadPool queue length and http.client.open_connections during the test.Content-Length.threadpool-queue-length with dotnet-counters.ss -tan state time-wait | wc -l during the test.HttpMessageHandler asserting one batch stock call per order.The rewrite: typed clients with resilience, async all the way, parallel independent calls, a batch call and a DTO:
// Program.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Http.Resilience;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<ShopDb>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Shop")));
// Base addresses from configuration; pooled handlers; timeouts, retries and circuit breaker.
builder.Services.AddHttpClient<CustomerClient>(c => c.BaseAddress = new(builder.Configuration["Services:Customers"]!))
.AddStandardResilienceHandler();
builder.Services.AddHttpClient<InventoryClient>(c => c.BaseAddress = new(builder.Configuration["Services:Inventory"]!))
.AddStandardResilienceHandler();
builder.Services.AddHttpClient<ShippingClient>(c => c.BaseAddress = new(builder.Configuration["Services:Shipping"]!))
.AddStandardResilienceHandler();
builder.Services.AddScoped<OrderDetailsQuery>();
var app = builder.Build();
app.MapGet("/orders/{id:int}", async (int id, OrderDetailsQuery query, CancellationToken ct) =>
await query.GetAsync(id, ct) is { } dto ? Results.Ok(dto) : Results.NotFound());
app.Run();
// Response contract: only what the screen needs, no PII beyond the display name.
public sealed record OrderDetailsDto(int Id, string Number, string CustomerName,
IReadOnlyList<OrderLineDto> Lines, string? ShippingStatus);
public sealed record OrderLineDto(int ProductId, string ProductName, int Quantity, decimal UnitPrice, int? InStock);
public sealed class OrderDetailsQuery(ShopDb db, CustomerClient customers,
InventoryClient inventory, ShippingClient shipping)
{
public async Task<OrderDetailsDto?> GetAsync(int id, CancellationToken ct)
{
var order = await db.Orders.AsNoTracking()
.Where(o => o.Id == id)
.Select(o => new
{
o.Id, o.Number, o.CustomerId,
Lines = o.Lines.Select(l => new { l.ProductId, l.Product.Name, l.Quantity, l.UnitPrice }).ToList()
})
.FirstOrDefaultAsync(ct); // projection: no entity graph, no tracking
if (order is null) return null;
// Independent calls in parallel; stock in ONE batch call instead of one per line.
var customerTask = customers.GetDisplayNameAsync(order.CustomerId, ct);
var stockTask = inventory.GetStockAsync(order.Lines.Select(l => l.ProductId).Distinct().ToArray(), ct);
var shippingTask = shipping.GetStatusAsync(order.Id, ct);
await Task.WhenAll(customerTask, stockTask, shippingTask);
var stock = await stockTask;
return new OrderDetailsDto(order.Id, order.Number, await customerTask,
[.. order.Lines.Select(l => new OrderLineDto(l.ProductId, l.Name, l.Quantity, l.UnitPrice,
stock.TryGetValue(l.ProductId, out var s) ? s : null))],
await shippingTask);
}
}
public sealed class CustomerClient(HttpClient http)
{
public async Task<string> GetDisplayNameAsync(int customerId, CancellationToken ct) =>
(await http.GetFromJsonAsync<CustomerSummary>($"/customers/{customerId}/summary", ct))?.DisplayName ?? "";
private sealed record CustomerSummary(string DisplayName);
}
public sealed class InventoryClient(HttpClient http)
{
public async Task<IReadOnlyDictionary<int, int>> GetStockAsync(int[] productIds, CancellationToken ct) =>
productIds.Length == 0 ? new Dictionary<int, int>() :
await http.GetFromJsonAsync<Dictionary<int, int>>(
$"/stock?{string.Join('&', productIds.Select(p => $"ids={p}"))}", ct) ?? [];
}
public sealed class ShippingClient(HttpClient http)
{
public async Task<string?> GetStatusAsync(int orderId, CancellationToken ct) =>
(await http.GetFromJsonAsync<ShippingSummary>($"/orders/{orderId}/status", ct))?.Status;
private sealed record ShippingSummary(string Status);
}
<!-- Directory.Build.props: guard rails so this doesn't come back -->
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Threading.Analyzers" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.BannedApiAnalyzers" PrivateAssets="all" />
<AdditionalFiles Include="$(MSBuildThisFileDirectory)BannedSymbols.txt" />
</ItemGroup>
<!-- BannedSymbols.txt: M:System.Net.Http.HttpClient.#ctor;Use IHttpClientFactory or a typed client -->
new HttpClient() with a using block. Why it is wrong: disposing per call still creates a new pool and connection every time. Instead: IHttpClientFactory or a long-lived client..Result with .GetAwaiter().GetResult(). Why it is wrong: it still blocks a thread; it only changes how exceptions are wrapped. Instead: make the handler async and await.Task.WhenAll. Why it is wrong: it bursts N requests and still makes N calls. Instead: a batch endpoint; bounded parallelism only as a fallback.[JsonIgnore] on entities. Why it is wrong: the next property added leaks by default, and the query still over-fetches. Instead: project to a response DTO.SaveChanges can write it back. Instead: AsNoTracking and build the DTO from separate data.A good performance review is mostly about failure modes under load, not micro-optimisations. The first two findings here don't show up in a functional test or at low traffic; they show up as a 2 a.m. incident with low CPU and timeouts everywhere. A senior names the mechanism (ThreadPool starvation, connection churn), asks for evidence, and adds analysers and checklists so the team doesn't need a senior in every review.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Block the PR | Stall, security or data-loss risks | Slower merge | Style issues |
| Approve with suggestions | Design and diagnostics improvements | Follow-up tickets | Anything that can cause an outage |
| Analysers / banned APIs | Patterns that recur across the team | Initial noise, suppression discipline | One-off issues |
| Load test as evidence | Hot endpoints, performance claims | CI time | Cold admin endpoints |
Opening a connection is expensive: a TCP handshake, a TLS handshake, and for SQL a login, so .NET keeps connections in pools and reuses them.
SocketsHttpHandler keeps a pool per host. Reuse it through a long-lived HttpClient or IHttpClientFactory, and set PooledConnectionLifetime so connections are recycled and DNS changes are noticed.Microsoft.Data.SqlClient pools per exact connection string, up to Max Pool Size = 100 by default. Open takes a pooled connection; Dispose returns it.Pool exhaustion shows up as requests queuing for a connection: HTTP time_in_queue rising, or SQL's "max pool size was reached" timeout. The fix is almost always a leak or slow calls, not a bigger pool: a bigger pool just moves the queue to the database or the downstream service.
An N+1 across services is a loop that calls a downstream API once per item: 200 items means 200 round trips, 200 failure points and a lot of load on the other team's service. The best fix is a batch endpoint: GET /products?ids=1,2,3 with a maximum batch size, deduplicated IDs, results keyed by ID and missing IDs reported, backed by one database query. On the client I chunk IDs with Enumerable.Chunk and run a few batches in parallel.
If the downstream has no batch support, I use Parallel.ForEachAsync with MaxDegreeOfParallelism so I don't fire 2,000 requests at once. The trade-off: bounded parallelism cuts wall-clock time but not load, and only a batch API reduces both. I prove it with dependency counts and p95 before and after.
Every response pays twice: serialisation time on the server and transfer time on the wire. On a phone over 4G with 60–100 ms RTT, a 2 MB JSON payload needs many TCP slow-start round trips, so it can take seconds even when the server answered in 40 ms. I shrink responses three ways:
Select in EF Core), so only the fields the screen uses are read and sent.I prove it with response bytes and client-side p95, not server time. The trade-off: compression costs CPU and needs care over HTTPS, and smaller pages mean more requests if the client really needs all the data.
How to tell it (STAR)
**S:** At [company], our order-details endpoint slowed to seconds at peak with CPU at about a third, and a security review found customer dates of birth in the response. **T:** I was asked to review the code and lead the fix. **A:** I ranked the findings: blocking `.Result` calls starving the ThreadPool and an HttpClient per call churning sockets first, then the entity graph leaking PII, then 22 sequential downstream calls. I proved the first two with dotnet-counters and a dump, and the rewrite used typed clients with resilience, async all the way, parallel calls, a batch stock endpoint and a DTO. I added analysers and a CI load test. **R:** p95 at peak dropped to [180 ms], calls per request went from 22 to [3], the response from 380 KB to [6 KB], and no PII left the API.
Last updated 23 Nov 2026.