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

📚 Interview question

What are compiled queries and compiled models in EF Core, and what problem does each solve? Explain the per-query and start-up overhead they remove, EF.CompileAsyncQuery, dotnet ef dbcontext optimize, precompiled queries, the current state of Native AOT support, and when none of them is worth it.

Covers where EF Core spends time outside SQL (query compilation and cache lookup, model building at start-up), compiled queries with EF.CompileAsyncQuery, compiled models with dotnet ef dbcontext optimize and MSBuild integration, precompiled queries and the experimental Native AOT support in EF Core 10.

Senior Theory Advanced compiled-models compiled-queries ef-core native-aot performance startup-performance

🎯 Key points

  • EF Core caches translated queries; each execution still extracts parameters and looks up the expression tree
  • EF.CompileAsyncQuery skips that lookup: low microseconds per call, only for very hot, trivial queries
  • Model building runs once per process at first use; large models (hundreds of entities) cost seconds
  • Compiled model: dotnet ef dbcontext optimize generates model code; UseModel loads it
  • Regenerate on model change; EF Core 9+ MSBuild integration (EFOptimizeContext) does it on build
  • Precompiled queries (--precompile-queries) generate interceptors; experimental, static queries only
  • Native AOT with EF Core 10 is still experimental and not recommended for production
  • Measure first: SQL time usually dominates; use start-up traces and BenchmarkDotNet

⏱ 30-second answer

They target two different overheads outside the SQL. Compiled queries (EF.CompileAsyncQuery) remove the per-execution work of looking up a LINQ query in EF Core's query cache (hashing and comparing the expression tree). EF Core already caches translations, so the gain is microseconds per call, worth it only for very hot queries. Compiled models (dotnet ef dbcontext optimize) remove start-up work: building the model by convention and reflection on first use, which can take seconds for hundreds of entity types. They must be regenerated when the model changes (EF Core 9+ can do it on build). Precompiled queries and Native AOT go further but are still experimental in EF Core 10. The trade-off: real gains in narrow cases, extra build steps and limitations everywhere else, so I measure first.

🗣 Full answer (senior)

How I would answer this in an interview

"When an EF Core query runs, there's work before the SQL: EF Core takes the LINQ expression tree, computes a cache key, and looks it up in its compiled query cache. The first time, it translates the query to SQL and builds a materialiser delegate; after that it reuses them, but the lookup still walks and compares the expression tree on every call. Separately, the first use of a context type builds the model: it scans entity types, applies conventions and your configuration. For a typical model that's tens of milliseconds; for a model with several hundred entities it can be several seconds of cold start.

Compiled queries attack the first cost. EF.CompileAsyncQuery turns the LINQ into a delegate once, so calls skip the cache lookup. Because EF Core already caches, the gain is small, a few microseconds per execution, and it only shows on queries running thousands of times a second where the SQL itself is trivial, like a key lookup. Compiled models attack the second cost. dotnet ef dbcontext optimize generates C# that constructs the model directly, and you load it with UseModel. The catch is that it's generated code: if someone changes the model and doesn't regenerate, it's out of date. EF Core 9 added MSBuild integration so it can regenerate on build, and some features have limitations with compiled models, so I check the docs list for the version in use.

For example, at [company] we had [a function app / container] with [about 600 entity types] where the first request after a scale-out took [around 8 seconds]. I [generated a compiled model and wired regeneration into the build], and the first request dropped to [about 1.5 seconds]. Beyond that, EF Core 9 introduced precompiled queries and Native AOT support, and as of EF Core 10 they're still marked experimental, so I wouldn't ship them to production yet. The mistake I see is reaching for compiled queries when the time is in SQL. I profile first."


Which overhead each one removes

Feature Removes Typical gain Cost
Query cache (built in) Re-translating LINQ each time Large, automatic Cache lookup per call
EF.CompileQuery / CompileAsyncQuery The cache lookup Microseconds per call Separate static delegate per query; no composition after compile
Compiled model (dbcontext optimize) Model building at first use Seconds for very large models Generated code to regenerate; feature limitations
Precompiled queries (--precompile-queries) Runtime translation entirely Start-up and AOT enablement Experimental; limitations on dynamic queries
Native AOT JIT and reflection Start-up, memory Experimental for EF Core 10; many restrictions

