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.
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.
"The pattern I look for is an
awaitinside aforeachthat 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 fromContains, or a table-valued parameter for big lists. On the client I split the IDs withEnumerable.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 useParallel.ForEachAsyncwithMaxDegreeOfParallelismset to something the downstream can take, maybe 8, pass the cancellation token, and handle 429 responses withRetry-Afterthrough the resilience handler.The mistake I see is replacing the sequential loop with
Task.WhenAllover 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."
| 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 |
| 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].)
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%.
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
Chunk and Parallel.ForEachAsync with an explicit DOP and cancellationRed flags
Task.WhenAll over a large listfor 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.
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).missing list. Never rely on order.| 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.
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:
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.Exception property holds an AggregateException with all of them.ConcurrentDictionary or a pre-sized array indexed by position; never a plain List<T>.await Task.Delay(5) per request and benchmark the three approaches with BenchmarkDotNet; repeat with 50 ms to simulate a cross-region hop.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.MaxDegreeOfParallelism from 2 to 64 and watch the stub's concurrent requests and your p99.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);
}
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.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.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.Contains/IN query, or a TVP for very large lists.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.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.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 |
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.
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:
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.
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.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.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.
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%].
Last updated 23 Nov 2026.