Bullet 指南:在 Rails 开发中检测 N+1 查询与无效预加载

原创2026-10-14 23:20:081,849 阅读
文章标签:代码质量后端

Bullet 指南:在 Rails 开发中检测 N+1 查询与无效预加载

Bullet 是一个面向 Rails 应用的性能辅助 Gem,它会在开发过程中持续观察你的查询行为,当出现 N+1 查询(N+1 queries)、未使用的 eager loading(unused eager loading) 以及 本可用 counter cache 优化的 COUNT 查询 时主动向你发出通知。本文以仓库根目录的 README.md 为骨架,结合仓库源码(如 lib/bullet.rb、lib/bullet/detector、lib/bullet/rack.rb)讲解安装、配置、通知渠道、Safe list、按需暂停、测试集成与完整演练,让你在开发阶段就把查询性能问题消灭在萌芽状态。

Bullet 能检测的三类问题

Bullet 的设计目标非常聚焦:通过减少查询次数来提升应用性能。它在你开发应用的过程中监控查询,并在以下三种场景提醒你:

  1. N+1 查询:应该使用 eager loading 的地方没有使用。典型场景是在遍历 @posts 时对每条 Post 逐个访问 post.comments,产生 1 + N 条 SQL。
  2. 未使用的 eager loading:已经使用了 includes / preload 预加载,但关联对象在代码中根本没有被访问,预加载是浪费。
  3. 需要 counter cache:本可以用 counter_cache 消除的 COUNT 查询。例如循环中调用 post.comments.size,其实可以通过在 comments_count 字段上维护计数器来避免。

从仓库源码看,这三类检测分别由 lib/bullet/detector/n_plus_one_query.rb、lib/bullet/detector/unused_eager_loading.rb 和 lib/bullet/detector/counter_cache.rb 实现,并由 lib/bullet.rb 中的 DETECTORS 常量统一注册。

最佳实践:只在 development 模式或自定义环境(staging、profile 等)使用 Bullet。正如 README 所说,你最不希望看到的是客户收到关于"你太懒了"的告警。

支持范围与版本约束

Bullet 目前支持 activerecord >= 4.0 与 mongoid >= 4.0,并有明确的版本对应关系:

  • 使用 activerecord 2.x 时,请使用 bullet <= 4.5.0;
  • 使用 activerecord 3.x 时,请使用 bullet < 5.5.0。

仓库的 lib/bullet/dependency.rb 会根据当前 ORM 的版本号自动选择对应的适配文件:ActiveRecord 从 4.0 到 8.1 依次匹配 active_record4、active_record41、active_record42、active_record5、active_record52、active_record60、active_record61、active_record70、active_record71、active_record72、active_record80、active_record81(见 lib/bullet.rb 的 autoload 逻辑);Mongoid 则从 4.x 到 9.x 匹配 mongoid4x ~ mongoid9x 等文件。仓库目录中的 lib/bullet/active_record80.rb、lib/bullet/mongoid9x.rb 等文件即为各版本对应的补丁实现。当前仓库版本为 8.1.3(见 lib/bullet/version.rb)。

安装与启用

安装方式

作为 Gem 安装:

gem install bullet

或加入 Gemfile(Bundler 方式):

gem 'bullet', group: 'development'

注意:务必确保 bullet gem 添加在 activerecord(rails)和 mongoid 之后。

通过生成器快速启用

Bundler 安装后,运行内置生成器即可自动写入默认配置:

bundle exec rails g bullet:install

生成器会向 config/environments/development.rb 写入默认配置,并交互式询问是否同时在 test 环境启用(详见 lib/generators/bullet/install_generator.rb)。development 环境的默认写入内容为:

config.after_initialize do
  Bullet.enable        = true
  Bullet.alert         = true
  Bullet.bullet_logger = true
  Bullet.console       = true
  Bullet.rails_logger  = true
  Bullet.add_footer    = true
end

若选择在 test 环境启用,则写入:

config.after_initialize do
  Bullet.enable        = true
  Bullet.bullet_logger = true
  Bullet.raise         = true # raise an error if n+1 query occurs
end

配置详解

Bullet 默认不启用任何通知系统,除非你显式开启。在 config/environments/development.rb 的 config.after_initialize 中追加如下配置:

