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

📚 Interview question

Show me how you would remove N+1 calls to a downstream API. Write a batch endpoint, a client that chunks IDs into batches, and a bounded-concurrency fallback with Parallel.ForEachAsync for an API that has no batch support, and explain how you would prove it is faster.

Covers replacing per-item downstream calls with a batch endpoint, chunking with Enumerable.Chunk, bounded parallelism with Parallel.ForEachAsync and MaxDegreeOfParallelism, partial failures, and measuring the gain.

Mid-Level Coding Intermediate api-performance batching httpclient n-plus-one parallel-foreachasync performance

🎯 Key points

  • N+1 across services: one call per item turns into N round trips, N log lines and N chances to fail; cost scales with RTT, so cross-region or internet hops make it far worse
  • Batch endpoint: GET /products?ids= or POST /products/query with a max batch size (e.g. 100), deduplicated IDs, results keyed by ID, missing IDs reported
  • Server side maps a batch to one query: EF Core 10 translates Contains to padded scalar parameters (EF Core 8–9 used one OPENJSON parameter); a TVP for thousands of IDs; never a loop
  • Client chunks IDs with Enumerable.Chunk and runs a few batches in parallel
  • No batch API: Parallel.ForEachAsync with MaxDegreeOfParallelism (e.g. 8) and the CancellationToken, never unbounded Task.WhenAll over thousands of items
  • Batch size trade-off: bigger batches mean fewer round trips but larger queries, payloads and blast radius per failure
  • Respect downstream rate limits (429 + Retry-After) and handle failures per item or per chunk
  • Prove it with BenchmarkDotNet, then Application Insights dependency counts and client p95 in production

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"The pattern I look for is an await inside a foreach that calls another service, like getting product details for each order line. It's the distributed version of the EF Core N+1: each call is fast, but 200 of them in sequence at 5 ms each is a second, and it puts 200 requests on the downstream for every one of ours.

The real fix is a batch endpoint. I design it with a hard maximum, say 100 IDs per call, deduplicate the IDs, return results keyed by ID so order doesn't matter, and explicitly list IDs that weren't found instead of failing the whole batch. Server side it becomes one query, WHERE Id IN (...), which EF Core generates from Contains, or a table-valued parameter for big lists. On the client I split the IDs with Enumerable.Chunk(100) and run a small number of chunks in parallel. When I don't own the downstream and it has no batch support, I use Parallel.ForEachAsync with MaxDegreeOfParallelism set to something the downstream can take, maybe 8, pass the cancellation token, and handle 429 responses with Retry-After through the resilience handler.

The mistake I see is replacing the sequential loop with Task.WhenAll over every item. It is faster on a laptop and then fires 2,000 concurrent requests in production, exhausts connections, trips the downstream's rate limiter and makes everything slower. Parallelism hides round trips; batching removes them."


Options compared

Approach Round trips for 200 items Downstream load When to use
Sequential loop 200 200 requests Never on a hot path
Unbounded Task.WhenAll 200 at once Burst of 200 Small, known-tiny N only
Parallel.ForEachAsync (DOP 8) 200, 8 at a time 200 requests, smoothed No batch API available
Batch endpoint (100 per call) 2 2 requests, 1 query each Whenever you can

Measured result (example)

Method Mean Allocated Downstream calls
Sequential, 200 IDs 1,060 ms 3.1 MB 200
Parallel.ForEachAsync DOP 8 140 ms 3.3 MB 200
Batch, chunks of 100 12 ms 0.4 MB 2

(Against a local stub with 5 ms latency, measured with BenchmarkDotNet and [MemoryDiagnoser].)

Production example

An order-pricing service called the catalogue API once per line. After adding a batch endpoint and chunked client, calls per pricing request fell from a p95 of 180 to 2, pricing p95 dropped from 950 ms to 85 ms, and catalogue request volume fell by 97%.

🔍 What the interviewer is checking

Checks that the candidate can spot and remove N+1 calls between services, write correct bounded concurrency, and design a usable batch contract.

Green flags

  • Designs the batch endpoint with limits, keyed results and missing IDs
  • Uses Chunk and Parallel.ForEachAsync with an explicit DOP and cancellation
  • Thread-safe result collection
  • Measures dependency counts and latency before and after

Red flags

  • Unbounded Task.WhenAll over a large list
  • Batch endpoint implemented as a server-side loop
  • No thought for downstream rate limits or partial failure

