📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Code review: an order-details endpoint creates a new HttpClient for every call, calls the customer, product and shipping services one item at a time in a loop, blocks on .Result, and returns the full EF Core entity graph to the client. What problems do you find, ranked by severity, and how would you rewrite it?

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.

Senior CodeReview Advanced api-performance code-review httpclient n-plus-one performance sync-over-async

🎯 Key points

  • Severity 1 (stall/outage): .Result sync-over-async causes ThreadPool starvation; new HttpClient per call causes socket/SNAT exhaustion
  • Severity 1 (security/privacy): returning the entity graph leaks fields (e.g. customer PII, internal costs) and risks lazy-loading cycles
  • Severity 2: sequential per-item downstream calls (N+1) multiply latency by item count; use batch endpoints and bounded parallel fan-out
  • Severity 2: no timeouts, no CancellationToken, no resilience: one slow dependency holds threads and connections for HttpClient's 100 s default
  • Severity 3: no logging of dependency failures, no correlation; diagnostics depend on OpenTelemetry/App Insights
  • Rewrite: typed clients via IHttpClientFactory + AddStandardResilienceHandler, async all the way with the request's CancellationToken, Task.WhenAll for independent calls, batch API, AsNoTracking projection to a DTO
  • EF Core 10 notes: Contains over a list now uses padded parameters, projections avoid tracking and cycles; consider a compiled query for the hot path
  • Close the review: blocking vs suggested comments, analysers (VSTHRD002, banned API for new HttpClient), unit tests with a fake HttpMessageHandler, and a load test proving p95 and dependency counts

⏱ 30-second answer

I rank findings by what hurts production first:

  1. Stall and outage: .Result blocks ThreadPool threads (sync-over-async → starvation), and new HttpClient() per call churns sockets until socket or SNAT exhaustion.
  2. Security and privacy: returning the EF Core entity graph leaks fields the client must not see and can trigger lazy-loading cycles.
  3. Latency: one downstream call per item, sequentially, is an N+1 across services; no timeouts or cancellation.
  4. Diagnostics and design: no structured logging of failures, business logic in the endpoint.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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: .Result on an async call inside a request handler, and new 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 IHttpClientFactory and the standard resilience handler, async all the way with the cancellation token passed through, the customer and shipping calls in parallel with Task.WhenAll, a batch GET /products?ids= instead of one call per line, and an AsNoTracking projection 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."


Code under review

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
});

Findings, ranked by severity

# 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

The rewrite

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.

How I'd close the review

  • Blocking: findings 1–4 and 6. I'd link the ThreadPool and connection-pooling guidance and ask for a k6 load test showing p95 and dependency counts.
  • Suggested: 7–9, and moving URLs to configuration.
  • Guard rails: enable the Microsoft.VisualStudio.Threading analysers (VSTHRD002 for synchronous waits), CA2000, and a banned-API rule (Microsoft.CodeAnalysis.BannedApiAnalyzers) for new HttpClient() outside the composition root; add "no entities in responses" to the PR checklist.

Production example

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.

🔍 What the interviewer is checking

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

  • Names ThreadPool starvation and connection exhaustion as the top risks
  • Flags the entity graph as a privacy and over-fetching problem
  • Uses typed clients, resilience, async, Task.WhenAll and a batch call in the rewrite
  • Closes with blocking vs suggested comments, analysers and a load test

Red flags

  • Starts with naming or formatting
  • Wraps new HttpClient() in using and calls it fixed
  • Keeps returning entities

📚 Learn in depth

1. How sync-over-async starves the ThreadPool

request 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.

2. How per-call HttpClient exhausts connections

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.

3. Why returning entities is a security and performance bug

  • Over-exposure: every mapped property is serialised, including PII (date of birth, phone) and commercial data (cost price). Under the Privacy Act 1988 (APP 11 security, APP 6 use and disclosure) that's an incident.
  • Over-fetching: Include chains load columns the client never shows; serialisation and payload size grow with the graph.
  • Cycles: Order → Customer → Orders throws or bloats with ReferenceHandler.Preserve.
  • Tracking: mutating tracked entities with remote data (line.Product.Stock = ...) risks writing it back if SaveChanges is called later in the scope.

4. Sequential N+1 across services

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.

5. Cancellation and timeouts in .NET 10

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)
  • Request cancellation: a 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.
  • Timeouts per dependency: 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.
  • Your own deadline: for optional sections, link the request token with a timeout:
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
  • Endpoint timeouts: ASP.NET Core's request timeouts middleware (AddRequestTimeouts + .WithRequestTimeout(...)) sets a server-side budget per endpoint and cancels the request token when it is exceeded.
  • Don't swallow OperationCanceledException when the caller cancelled; let it end the request.