config.after_initialize do
  Bullet.enable = true
  Bullet.sentry = true
  Bullet.alert = true
  Bullet.bullet_logger = true
  Bullet.console = true
  Bullet.xmpp = { :account  => 'bullets_account@jabber.org',
                  :password => 'bullets_password_for_jabber',
                  :receiver => 'your_account@jabber.org',
                  :show_online_status => true }
  Bullet.rails_logger = true
  Bullet.honeybadger = true
  Bullet.bugsnag = true
  Bullet.appsignal = true
  Bullet.airbrake = true
  Bullet.rollbar = true
  Bullet.add_footer = true
  Bullet.footer_position = 'bottom_left'  # or 'bottom_right', 'top_left', 'top_right'
  Bullet.skip_html_injection = false
  Bullet.skip_http_headers = false
  Bullet.stacktrace_includes = [ 'your_gem', 'your_middleware' ]
  Bullet.stacktrace_excludes = [ 'their_gem', 'their_middleware', ['my_file.rb', 'my_method'], ['my_file.rb', 16..20] ]
  Bullet.slack = { webhook_url: 'http://some.slack.url', channel: '#default', username: 'notifier' }
  Bullet.opentelemetry = true
  Bullet.raise = false
  Bullet.always_append_html_body = false
  Bullet.skip_user_in_notification = false
end

通知系统参数一览

Bullet 的通知机制是 uniform_notifier 中的 delegate 与 available_notifiers 动态生成逻辑)。各参数含义如下:

参数 作用
Bullet.enable 启用 Bullet,否则整个 Gem 不做任何事。对应 lib/bullet.rb 中的 enable=,开启时会重置 Safe list 并加载对应 ORM 的补丁
Bullet.sentry 将通知发送到 Sentry
Bullet.alert 在浏览器中弹出 JavaScript alert 对话框
Bullet.bullet_logger 写入 Bullet 日志文件(Rails.root/log/bullet.log)。实现见 lib/bullet.rb:会自动创建 log 目录并以同步模式打开日志文件
Bullet.console 将警告写入浏览器的 console.log(Safari/Webkit 浏览器或装有 Firebug 的 Firefox)
Bullet.xmpp 发送 XMPP/Jabber 通知给 receiver。注意:当前代码不会自动处理加好友,需要先让两个账号互相知晓对方,否则收不到通知。若频繁重启开发服务器导致"上线"提示音烦人,可将 :show_online_status 设为 false,通知仍会发送,只是 Bullet 账号不再播报在线状态
Bullet.rails_logger 直接把警告写入 Rails 日志
Bullet.honeybadger 发送通知到 Honeybadger
Bullet.bugsnag 发送通知到 bugsnag
Bullet.appsignal 发送通知到 AppSignal
Bullet.airbrake 发送通知到 airbrake
Bullet.rollbar 发送通知到 rollbar
Bullet.add_footer 在页面左下角显示警告详情 footer。双击 footer 或点击关闭按钮可隐藏
Bullet.footer_position footer 在页面上的位置,合法值为 'bottom_left'(默认)、'bottom_right'、'top_left'、'top_right'。当默认位置与浏览器 UI 元素(如 Chrome 的 URL 预览)冲突时很有用。对应 CSS 实现见 lib/bullet/rack.rb 的 footer_position_css
Bullet.skip_html_injection 禁止 Bullet 向返回的 HTML 中注入代码。若要接收 alert、显示 footer 或 console 日志,该项必须为 false
Bullet.skip_http_headers 不向 API 请求添加 header,并移除依赖这些 header 的 JavaScript。注意:这会阻止 Bullet 向浏览器 console 写入日志或更新 footer
Bullet.stacktrace_includes 在堆栈跟踪中包含包含这些子串的路径,即使它们不在你的主应用中
Bullet.stacktrace_excludes 忽略堆栈跟踪中包含这些子串的路径,即使它们不在你的主应用中。每项可以是字符串(匹配子串)、正则表达式,或数组:数组第一项是要匹配的路径,第二项是要排除的具体行号、行号 Range、或(不带参数的)方法名,用于只排除文件中特定行。对应实现见 lib/bullet/stack_trace_filter.rb 的 pattern_matches?
Bullet.slack 发送通知到 Slack,支持 webhook_url、channel、username
Bullet.opentelemetry 发送通知到 OpenTelemetry
Bullet.raise 直接抛出异常,适合让测试在存在未优化查询时失败。实现见 lib/bullet.rb:为 true 时 UniformNotifier.raise 被设置为 Notification::UnoptimizedQueryError
Bullet.always_append_html_body 即使当前没有通知也总是追加 HTML body。注意:console 或 add_footer 必须同时为 true。对单页应用(SPA)很有用,因为初始页面加载可能没有任何通知
Bullet.skip_user_in_notification 从通知中排除操作系统用户(whoami)。相关实现在 lib/bullet/notification/base.rb 的 whoami 方法中