Production example

A serverless API [in a system I worked on] with about 600 entity types had cold starts of around 8 seconds, mostly model building, visible in a start-up trace. A compiled model brought the first request to about 1.5 seconds. Compiled queries on the hottest lookup, by contrast, saved about 4 microseconds per call: measurable in BenchmarkDotNet, invisible in production p95, so we kept only the compiled model.

🔍 What the interviewer is checking

Checks that the candidate understands where EF Core spends time outside SQL, can distinguish compiled queries from compiled models, knows the current status of precompiled queries and Native AOT, and measures before optimising.

Green flags

  • Explains the query cache and what compiled queries skip
  • Knows compiled models target start-up and must be regenerated (MSBuild integration)
  • States Native AOT and precompiled queries are still experimental in EF Core 10
  • Mentions the Expression.Constant cache-miss problem
  • Measures with start-up traces and BenchmarkDotNet

Red flags

  • Thinks EF Core translates every query from scratch every time
  • Recommends compiled queries for slow SQL
  • Claims Native AOT is production-ready for EF Core

📚 Learn in depth

1. The query pipeline and its cache

LINQ expression tree
   │  (every execution)
   ├─ parameter extraction: closure values become parameters
   ├─ cache lookup: hash + structural comparison of the tree
   │
   ├─ cache miss (first time): translate -> SQL + materialiser delegate -> store
   └─ cache hit: reuse SQL and delegate
   │
   └─ execute command, materialise rows

Parameter extraction and the cache lookup are the per-call overhead compiled queries remove; translation already happens only once. If you inline constants that change (for example by building expressions with Expression.Constant for user input), every variation is a cache miss and a new translation: that's the real performance bug to look for. It shows up as high CPU and a falling query cache hit rate in the EF Core event counters (dotnet-counters monitor Microsoft.EntityFrameworkCore).

2. Compiled queries

EF.CompileAsyncQuery((AppDbContext db, int id) => db.Orders.Single(o => o.Id == id)) returns a delegate that takes the context and parameters. EF Core translates it once; calls go straight to execution. Limits: you cannot compose more LINQ on the result, parameters must be passed as arguments, and each shape needs its own delegate. Gains are in the low microseconds per call, so they matter only at thousands of executions per second on queries whose SQL takes well under a millisecond.

3. Model building and compiled models

The model is built once per context type per process and then cached; every context instance reuses it. The cost is paid at first use: EF Core runs conventions over every entity type, reads attributes and your OnModelCreating, and builds the runtime model. That cost grows with entity and property count. A compiled model doesn't change how the model is used at run time; it changes how it is built. dotnet ef dbcontext optimize --output-dir CompiledModels --namespace Shop.Data.CompiledModels generates classes that construct the runtime model directly, and the context uses options.UseModel(AppDbContextModel.Instance). EF Core 9+ can generate it during build with the Microsoft.EntityFrameworkCore.Tasks package and <EFOptimizeContext>true</EFOptimizeContext>, which removes the stale-model risk. Some features have historically had limitations with compiled models; check the current list for your EF Core version.

4. Precompiled queries and Native AOT

EF Core 9 added experimental support for precompiling LINQ queries at publish time using C# interceptors, which also enables Native AOT. As of EF Core 10 (November 2026), Microsoft still marks Native AOT and query precompilation as experimental and not recommended for production. Known limitations: only queries the analyser can see statically are precompiled, so dynamically composed queries (built conditionally across methods, or from expression builders) are not supported; value converters that use captured state are not supported; and the database provider must implement support. Third-party reports have described build-time memory problems with PublishAot plus EFOptimizeContext in some 10.0.x patch versions, so pin and test patch versions if you experiment.

5. How to measure

  • Start-up: dotnet-trace collect around the first request, or simple timing around the first query; Application Insights request duration for the first request after a restart.
  • Per query: BenchmarkDotNet comparing a normal and a compiled query on a fast key lookup against a local database.
  • In production: compare SQL dependency duration with request duration; if SQL is 95% of the time, neither feature helps. Illustrative numbers: a compiled query saving 3 to 5 microseconds on a 0.3 ms lookup is about 1%; a compiled model saving 6 seconds of cold start on a 600-entity model is the whole problem.

