skip to content

Performance & Deployment

Making an ASP.NET Core app fast and shipping it: Native AOT and trimming, async request code that avoids thread-pool starvation, and container images. Interviewers probe the trade-offs.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

14

In ASP.NET Core 10, what is Native AOT publishing, and what do you gain and give up compared with a normal JIT-compiled app?

level: juniorimportance: must knowfreq 48%

answer

  1. machine code produced at publish time
  2. <PublishAot>true</PublishAot> in the csproj
  3. start-up time, memory, image size
  4. one runtime identifier, no cross-OS publish
  5. Minimal APIs yes, MVC no

basics

~20 s

Native AOT, switched on with PublishAot in the project file, compiles the app into one native executable at publish time. It starts faster, uses less memory and needs no installed runtime, but loses runtime reflection and code generation, MVC and cross-OS publishing.

solid answer

~50 s

Native AOT is a publish mode: with `<PublishAot>true</PublishAot>` in the `.csproj`, `dotnet publish` compiles the app, the libraries it uses and a stripped-down runtime into **one native executable** for a single runtime identifier, so there is no JIT at start-up and no .NET runtime to install. The gains are **faster start-up, a smaller working set and a smaller deployment** than an untrimmed app, which suits scale-to-zero containers and cold-start-sensitive endpoints. The costs: the app is always trimmed, so **unbounded reflection, `Reflection.Emit` and dynamic assembly loading** do not work; **MVC controllers, Razor Pages, Session, Blazor Server and OData are not supported**, leaving Minimal APIs (plus gRPC and worker services); JSON must use source-generated metadata; publish is slower, needs a native toolchain and cannot cross operating systems. `dotnet run` still uses the JIT, so you test the published binary.

code

xml · 9 lines
xml
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <InvariantGlobalization>true</InvariantGlobalization>
    <PublishAot>true</PublishAot>
  </PropertyGroup>
</Project>

go deeper

for a junior

Recall the switch, PublishAot in the csproj, and the three wins: start-up time, memory and size. Know that it means Minimal APIs, not MVC controllers.

for a middle

Explain that publish compiles to one native executable per runtime identifier, always trims, and that dotnet run still uses the JIT, so you test the published output.

for a senior

Decide when the trade is worth it: scale-to-zero and dense hosting yes, a large controller or reflection-heavy API no. Insist on zero AOT warnings and a test of the published binary.

for a principal

Weigh AOT as a portfolio choice: which services earn its constraints, what it does to library selection, build agents and toolchains, and how to keep a JIT fallback path.