检测器开关

Bullet 允许单独关闭任意检测器:

# 以下每一项默认均为 true

# 检测 N+1 查询
Bullet.n_plus_one_query_enable     = false

# 检测未使用的预加载关联
Bullet.unused_eager_loading_enable = false

# 检测可用 counter_cache 避免的多余 COUNT 查询
Bullet.counter_cache_enable        = false

从源码看,这三个开关的读取方法(n_plus_one_query_enable?、unused_eager_loading_enable?、counter_cache_enable?)在 lib/bullet.rb 中实现:未显式赋值时默认视为 true,且均以 Bullet.enable 为前提;三个检测器在各自入口处(如 n_plus_one_query.rb、unused_eager_loading.rb、counter_cache.rb)都会先检查对应开关再继续。

Safe list:忽略不想修的问题

有时 Bullet 会提醒一些你不想处理、或来自第三方代码的查询问题,可以通过 Safe list 忽略它们:

Bullet.add_safelist :type => :n_plus_one_query, :class_name => "Post", :association => :comments
Bullet.add_safelist :type => :unused_eager_loading, :class_name => "Post", :association => :comments
Bullet.add_safelist :type => :counter_cache, :class_name => "Country", :association => :cities

底层实现见 lib/bullet.rb:add_safelist 会把 (type, class_name, association) 三元组存入按类型分类的哈希中;三个检测器在创建通知前都会通过 Bullet.get_safelist_associations(type, klazz) 过滤掉已在 Safe list 中的关联(如 n_plus_one_query.rb、unused_eager_loading.rb、counter_cache.rb)。此外还提供了 delete_safelist、clear_safelist 等配套 API。

在特定 action 中跳过 Bullet

如果只想在部分 controller action 中跳过检测,可以使用 Bullet.skip。它是线程安全的,在 Puma 等多线程环境下工作正常:

class ApplicationController < ActionController::Base
  around_action :skip_bullet, if: -> { defined?(Bullet) }

  def skip_bullet
    Bullet.skip { yield }
  end
end

更细粒度的控制可以使用 Bullet.pause 与 Bullet.resume:

Bullet.pause   # 暂时禁用当前线程的检测
Bullet.resume  # 恢复当前线程的检测
Bullet.paused? # 检查当前线程的检测是否已暂停

注意:不要在运行时切换 Bullet.enable,因为它修改的是全局、非线程安全的标志位。请改用 Bullet.skip、Bullet.pause,或 Bullet.start_request/Bullet.end_request。

从 lib/bullet.rb 的实现看,pause/resume/skip 都只操作 Thread.current 的线程变量,skip 会记录进入前的状态并在 ensure 中恢复,这正是其线程安全性的来源。

解读 Bullet 日志

Bullet 日志文件 log/bullet.log 中的内容形如:

N+1 Query 示例:

2009-08-25 20:40:17[INFO] USE eager loading detected:
  Post => [:comments]·
  Add to your query: .includes([:comments])
2009-08-25 20:40:17[INFO] Call stack
  /Users/richard/Downloads/test/app/views/posts/index.html.erb:8:in `each'
  /Users/richard/Downloads/test/app/controllers/posts_controller.rb:7:in `index'

第一条日志是遇到 N+1 查询的通知,后续条目是调用堆栈,方便你精确定位查询被调用的代码位置并修复。对应通知格式实现见 lib/bullet/notification/n_plus_one_query.rb:标题形如 USE eager loading detected,正文包含 Add to your query: .includes([:comments]) 这样的修复建议。

