Sunday, November 16, 2025

EF - N+1 Problem

 ✅ What is the N+1 Query Problem?

The N+1 problem occurs when your code runs:

  • 1 query to load a list of parent records

  • + N additional queries to load related data for each item individually

So total queries = 1 + N
This is hugely inefficient.


🟦 Simple Example (Best way to understand)

Suppose you want to load a list of Employees and their Projects.

You write:

var employees = context.Employees.ToList(); foreach (var emp in employees) { Console.WriteLine(emp.Projects.Count); }

❌ What actually happens with Lazy Loading:

Query 1:

SELECT * FROM Employees;

Now assume Employees table has 10 records.

When we loop through them, EF loads Projects for each employee:

Query 2:

SELECT * FROM Projects WHERE EmployeeId = 1;

Query 3:

SELECT * FROM Projects WHERE EmployeeId = 2;

Query 4:

SELECT * FROM Projects WHERE EmployeeId = 3;

… and so on 10 times.


✔ Total queries = 1 (main query) + 10 (project queries) = 11 queries

This is the N+1 problem.


🟥 Why is this bad?

  • Causes too many database round-trips

  • Slows applications massively

  • Wastes network + DB CPU

  • Very harmful in Web APIs, where response time matters


🟩 How to Fix the N+1 Problem? (Eager Load)

Use .Include():

var employees = context.Employees .Include(e => e.Projects) .ToList();

✔ SQL Generated (Single JOIN Query):

SELECT * FROM Employees LEFT JOIN Projects ON Projects.EmployeeId = Employees.Id;

✔ Total queries = 1 query only

No matter how many employees exist.


🟧 Interview Answer (Best Version)

The N+1 problem happens when the application fires one query to fetch the main data and then fires N additional queries to load related data for each item. This usually happens with lazy loading.

For example, loading 100 employees and then loading each employee’s projects separately results in 101 queries.

The solution is using eager loading with .Include() to fetch all related data in a single query.


🟦 Analogy (Very Easy to Remember)

Imagine you want 10 grocery items.

❌ Lazy Loading Way (N+1)

  • You go to the store (1 trip)

  • Then you go back 10 separate times to buy each item (10 trips)

Total trips = 11

✔ Eager Loading Way

  • You go once and buy all 10 items together

Total trips = 1

No comments:

Post a Comment

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...