📚 Learn in depth

1. The distributed N+1

for each line (200):
   orders-api --GET /products/17--> catalogue-api --SELECT ... WHERE Id=17--> SQL
= 200 HTTP round trips + 200 SQL round trips

batched:
   orders-api --GET /products?ids=1..100--> catalogue-api --SELECT ... WHERE Id IN (...)--> SQL
   orders-api --GET /products?ids=101..200--> ...
= 2 HTTP round trips + 2 SQL round trips

The cost of each round trip depends on distance. Inside Azure Australia East it may be 1–2 ms, so 200 calls cost a few hundred milliseconds; if the downstream is in Australia Southeast (~10–15 ms) or overseas (150+ ms), the same loop costs seconds to tens of seconds. That is why N+1 problems often appear only after a service moves region or a dependency becomes a SaaS API.

2. Designing a batch endpoint

  • Shape: GET /products?ids=1,2,3 is cacheable but limited by URL length (keep under ~2 KB); POST /products/query with a body for large ID lists (it's a safe query, document that it's idempotent).
  • Limits: a maximum batch size, validated, returning 400 if exceeded. It protects the server and keeps response size bounded.
  • Result shape: a dictionary or list with IDs, plus a missing list. Never rely on order.
  • Partial failure: per-item errors in the result, not a 500 for the whole batch, when items are independent.
  • Batch size trade-off: larger batches mean fewer round trips but bigger SQL statements, larger responses (more memory, possible LOH allocations), longer single requests and a bigger blast radius when one call fails or times out. 50–200 is a common sweet spot; measure.

3. How EF Core translates Contains, and when to use a TVP

Approach How Fits Watch out for
EF Core 10 default ids.Contains(p.Id) becomes IN (@ids1, @ids2, ...) with the parameter count padded up to a bucket size, so nearby list sizes share a plan and the optimiser sees real cardinality Normal batch sizes (tens to hundreds) Very large lists mean many parameters (SQL Server allows 2,100 per command)
EF Core 8–9 default, or EF.Parameter(ids) in EF Core 10 One JSON parameter expanded with OPENJSON Large lists; one plan for any size Fixed cardinality guess for OPENJSON can give poor plans; upgrading from 8/9 to 10 changes the SQL, so re-check plans
EF.Constant(ids) or EF Core 7 and earlier Literal values inlined Small, fixed lists A new plan per distinct list: plan cache bloat
Table-valued parameter SqlParameter with SqlDbType.Structured and a user-defined table type, joined in SQL Thousands of IDs, stored procedures, Dapper Needs a table type in the schema; EF Core needs raw SQL
Temp table / SqlBulkCopy Load IDs, then join Tens of thousands of IDs, reports More round trips, more code

Rule of thumb: the EF Core default for normal batch sizes (another reason to cap batches at around 100); a TVP when lists regularly run into the thousands or the plan shows bad estimates. The translation mode can also be set globally on the SQL Server options builder.

4. Parallel.ForEachAsync internals and error handling

Parallel.ForEachAsync(source, new ParallelOptions { MaxDegreeOfParallelism = 8, CancellationToken = ct }, body) starts up to 8 workers that pull items from the source and await the body. Default DOP is Environment.ProcessorCount, a CPU-oriented default that is often wrong for I/O; choose it based on what the downstream can handle.

Error handling is the part people get wrong:

  • When a body throws, Parallel.ForEachAsync cancels the token it passes to the other bodies and stops taking new items. Bodies already running see cancellation only if they pass that token on.
  • Once all running bodies finish, the returned task faults. Awaiting it rethrows the first exception; the task's Exception property holds an AggregateException with all of them.
  • So: if one failure should abort the whole operation, let it throw. If items are independent (most batch lookups), catch inside the body, record the failure per item or chunk, and keep going.
  • Collect results into a ConcurrentDictionary or a pre-sized array indexed by position; never a plain List<T>.

5. Why unbounded Task.WhenAll hurts

  • Opens many connections at once (HTTP/1.1) or queues on HTTP/2 stream limits.
  • Triggers downstream rate limiting (429) and retries, amplifying load.
  • Spikes memory with all responses buffered at once.
  • Makes latency less predictable at p99.

6. Measuring

  • BenchmarkDotNet against a local stub with injected latency, comparing sequential, bounded parallel and batched.
  • Application Insights: dependency count per operation and total duration before/after, in production.
  • Client view: real user monitoring p95 for the screens that use the endpoint.
  • Downstream view: request rate and CPU of the called service, which is often the bigger win.

