Skip to main content

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.

R
Raza Hussain
· Updated: · 9 min read · 660
Stack of identical SELECT ... WHERE key = ? cards with one in red, under the headline Duplicate queries Bullet misses

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 in rescue_from handlers. 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

  1. Count before you change anything: run the concern on the slow page and read the [repeated query] lines. High db= counts come first, then high cache= counts.
  2. A cache= repeat skips the database but still builds a new object, so it is worth removing when the count is high.
  3. Make sure repeated calls use one form (find_by everywhere, not mixed with where.first), so the cache can match them.
  4. Load per-request values once: a local variable, or Current for values used across views.
  5. Keep Bullet in test with Bullet.raise = true for 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.

Was this article helpful?

Your feedback helps us improve our content

Be the first to vote!

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.

660

Leave a Response

Responses (0)

No responses yet

Be the first to share your thoughts

R

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.

💼 15 years experience 📝 63 posts