## What Native AOT is **Native ahead-of-time (AOT) compilation** turns a .NET app into machine code when you publish it, instead of shipping IL that the **just-in-time (JIT) compiler** translates while the process runs. The output is a **single native executable** that contains your code, the parts of the libraries it actually reaches, and a stripped-down runtime. Nothing has to be installed on the target machine, and no method has to be compiled before it can serve its first request. In ASP.NET Core 10 you switch it on with one MSBuild property: ```xml <PropertyGroup> <PublishAot>true</PublishAot> </PropertyGroup> ``` The property belongs in the project file rather than on the command line, because it changes more than publish: it turns on the trim and AOT analyzers during every build and enables the source generators that replace reflection. The `webapiaot` template ("ASP.NET Core Web API (native AOT)") creates a project with `PublishAot` and `InvariantGlobalization` already set and a `Program.cs` built on `WebApplication.CreateSlimBuilder`. ## What you gain The ASP.NET Core documentation lists three benefits, measured against the same app published as a trimmed or untrimmed JIT app: | Benefit | Why it happens | Where it pays | |---|---|---| | **Reduced start-up time** | No JIT work before the first request; code is already native | Scale-to-zero, autoscaling, rolling deployments | | **Reduced memory demand** | No JIT, less runtime machinery in memory | Higher deployment density | | **Smaller disk footprint** | Trimming drops unreachable code | Smaller container images, faster pulls | Picture a **cold-start-sensitive image-resize API**: a container that scales from zero when an upload arrives and must answer quickly. Start-up time is most of that budget, so it is the textbook Native AOT candidate. AOT is a start-up, memory and size optimisation. It is not a promise of more requests per second under steady load, so measure throughput before and after rather than assuming it. ## What you give up - **Run-time code generation and dynamic loading.** The .NET docs list no `System.Reflection.Emit`, no `Assembly.LoadFile`, and `System.Linq.Expressions` running only in interpreted form. - **Unbounded reflection.** Native AOT always trims, so code reached only through reflection may simply not be in the executable. - **Several ASP.NET Core features.** The support table marks **MVC, Blazor Server, Session, OData, SPA and "other authentication"** as not supported; **Minimal APIs and SignalR** as partially supported; and CORS, health checks, JWT bearer authentication, output caching, rate limiting, static files, WebSockets and gRPC as supported. - **Reflection-based JSON.** Request and response types need a source-generated `JsonSerializerContext`. - **Portability of the binary.** You publish for one runtime identifier, and Native AOT does not support cross-OS compilation; a Linux binary runs on the distribution version it was built on or a newer one. - **Build convenience.** Publishing needs the platform's native toolchain (for example clang on Linux or the C++ desktop workload in Visual Studio on Windows) and takes noticeably longer. ## How you know it will work 1. **Read the warnings.** With `PublishAot` set, analyzers report trim warnings (`IL2026`) and AOT warnings (`IL3050`) during build, and publish analyses the whole app again, NuGet packages included. The docs' rule: if publish produces no AOT warnings, the app can be expected to behave like its JIT-compiled version. 2. **Test the published executable.** `dotnet run` still uses the JIT even when `PublishAot` is set, so a run under the debugger proves nothing about trimming. 3. **Publish early and often**, so a new package that is not AOT-compatible shows up in the week it was added. ## Native AOT versus its neighbours - **ReadyToRun** (`PublishReadyToRun`) pre-compiles IL but keeps the JIT and full reflection; start-up improves less, compatibility is untouched. - **Trimming alone** (`PublishTrimmed`) shrinks a self-contained app but still JIT-compiles it. - **Native AOT** implies trimming and removes the JIT, which is why it gains the most and restricts the most. Choose it for small Minimal API services where start-up and density dominate. Keep the JIT for a large controller-based API, a Razor Pages site, or anything built on reflection-heavy libraries.

  • Does `dotnet run` exercise the Native AOT build when PublishAot is set?
    No. `PublishAot` only changes what `dotnet publish` produces; `dotnet run` and the debugger still run IL on the JIT. What you do get at build time are the trim and AOT analyzers and the source generators. So the only real proof is running the published native executable, ideally in the same container image you deploy.
  • How does Native AOT differ from ReadyToRun?
    ReadyToRun (`PublishReadyToRun`) adds pre-compiled native code to ordinary IL assemblies, so start-up improves, but the JIT, full reflection and dynamic loading all remain. Native AOT removes the JIT, always trims and produces one executable, so it gains more start-up time and memory but restricts which APIs and ASP.NET Core features you may use.

Native AOT is like furniture assembled at the factory: it arrives ready to use with no assembly on site, but you can no longer fit parts the factory did not know about when it built the piece.

  • Native AOT makes every ASP.NET Core app faster, including MVC controller APIs.
  • Setting PublishReadyToRun is the switch that produces a Native AOT executable.
  • dotnet run on a PublishAot project already tests the native executable.
  • A Native AOT binary published on Windows can be copied into a Linux container.
  • Native AOT keeps the JIT around as a fallback for reflection-heavy code.
open as a page

In ASP.NET Core 10, what is the difference between framework-dependent and self-contained publish output, and which one does dotnet publish produce by default?

level: juniorimportance: must knowfreq 55%

basics

~20 s

Framework-dependent output, the default, holds only the app and its dependencies and runs on an installed .NET and ASP.NET Core runtime that it rolls forward to the latest patch. Self-contained output also ships the runtime: bigger, platform-specific, patched only by republishing.

open as a page

In an ASP.NET Core 10 endpoint, why is calling .Result or .Wait() on a Task harmful, and what should you write instead?

level: juniorimportance: must knowfreq 72%

basics

~20 s

Blocking on .Result or .Wait() parks a thread-pool thread until the awaited I/O finishes, so under load ASP.NET Core runs out of free threads and every request slows down. Make the handler async and await the call instead.

open as a page

With the .NET 10 SDK, how does dotnet publish /t:PublishContainer build an ASP.NET Core image without a Dockerfile, and what defaults does it apply?

level: middleimportance: must knowfreq 45%

basics

~20 s

PublishContainer publishes the app and layers the output onto an inferred Microsoft base image (aspnet:10.0 for a web app), with no Dockerfile. It names the image after the assembly, tags it latest, and takes user and port from the base image.

open as a page