Try it yourself

  1. Build a stub API with await Task.Delay(5) per request and benchmark the three approaches with BenchmarkDotNet; repeat with 50 ms to simulate a cross-region hop.
  2. Add a batch endpoint using EF Core Contains and check the generated SQL in the log for 7, 8 and 9 IDs (note the padding); then compare EF.Parameter(ids) and a TVP with 5,000 IDs.
  3. Change MaxDegreeOfParallelism from 2 to 64 and watch the stub's concurrent requests and your p99.
  4. Make the stub fail 1 in 20 requests and compare letting the exception escape with catching per chunk.
  5. Query Application Insights for dependency counts per operation before and after.

💻 Code

Batch endpoint (server), a chunked batch client with per-chunk error handling, and a bounded fallback for a downstream without batch support:

// Catalogue.Api: Program.cs
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<CatalogueDb>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Catalogue")));
var app = builder.Build();

const int MaxBatch = 100; // also keeps EF Core 10's padded IN-parameters well under SQL Server's 2,100 limit

app.MapGet("/products", async (int[] ids, CatalogueDb db, CancellationToken ct) =>
{
    var distinct = ids.Distinct().ToArray();
    if (distinct.Length is 0 or > MaxBatch)
        return Results.ValidationProblem(new Dictionary<string, string[]>
        { ["ids"] = [$"Provide 1 to {MaxBatch} ids."] });

    var found = await db.Products.AsNoTracking()
        .Where(p => distinct.Contains(p.Id))               // one query: IN (@ids1, @ids2, ...) padded, EF Core 10
        .Select(p => new ProductDto(p.Id, p.Name, p.Price))
        .ToListAsync(ct);

    var missing = distinct.Except(found.Select(f => f.Id)).ToArray();
    return Results.Ok(new ProductBatch(found, missing));   // keyed by id, missing reported
});

app.Run();

public sealed record ProductDto(int Id, string Name, decimal Price);
public sealed record ProductBatch(IReadOnlyList<ProductDto> Items, IReadOnlyList<int> Missing);
// Orders.Api: typed client
using System.Collections.Concurrent;

public sealed record ProductLookup(IReadOnlyDictionary<int, ProductDto> Found, IReadOnlyList<int> Failed);

public sealed class CatalogueClient(HttpClient http, ILogger<CatalogueClient> logger)
{
    private const int BatchSize = 100;

    // Preferred: few round trips, few downstream queries.
    public async Task<ProductLookup> GetProductsAsync(IEnumerable<int> ids, CancellationToken ct)
    {
        var found = new ConcurrentDictionary<int, ProductDto>();
        var failed = new ConcurrentBag<int>();

        await Parallel.ForEachAsync(ids.Distinct().Chunk(BatchSize),
            new ParallelOptions { MaxDegreeOfParallelism = 4, CancellationToken = ct },
            async (chunk, token) =>
            {
                try
                {
                    var query = string.Join('&', chunk.Select(id => $"ids={id}"));
                    var batch = await http.GetFromJsonAsync<ProductBatch>($"/products?{query}", token);
                    foreach (var p in batch?.Items ?? []) found[p.Id] = p;
                }
                catch (HttpRequestException ex) // retries already done by the resilience handler
                {
                    // Items are independent: record the failed chunk instead of aborting all chunks.
                    logger.LogWarning(ex, "Catalogue batch of {Count} ids failed", chunk.Length);
                    foreach (var id in chunk) failed.Add(id);
                }
            });

        return new ProductLookup(found, [.. failed]);
    }

    // Fallback when the downstream only has GET /products/{id}: bounded, not unbounded.
    public async Task<ProductLookup> GetOneByOneAsync(IEnumerable<int> ids, CancellationToken ct)
    {
        var found = new ConcurrentDictionary<int, ProductDto>();
        var failed = new ConcurrentBag<int>();

        await Parallel.ForEachAsync(ids.Distinct(),
            new ParallelOptions { MaxDegreeOfParallelism = 8, CancellationToken = ct }, // what the downstream can take
            async (id, token) =>
            {
                try
                {
                    using var response = await http.GetAsync($"/products/{id}", token);
                    if (response.StatusCode == System.Net.HttpStatusCode.NotFound) return; // just missing
                    response.EnsureSuccessStatusCode();
                    if (await response.Content.ReadFromJsonAsync<ProductDto>(token) is { } p) found[id] = p;
                }
                catch (HttpRequestException ex)
                {
                    logger.LogWarning(ex, "Catalogue lookup for {ProductId} failed", id);
                    failed.Add(id);
                }
            });

        return new ProductLookup(found, [.. failed]);
    }
}

