Duplicate Queries in Rails: What Bullet Misses and How to Find Them
The same SELECT repeating inside one request is not an N+1. What the query cache hides, what Bullet does not report, and how to count and remove repeats.
Your log shows the same SELECT again and again while one page renders, and it is not an N+1. It is one lookup, such as a settings row, the current account or a feature flag, called from a layout, a helper and several partials. This post shows what Rails already does about it, where the Bullet gem fits, and how to find and remove the repeats.
Every result below came from ActiveRecord 8.1.1 on PostgreSQL 15.10, using standalone Ruby scripts against a throwaway database on a laptop. The logging concern near the end was also run in a Rails 8.1.1 request (an integration test) with the query cache on. The numbers are query counts, not response times.
Duplicate queries are not N+1 queries
An N+1 loads a list and then runs one more query per row through an association:
Post.limit(10).each { |post| post.author.name }
# 1 query for posts + 10 queries for authors, each with a different id
A duplicate query repeats the exact same SQL with the same values:
Post.order(:id).map do |post|
"#{post.title} #{Setting.find_by(key: "currency")&.value}"
end
With three posts and no query cache, ActiveRecord sent four queries: one for the posts and three identical ones for the setting.
SELECT "posts".* FROM "posts" ORDER BY "posts"."id" ASC
SELECT "settings".* FROM "settings" WHERE "settings"."key" = $1 LIMIT $2 -- 3 times
The fixes differ. An N+1 needs eager loading (includes, preload). A duplicate needs the value loaded once and reused.
What Bullet detects
The Bullet README lists three detectors: N+1 queries, unused eager loading, and places where a counter cache would help. All three are about associations. The README does not describe any check for the same non-association query running many times, so do not rely on Bullet for this problem.
Bullet is still worth installing for the N+1 cases. The README’s test setup uses Bullet.raise = true in config/environments/test.rb, so a test fails when it triggers an N+1. For the tested N+1 fix itself, see the N+1 query fix page.
The query cache hides many duplicates inside a request
Rails has an SQL query cache. The Rails caching guide explains it: inside one request, when Rails sees the same query again, it reuses the stored result instead of asking the database.
I reproduced it with ActiveRecord::Base.cache, the block form of the same cache:
ActiveRecord::Base.cache do
Post.order(:id).map { |post| "#{post.title} #{Setting.find_by(key: "currency")&.value}" }
end
Two queries went to the database. The other two setting lookups were served from the cache and show up in the log with a CACHE prefix. Inside a normal controller action, many duplicates never reach PostgreSQL. The cache is limited, though. By default it keeps 100 queries per thread and evicts the least recently used entry past that, so a page with many different queries can push a repeat out. The query_cache key in database.yml sets the size. 0 or false does not turn the cache off: in a test with query_cache: false, a repeated query was still served from the cache, because those values remove the size limit. To skip the cache for a block of code, wrap it in ActiveRecord::Base.uncached. Even when the cache works, three things make duplicates worth removing.
Writes clear the cache. A write through ActiveRecord clears it, and so does a raw connection.execute, even for a SELECT. The exception is code wrapped in uncached(dirties: false). In this block, the second find_by went to the database again:
ActiveRecord::Base.cache do
Setting.find_by(key: "currency") # database
Post.create!(title: "new") # INSERT clears the query cache
Setting.find_by(key: "currency") # database again
end
Only identical SQL matches. find_by(key:) and where(key:).first load the same row, but the second adds ORDER BY "settings"."id", so it is a different query and both went to the database:
SELECT "settings".* FROM "settings" WHERE "settings"."key" = $1 LIMIT $2
SELECT "settings".* FROM "settings" WHERE "settings"."key" = $1 ORDER BY "settings"."id" ASC LIMIT $2
A cache hit still builds a new object. Two cached find_by calls returned two different Ruby objects (a.equal?(b) was false). Each one is a fresh model instance, so the repeats still cost Ruby time and memory.
The cache also only exists where Rails turns it on. In a plain Ruby script without the block above, every repeat went to the database, as the first example showed.
Find the duplicates in one request
The sql.active_record event carries the SQL, the bind values and a cached flag. All three are listed in the Active Support instrumentation guide. This development-only concern counts each repeated query in a request. It reports database hits and cache hits separately, so repeats the cache absorbed still show up:
# app/controllers/concerns/duplicate_query_log.rb
module DuplicateQueryLog
extend ActiveSupport::Concern
included do
around_action :log_duplicate_queries, if: -> { Rails.env.local? } # development and test
end
private
def log_duplicate_queries(&action)
owner = Thread.current
counts = Hash.new(0)
callback = lambda do |*, payload|
next unless Thread.current.equal?(owner) # other threads' requests
next if %w[SCHEMA TRANSACTION].include?(payload[:name])
binds = payload[:type_casted_binds]
binds = binds.call if binds.respond_to?(:call) # cache hits pass a lambda in 8.1
counts[[payload[:cached] ? :cache : :db, payload[:sql], binds]] += 1
end
ActiveSupport::Notifications.subscribed(callback, "sql.active_record", &action)
ensure
report_repeated_queries(counts) if counts # also when the action raised
end
def report_repeated_queries(counts)
counts.group_by { |(_, sql, binds), _| [sql, binds] }.each do |(sql, binds), rows|
db = rows.sum { |(source, *), n| source == :db ? n : 0 }
cache = rows.sum { |(source, *), n| source == :cache ? n : 0 }
next if db + cache < 2
Rails.logger.warn("[repeated query] db=#{db} cache=#{cache} #{sql} #{binds.inspect}")
end
end
end
Add include DuplicateQueryLog to ApplicationController. Rails.env.local? is true in development and test, so the concern runs in both. I tested it in a Rails 8.1.1 integration test. In the first request, the code looked up the same user three times, created a record, and then looked the user up once more. The concern logged:
[repeated query] db=2 cache=2 SELECT "users".* FROM "users" WHERE "users"."email" = $1 LIMIT $2 ["x@example.com", 1]
The first lookup went to the database and the next two came from the cache. The write cleared the cache, so the fourth lookup went to the database again. A second request in the same test started with cache entries left over from the first, because integration tests share one connection inside the test transaction. Read the counts from development, not from a test that makes several requests. The report also runs when the action raises. A lookup with a different email in the same request was not reported, because its bind value differs. BEGIN and COMMIT lines are skipped.
The subscription is global, so the Thread.current check keeps other requests out on a thread-per-request server such as Puma. In a standalone two-thread script, a second thread ran 200 lookups during the block and none were counted. On a fiber-based server (Falcon, or isolation_level = :fiber), several requests share a thread, so their queries would be counted together.
What it does not cover:
- Queries this request runs on other threads, such as
load_async. - Queries in Rack middleware (session stores, authentication middleware), in callbacks declared before the
include, and inrescue_fromhandlers. All of these run outside the wrapped action. - Background jobs, because it only wraps controller actions.
In Rails 8.1, type_casted_binds is a lambda on cache hits and an array otherwise, and the respond_to?(:call) check handles both. Another version may pass something different, so check the first log line after an upgrade. With prepared_statements: false, a common setting behind PgBouncer, the values are written into the SQL and the binds array is empty. Grouping still works, but the log lines look different from the example above.
This is a counter, not a profiler. It does not time anything. For timings, use EXPLAIN ANALYZE (see the EXPLAIN page).
Remove them: load once, pass it down
The simplest fix is to read the value once and pass it in:
currency = Setting.find_by(key: "currency")&.value
Post.order(:id).map { |post| "#{post.title} #{currency}" }
This sent two queries for any number of posts.
When the value is needed in many partials and helpers, store it for the request with ActiveSupport::CurrentAttributes (API docs):
# app/models/current.rb
class Current < ActiveSupport::CurrentAttributes
attribute :currency
def currency
super || (self.currency = Setting.find_by(key: "currency")&.value)
end
end
Three calls to Current.currency sent one query. After Current.reset, the next call queried again. Rails resets current attributes before and after each request, so values do not leak between requests.
If app/models/current.rb already exists, add the attribute to it rather than defining a second class. The Rails 8 authentication generator creates that file.
Do not use the || pattern for a value that can legitimately be nil or false. Both are falsy, so the query runs again on every call. Store a sentinel or check attributes.key? instead.
Checklist
- Count before you change anything: run the concern on the slow page and read the
[repeated query]lines. Highdb=counts come first, then highcache=counts. - A
cache=repeat skips the database but still builds a new object, so it is worth removing when the count is high. - Make sure repeated calls use one form (
find_byeverywhere, not mixed withwhere.first), so the cache can match them. - Load per-request values once: a local variable, or
Currentfor values used across views. - Keep Bullet in test with
Bullet.raise = truefor N+1s. It is a different problem from duplicates.
Tested conversions for this topic
Each page shows the SQL, the ActiveRecord code, and the SQL Rails actually generated on Rails 8.1.1.
- Rails N+1 Query Fix: includes and strict_loading Fix N+1 queries in Rails with includes, preload and strict_loading. Query counts measured on Rails 8.1 and PostgreSQL 16: 10 queries drop to 2.
Was this article helpful?
Your feedback helps us improve our content
How We Verify Conversions
Every conversion shown on this site follows a strict verification process to ensure correctness:
- Compare results on same dataset — We run both SQL and ActiveRecord against identical test data and verify results match
-
Check generated SQL with
to_sql— We inspect the actual SQL Rails generates to catch semantic differences (INNER vs LEFT JOIN, WHERE vs ON, etc.) - Add regression tests for tricky cases — Edge cases like NOT EXISTS, anti-joins, and predicate placement are tested with multiple scenarios
- Tested on Rails 8.1.1 — All conversions verified on current Rails version to ensure compatibility
Last updated: December 03, 2026
Try These Queries in Our Converter
See the SQL examples from this article converted to ActiveRecord—and compare the SQL Rails actually generates.
Deep Dive into ActiveRecord
Raza Hussain
Full-stack developer specializing in Ruby on Rails, React, and modern JavaScript. 15+ years upgrading and maintaining production Rails apps. Led Rails 4/5 → 7 upgrades with 40% performance gains, migrated apps from Heroku to Render cutting costs by 35%, and built systems for StatusGator, CryptoZombies, and others. Available for Rails upgrades, performance work, and cloud migrations.
More on Ruby & Rails Core
ActiveRecord where vs find_by — Which to Use When
where returns a relation, find_by returns one record or nil. Here's when each is correct, what breaks if you pick wrong, and Rails 7/8 production patterns.
Rails Counter Cache—When Posts.count Brought Down Production
posts.count hit the database on every request and brought down production. Here's how counter cache fixes it, what to watch for, and how to backfill safely.
ActiveRecord to Raw SQL—When ORM Costs 80% Performance in Production
When ActiveRecord's abstraction costs 80% of query performance, raw SQL is the right call. Here's how to know when to drop down and do it safely in Rails.
Leave a Response
Responses (0)
No responses yet
Be the first to share your thoughts