Entity Framework Core at Scale: Why Your App Crumbles with Millions of Records (and How to Prevent It)

Automated English translation of the original Spanish article. Code examples keep their original identifiers.

When you’re working on small or medium projects with Entity Framework Core, everything runs like a charm: expressive queries, clean code, productivity through the roof.

And then suddenly… millions of records arrive.

It’s not that the data grows gradually and gives you time to react. No. One day you’re comfortable with 50,000 rows, and the next day your application starts struggling: queries that used to run in milliseconds now take seconds (or minutes), SaveChanges() turns into torture, memory spikes, and timeouts pop up everywhere.

This article is a practical, direct guide to understanding why this happens and, above all, what you can do right now to keep your application breathing when data gets serious. Updated for 2026 with the best features EF Core 8 and 9 bring to the table.

1. Why Does Everything Break with High Data Volumes?

EF Core isn’t poorly built. Its default design is simply tuned for convenience, not for extreme scale without tuning.

The Main Culprit: The Change Tracker

Every time you load an entity, EF Core pushes it into its Change Tracker. That system:

  • remembers the original state of each object
  • detects what changed
  • generates the corresponding INSERT/UPDATE/DELETE statements

Sounds great… until you have hundreds of thousands or millions of entities in memory. The Change Tracker’s overhead grows almost linearly (many internal operations are O(n)). With 10 records, you won’t even notice. With 100,000, it becomes noticeable. With several millions… it’s a brutal bottleneck.

Small vs. Large: How Behavior Shifts

ScenarioWhat Actually Happens
Small projectEverything is fast, low latency, GC is practically invisible
Large datasetFrequent GC runs, high CPU, queries slow down
Bulk operationsSaveChanges() can jump from seconds to minutes (or worse)

Warning Signs That Something Is Wrong (Your Personal Radar)

  • Application memory steadily climbs (especially inside loops)
  • The Garbage Collector is working like crazy
  • High CPU caused solely by EF operations
  • You see slow queries in SQL logs
  • Timeouts on operations that “should be fast”

If you spot two or more of these… it’s time to take action.

2. Query Patterns That Actually Scale

Golden Rule for Reads: AsNoTracking()

If you’re only reading and not modifying anything, always use:

var data = context.Orders
    .AsNoTracking()
    .Where(x => x.Status == "Completed")
    .ToList();

This tells EF: “don’t put these in the Change Tracker.” Less memory, less CPU, better performance. It’s one of the cheapest and most effective optimizations you can make.

Project to DTOs Instead of Fetching Full Entities

Don’t pull the entire heavy object if you only need three fields:

var orders = context.Orders
    .Select(o => new OrderDto
    {
        Id = o.Id,
        Total = o.Total,
        Date = o.OrderDate
    })
    .ToList();

Less data over the network, fewer objects in memory, less work for the Change Tracker.

Pagination: Forget Offset on Large Tables

This does NOT scale well:

.Skip(100_000).Take(50)

Beyond a certain threshold, a large OFFSET forces the database to scan everything that came before -> terribly slow.

Better: keyset pagination (or seek method)

.Where(x => x.Id > lastId)
.OrderBy(x => x.Id)
.Take(50)

It leverages indexes, is predictable, and scales linearly.

3. Never Load EVERYTHING into Memory (Please)

The classic mistake I’ve seen a thousand times:

var all = context.Logs.ToList();

With 5 million rows -> goodbye memory, hello OutOfMemoryException or the GC freezing everything for seconds.

The Grown-Up Way: Batch Processing

int batchSize = 1000;
long lastId = 0;

while (true)
{
    var batch = context.Logs
        .Where(x => x.Id > lastId)
        .OrderBy(x => x.Id)
        .Take(batchSize)
        .AsNoTracking()
        .ToList();

    if (!batch.Any()) break;

    // Procesar el batch (p.ej. enviar a un queue, calcular algo, etc.)
    lastId = batch.Max(x => x.Id);
}

This pattern is a lifesaver whenever you need to touch millions of rows.

How to Hunt Down Problematic Queries

  • Enable EF logging (carefully in production)
  • Use SQL Profiler, pgAdmin, Azure Data Studio, etc.
  • MiniProfiler or Application Insights inside the app
  • Look for: massive Includes, N+1 patterns, unnecessary SELECT * queries