Your team sets PublishAot on an existing ASP.NET Core 10 API built with controllers and Session; what breaks, and how do IL2026 and IL3050 warnings flag it first?

level: seniorimportance: must knowfreq 42%

basics

~20 s

MVC controllers and Session are not supported under Native AOT: AddControllers and AddSession carry RequiresUnreferencedCode, so the build reports IL2026, and calls marked RequiresDynamicCode report IL3050. Publish rescans every package; any warning means the native app may fail at run time.

open as a page

Under load, an ASP.NET Core 10 freight-dashboard report endpoint goes from 200 ms to several seconds while CPU stays low; how do you confirm thread-pool starvation and fix it?

level: seniorimportance: must knowfreq 55%

basics

~20 s

Reproduce it under a load test, then watch the runtime's thread-pool metrics: thread count creeping up while CPU stays low and the queue grows. Thread stacks blocked in Wait or GetResult name the culprit. Fix that code path to await instead of blocking.

open as a page

In ASP.NET Core 10, what does WebApplication.CreateSlimBuilder leave out compared with CreateBuilder, and how do you restore HTTPS or a regex route constraint?

level: middleimportance: should knowfreq 30%

basics

~10 s

CreateSlimBuilder keeps configuration, user secrets and console logging but drops Kestrel HTTPS and HTTP/3, IIS integration, extra logging providers, hosting startup and the regex route constraint. UseKestrelHttpsConfiguration restores HTTPS; AddRouting or SetParameterPolicy restores regex.

open as a page

Why does an ASP.NET Core 10 app in an official .NET container listen on port 8080 instead of 80, and which user does it run as?

level: middleimportance: should knowfreq 48%

basics

~20 s

Since .NET 8 the official images set ASPNETCORE_HTTP_PORTS=8080 so the app can run as the non-root app user (APP_UID 1654), which cannot bind port 80. SDK-built and chiseled images run as that user; a Dockerfile on the regular image needs USER $APP_UID.

open as a page

In ASP.NET Core 10, why does a synchronous Request.Body read throw on Kestrel, and why is Request.Form still risky although it does not throw?

level: middleimportance: should knowfreq 38%

basics

~10 s

Kestrel's AllowSynchronousIO defaults to false, so a synchronous body Read throws InvalidOperationException. Request.Form never touches that guard: it reads the form asynchronously and blocks on the result, which is sync-over-async. Use await Request.ReadFormAsync().

open as a page

In ASP.NET Core 10, how do returning a lazy IEnumerable<T>, a List<T> from ToListAsync and an IAsyncEnumerable<T> differ for a large query result?

level: middleimportance: should knowfreq 40%

basics

~20 s

A lazy IEnumerable<T> backed by a query is enumerated synchronously during serialization, blocking a thread on I/O. ToListAsync is async but holds the whole result in memory. IAsyncEnumerable<T> lets System.Text.Json stream items as they arrive. Paginate anyway.

open as a page

In an ASP.NET Core 10 Native AOT Minimal API, why is a JsonSerializerContext inserted at index 0 of TypeInfoResolverChain, and what happens to a type you forgot to list?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Native AOT cannot serialize JSON by reflection, so every body type needs source-generated metadata from a JsonSerializerContext. Index 0 makes it the first resolver asked. A type missing from the context has no metadata, so the native app throws at run time.

open as a page

When would you base an ASP.NET Core 10 image on a noble-chiseled .NET image, and what breaks if the app needs globalization but you skip the -extra variant?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Chiseled images hold only what .NET needs: no shell, no package manager, non-root by default, so they are smaller with less to patch. The plain variant lacks ICU and time-zone data and forces invariant globalization; apps needing them use -extra.

open as a page

In ASP.NET Core 10 Minimal APIs, what does the Request Delegate Generator do, when is it switched on, and why might it skip an endpoint?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

The Request Delegate Generator is a source generator that writes each Minimal API endpoint's request delegate at compile time instead of building it by reflection at start-up. PublishAot or PublishTrimmed turns it on; it skips endpoints it cannot analyse statically and reports RDG diagnostics.

open as a page

In ASP.NET Core 10, when does Microsoft.Extensions.ObjectPool's ObjectPool<T> help a hot endpoint, and how do its retention limit and IResettable behave?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

ObjectPool<T> pays off only for objects that are expensive to create and used on every request, such as large StringBuilders. Get creates a new object when the pool is empty; Return keeps at most ProcessorCount * 2 and calls IResettable.TryReset first.

open as a page