// Program.cs:
// builder.Services.AddHttpClient<CatalogueClient>(c => c.BaseAddress = new("https://catalogue.internal"))
//     .AddStandardResilienceHandler(); // timeouts, jittered retries honouring 429 Retry-After, circuit breaker
// Benchmark sketch proving the change (BenchmarkDotNet)
using BenchmarkDotNet.Attributes;
using Microsoft.Extensions.Logging.Abstractions;

[MemoryDiagnoser]
public class CatalogueCallsBenchmark
{
    private CatalogueClient _client = default!;
    private readonly int[] _ids = Enumerable.Range(1, 200).ToArray();

    [GlobalSetup] public void Setup() =>
        _client = new CatalogueClient(new HttpClient { BaseAddress = new("http://localhost:5080") }, // stub with 5 ms delay
                                      NullLogger<CatalogueClient>.Instance);

    [Benchmark(Baseline = true)] public Task OneByOne() => _client.GetOneByOneAsync(_ids, CancellationToken.None);
    [Benchmark] public Task Batched() => _client.GetProductsAsync(_ids, CancellationToken.None);
}

⚠ Common mistakes

  • Mistake: Optimising without measuring, e.g. adding parallelism everywhere because "loops are slow". Why it is wrong: the loop may run over three items. Instead: check dependency counts per request in Application Insights and fix the high-N paths.
  • Mistake: Micro-optimising a nightly job's call loop while the hot request path still does N+1. Why it is wrong: effort goes where users don't feel it. Instead: rank by calls per minute × N.
  • Mistake: Stopping at a benchmark. Why it is wrong: a local stub doesn't show real RTT, downstream contention or rate limits. Instead: confirm in production with Application Insights dependency counts, client p95 (RUM) and the downstream's request rate, ideally behind a feature flag so you can compare.
  • Mistake: await Task.WhenAll(ids.Select(Get)) over thousands of IDs. Why it is wrong: it bursts thousands of requests, exhausts connections and trips rate limits. Instead: batch, or Parallel.ForEachAsync with a chosen MaxDegreeOfParallelism.
  • Mistake: Leaving MaxDegreeOfParallelism at the default for I/O. Why it is wrong: the default is CPU-based and unrelated to downstream capacity. Instead: set it from the downstream's limits and load-test it.
  • Mistake: Letting one failed item abort Parallel.ForEachAsync. Why it is wrong: the first exception cancels everything else, so one bad ID fails the whole page. Instead: catch inside the body for independent items and return failures explicitly.
  • Mistake: A batch endpoint without a maximum size. Why it is wrong: a 50,000-ID request produces a huge query and response, and can exceed SQL Server's 2,100-parameter limit. Instead: validate a cap and return 400 when exceeded.
  • Mistake: Implementing the batch endpoint as a loop over single lookups. Why it is wrong: it moves the N+1 to the database. Instead: one Contains/IN query, or a TVP for very large lists.
  • Mistake: Assuming the SQL for Contains is the same after an EF Core upgrade. Why it is wrong: EF Core 10 switched from OPENJSON to padded parameters, which changes plans. Instead: re-check the generated SQL and Query Store after upgrading.
  • Mistake: Writing to a List<T> from inside Parallel.ForEachAsync. Why it is wrong: List<T> isn't thread-safe and loses items or throws. Instead: ConcurrentDictionary/ConcurrentBag, or index into a pre-sized array.

🏛 Senior insight: trade-offs

Batching is a contract decision, not just a client trick: it needs the downstream team to offer a batch endpoint with clear limits and partial-failure semantics. When you own both sides, add it early for any lookup that is naturally called in a loop. Bounded parallelism is the polite fallback when you don't own the downstream, and the degree of parallelism should be agreed with that team, because your speed-up is their load spike.

