Andrew's Digital Garden

The N+1 problem

Introducing a [[microservices]] [[architecture]] means you have to solve some new problems. One of these is how to combine [[data]] across multiple services, as a database join may not work anymore.

The N+1 problem is a problem of querying too much data. Or rather, making too many queries. 1 query for the original table, and N queries for the related table.

SELECT * FROM Orders o JOIN Customer c ON c.CustomerId = o.CustomerId

Is one query

var customers = GetCustomers(); foreach (var c in customers) { var orders = GetOrders(c.CustomerId); // … }

Looks okay, but is actually N+1.

The solution to the problem is to eagerly load dependent relationships before iterating them.

[[smells]]

The N+1 problem