skip to content

In a Rails app, what do the sql.active_record and process_action.action_controller events carry, and how would you use them to catch slow queries and actions?

level: middleimportance: must knowfreq 40%

answer

  1. one event per query, one per action
  2. payload[:sql], [:name], [:cached]
  3. row_count and type_casted_binds
  4. status, view_runtime, db_runtime
  5. append_info_to_payload adds keys

basics

~20 s

sql.active_record fires per query with the SQL, its name ("Order Load"), binds, row_count and a cached flag; process_action.action_controller fires per action with controller, action, filtered params, status, view_runtime and db_runtime. Subscribe and compare event.duration with a threshold.

solid answer

~40 s

`sql.active_record` is published for every query an Active Record connection runs. Its payload carries `:sql`, `:name` (such as "Order Load", or "SCHEMA" for schema lookups), `:binds` and `:type_casted_binds`, `:async`, `:connection`, `:transaction`, `:row_count` and `:affected_rows`, plus `cached: true` when the query cache answered. `process_action.action_controller` wraps each controller action; its payload has `:controller`, `:action`, filtered `:params`, `:headers`, `:format`, `:method`, the filtered `:path`, `:request`, `:response`, `:status`, `:view_runtime` and `:db_runtime`. To catch slow work, subscribe with a one-argument block and compare `event.duration` (milliseconds) to a threshold, skipping cached and SCHEMA queries. Add your own keys, such as an order id, by overriding `append_info_to_payload` in the controller and calling `super`.

code

ruby · 15 lines
ruby
# config/initializers/slow_work.rb
SLOW_SQL_MS = 100

ActiveSupport::Notifications.subscribe("sql.active_record") do |event|
  payload = event.payload
  next if payload[:cached] || payload[:name] == "SCHEMA" || event.duration < SLOW_SQL_MS
  Rails.logger.warn("slow_sql ms=#{event.duration.round} name=#{payload[:name]} sql=#{payload[:sql]}")
end

ActiveSupport::Notifications.subscribe("process_action.action_controller") do |event|
  payload = event.payload
  next unless payload[:controller] == "CheckoutsController" && event.duration > 800
  Rails.logger.warn("slow_checkout ms=#{event.duration.round} status=#{payload[:status]} " \
                    "db=#{payload[:db_runtime]&.round} view=#{payload[:view_runtime]&.round} order=#{payload[:order_id]}")
end

go deeper

for a junior

Recall that every query publishes sql.active_record and every action publishes process_action.action_controller, and that event.duration is in milliseconds.

for a middle

Name the payload keys you would use — sql, name, cached, row_count; status, db_runtime, view_runtime — and write a filtered slow-query subscriber.

for a senior

Add context with append_info_to_payload, keep binds and personal data out of logs, and explain where db_runtime comes from so you can trust the numbers.

for a principal

Decide which signals come from these events in-process and which from database-side tooling, so slow-work detection is consistent across services.

## The two events everyone instruments Rails publishes dozens of events, but two carry most production questions: **which queries are slow** and **which actions are slow**. Both are ordinary `ActiveSupport::Notifications` events, so a one-argument subscriber receives an `Event` whose `duration` is in milliseconds. ## sql.active_record Published by the connection adapter's `log` method around every statement. | Key | Contents | |---|---| | `:sql` | the SQL string | | `:name` | a label such as `"Order Load"`, `"Ticket Create"`, `"SCHEMA"`, `"TRANSACTION"` | | `:binds`, `:type_casted_binds` | bind attributes and their database values; Active Record's own log subscriber calls `type_casted_binds` first if it responds to `call` | | `:async` | `true` for queries run with `load_async` | | `:allow_retry` | whether the adapter may retry it | | `:connection`, `:transaction` | the adapter and the current user transaction (`nil` outside one) | | `:row_count`, `:affected_rows` | rows returned and rows changed | | `:cached` | added as `true` when the query cache served the result | | `:statement_name` | PostgreSQL prepared statement name | Active Record's own log subscriber ignores the `"SCHEMA"` and `"EXPLAIN"` names, and a slow-query subscriber usually should too, along with cached hits, whose duration is near zero. ## process_action.action_controller Published once per controller action, around the whole action including rendering. `start_processing.action_controller` fires just before it with the same request keys. - `:controller`, `:action` — `"CheckoutsController"`, `"create"`. - `:params` — the request parameters **after** `filter_parameters` masking; `:path` is the filtered path. - `:headers`, `:format`, `:method`, `:request`, `:response`. - `:status` — the response status, or the status Rails maps the exception to when the action raises. - `:view_runtime`, `:db_runtime` — milliseconds spent rendering and in Active Record during the action; Active Record also adds `:queries_count` and `:cached_queries_count`. ## Building a slow-work subscriber 1. **Register once at boot** in `config/initializers/`. 2. **Use a one-argument block** so you get `event.duration` directly. 3. **Filter early**: skip `payload[:cached]`, the `SCHEMA` name and anything below the threshold before doing any work. 4. **Record the minimum**: the SQL, the name, the duration and a request identifier — never the raw binds, which may hold personal data. 5. **Keep it cheap**: append to a log line or an in-memory counter; do not run queries or network calls inside the subscriber. ## Adding your own keys `append_info_to_payload(payload)` is a controller hook Rails calls after every action, inside `process_action`'s instrumentation. Override it, call `super` so `view_runtime` and `db_runtime` are still filled, and add keys such as `:order_id`. Every subscriber to `process_action.action_controller` then sees them. ## Reading the numbers - `view_runtime + db_runtime` rarely equals the action's `duration`: Ruby work in the controller, callbacks, serialization and anything outside Active Record and views make up the rest. - A large `queries_count` with a small `db_runtime` points at many fast queries — often an N+1 pattern — rather than one slow one. - High `cached_queries_count` means the query cache is absorbing repeated reads within the request; the duplicates are still worth removing. - Durations measure the whole block, including time waiting for a database connection or a lock, so a "slow query" can be a contended one. ## Things that surprise people - `db_runtime` is itself fed by a subscriber: `ActiveRecord::RuntimeRegistry` is registered with `monotonic_subscribe` on `sql.active_record` and adds up each query's time per request. - The payload holds live objects (`:connection`, `:request`, `:response`); read what you need inside the subscriber and never keep references. - Rails 8.1 also re-emits many of these events through `Rails.event` as structured events, such as `action_controller.request_completed`; the Notifications events remain and are what most existing tooling listens to.

  • Why should a slow-query subscriber skip events whose payload has cached: true?
    Those results came from Active Record's query cache, so no SQL reached the database and the duration is close to zero. Counting them inflates query totals; logging them as slow is impossible. Rails' own runtime registry counts them separately as cached queries for the same reason.
  • Where does process_action.action_controller get db_runtime from?
    `ActiveRecord::RuntimeRegistry` is subscribed with `monotonic_subscribe` to `sql.active_record` and adds every query's time to a per-thread counter. Active Record's controller runtime module overrides `append_info_to_payload` to copy that total into `:db_runtime`, which the request log line then prints as ActiveRecord time.
  • What does :status contain when the action raises an exception?
    Rails rescues inside the instrumentation, sets `:status` to the code `ActionDispatch::ExceptionWrapper` maps that exception class to — 404 for a missing record, 500 for an unexpected error — and re-raises. The payload also carries `:exception` and `:exception_object`.

  • process_action.action_controller payload params are the raw, unfiltered parameters
  • sql.active_record fires only for slow queries above a threshold
  • A query served by the query cache does not publish sql.active_record
  • Adding a key to the action payload means instrumenting process_action again yourself
  • event.duration for these events is reported in seconds