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

📚 Interview question

How do you make async code in .NET fast, not just correct? Explain when ValueTask helps, when you can avoid an async state machine, whether ConfigureAwait(false) matters in ASP.NET Core, and how you limit parallelism when fanning out I/O.

Async performance in .NET 10: ValueTask and pooled builders, eliding the async state machine safely, the real effect of ConfigureAwait in ASP.NET Core versus libraries, and bounding concurrent fan-out.

Mid-Level Theory Intermediate aspnet-core async concurrency configureawait performance valuetask

🎯 Key points

  • Async cost: state machine box, Task allocation, continuation scheduling; usually tiny next to I/O
  • ValueTask<T> avoids the Task allocation when results often complete synchronously (cache hits, buffered reads)
  • ValueTask rules: await once, never block on it, never await concurrently
  • Elide async (return the Task directly) only for simple pass-through without using/try/AsyncLocal
  • ConfigureAwait(false): no effect in ASP.NET Core (no SynchronizationContext); still use it in libraries
  • Bound fan-out: Parallel.ForEachAsync with MaxDegreeOfParallelism or SemaphoreSlim, not unbounded Task.WhenAll
  • Never Task.Run around I/O in ASP.NET Core; measure with BenchmarkDotNet and alloc-rate

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

🗣 Full answer (senior)

How I would answer this in an interview

"I first put async cost in perspective. When an async method actually suspends, it allocates the state machine box, possibly a Task, and schedules a continuation; that's a few hundred bytes and well under a microsecond. Against a 5-millisecond database call it's noise, so I only tune async code when a profile shows it on a hot path, such as a cache read called millions of times or a stream parser.

On those paths I use a few tools. ValueTask<T> is for methods that usually complete synchronously, like a memory cache hit: the result is returned inline with no allocation, and only the miss path allocates. Callers must await it once and never call .Result on an incomplete one. I elide async and just return the Task for one-line pass-through wrappers, but never when there's a using, a try/catch or AsyncLocal state, because the disposal or exception happens at the wrong time. ConfigureAwait(false) is a library concern: ASP.NET Core has no SynchronizationContext, so in app code it changes nothing, while in a NuGet package it protects UI and legacy callers.

The mistake I see is people obsessing over those details while doing Task.WhenAll over 5,000 HTTP calls with no limit. That exhausts sockets and the downstream service. Bounding concurrency with Parallel.ForEachAsync and a MaxDegreeOfParallelism, and making sure nothing blocks a thread, is where async performance is really won."


Where async costs come from

Cost When it happens Mitigation
State machine box Method suspends at an await Elide for pass-through; PoolingAsyncValueTaskMethodBuilder on extreme hot paths
Task<T> allocation Every call (cached for some values like Task.CompletedTask, small ints, bools) ValueTask<T> when sync completion is common
Continuation scheduling On resume Usually negligible; avoid unnecessary awaits in loops
Blocked threads .Result, .Wait(), sync I/O Async all the way
Unbounded fan-out WhenAll over a huge list Parallel.ForEachAsync, SemaphoreSlim, Channels

Task vs ValueTask

Task<T> ValueTask<T>
Allocation on sync completion Yes (unless cached) No
Await multiple times Yes No
WhenAll, store in a field Yes Convert with .AsTask() first
Default choice Yes Only when measured hot and often synchronous

ConfigureAwait

Context Effect of ConfigureAwait(false)
ASP.NET Core app code None (no SynchronizationContext)
Library used by WPF/WinForms/MAUI/legacy ASP.NET Avoids marshalling back and the classic deadlock
ConfigureAwaitOptions (.NET 8+) SuppressThrowing, ForceYielding for specific needs

Production example

A pricing API fanned out to a supplier for every line of a quote with Task.WhenAll; quotes with 800 lines opened 800 concurrent connections and drew 429s. Limiting to 16 concurrent calls with Parallel.ForEachAsync cut large-quote p95 from 9 s to 2.1 s with zero 429s. Separately, switching a hot cache lookup to ValueTask<T> cut 120 MB/s of allocations at 50,000 calls a second.

🔍 What the interviewer is checking

Checks whether the candidate understands where async overhead really comes from and focuses on the optimisations that matter in production.

Green flags

  • Knows ValueTask's benefit and its consumption rules
  • Explains when eliding async is unsafe
  • States that ConfigureAwait has no effect in ASP.NET Core app code
  • Bounds fan-out and mentions connection pools or rate limits

Red flags

  • Uses ValueTask everywhere by default
  • Wraps I/O in Task.Run
  • Unbounded WhenAll over user-sized input

📚 Learn in depth

1. What the compiler generates

An async method becomes a struct state machine plus a builder. If every await completes synchronously, the struct stays on the stack and the builder returns a completed task (cached for common values). The first time an await is incomplete, the state machine is boxed to the heap so it can resume later, and the builder creates the Task<T> the caller awaits.

call --> run to first await --(completed?)--> continue inline --> return cached/completed task
                              \--(pending)--> box state machine, register continuation,
                                               return Task; resume later on ThreadPool

