Rails N+1 Queries: How to Detect and Fix Them with Prosopite, Bullet and strict_loading

A Rails N+1 query happens when you load a list of records and then run one extra query per record to fetch an association, so 50 orders become 51 queries. It’s the most common reason a Rails page gets slower as data grows. This guide shows how to detect N+1 queries automatically in development and tests, fix them with includes, and stop new ones from shipping with strict_loading.
TL;DR
- An N+1 is one query for the list plus one per row for an association; the fix is almost always
includes(:association).- Prosopite catches N+1s Bullet misses and can fail your test suite when one appears.
strict_loadingturns a lazy load into an exception, so a forgottenincludesbreaks in development instead of slowing production.
What is an N+1 query in Rails?
It’s a loop that triggers a lazy-loaded association. This view code looks harmless:
<%# app/views/books/index.html.erb %>
<% @books.each do |book| %>
<p><%= book.title %> by <%= book.author.name %></p>
<% end %>
But the log shows one SELECT for the books and one per book for its author:
Book Load (0.4ms) SELECT "books".* FROM "books" LIMIT 50
Author Load (0.1ms) SELECT "authors".* FROM "authors" WHERE "authors"."id" = 1 LIMIT 1
Author Load (0.1ms) SELECT "authors".* FROM "authors" WHERE "authors"."id" = 2 LIMIT 1
Author Load (0.1ms) SELECT "authors".* FROM "authors" WHERE "authors"."id" = 3 LIMIT 1
Each query is fast, which is why N+1s hide in development. In production, 50 round trips at 1–2 ms of network latency each add 50–100 ms to the page, and they also hold a connection from the pool for that time.
Prerequisites
- Rails 7.2 or 8.x (the code here was tested on Rails 8.1 with Ruby 3.3).
- Development logs showing SQL (the default in
development).
Step 1: Detect N+1 queries with Prosopite
Prosopite detects N+1s by spotting the same query fingerprint repeated from the same call stack. That’s why it catches cases Bullet misses, such as queries that don’t come from an association.
# Gemfile
group :development, :test do
gem "prosopite"
gem "pg_query" # optional, more precise fingerprints on PostgreSQL
end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
if Rails.env.development?
around_action :n_plus_one_detection
def n_plus_one_detection
Prosopite.scan
yield
ensure
Prosopite.finish
end
end
end
# config/environments/development.rb
config.after_initialize do
Prosopite.rails_logger = true
Prosopite.add_footer = true
end
Then make the test suite fail on any N+1:
# config/environments/test.rb
config.after_initialize do
Prosopite.raise = true
end
# test/test_helper.rb
class ActiveSupport::TestCase
setup { Prosopite.scan("#{self.class}##{name}") }
teardown { Prosopite.finish }
end
Pro Tip: use around_action, not a before_action/after_action pair. If the action raises, the after_action never runs and the scan stays open.
Prosopite or Bullet?
| Prosopite | Bullet | |
|---|---|---|
| How it detects | Repeated query fingerprints | Association loading patterns |
| Non-association N+1s | Yes | No |
| Unused eager loading warnings | No | Yes |
| Fail tests | Prosopite.raise = true |
Bullet.raise = true |
Bullet is still useful for one thing Prosopite doesn’t do: warning when you includes an association you never use. Many teams run Prosopite in tests and Bullet in development.
Step 2: Fix it with includes, preload or eager_load
Tell Active Record to load the association up front:
# app/controllers/books_controller.rb
def index
@books = Book.includes(:author).order(created_at: :desc).limit(50)
end
Now there are two queries, whatever the number of books:
Book Load (0.4ms) SELECT "books".* FROM "books" ORDER BY "books"."created_at" DESC LIMIT 50
Author Load (0.3ms) SELECT "authors".* FROM "authors" WHERE "authors"."id" IN (1, 2, 3, ...)
| Method | SQL | Use it when |
|---|---|---|
preload |
Separate query per association | You never filter by the association |
eager_load |
One LEFT OUTER JOIN |
You filter or sort by the association’s columns |
includes |
preload, switching to a JOIN when you reference the table |
Default choice |
Nested associations take a hash: Book.includes(author: :publisher, reviews: :user). For counts, use a counter cache instead of calling book.reviews.count in the loop.
Step 3: Block lazy loading with strict_loading
strict_loading makes a lazy load raise instead of silently running a query:
Book.strict_loading.first.author
# ActiveRecord::StrictLoadingViolationError:
# `Book` is marked for strict_loading. The Author association named `:author` cannot be lazily loaded.
Turn it on for the whole app, but log in production instead of raising:
# config/application.rb
config.active_record.strict_loading_by_default = true
# config/environments/production.rb
config.active_record.action_on_strict_loading_violation = :log
On an existing app, enable it per association first (has_many :reviews, strict_loading: true) on your busiest models, then go app-wide once the violations are gone.
Verify it works
bin/rails test
Remove an includes on purpose and run the tests again. The test that renders the page should fail with Prosopite::NPlusOneQueriesError, listing the repeated queries and a suggested fix such as Book.includes(:author). Put the includes back and it passes.
Troubleshooting
PG::UndefinedTable: missing FROM-clause entry for table “authors”
You used includes with a string condition on the association’s table, so Rails didn’t know it needed a JOIN. Add .references(:author), or use eager_load(:author).
Prosopite reports an N+1 in a background job
The scan only covers what you wrap. Wrap the job’s perform the same way, or allowlist a known path with Prosopite.allow_stack_paths = ["app/jobs/legacy_export_job.rb"] until you fix it.
StrictLoadingViolationError in a serializer or mailer
The record was loaded without the association the serializer needs. Add it to the query that builds the record, for example Order.includes(:line_items).find(id), instead of turning strict loading off.
Once queries are clean, the Rails performance optimization guide covers the next fixes by impact, and the connection pool guide explains why fewer queries per request also means fewer pool timeouts.
Author Perspective
I’ve stopped hunting N+1s by reading logs. On every app I take over, I add Prosopite to the test suite on day one and fix whatever fails. It’s usually a dozen cases, most of them in serializers and mailers nobody looks at. Then I turn on strict_loading_by_default in development. It’s annoying for a week, then it simply becomes how you write queries.
FAQ
Does includes always fix an N+1 query in Rails?
Only if the code then uses the loaded association. Calling a scope or a method with its own query on it, such as book.reviews.where(approved: true), runs a new query per record anyway. Preload a scoped association instead, for example has_many :approved_reviews.
Should I use strict_loading in production?
Yes, but set action_on_strict_loading_violation to :log in production. You get a log line for every lazy load without breaking a page for users, and you fix the cases before making it raise.
Is an N+1 query always a problem?
No. Two or three lazy loads on a page that shows one record cost almost nothing. It becomes a problem in lists, where the number of queries grows with the number of rows.