Skip to content

.NET Core deploy on PaaS — runtime trimming, ahead-of-time compilation, image size

How trimming, ReadyToRun, and Native AOT change the shape of a .NET 8 deploy on PaaS — what each one costs, what each one buys.

You publish a vanilla dotnet publish of an ASP.NET Core 8 service and the resulting image is 230 MiB. Cold start on a PaaS scale-up takes nine seconds — six of which are JIT warmup. The team next door ships a Go service with similar functionality in a 22 MiB image that boots in 200 ms. Everyone wants to know which knob to turn. The answer is three knobs — trimming, ReadyToRun, and Native AOT — and they have very different costs and very different payoffs.

What’s happening

Three optimizations available in .NET 8, in increasing order of aggressiveness:

  • Trimming (<PublishTrimmed>true</PublishTrimmed>) — at publish time, the SDK does a reachability analysis and drops IL that nothing references. Cuts published size by 40-70%. Works on most ASP.NET Core code; breaks on apps that use reflection heavily without DynamicallyAccessedMembers annotations.
  • ReadyToRun (<PublishReadyToRun>true</PublishReadyToRun>) — precompiles IL to native code at publish time. The JIT still runs but does less work at startup. Image gets larger (the binary now contains both IL and native code), but cold start drops 40-60%. Compatible with everything trimming is compatible with.
  • Native AOT (<PublishAot>true</PublishAot>) — full ahead-of-time compilation. The JIT is removed entirely; the binary is a single native executable. Startup is ~10 ms instead of 5-9 s. Image size is the smallest of all three options. But: many things break — reflection, dynamic code generation, runtime plugin loading, Microsoft.Extensions.Configuration.Binder without source generators, certain serializers.

The choice depends on which constraint hurts most: cold-start latency (AOT), image size (AOT or trimmed), or compatibility with the ecosystem (trim + R2R is the safe combination).

How to verify

# Image size and layer breakdown
docker images myorg/api:dotnet
docker history myorg/api:dotnet --no-trunc | head -20

# What did publish actually produce?
docker run --rm myorg/api:dotnet ls -la /app
docker run --rm myorg/api:dotnet du -sh /app /usr/share/dotnet 2>/dev/null

# Cold start time — measure from container create to first 200 OK
time docker run --rm -d --name aot-test -p 8080:8080 myorg/api:dotnet
until curl -fsS http://127.0.0.1:8080/healthz >/dev/null; do sleep 0.1; done
echo "First 200 OK"
docker rm -f aot-test

If the published output contains a Microsoft.NETCore.App.Runtime.* directory, you’re running framework-dependent — the .NET runtime is in the image as a separate folder. If you see a single ~50 MiB executable named after your project, you’re self-contained or AOT.

The fix

Three production-ready setups.

Setup 1 — trimming + ReadyToRun (the safe default):

<!-- MyApi.csproj -->
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <InvariantGlobalization>true</InvariantGlobalization>

    <PublishTrimmed>true</PublishTrimmed>
    <TrimMode>partial</TrimMode>
    <PublishReadyToRun>true</PublishReadyToRun>
    <PublishReadyToRunComposite>true</PublishReadyToRunComposite>
    <PublishSingleFile>true</PublishSingleFile>
    <SelfContained>true</SelfContained>
    <RuntimeIdentifier>linux-x64</RuntimeIdentifier>

    <DebugType>embedded</DebugType>
    <EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator>
  </PropertyGroup>
</Project>

TrimMode=partial is much safer than full — it only trims assemblies that opt in via [AssemblyMetadata("IsTrimmable", "true")]. Microsoft’s stack is mostly opt-in; third-party libraries are not. Start with partial, watch your test suite, and switch to full only if all your dependencies survive.

PublishReadyToRunComposite=true produces a single composite native image instead of one per assembly — smaller binary, faster startup. The trade-off: you can’t update individual assemblies without republishing the whole thing.

InvariantGlobalization=true removes ICU globalization data (40-60 MiB). If you don’t need locale-aware string comparison, sorting, or formatting, take the savings. Many APIs only do CultureInfo.InvariantCulture work; check before turning this on.

Setup 2 — Native AOT (smallest, fastest, fewest features):

<!-- MyApi.csproj — AOT variant -->
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <InvariantGlobalization>true</InvariantGlobalization>

    <PublishAot>true</PublishAot>
    <StripSymbols>true</StripSymbols>
    <OptimizationPreference>Speed</OptimizationPreference>
    <IlcOptimizationPreference>Speed</IlcOptimizationPreference>
    <IlcInstructionSet>x86-x64-v2</IlcInstructionSet>
    <RuntimeIdentifier>linux-x64</RuntimeIdentifier>

    <EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator>
    <EnableRequestDelegateGenerator>true</EnableRequestDelegateGenerator>
    <JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>
  </PropertyGroup>