Try it yourself

  1. Benchmark a key lookup as a normal query and with EF.CompileAsyncQuery; note the difference in microseconds and allocations.
  2. Generate a model with 300 entity types, time the first query cold, then generate a compiled model and repeat.
  3. Add <EFOptimizeContext>true</EFOptimizeContext> and confirm the compiled model regenerates on build after a model change.
  4. Build a query with Expression.Constant for user input in a loop and watch the query cache hit rate fall in dotnet-counters.
  5. Read the current EF Core docs page on Native AOT and precompiled queries and list the limitations that would block your app.

💻 Code

A compiled query for a hot lookup, and a compiled model wired into DI.

namespace Shop.Data;

using Microsoft.EntityFrameworkCore;

public sealed record ProductPrice(int Id, decimal Price);

public static class HotQueries
{
    // Translated once; each call skips the expression-tree cache lookup.
    public static readonly Func<AppDbContext, int, CancellationToken, Task<ProductPrice?>> PriceById =
        EF.CompileAsyncQuery((AppDbContext db, int id, CancellationToken ct) =>
            db.Products
                .Where(p => p.Id == id)
                .Select(p => new ProductPrice(p.Id, p.Price))
                .FirstOrDefault());
}

public sealed class PriceService(AppDbContext db)
{
    public Task<ProductPrice?> GetAsync(int id, CancellationToken ct) => HotQueries.PriceById(db, id, ct);
}
# Generate a compiled model once (or let MSBuild do it on every build, below).
dotnet ef dbcontext optimize --output-dir CompiledModels --namespace Shop.Data.CompiledModels
<!-- Shop.Data.csproj: regenerate the compiled model on build (EF Core 9+). -->
<PropertyGroup>
  <EFOptimizeContext>true</EFOptimizeContext>
</PropertyGroup>
<ItemGroup>
  <PackageReference Include="Microsoft.EntityFrameworkCore.Tasks" Version="10.0.*" PrivateAssets="all" />
</ItemGroup>
// Program.cs: load the generated model instead of building it at first use.
builder.Services.AddDbContext<AppDbContext>(o => o
    .UseSqlServer(builder.Configuration.GetConnectionString("Shop"))
    .UseModel(Shop.Data.CompiledModels.AppDbContextModel.Instance));

⚠ Common mistakes

  • Mistake: Using compiled queries to fix a slow endpoint. Why it is wrong: they save microseconds of EF Core overhead; slow endpoints are dominated by SQL time. Instead: compare SQL dependency time with request time first.
  • Mistake: Confusing compiled queries with compiled models. Why it is wrong: one removes per-call cache lookup, the other removes start-up model building. Instead: pick based on whether the problem is hot-path CPU or cold start.
  • Mistake: Generating a compiled model by hand and forgetting to regenerate it. Why it is wrong: the runtime uses a stale model, causing wrong mappings or errors after a model change. Instead: regenerate on build with MSBuild integration or add a CI check.
  • Mistake: Shipping Native AOT with EF Core 10 to production. Why it is wrong: Microsoft marks it experimental with significant limitations. Instead: keep it to experiments; use ReadyToRun and a compiled model for start-up today.
  • Mistake: Building queries with Expression.Constant for changing values. Why it is wrong: every value is a new cache entry and a new translation, costing CPU and memory. Instead: capture values in closures so EF Core parameterises them.
  • Mistake: Compiling every query "for performance". Why it is wrong: extra static delegates, no composition, harder code for no measurable gain. Instead: compile only proven hot queries.

🏛 Senior insight: trade-offs

Most EF Core time in production is SQL and network, so these features are for the cases where profiling shows EF Core itself on the critical path: cold starts with very large models (serverless, scale-to-zero containers, frequent scale-outs) and extremely hot, trivial queries. I keep compiled models generated by the build so they cannot go stale, and I treat precompiled queries and Native AOT as watch items until Microsoft drops the experimental label.

Option When it fits Cost When not to
Compiled query Hot key lookups at thousands of calls per second Static delegates, no composition Anything dominated by SQL time
Compiled model Large models, cold-start sensitive hosting Build step, feature limitations Small models (start-up already fast)
ReadyToRun / tiered PGO General start-up and JIT cost Larger binaries When AOT is required anyway
Precompiled queries / Native AOT Experiments, edge deployments Experimental in EF Core 10, many limits Production systems today

