N+1 queries in Rails: how to find them, fix them and keep them from coming back
What the N+1 problem is in Active Record, when to use includes, preload or eager_load, and how strict_loading stops regressions.
In short
An N+1 query happens when code loads a list of records with one query and then fires one extra query per record to read an association. In Rails you fix it by loading the association up front with includes, preload or eager_load; to prevent regressions, enable strict_loading, which raises (or logs) whenever an association is lazily loaded.
What an N+1 query is
The name describes the query count: 1 query to fetch the main list and N additional queries, one per item, when an association is accessed. The code looks harmless because Active Record loads associations lazily: the query only runs when the attribute is read.
posts = Post.order(created_at: :desc).limit(20)
posts.each do |post|
puts "#{post.title} — #{post.author.name}"
end
This snippet runs 21 queries: one for the posts and twenty for the authors. The development log makes the pattern easy to spot, because the same query repeats with different IDs:
SELECT "posts".* FROM "posts" ORDER BY "posts"."created_at" DESC LIMIT 20
SELECT "authors".* FROM "authors" WHERE "authors"."id" = $1 LIMIT 1 [["id", 7]]
SELECT "authors".* FROM "authors" WHERE "authors"."id" = $1 LIMIT 1 [["id", 3]]
SELECT "authors".* FROM "authors" WHERE "authors"."id" = $1 LIMIT 1 [["id", 7]]
...
With 20 records the cost goes unnoticed. With a paginated list of 100 items and two associations per item, that is 201 round trips to the database per request, and the network latency between application and database starts to dominate response time.
includes, preload and eager_load: which one to use
All three solve the problem by loading the association before the loop, but they generate different SQL.
| Method | Generated SQL | When to use it |
|---|---|---|
preload | One separate query per association, with WHERE id IN (...) | When you only need to display the associated data |
eager_load | A single query with LEFT OUTER JOIN | When you need to filter or sort by columns of the association |
includes | Uses preload by default and switches to eager_load when the query references the associated table | A reasonable default when you don't want to decide manually |
# 2 queries: posts + authors WHERE id IN (...)
Post.preload(:author).limit(20)
# 1 query with LEFT OUTER JOIN, allows filtering by the association
Post.eager_load(:author).where(authors: { active: true })
# includes decides on its own: here it becomes eager_load because of the where on authors
Post.includes(:author).where(authors: { active: true })
# nested associations
Post.includes(comments: :author).limit(20)
A practical note: eager_load on has_many associations multiplies the returned rows (a post with 50 comments becomes 50 rows in the result). For large lists, preload usually transfers less data, even though it runs more than one query.
Counting: count, size and counter_cache
A less obvious N+1 shows up in counts. post.comments.count always runs a SELECT COUNT(*), even when the comments were already loaded with includes. post.comments.size, on the other hand, uses the loaded collection when it exists and only queries the database when it doesn't.
posts = Post.includes(:comments).limit(20)
posts.each { |post| post.comments.count } # 20 COUNT queries, ignores the preload
posts.each { |post| post.comments.size } # 0 extra queries
When the page only needs the number, loading every comment is waste. In that case a counter_cache keeps the count in a column on the post itself:
class Comment < ApplicationRecord
belongs_to :post, counter_cache: true # requires a posts.comments_count column
end
Preventing regressions with strict_loading
Fixing an N+1 once doesn't stop another one from appearing in the next view change. Since Rails 6.1, strict_loading turns lazy loading into an error, so the problem surfaces in tests instead of in production.
# On a single query
posts = Post.strict_loading.limit(20)
posts.first.author # => ActiveRecord::StrictLoadingViolationError
# On a whole model
class Post < ApplicationRecord
self.strict_loading_by_default = true
end
# Application-wide (config/application.rb or per environment)
config.active_record.strict_loading_by_default = true
In an existing codebase, turning strict mode on globally breaks a lot at once. Gradual adoption works better: set config.active_record.action_on_strict_loading_violation = :log in production to only record violations, keep raising in development and test, and fix each spot as it shows up.
How to find N+1 queries in an existing application
- Development log: look for the same query repeated with different IDs within a single request.
- The Bullet gem: detects N+1 queries and also the opposite case, when an
includesloads data that is never used. - Tests with strict_loading: running the suite with strict mode on reveals the lazy-loading spots that your tests cover.
- APM in production: tracing tools show requests with dozens of identical database spans.
Once the N+1 is gone, the next bottleneck is usually the query itself. If it filters or sorts by columns without an index, see how to choose PostgreSQL indexes and validate them with EXPLAIN ANALYZE. And to notice when a performance regression reaches production, monitoring with a response-time threshold helps you catch the slowdown before your users do.
Related writing
All writing-
Software Engineering · · 3 min read
PostgreSQL indexes: B-tree, GIN and partial indexes, validated with EXPLAIN ANALYZE
How to choose between B-tree, GIN, composite and partial indexes in PostgreSQL, read the plan with EXPLAIN ANALYZE, and create indexes without locking production.
-
Software Engineering · · 4 min read
Uptime monitoring: why you should alert only after consecutive failures
How to build an availability monitor that catches real outages without false alarms: consecutive failures, detection time, states and a C# example.
-
AI Engineering · · 4 min read
Local RAG with Ollama: how retrieval-augmented generation works
What RAG is, how each stage works (chunking, embeddings, retrieval and generation), and how to build a local, private version with Ollama and Python.