2. ValueTask

ValueTask<T> is a struct wrapping either a T (sync result), a Task<T> or an IValueTaskSource<T> (a reusable, poolable completion object). Sockets and PipeReader use IValueTaskSource so steady-state reads allocate nothing. Because the source may be reused after you consume it, awaiting twice or awaiting concurrently is undefined behaviour. [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))] (.NET 6+) pools the boxes for a method, trading memory held in pools for fewer allocations; measure before using it.

3. Eliding async

public Task<User?> GetAsync(int id, CancellationToken ct) => _repo.GetAsync(id, ct); // fine

This is safe when the method only forwards. It breaks when the method has a using (the resource is disposed before the task completes), a try/catch (exceptions surface outside it), or argument validation you expect to throw lazily.

4. SynchronizationContext and ConfigureAwait

await captures SynchronizationContext.Current (or a non-default TaskScheduler) and posts the continuation back to it. UI frameworks and classic ASP.NET have one; ASP.NET Core and console apps don't, so continuations run on the ThreadPool anyway. Libraries can't know their host, so they keep ConfigureAwait(false).

5. Bounded concurrency

Each concurrent outbound call holds a socket or pooled connection, memory for buffers, and load on the downstream service. Parallel.ForEachAsync(items, new ParallelOptions { MaxDegreeOfParallelism = 16, CancellationToken = ct }, ...) runs at most 16 bodies at once. SemaphoreSlim(16) around WhenAll does the same with more control. For pipelines, a bounded Channel<T> adds backpressure.

6. Things that are not optimisations

  • Task.Run around async I/O in ASP.NET Core: adds a ThreadPool hop and gains nothing.
  • async void: loses exceptions and can crash the process.
  • Making CPU-bound code 'async': it still uses a thread.

Try it yourself

  1. Benchmark a cache lookup returning Task<int> vs ValueTask<int> with [MemoryDiagnoser] at 100% and 50% hit rates.
  2. Write a pass-through method with a using and elide async; write a test that shows the object disposed too early.
  3. Fan out 1,000 calls to a local endpoint with WhenAll vs Parallel.ForEachAsync (MaxDegreeOfParallelism 16); compare latency and dotnet-counters connection counts.
  4. Decompile an async method with SharpLab to see the generated state machine.

💻 Code

A hot cache lookup using ValueTask<T>, a safe elided pass-through, and a bounded fan-out.

using System.Collections.Concurrent;

namespace Perf.Async;

public sealed record Price(string Sku, decimal Amount);

public interface IPriceSource
{
    Task<Price> FetchAsync(string sku, CancellationToken ct);
}

public sealed class PriceCache(IPriceSource source)
{
    private readonly ConcurrentDictionary<string, Price> _cache = new();

    // Hit path: completes synchronously, no Task allocation.
    // Miss path: falls through to a real async method.
    public ValueTask<Price> GetAsync(string sku, CancellationToken ct) =>
        _cache.TryGetValue(sku, out var price)
            ? ValueTask.FromResult(price)
            : new ValueTask<Price>(LoadAsync(sku, ct));

    private async Task<Price> LoadAsync(string sku, CancellationToken ct)
    {
        var price = await source.FetchAsync(sku, ct);
        _cache[sku] = price;
        return price;
    }

    // Safe to elide async: pure pass-through, no using/try/AsyncLocal.
    public Task<Price> RefreshAsync(string sku, CancellationToken ct) => source.FetchAsync(sku, ct);
}

public sealed class QuoteService(PriceCache cache)
{
    // Bounded fan-out: at most 16 concurrent lookups, so a 5,000-line quote
    // can't open 5,000 connections to the supplier.
    public async Task<IReadOnlyList<Price>> PriceQuoteAsync(IReadOnlyList<string> skus, CancellationToken ct)
    {
        var results = new Price[skus.Count];
        await Parallel.ForEachAsync(
            Enumerable.Range(0, skus.Count),
            new ParallelOptions { MaxDegreeOfParallelism = 16, CancellationToken = ct },
            async (i, token) => results[i] = await cache.GetAsync(skus[i], token));
        return results;
    }
}

⚠ Common mistakes

  • Mistake: Optimising without measuring. Why it is wrong: Async overhead is usually invisible next to I/O; you add complexity for nothing. Instead: Profile and benchmark the hot path first.
  • Mistake: Micro-optimising cold paths with ValueTask everywhere. Why it is wrong: It adds consumption rules with no measurable gain. Instead: Default to Task; use ValueTask where sync completion is common and the call is hot.
  • Mistake: Awaiting a ValueTask twice or calling .Result on it. Why it is wrong: The underlying source may be reused, giving wrong results or exceptions. Instead: Await once, or call .AsTask() if you need Task semantics.
  • Mistake: Eliding async in a method with using. Why it is wrong: The resource is disposed before the returned task finishes. Instead: Keep async/await whenever there's cleanup or exception handling.
  • Mistake: Adding ConfigureAwait(false) everywhere in ASP.NET Core apps 'for speed'. Why it is wrong: There's no context to avoid; it's noise. Instead: Use it in libraries.
  • Mistake: Unbounded Task.WhenAll over large inputs. Why it is wrong: Exhausts sockets, connection pools and downstream rate limits. Instead: Parallel.ForEachAsync with a limit, or SemaphoreSlim.
  • Mistake: Task.Run around I/O in a request. Why it is wrong: Wastes a ThreadPool thread and a hop. Instead: Call the async API directly.