4. Bulk Operations: Where People Suffer the Most

What NOT to do:

context.AddRange(muchasEntidades);
context.SaveChanges();

EF generates thousands of individual INSERTs + full tracking. Absolutely terrible.

Slightly Better: Batching with SaveChanges

int batchSize = 1000;

foreach (var chunk in entities.Chunk(batchSize))
{
    context.AddRange(chunk);
    context.SaveChanges();
}

Better than nothing, but it still relies on the Change Tracker and transactions per batch.

The Modern Way (EF Core 7+, Improved in 8 and 9): ExecuteUpdate / ExecuteDelete

// Marcar como procesados miles o millones de filas
await context.Logs
    .Where(l => l.Created < thresholdDate && !l.Processed)
    .ExecuteUpdateAsync(setters => setters
        .SetProperty(l => l.Processed, true));

// Borrar órdenes antiguas
await context.OldOrders
    .Where(o => o.OrderDate < twoYearsAgo)
    .ExecuteDeleteAsync();

A single SQL statement, loading nothing into memory, zero Change Tracker involvement. A night-and-day difference.

Limitation: you can only execute what SQL can directly understand. If you need complex per-row logic -> you’ll need batching + a bulk library.

Bulk Libraries for Heavy Lifting

EFCore.BulkExtensions, Entity Framework Extensions, etc. provide:

  • BulkInsert
  • BulkUpdate
  • BulkDelete
  • BulkMerge / Upsert

They remain the undisputed kings for bulk inserts or very specific scenarios.

5. Model and Schema Design: Where Major Performance Is Won (or Lost)

Indexes: Not Optional, Mandatory

If you frequently filter, sort, or join by a column, index it. Period.

  • Primary key -> already indexed (good)
  • Frequent WHERE columns (Status, Created, UserId, etc.) -> simple index
  • Common combinations (WHERE + ORDER BY) -> composite index
  • JOIN columns -> index on the foreign key

Without proper indexes, EF Core might generate decent queries… but the database will execute full table scans. And with millions of rows, that means death.

Also make sure database statistics are up to date (in SQL Server: UPDATE STATISTICS; in Postgres it’s usually automatic, but always worth verifying).

Separate What Is Heavy

Logs, audit trails, change history, events… don’t put them in the same table as core entities if you can avoid it.

Real options:

  • Separate tables (Logs, AuditLog, OrderHistory…)
  • Partitioned tables (by date, by tenant…)
  • Separate databases for write vs. analytics (we’ll cover CQRS shortly)

This prevents a heavy reporting query from dragging down your entire transactional application.

Controlled Denormalization (Yes, Sometimes You Have To)

For critical reporting or high-frequency queries, duplicating data can be the cheapest option.

Common examples:

  • A computed and persisted TotalWithTax column
  • An “OrderSummary” table with precomputed data

Since EF Core 7+, you can use JSON columns natively (very handy in Postgres with jsonb, in SQL Server with NVARCHAR(MAX) + JSON checks):

modelBuilder.Entity<Order>()
    .Property(o => o.Details)
    .HasColumnType("jsonb");  // Postgres
    // o en SQL Server: .HasColumnType("nvarchar(max)");

This allows you to store complex structures without creating 20 extra columns.

6. Lightweight Read/Write Separation (“Lightweight” CQRS)

You don’t need microservices architecture or Event Sourcing to benefit from this.

Simple idea:

  • Write: use standard EF Core (with Change Tracker, validations, business logic)
  • Read: use the fastest, most lightweight approach available

Options for reads:

  • Raw SQL using FromSqlRaw() or FromSqlInterpolated()
  • Dapper (extremely lightweight and fast)
  • Database views or materialized views
  • A second DbContext optimized strictly for reads

Example of context separation:

// WriteDbContext --> Change Tracking activado, con todas las entidades
public class WriteDbContext : DbContext { ... }

// ReadDbContext --> AsNoTracking por defecto en el constructor
public class ReadDbContext : DbContext
{
    public ReadDbContext(DbContextOptions options) : base(options)
    {
        ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
    }
}

In your DI setup:

services.AddDbContext<WriteDbContext>(...);
services.AddDbContext<ReadDbContext>(...);

And you inject whichever fits your use case.