Unused eager loading 示例:

2009-08-25 20:53:56[INFO] AVOID eager loading detected
  Post => [:comments]·
  Remove from your query: .includes([:comments])
2009-08-25 20:53:56[INFO] Call stack

这些行表示发现了未被使用的预加载。对应实现见 lib/bullet/notification/unused_eager_loading.rb。

Need counter cache 示例:

2009-09-11 09:46:50[INFO] Need Counter Cache
  Post => [:comments]

对应实现见 lib/bullet/notification/counter_cache.rb,标题为 Need Counter Cache with Active Record size。

值得说明的是,日志中的 .includes(...) 建议并非总是最优:对于多对多或 has_many :through 这类可能需要多次 JOIN 的场景,preload 或分次加载往往更合适,实际取舍需要结合业务判断。通知数据中还会附带当前请求 URL 和操作系统用户(除非 skip_user_in_notification 开启),见 lib/bullet/notification/base.rb。

通过 URL 参数跳过 HTML 注入

你可以给请求添加 URL 查询参数 skip_html_injection,让当前这次 HTML 请求表现得如同开启了 Bullet.skip_html_injection:

http://localhost:3000/posts?skip_html_injection=true

该行为的解析实现位于 lib/bullet/rack.rb 的 skip_html_injection? 与 simple_parse_query_string,测试覆盖见 spec/bullet/rack_spec.rb。

关于 XMPP/Jabber、Airbrake 与 Growl

XMPP/Jabber 和 Airbrake 的支持细节参考 uniform_notifier 项目(lib/bullet.rb 中所有通知配置均委托给它)。Growl 支持已从 uniform_notifier 1.16.0 起被移除,如果仍需要使用 Growl,请固定使用 uniform_notifier 1.15.0。

高级用法

与 ActiveJob 配合

在你的 ApplicationJob 中引入 Bullet::ActiveJob:

class ApplicationJob < ActiveJob::Base
  include Bullet::ActiveJob if Rails.env.development?
end

实现见 lib/bullet/active_job.rb:included 钩子会给 Job 注册 around_perform,内部通过 Bullet.profile { block.call } 包裹执行。

与其他后台任务方案配合

使用 Bullet.profile 方法手动包裹:

class ApplicationJob < ActiveJob::Base
  around_perform do |_job, block|
    Bullet.profile do
      block.call
    end
  end
end

Bullet.profile 的实现见 lib/bullet.rb:在 Bullet 启用时依次执行 start_request → 执行任务 → 若有通知则 perform_out_of_channel_notifications → 最后 end_request(ensure 保证清理),并原样返回任务的返回值;未启用时则直接透传执行。

与 Sinatra 配合

配置并使用 Bullet::Rack 中间件:

configure :development do
  Bullet.enable = true
  Bullet.bullet_logger = true
  use Bullet::Rack
end

如果应用通过独立中间件生成 Content-Security-Policy,请确保 Bullet::Rack 加载在该中间件之前。在 Rails 中,Bullet 通过 Railtie 自动挂载该中间件(见 lib/bullet.rb),且当检测到 CSP 中间件时会用 insert_before 插到它前面,以保证注入的 footer/script 能拿到 CSP nonce(相关逻辑见 lib/bullet/rack.rb)。

Bullet::Rack 的完整工作流程(见 lib/bullet/rack.rb)值得了解:

  1. 请求进入时调用 Bullet.start_request,初始化线程级检测上下文;
  2. 调用下游应用拿到 status/headers/response;
  3. 若存在通知(或 always_append_html_body 开启)且满足注入条件(非文件、非 SSE、非空响应、状态码 200、HTML 请求),则向响应体追加 footer、内联通知和 XHR 脚本,并同步修正 Content-Length;
  4. 对非 HTML 请求(如 API),则以 X-bullet-footer-text / X-bullet-console-text 响应头输出(注意头大小会被截断到 8KB 以内,见 set_header);
  5. 最后执行 Bullet.end_request 清理线程状态(ensure 保证)。

在测试中运行

首先在 test 环境启用 Bullet:

# config/environments/test.rb
config.after_initialize do
  Bullet.enable = true
  Bullet.bullet_logger = true
  Bullet.raise = true # raise an error if n+1 query occurs
end

注意:Controller 与 integration 测试可以自动工作,因为 Bullet 的 Rack 中间件会把每个 HTTP 请求用 Bullet.start_request/Bullet.end_request 包裹。但 model 测试以及其他不经过 Rack 中间件的测试(如直接调用模型方法)需要手动包裹。

然后按如下方式包裹每个测试:

RSpec:

# spec/rails_helper.rb
RSpec.configure do |config|
  config.before(:each) do
    Bullet.start_request
  end

  config.after(:each) do
    Bullet.perform_out_of_channel_notifications if Bullet.notification?
    Bullet.end_request
  end
end

Minitest:

# test/test_helper.rb
module ActiveSupport
  class TestCase
    def before_setup
      Bullet.start_request
      super
    end

    def after_teardown
      super
      Bullet.perform_out_of_channel_notifications if Bullet.notification?
      Bullet.end_request
    end
  end
end

Bullet.start_request 的实现见 lib/bullet.rb:它为当前线程初始化通知收集器、对象关联注册表、可能/不可能对象集合、预加载记录和调用栈等线程变量;end_request 则逐一清理(见 lib/bullet.rb)。仓库的 spec/bullet_spec.rb 与各检测器测试(如 spec/bullet/detector/n_plus_one_query_spec.rb)可作为这些 API 用法的参考。

Debug 模式

Bullet 会输出一些详细信息。开启 debug 模式只需设置环境变量:

BULLET_DEBUG=true

对应实现在 lib/bullet.rb 的 debug 方法:仅在 ENV<a href="https://link.gitcode.com/i/2a37612503ec03b43db3e4ac395cfa31" target="_blank">'BULLET_DEBUG'] == 'true' 时输出 [Bullet][标题] 消息,各检测器中遍布此类调试输出(如 [n_plus_one_query.rb 中会打印被判定为 N+1 的对象与关联)。

完整演练:从创建应用到修复三类问题

以下按 README 的 Demo 步骤,用一个最小 Rails 应用完整走一遍"发现问题 → 修复 → 验证"的闭环。

1. 创建示例应用

$ rails new test_bullet
$ cd test_bullet
$ rails g scaffold post name:string
$ rails g scaffold comment name:string post_id:integer
$ bundle exec rails db:migrate

2. 定义模型关联

修改 app/models/post.rb 和 app/models/comment.rb:

class Post < ApplicationRecord
  has_many :comments
end

class Comment < ApplicationRecord
  belongs_to :post
end

3. 构造测试数据

进入 rails c 执行:

post1 = Post.create(:name => 'first')
post2 = Post.create(:name => 'second')
post1.comments.create(:name => 'first')
post1.comments.create(:name => 'second')
post2.comments.create(:name => 'third')
post2.comments.create(:name => 'fourth')

4. 制造 N+1 查询

修改 app/views/posts/index.html.erb:

<% @posts.each do |post| %>
  <tr>
    <td><%= post.name %></td>
    <td><%= post.comments.map(&:name) %></td>
    <td><%= link_to 'Show', post %></td>
    <td><%= link_to 'Edit', edit_post_path(post) %></td>
    <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
<% end %>

5. 加入 Gem 并安装

gem "bullet"

然后运行 bundle install。

6. 启用 Bullet

bundle exec rails g bullet:install

7. 启动服务器

$ rails s

8. 访问并观察 N+1 告警

访问 http://localhost:3000/posts,会看到弹窗提示:

The request has unused preload associations as follows:
None
The request has N+1 queries as follows:
model: Post => associations: [comment]

意思是 Post 对象到 Comment 关联存在 N+1 查询。同时 log/bullet.log 中追加了日志:

2010-03-07 14:12:18[INFO] N+1 Query in /posts
  Post => [:comments]
  Add to your finder: :include => [:comments]
2010-03-07 14:12:18[INFO] N+1 Query method call stack
  /home/flyerhzm/Downloads/test_bullet/app/views/posts/index.html.erb:14:in `_render_template__600522146_80203160_0'
  /home/flyerhzm/Downloads/test_bullet/app/views/posts/index.html.erb:11:in `each'
  /home/flyerhzm/Downloads/test_bullet/app/views/posts/index.html.erb:11:in `_render_template__600522146_80203160_0'
  /home/flyerhzm/Downloads/test_bullet/app/controllers/posts_controller.rb:7:in `index'

此时生成的 SQL 是典型的 N+1:

Post Load (1.0ms)   SELECT * FROM "posts"
Comment Load (0.4ms)   SELECT * FROM "comments" WHERE ("comments".post_id = 1)
Comment Load (0.3ms)   SELECT * FROM "comments" WHERE ("comments".post_id = 2)

9. 修复 N+1 查询

修改 app/controllers/posts_controller.rb:

def index
  @posts = Post.includes(:comments)

  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render :xml => @posts }
  end