Option When it fits Cost When not to
Batch endpoint You own or can influence the downstream API design, validation Items need different auth or tenants per call
Chunked batches in parallel Very large ID sets A little client code Small N: one batch is enough
Parallel.ForEachAsync with DOP No batch API Same total load When rate limits are tight: go sequential with caching
Cache or replicate the data Read-heavy reference data Staleness, infrastructure Data that must be current to the second

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions throttling concurrent async work Why: Checks they can throttle async work with SemaphoreSlim and know when that beats Parallel.ForEachAsync.
    How to answer

    SemaphoreSlim is a lightweight, in-process counting semaphore that supports WaitAsync, so it works with async/await. With a count of 1 it is an async lock: await gate.WaitAsync(ct); try { ... } finally { gate.Release(); }. With a count of N it limits how many async operations run at once, for example ten concurrent calls to a partner API. It is not re-entrant and has no owner, so calling it again from inside the protected section deadlocks, and every successful wait must be paired with exactly one Release in finally.

  2. When: Candidate talks about many calls per screen or per request Why: Checks their architectural options for chatty APIs beyond batching.
    How to answer

    Chattiness turns latency into round trips × RTT: 25 sequential calls over an 80 ms mobile link is two seconds before any server work. I first measure it with distributed traces (Application Insights end-to-end transactions) to count calls per operation and find the critical path. Then:

    • Client to server: an aggregate endpoint or a backend for frontend (BFF) that returns what one screen needs, fanning out server-side where RTT is sub-millisecond.
    • Service to service: batch APIs instead of N+1 calls, gRPC with streaming for high-volume links, and caching or replicating read data via events.

    If two services always call each other, the real fix may be the boundary. The trade-off: fewer round trips cost coupling, ownership and more complex failure handling.

  3. When: Candidate discusses parallelism limits or async overhead Why: Checks their understanding of async performance and fan-out limits.
    How to answer

    Async overhead is small (a state machine, a Task allocation and a continuation), so I only tune it on hot paths a profile points to.

    • ValueTask<T> removes the Task allocation when the method usually completes synchronously, such as a cache hit. Callers must await it exactly once.
    • Eliding async/await and returning the inner Task saves a state machine for pure pass-through methods, but not when there's using, try or AsyncLocal state.
    • ConfigureAwait(false) changes nothing in ASP.NET Core, which has no SynchronizationContext; it still matters in shared libraries.
    • The biggest real win is bounding parallelism with Parallel.ForEachAsync or SemaphoreSlim so a fan-out doesn't exhaust connection pools.

    The trade-off: these micro-optimisations add rules and risk, so the benchmark must justify them.

🛠 Real-world problems: how you handle them

Order pricing slowed by one catalogue call per line
Situation
An order-pricing service in [an e-commerce platform] on Azure Container Apps, Australia East. Large business orders have [up to 300] lines. Black Friday traffic expected at [5×] normal.
Signals
Pricing p95 of [950 ms] and p99 of several seconds for large orders; Application Insights showing up to [300] dependency calls to catalogue per request; catalogue team reporting 429s and asking us to slow down.
Investigation
Application Insights end-to-end transactions showed sequential `GET /products/{id}` calls. A KQL query over `dependencies` grouped by `operation_Id` confirmed calls per request scaled with line count. A BenchmarkDotNet run against a stub with 5 ms latency quantified sequential vs bounded parallel vs batched.
Resolution
Immediate: switched the loop to `Parallel.ForEachAsync` with DOP 8 (agreed with the catalogue team) and the standard resilience handler for 429s. Real fix: worked with the catalogue team to add `GET /products?ids=` with a 100-ID cap, then chunked client calls. Added HybridCache for product data with a 5-minute TTL.
Prevention
A Roslyn analyser or code-review checklist item flagging `await` on HTTP clients inside loops; a dashboard of dependency calls per operation with an alert; a k6 test with large orders in the pipeline.

How to tell it (STAR)

**S:** At [company], our pricing service got slow for big business orders, and the catalogue team was rate-limiting us ahead of [Black Friday]. **T:** As [the senior engineer on pricing], I needed to cut latency and our load on catalogue before the peak. **A:** Traces showed one catalogue call per order line, up to 300 per request. I first bounded the loop with Parallel.ForEachAsync at a concurrency we agreed with the catalogue team, then designed a batch endpoint with them, with a 100-ID cap and a missing list, and added a short cache. I proved each step with BenchmarkDotNet and then Application Insights. **R:** Calls per request dropped from about 300 to [2], pricing p95 went from [950 ms] to [85 ms], and catalogue traffic from us fell by [97%].

↩ Usually asked after

More in API Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me