February 19, 2025

Paul Gradie

Read Time: ~8 minutes

<aside> 📌 At Empower, we seek individuals who challenge personal assumptions, value ownership and trust, and strive for excellence to inspire and empower their team. If this article connected with you, join our team!

Join Empower.

</aside>

<aside> 📎 In this post, Paul Gradie reveals how the notorious N+1 problem in EF Core—where seemingly simple data retrieval turns into a series of inefficient database trips—can be the hidden culprit behind performance woes. He breaks down how lazy loading and loops can lead to unnecessary queries, and shares actionable fixes to streamline your code. Dive in to uncover tips that will help you optimize your data access and keep your app running smoothly!

</aside>

https://open.spotify.com/episode/0EW6vGFOrdSyH1rFSL9wto?si=a589530848664d09

You’ve probably heard of the N+1 problem. Maybe someone mumbled it during a code review. Maybe it came up when your team was debugging a mysteriously sluggish app. Or, if you're like me, you might have just nodded confidently and made a mental note to Google it later. Whatever the case, if you’re working with Entity Framework Core (EF Core) and relational data, the N+1 problem is a lurking performance killer.

Let’s unravel it together.


What Is the N+1 Problem?

In summary - it is database lookup problem where your code is making far too many trips back and forth to the store to retrieve records one at a time instead of returning them all at once.

Imagine you're hosting a pizza party for your friends. You call up your favorite pizza place and order 10 pizzas - one for each friend.

The delivery service brings you the 10 pizzas, but here's the catch: they only bring the crust and sauce. No cheese, no toppings. They promise to bring the toppings separately. So, one by one, they return, each time bringing just a single topping for one pizza. They do this 10 times—once for each pizza.

By the time the last pizza finally gets its toppings, your friends are starving and frustrated. The pizza party has turned into a disaster, and you're wondering why you didn’t just order the whole pizza, toppings and all, in a single trip.

This is the N+1 problem in EF Core. It happens when your application makes 1 query to fetch a list of entities (e.g., 10 pizzas) and then N additional queries to fetch related data for each item in that list (e.g., the toppings for each pizza). Instead of efficiently retrieving everything in one go, the app repeatedly fetches extra data in individual queries, causing delays and inefficiency.