</Project>

A minimal AOT-friendly Program.cs:

using System.Text.Json.Serialization;

var builder = WebApplication.CreateSlimBuilder(args);

builder.Services.ConfigureHttpJsonOptions(options =>
{
    options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default);
});

var app = builder.Build();

app.MapGet("/healthz", () => Results.Ok(new HealthResponse("ok", DateTime.UtcNow)));
app.MapGet("/items/{id:int}", (int id) => new Item(id, $"Item {id}"));

app.Run();

public record HealthResponse(string Status, DateTime Timestamp);
public record Item(int Id, string Name);

[JsonSerializable(typeof(HealthResponse))]
[JsonSerializable(typeof(Item))]
public partial class AppJsonContext : JsonSerializerContext { }

Three things that make this AOT-friendly: CreateSlimBuilder skips configuration providers AOT can’t handle; the source-generated JsonSerializerContext replaces runtime reflection-based JSON; EnableRequestDelegateGenerator source-generates the MapGet parameter binding instead of using reflection.

If your service uses Entity Framework Core, MediatR with reflection-based handlers, or any library that does Activator.CreateInstance on user types — AOT will either fail to compile or fail at runtime. Test extensively before committing.

Setup 3 — Dockerfile that builds either:

# syntax=docker/dockerfile:1.7
ARG VARIANT=trim_r2r
FROM mcr.microsoft.com/dotnet/sdk:8.0-alpine AS build

# AOT needs build deps; trim/R2R does not. Cheap to install either way.
RUN apk add --no-cache clang lld zlib-dev krb5-libs libgcc libstdc++

WORKDIR /src
COPY ["MyApi.sln", "."]
COPY ["src/MyApi/MyApi.csproj", "src/MyApi/"]
RUN dotnet restore "src/MyApi/MyApi.csproj"

COPY . .
WORKDIR /src/src/MyApi

ARG VARIANT
RUN if [ "$VARIANT" = "aot" ]; then \
      dotnet publish -c Release -r linux-x64 \
        -p:PublishAot=true \
        -p:StripSymbols=true \
        -o /publish; \
    else \
      dotnet publish -c Release -r linux-x64 \
        -p:PublishTrimmed=true \
        -p:PublishReadyToRun=true \
        -p:PublishSingleFile=true \
        -p:SelfContained=true \
        -o /publish; \
    fi

# Choose runtime base by variant
FROM mcr.microsoft.com/dotnet/runtime-deps:8.0-alpine AS runtime

RUN apk add --no-cache curl icu-data-full \
  && addgroup -S app -g 1001 \
  && adduser -S app -G app -u 1001 -h /app

WORKDIR /app
COPY --from=build --chown=app:app /publish .

USER app
ENV ASPNETCORE_URLS=http://+:8080 \
    DOTNET_RUNNING_IN_CONTAINER=true \
    DOTNET_USE_POLLING_FILE_WATCHER=false \
    DOTNET_EnableDiagnostics=0

EXPOSE 8080
HEALTHCHECK --interval=10s --timeout=2s --start-period=15s --retries=3 \
  CMD curl -fsS http://127.0.0.1:8080/healthz || exit 1

ENTRYPOINT ["./MyApi"]

Build either variant from the same Dockerfile:

# Default: trim + R2R, ~85 MiB image
docker build -t myorg/api:trim .

# AOT, ~25 MiB image
docker build -t myorg/api:aot --build-arg VARIANT=aot .

The runtime-deps base is the minimal one — no shared .NET framework, just the libraries dotnet needs (zlib, icu). Self-contained publish includes the runtime in your binary, so that’s all you need.

What you actually get

For an empty ASP.NET Core 8 minimal API (one GET endpoint), measured on the same hardware:

VariantImage sizeCold startMemory (RSS at idle)
dotnet publish (no opts)230 MiB4-6 s95 MiB
Trim + R2R85 MiB1.5-2 s70 MiB
Native AOT25 MiB30-80 ms30 MiB

The trim + R2R numbers are what most teams should target. Native AOT is appealing for serverless-style PaaS apps where containers spin up and down per request — the order-of-magnitude cold-start improvement makes scale-to-zero finally viable. But the ecosystem cost is real; budget for porting libraries or replacing reflection-heavy code paths.

A common middle path: ship trim + R2R for everything by default, take a few services to AOT once you’ve verified your stack survives. Don’t commit the whole codebase to AOT until you’ve shipped at least one service end-to-end without surprises.


We size .NET workloads on Cloud PaaS, pick the right trim/AOT trade-off per service, and bake cold-start measurement into deploys via our deployment management plane. If your .NET images are bigger than they should be and cold starts are hurting autoscale economics, start a sizing conversation.