6. EF Core 10 notes for this endpoint

  • Projection with 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.
  • For a very hot endpoint, EF.CompileAsyncQuery removes per-call query compilation overhead; measure first, because EF's query cache already helps.
  • Avoid Include chains in read endpoints; projection generates a narrower SQL statement and avoids cartesian explosion.

7. Testing the rewrite

  • Unit tests: give the typed clients an 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.
  • Integration tests: 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).
  • Performance tests: a k6 test in CI with thresholds on p95 and error rate; Application Insights dependency counts in a staging run.

8. Evidence for the review

  • k6 load test: p95, error rate and throughput before/after.
  • Application Insights: dependency calls per request and the end-to-end transaction view.
  • dotnet-counters: ThreadPool queue length and http.client.open_connections during the test.
  • Response size from Content-Length.

Try it yourself

  1. Run the original endpoint under a k6 test at 100 VUs with stub dependencies that delay 50 ms; watch threadpool-queue-length with dotnet-counters.
  2. Count TIME_WAIT sockets with ss -tan state time-wait | wc -l during the test.
  3. Apply the rewrite and compare p95, dependency counts and response size.
  4. Write a unit test with a fake HttpMessageHandler asserting one batch stock call per order.
  5. Close the client mid-request and confirm in the logs that the SQL query and downstream calls were cancelled.
  6. Turn on VSTHRD002 and the banned API analyser and see which lines they flag.

💻 Code

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 -->

⚠ Common mistakes

  • Mistake: Optimising without measuring, e.g. approving or rejecting the rewrite on opinion. Why it is wrong: reviewers argue about style while the outage risk goes unproven. Instead: ask for a load test with p95, dependency counts and ThreadPool queue length before and after.
  • Mistake: Micro-optimising cold paths in the review, like nitpicking LINQ in a startup method. Why it is wrong: it buries the findings that matter. Instead: rank by production impact and keep minor points as suggestions.
  • Mistake: Leading with naming and formatting comments. Why it is wrong: the author fixes the easy things and the blocking problems survive. Instead: put stalls, security and data-correctness issues first and mark them blocking.
  • Mistake: Fixing 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.
  • Mistake: Replacing .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.
  • Mistake: Parallelising the per-line loop with unbounded 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.
  • Mistake: Hiding fields with [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.
  • Mistake: Mutating tracked entities with data from other services. Why it is wrong: a later SaveChanges can write it back. Instead: AsNoTracking and build the DTO from separate data.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions IHttpClientFactory or connection reuse Why: Checks their depth on HTTP and SQL connection pooling and pool exhaustion.
    How to answer

    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.

    • HTTP: 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.
    • SQL: 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.

  2. When: Candidate proposes a batch endpoint or bounded parallelism Why: Checks they can implement batching and Parallel.ForEachAsync correctly.
    How to answer

    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.

  3. When: Candidate mentions DTOs, projection or response size Why: Checks their understanding of how payload size drives latency and how to shrink it.
    How to answer

    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:

    • Pagination with a capped page size, so no endpoint returns "everything".
    • Projection to a purpose-built DTO (Select in EF Core), so only the fields the screen uses are read and sent.
    • Compression (Brotli or Gzip), which cuts JSON by 5–10×.

    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.

🛠 Real-world problems: how you handle them

Order-details endpoint melts down at peak despite low CPU
Situation
An order-details endpoint in [an e-commerce platform] on Azure App Service, Australia East, serving the web and mobile apps. Typical orders have [20] lines. Traffic peaks at [200] requests/s during promotions.
Signals
At peak, p95 rose from [300 ms] to [2.4 s] and some requests hit the 100 s HttpClient timeout. CPU sat at [35%]. Some instances logged `SocketException`. A security review separately flagged customer date of birth in browser network traces.
Investigation
dotnet-counters showed `threadpool-queue-length` in the hundreds and thread count creeping up. A dotnet-dump showed most threads blocked in `Task.Wait` under the endpoint. Application Insights end-to-end transactions showed [22] sequential dependency calls per request. `ss` showed thousands of TIME_WAIT sockets. Diffing the JSON against the DTO the screen used showed PII and cost price in the response.
Resolution
Immediate: scaled out and raised the instance count to absorb load while the fix was built. Fix: the review's rewrite: typed clients with resilience, async all the way, parallel independent calls, a batch stock endpoint and a projected DTO without PII. The privacy team assessed the exposure under the Notifiable Data Breaches scheme.
Prevention
VSTHRD002 and a banned-API rule for `new HttpClient()` as build errors; a PR checklist item "no entities in responses"; a k6 test for the endpoint in CI with p95 and dependency-count thresholds; dashboards for ThreadPool queue length and dependency calls per request.

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.

More in API Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me