DEV Community

Cover image for Zero-Allocation Async Local Storage in .NET 11
Maayur Dahake
Maayur Dahake

Posted on

Zero-Allocation Async Local Storage in .NET 11

Zero-Allocation Async Local Storage in .NET 11

Production Context

High-throughput .NET backend services relying heavily on ambient context (such as tenant IDs, correlation IDs, or security principals via AsyncLocal<T>) frequently encounter silent allocation overhead. Every time an asynchronous continuation flows across execution contexts, the runtime historically duplicates internal dictionary nodes using a copy-on-write mechanism. Under massive concurrent loads, this triggers unnecessary Gen0 GC pressure.

.NET 11 addresses this bottleneck by redesigning the underlying runtime execution context flow to achieve zero-allocation context propagation.

Before

private static readonly AsyncLocal<UserContext> _ctx = new();

public void ProcessRequest(UserContext context)
{
    // Legacy flow allocates tree nodes on context flow
    _ctx.Value = context;
    await Task.Yield();
}
Enter fullscreen mode Exit fullscreen mode

After

private static readonly AsyncLocal<UserContext> _ctx = new();

public void ProcessRequest(UserContext context)
{
    // .NET 11 optimized runtime flow eliminates copy overhead
    _ctx.SetNoCopy(context);
    await Task.Yield();
}
Enter fullscreen mode Exit fullscreen mode

Why it matters

  • Zero Heap Allocations: Completely removes internal dictionary cloning during async/await handoffs.
  • Reduced GC Pressure: Keeps Gen0 clear during peak concurrent request traffic.
  • Predictable Latency: Prevents sudden latency spikes caused by tree restructuring under heavy async depth.

Watch out

While the context flow mechanism is now allocation-free, mutating captured reference types across concurrent threads without explicit synchronization will still lead to race conditions.

Have you profiled your ambient context overhead recently?

Top comments (0)