Backend Case Studies

Topic B1

N+1 queries

One request for the list, then one more for every row: why that is slow, and how to fetch everything at once.

10 min · beginner

Watch: count the lit posts. Each post is one question to the database. The first way asks many times; the second asks just twice.

ORM · 1 + NDATABASEpostsauthors1N = 8APP12345678N+1EAGER
Author data: one card per postPost rows (8 per page)Counter pins: one rises per queryEvery shuttle trip is one request (query) from the app to the database. N+1: 1 query for 8 articles, then 8 separate queries for each article's author, 9 queries in total, about 13.8 ms. Eager loading: 1 query for the articles and 1 query for all their authors, 2 queries in total, about 3.3 ms. Assumes a 1.0 ms round trip, 0.5 ms of work per query and 0.02 ms per row of data.
  1. SELECT * FROM posts ORDER BY id LIMIT 8;1.7 ms
  2. SELECT * FROM authors WHERE id = 3;1.5 ms
  3. SELECT * FROM authors WHERE id = 8;1.5 ms
  4. SELECT * FROM authors WHERE id = 1;1.5 ms
  5. SELECT * FROM authors WHERE id = 5;1.5 ms
  6. SELECT * FROM authors WHERE id = 6;1.5 ms
  7. SELECT * FROM authors WHERE id = 2;1.5 ms
  8. SELECT * FROM authors WHERE id = 7;1.5 ms
  9. SELECT * FROM authors WHERE id = 4;1.5 ms

Like shopping with too many trips

You need 8 items from a warehouse. Option one: go to the warehouse, get the list, come home. Go back for the first item, come home. Go back for the second, come home. And so on, 8 times. Nine trips in all. Option two: go with the full list and come home with everything. Two trips.

In the figure the warehouse is the database, the shuttle is one query (a request for data), and the tray at the front is the page the app is building. Every time the shuttle leaves, one counter pin goes up. Try both modes and compare the pins.

How it happens in code

Take a blog page that shows 8 articles with their authors' names. The most natural code looks harmless:

Code, for programmers1 query for the articles, then 1 more for every article
const posts = await db.post.findMany({ take: 8 });     // trip 1: the list
for (const post of posts) {
  const author = await db.author.findUnique({          // trips 2 to 9: one per post
    where: { id: post.authorId },
  });
  console.log(post.title, author.name);
}

Every query has to travel to the database and back, however little data it carries. For 8 articles the difference is 13.8 ms against 3.3 ms. For 100 articles: 155.5 ms against 7.0 ms. What costs is not the load, but the number of trips.

It often slips through because on a laptop the database is close and the data is small. On a real server with thousands of visitors, those little trips pile up.

The fix: fetch it all at once

Almost every ORM (the library that connects your code to the database) has a way to say "fetch the authors too while you're at it". It is called eager loading.

Code, for programmers2 queries, however many articles
const posts = await db.post.findMany({
  take: 8,
  include: { author: true },   // one extra query fetches every author at once
});
FrameworkEager loading
Prismainclude: { author: true }
Rails (ActiveRecord)Post.includes(:author)
DjangoPost.objects.select_related("author")
Laravel (Eloquent)Post::with('author')
Sequelizeinclude: [Author]
GraphQLDataLoader

Without an ORM the idea is the same: collect every author id, fetch them all in one query, then match them up in the app.

Code, for programmersOne query for every author, then matched with a Map
const posts = await sql`SELECT * FROM posts ORDER BY id LIMIT 8`;
const ids = [...new Set(posts.map((p) => p.author_id))];
const authors = await sql`SELECT * FROM authors WHERE id = ANY(${ids})`;
const byId = new Map(authors.map((a) => [a.id, a]));    // instant lookup by id
for (const post of posts) console.log(post.title, byId.get(post.author_id).name);

Quiz

  1. A page shows 50 comments with their authors, and authors are fetched one at a time. How many queries are sent?

  2. With eager loading, how many queries for 50 comments and their authors?

  3. Why is N+1 slow when every single query is fast?

  4. After fetching every author in one query, which data structure makes matching them fast?

0 of 4 answered.