🔗 Follow-ups the interviewer may ask

  1. When: Candidate talks about measuring where query time goes Why: Checks they can see the SQL and trace it back to the code before optimising EF Core overhead
    How to answer

    For one query, ToQueryString() shows the SQL without running it. For a running app, LogTo(Console.WriteLine, LogLevel.Information) or, in ASP.NET Core, setting the Microsoft.EntityFrameworkCore.Database.Command log category to Information logs each command with its duration. TagWith("Orders list") puts a SQL comment in the statement (and TagWithCallSite() adds file and line), so a slow query found in Query Store or a trace leads straight back to the code. EnableSensitiveDataLogging adds parameter values to logs: useful locally, but it leaks personal data and secrets, so never in production. In production, Application Insights / OpenTelemetry record each SQL command as a dependency with timing, and capturing SQL text is opt-in. The trade-off is visibility versus log volume, cost and privacy.

  2. When: Candidate mentions query cache misses from dynamic queries Why: Checks they can build dynamic queries that stay parameterised and cache-friendly
    How to answer

    Start from db.Products.AsNoTracking() as an IQueryable<T> and add Where clauses conditionally; each one ANDs into the same SQL WHERE. For OR logic, combine Expression<Func<T,bool>> predicates by rebinding their parameters (or use LinqKit), never Func<T,bool>, which would force in-memory evaluation.

    For sorting, map the client's string to a whitelisted dictionary of key-selector expressions and always add ThenBy(x => x.Id) so paging is stable. Cap the page size on the server. Values captured in closures become SQL parameters, so there's no injection risk and plans are reused.

    The trade-off: flexible search is easy to compose, but every optional filter combination is a different SQL shape, so index for the common ones and test the translation.

  3. When: Candidate mentions the compiled query cache Why: Checks they know constants in expression trees create a cache entry per value
    How to answer

    EF Core's query cache key includes constants in the expression tree, so queries built with Expression.Constant(userValue), string-built dynamic LINQ, or EF.Constant on varying values create a new cache entry and a new translation for every value. The impact: CPU spent translating on every request instead of once, memory growing with cached entries (until the cache's size limit evicts them, causing more re-translation), and on SQL Server a matching flood of single-use plans in the plan cache. Fix it by capturing values in closures (they become SQL parameters), building dynamic predicates with parameter expressions, avoiding EF.Constant for high-cardinality values, and confirming with the query cache hit rate in dotnet-counters monitor Microsoft.EntityFrameworkCore.

🛠 Real-world problems: how you handle them

Eight-second cold starts after scale-out
Situation
An ASP.NET Core API on Azure Container Apps [in Australia East] with a legacy EF Core model of [about 600 entity types], scaling out from [2 to 20] replicas during [morning] peaks.
Signals
The first request on each new replica took [7-9 seconds]; Application Insights showed long first-request durations after each scale-out with short SQL dependencies; users saw timeouts during peak.
Investigation
Captured a start-up trace with dotnet-trace and saw most time in EF Core model building (convention processing) on the first query. Confirmed SQL calls were fast. Benchmarked the hottest query with and without `EF.CompileAsyncQuery`: about 4 microseconds difference.
Resolution
Immediately: added a warm-up step in the readiness probe that runs a trivial query before the replica takes traffic. Then generated a compiled model, enabled `EFOptimizeContext` in the build so it regenerates automatically, and loaded it with `UseModel`.
Prevention
A CI step that fails if the compiled model differs from a fresh generation; a start-up time metric with an alert; readiness probes that include database warm-up; a note in the ADR that precompiled queries and Native AOT are revisited when no longer experimental.

How to tell it (STAR)

**S:** Our [API] on Azure Container Apps had [7-9 second] first requests on every new replica, which hurt us during morning scale-outs. **T:** I was asked to bring cold-start latency down without over-provisioning. **A:** A dotnet-trace capture showed the time was EF Core building our [600-entity] model, not SQL. I added a warm-up query to the readiness probe as an immediate fix, then generated a compiled model, had the build regenerate it automatically, and checked in CI that it never goes stale. I also benchmarked compiled queries and found they saved only microseconds, so I left them out. **R:** First-request time dropped to about [1.5 seconds], and the readiness probe means users no longer hit cold replicas at all.

More in EF Core Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me