🏛 Senior insight: trade-offs

The senior view is that async is mainly a scalability tool (threads aren't held during I/O), not a latency tool; the performance problems that matter are blocking, unbounded concurrency and chatty I/O, not state machine allocations. Reserve ValueTask and pooled builders for library-style hot paths and prove them with BenchmarkDotNet and production alloc-rate.

Technique When it fits Cost When not to
ValueTask<T> Hot, mostly synchronous completion Consumption rules; harder APIs Public APIs where callers will misuse it
Eliding async One-line forwarding Subtle bugs if cleanup added later Any using, try or validation
ConfigureAwait(false) Libraries Noise in app code ASP.NET Core application code
Bounded parallelism Fan-out to I/O Choosing and tuning a limit Strictly sequential workflows

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions ValueTask Why: Checks they know the ValueTask rules and IValueTaskSource in depth
    How to answer

    ValueTask<T> is a struct that holds either a result, a Task<T> or an IValueTaskSource<T>. It avoids allocating a task when a method usually completes synchronously (cache hits, buffered reads) and lets libraries pool the async case. The cost is stricter rules: await it once, never await it concurrently, and never read .Result before it completes; call .AsTask() if you need any of that. Use Task by default and choose ValueTask for measured hot paths or when an interface already uses it, like Stream.ReadAsync(Memory<byte>) or IAsyncDisposable.DisposeAsync.

  2. When: Candidate mentions ConfigureAwait Why: Checks they know SynchronizationContext behaviour and ConfigureAwaitOptions
    How to answer

    ConfigureAwait(false) tells an await not to resume on the captured SynchronizationContext or custom TaskScheduler; the continuation runs on a ThreadPool thread instead. Use it in general-purpose library code, which should not depend on or block the caller's context, to avoid deadlocks and save context switches. Do not use it in UI code that must touch controls after the await. In ASP.NET Core application code it is optional because there is no context. Since .NET 8, ConfigureAwait(ConfigureAwaitOptions) adds SuppressThrowing (await a Task without throwing) and ForceYielding (always continue asynchronously).

  3. When: Candidate mentions limiting parallelism Why: Checks they can compare Parallel.ForEachAsync, WhenAll and SemaphoreSlim
    How to answer

    Parallel.ForEachAsync (.NET 6+) runs an async body for each item in a sequence (IEnumerable<T> or IAsyncEnumerable<T>) with a bounded number of concurrent operations, set by ParallelOptions.MaxDegreeOfParallelism (default: processor count). The body receives a CancellationToken that is cancelled if any iteration throws, so it stops early on failure. It is the simplest way to say "process these 10,000 items, at most 20 at a time". Compared with Task.WhenAll it limits concurrency; compared with SemaphoreSlim it needs less code. It does not return results, so write to a concurrent collection or a preallocated array.

🛠 Real-world problems: how you handle them

Unbounded fan-out to a supplier API causes 429s and slow quotes
Situation
A B2B quoting API called a supplier pricing API once per quote line. Most quotes had [20] lines, but enterprise customers sent quotes with [800+] lines.
Signals
p95 for large quotes rose to [9 s]; the supplier returned HTTP 429 bursts; Application Insights showed hundreds of parallel dependency calls per request; outbound connection counts spiked.
Investigation
Application Insights end-to-end transactions showed the fan-out pattern; the code used Task.WhenAll over every line. dotnet-counters (System.Net.Http) showed current-requests and connection counts spiking per large quote. A k6 test with an 800-line quote reproduced it.
Resolution
Immediate: capped concurrency with Parallel.ForEachAsync (MaxDegreeOfParallelism 16) and added a standard resilience handler with retry honouring Retry-After. Longer term: negotiated a batch pricing endpoint and added a short-lived cache for repeated SKUs.
Prevention
Load test with a large-quote scenario in the pipeline; an analyser rule and review checklist item for unbounded WhenAll over input-sized collections; an alert on supplier 429 rate.

How to tell it (STAR)

**S:** At [company] our quote API priced each line by calling a supplier, and large enterprise quotes of [800] lines were taking about [9 seconds] and triggering 429s. **T:** I owned fixing it before a key customer's renewal. **A:** I traced one slow request in Application Insights and saw [800] parallel calls from an unbounded Task.WhenAll. I reproduced it with k6, capped concurrency at 16 with Parallel.ForEachAsync, added retry honouring Retry-After, and later worked with the supplier on a batch endpoint. **R:** Large-quote p95 fell to [2.1 seconds], 429s went to zero, and the batch endpoint later cut supplier calls by [90%].

↩ Usually asked after

More in Application Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me