end

10. 验证修复

刷新 http://localhost:3000/posts,不再有弹窗,日志也不再新增内容。生成的 SQL 变为一次 IN 查询:

Post Load (0.5ms)   SELECT * FROM "posts"
Comment Load (0.5ms)   SELECT "comments".* FROM "comments" WHERE ("comments".post_id IN (1,2))

N+1 查询修复完成。

11. 模拟未使用的 eager loading

保持 controller 不变(仍带 includes(:comments)),把视图改为不再访问 post.comments:

<% @posts.each do |post| %>
  <tr>
    <td><%= post.name %></td>
    <td><%= link_to 'Show', post %></td>
    <td><%= link_to 'Edit', edit_post_path(post) %></td>
    <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
<% end %>

12. 观察 unused eager loading 告警

刷新后弹窗提示:

The request has unused preload associations as follows:
model: Post => associations: [comment]
The request has N+1 queries as follows:
None

log/bullet.log 中追加:

2009-08-25 21:13:22[INFO] Unused preload associations: PATH_INFO: /posts;    model: Post => associations: [comments]·
Remove from your finder: :include => [:comments]

修复方式即按提示移除 includes(:comments)。从源码看,这类检测由 unused_eager_loading.rb 的 check_unused_preload_associations 在请求结束时执行:它把"实际预加载的关联集合"与"代码中真正调用过的关联集合"做差集,差值即未使用的预加载。

13. 模拟 counter_cache 场景

把 controller 改回不带预加载:

def index
  @posts = Post.all

  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render :xml => @posts }
  end
end

视图改为调用 post.comments.size:

<% @posts.each do |post| %>
  <tr>
    <td><%= post.name %></td>
    <td><%= post.comments.size %></td>
    <td><%= link_to 'Show', post %></td>
    <td><%= link_to 'Edit', edit_post_path(post) %></td>
    <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
<% end %>

14. 观察 counter cache 告警

刷新后弹窗提示:

Need counter cache
  Post => [:comments]

log/bullet.log 中追加:

2009-09-11 10:07:10[INFO] Need Counter Cache
  Post => [:comments]

常见问题与注意事项

  • 若 Bullet 不生效,请先禁用浏览器缓存(这是 README 明确给出的首要排查手段)。
  • 不要在运行时切换 Bullet.enable(全局标志,非线程安全),应使用 Bullet.skip / Bullet.pause / Bullet.resume 或 start_request / end_request 做线程级控制。
  • stacktrace_excludes 支持字符串、正则与 [路径, 行号|Range|方法名] 三种匹配形式,可实现"只忽略某个文件特定行/特定方法"的精确过滤。
  • 使用 Bullet.raise = true 时测试会在存在未优化查询时抛 UnoptimizedQueryError 而失败,这是把查询优化纳入 CI 的常用手段。
  • 从源码结构看(见 lib/bullet/active_record80.rb),Bullet 通过 prepend 在 ActiveRecord 的 find_by_sql、Relation#records、Preloader、Association 等核心路径上埋点,在"加载多条记录"时登记可能对象、在"加载单条记录"时登记不可能对象、在预加载时记录 eager loadings、在访问关联时登记实际调用,最终在 check_unused_preload_associations 与通知输出阶段汇总判断——这解释了它如何在不侵入业务代码的前提下完成三类检测。
登录后查看全文
bullet