Understanding Rails

Understanding Rails · Season 3: Active Record in depth

The N+1 query

Episode 20 · deep dive · about 4 minutes · Rails 8.1 · by

How was this episode?

The series' author reads every note, and no one else sees it. When something is wrong or unclear, it gets fixed and the episode re-cut. How this series stays right.

Was it clear?

Not endorsed yet. Are you a Rails developer? What's an endorsement?

Endorse this version To endorse: create an account, confirm your email, then link GitHub.

What changed

  • Version 2, November 20, 2026: Said that you must call notes_count or notes.size to use the counter cache, and that includes needs references with a SQL string.

Spot it in the log, fix it with includes, and keep it fixed.

Free to watch. If it helped, support the series.

Transcript

0:00 The N+1 query

Episode twenty. The N plus one query. It's the slow page you'll write by accident, in a view that looks perfectly fine. Today: how to spot it in the log, fix it with one line, and keep it fixed.

0:17 An innocent page

Here's an innocent page: the notes list. Each note shows its body, its notebook's name, and its tags. Two short lines, in the note partial.

0:27 Reading the log

Load it, and read the development log. The first query loads the notes. Then, for the first note, a query for its notebook, and another for its tags. Then the same two again for the next note. And the next.

0:41 N plus one

That's the N plus one: one query for the list, then one more for each of the N rows. This page has two of them at once. Five notes, eleven queries.

0:52 The arrow lines

The log tells you exactly where. Under each query, an arrow line points at the file and the line that asked for it: the note partial, line four. Rails shows these in development, because verbose query logs is on.

1:06 CACHE

Some lines say cache. Inside one request, Rails remembers a query it has already run, so the second look at the Work notebook comes from memory. That hides some of the cost. It doesn't fix the problem.

1:20 At 500 notes

Five notes feels fine. So we tried five hundred. One thousand and one queries, and the page took half a second, with the database on the same machine. Across a network to a real database server, every one of those trips costs more.

1:36 includes

The fix is one line, in the controller. Instead of Note dot all, Note dot includes, notebook, and tags.

1:44 Four queries

Now the log shows four queries, however many notes there are: the notes, then their notebooks with where id in, then their taggings, then their tags.

1:54 Before and after

At five hundred notes: four queries, and eighty eight milliseconds. The same page, and the same data, about six times faster.

2:03 preload and eager_load

Includes picks between two strategies, and you can name either one yourself. Preload runs a separate query for each association, like the ones we just saw. Eager load joins everything into one big query. Includes chooses preload, unless you filter by the association with a hash, or sort by it. Then it switches to eager load. With a SQL string, add references.

2:28 strict_loading

Fixing it once isn't enough. The next edit to that partial can bring it right back. Strict loading makes Rails refuse instead. Note dot strict loading, dot first, dot notebook, raises a strict loading violation error, the moment anything tries to load an association lazily. Set it on a model, and it guards every query of that model.

2:50 A test that counts

Or guard it with a test. Assert queries count, four, around a request for the notes page. With includes, it passes. Take includes away, and it fails: five instead of four queries were executed, and the message lists every one.

3:06 Small data is enough

Notice that the test data has only two notes, and it already caught the problem. An N plus one grows with the rows, so even a little data is enough to see it.

3:17 Counting in a loop

Counting has the same trap. Notebook dot all, and for each one, notes dot count, runs a count query for every notebook. The counter cache from episode eighteen keeps that number on the notebook, so read notes underscore count, or notes dot size, instead.

3:34 includes isn't free

Includes isn't free, either. It loads every associated row, whether the page uses it or not. Include what the page shows, and nothing more.

3:45 The rules

So: read your log, and look for the same query repeating. Load associations with includes, where the records are loaded. And keep it fixed, with strict loading, or a test that counts.

Next: validations, and the errors that come back from them.

Check your understanding

  1. A page loads 10 notes, then shows each note's notebook name. Nothing is preloaded. How many queries run?

    • 2
    • 10
    • 11
    • 20
    Show answer

    11. One query for the list, then one more for each of the 10 notes. That is the N plus one. Source: Active Record Query Interface: N + 1 queries problem (Rails Guides 8.1).

  2. You change Note.all to Note.includes(:notebook). What happens to the number of notebook queries as the list grows?

    • It stays at one, loading every notebook with WHERE id IN
    • It still grows by one per note, but the queries are cached
    • It drops to zero, because notebooks are joined into the notes query every time
    Show answer

    It stays at one, loading every notebook with WHERE id IN. includes loads the notes, then all their notebooks in one query, however many notes there are. Source: Active Record Query Interface: includes (Rails Guides 8.1).

  3. What does Note.strict_loading.first.notebook do?

    • Loads the notebook with a warning in the log
    • Returns nil
    • Loads the notebook and every note in it
    • Raises ActiveRecord::StrictLoadingViolationError
    Show answer

    Raises ActiveRecord::StrictLoadingViolationError. Strict loading makes Rails refuse to load an association lazily, so the N plus one fails loudly instead of slowly. Source: Active Record Query Interface: strict_loading (Rails Guides 8.1).

  4. A test wraps a request for the notes page in assert_queries_count(4). Someone removes the includes. What happens?

    • The test still passes, because the test data is small
    • The test fails, because more than 4 queries ran
    • The test is skipped
    Show answer

    The test fails, because more than 4 queries ran. assert_queries_count checks the exact number of queries in the block. Even two notes add queries without includes. Source: ActiveRecord::Assertions::QueryAssertions (Rails API 8.1).

Sources

Every example in this episode was run on Rails 8.1.4.1 and Ruby 4.0.2.

Comments

Sign in to comment or sign up.