Very Useful Bonus: DbContext Pooling for High-Traffic APIs

In applications with high concurrent requests (Web API, Blazor Server, etc.):

builder.Services.AddDbContextPool<MyDbContext>(options =>
    options.UseSqlServer(connectionString));

Reduces the constant creation and disposal of DbContext instances -> lowers GC pressure, improves throughput under heavy load.

7. Real-World Case Study: Reprocessing Millions of Records

The Approach We All Try the First Time (and Never Should Again)

var logs = context.Logs.ToList();

foreach (var log in logs)
{
    log.Processed = true;
}

context.SaveChanges();

Result with 3–5 million rows:

  • Memory > 3–5 GB
  • Duration: 30 minutes to several hours
  • Potential timeouts, OutOfMemory exceptions, locked database

Realistic and Effective Approach (2026)

  1. If the update is uniform (the same change across all matching records) -> ExecuteUpdateAsync
await context.Logs
    .Where(l => l.Created < threshold && !l.Processed)
    .ExecuteUpdateAsync(s => s.SetProperty(l => l.Processed, true));

Typical duration: seconds to a few minutes.

  1. If you need per-record logic -> batch reading + processing + optimized writes
  • AsNoTracking() + keyset pagination
  • Process batch
  • Save with ExecuteUpdateAsync when possible, or via a bulk library
  1. For massive inserts or upserts -> EFCore.BulkExtensions or similar

Typical Real-World Results (Approximate)

StrategyTime (Millions of Rows)Peak Memory
Load everything + SaveChanges30–120 minutes>2–5 GB
Batches of 1,000 with SaveChanges5–15 minutes300–800 MB
ExecuteUpdateAsync / ExecuteDelete30 seconds – 3 minutes<200 MB
Bulk library (insert/update)10 seconds – 2 minutes<150 MB

The difference isn’t “slightly better.” It’s fundamentally structural.

8. Anti-Patterns I See All the Time (Avoid Them)

  • Calling .ToList() or .ToArray() “just in case”
  • Overusing .Include() and dragging in half the entity graph
  • Using EF Core for heavy analytical reporting (dashboards, BI…)
  • Massive transactions wrapping thousands of changes
  • Failing to index filtered columns
  • Mixing heavy reads and writes in the same context
  • Skipping DbContext Pooling in high-concurrency APIs

9. Quick Checklist Before Your App Scales (or When It’s Already Suffering)

  • Are you using AsNoTracking() on all read-only queries?
  • Do you project to DTOs or anonymous types when you don’t need modifications?
  • Do you use keyset pagination instead of offset for deep pages?
  • Do you process high data volumes in batches?
  • Are you taking advantage of ExecuteUpdateAsync and ExecuteDeleteAsync?
  • Do you have indexes on all frequent WHERE/ORDER BY/JOIN columns?
  • Are database statistics up to date?
  • Do you use bulk libraries for massive inserts or merges?
  • Have you considered separating reads and writes (at least with two DbContexts)?
  • Do you monitor SQL logs + memory/CPU metrics in production?

Scale EF Core to Match Your App’s Size

Entity Framework Core is an incredible tool. On small to medium projects, it makes you feel like a superhero: you write expressive code, switch databases in minutes, and everything “just works.”

Yet when data shifts from “thousands” to “millions,” EF Core doesn’t break… it behaves exactly as designed. The problem is almost never the library itself. It’s that we keep using it with the exact same patterns we used back when we had 10,000 rows.

The good news: with relatively simple adjustments (AsNoTracking, projections, keyset pagination, batching, ExecuteUpdate/Delete, solid indexes, and a bulk library when needed), you can multiply performance by 10x, 50x, or even 100x without ditching EF Core.

The key is knowing where EF Core adds value (business logic, transactions, consistency) and where it costs you dearly (bulk reads, reporting, mass operations). In those latter cases, don’t hesitate to reach for lighter tools or raw SQL.

So next time someone tells you “EF Core doesn’t scale,” ask them how many records they have and how they’re writing their queries. Because most of the time it’s not that EF Core won’t scale… it’s that we’re still using it like we’re querying a 500-row test database.

Have you run into any of these situations? What trick saved your skin when dealing with millions of records? Let me know in the comments—there’s always something new to learn.

Keep on coding.