In a Rails app, why can one ActiveSupport::Notifications subscriber on sql.active_record slow down or break every request, and how do you keep it safe?
answer
- inline on the instrumenting thread
- cost multiplied by events per request
- subscriber errors re-raised to the caller
- listening? lets unwatched events skip timing
- no queries inside a SQL subscriber
basics
~20 sNotifications subscribers run synchronously on the thread that fired the event, so their cost is paid on every query, and an exception they raise propagates into the query that fired it. Keep them filtered, cheap, I/O-free and rescued.
solid answer
~40 sA subscriber is called inline by `instrument`, on the request's own thread, after each event. A 2 ms subscriber on `sql.active_record` costs 300 ms on a checkout that runs 150 queries. Worse, the fanout runs every subscriber and then re-raises: one failing subscriber's exception surfaces as is, several are wrapped in `ActiveSupport::Notifications::InstrumentationSubscriberError` — either way the query, and so the request, fails. `ActiveSupport::LogSubscriber` and the 8.1 structured event subscribers rescue and report errors instead; plain blocks and `ActiveSupport::Subscriber` do not. One-argument subscribers also cost more, because each `Event` records CPU time, GC time and allocations. Keep subscribers registered once at boot, filter first, aggregate in memory or hand off to a buffer, rescue your own errors, and never query the database inside a `sql.active_record` subscriber — that query publishes another event.
code
ruby · 9 lines# config/initializers/sql_metrics.rb
ActiveSupport::Notifications.subscribe("sql.active_record") do |_name, start, finish, _id, payload|
next if payload[:cached] || payload[:name] == "SCHEMA"
ms = (finish - start) * 1000.0
next if ms < 50
SqlStats.increment(payload[:name], ms) # in-memory counter, flushed elsewhere
rescue => e
Rails.error.report(e, handled: true, source: "sql_metrics")
endgo deeper
Remember that Notifications subscribers run inline, during the request, so a slow or failing subscriber slows or fails the request.
Explain the cost multiplication per query, how exceptions propagate through the fanout, and why LogSubscriber behaves differently.
Diagnose a production slowdown traced to instrumentation: identify the subscriber, avoid recursion, filter early, move I/O off the request thread and rescue inside the handler.
Set a budget and an ownership rule for in-process instrumentation, so every gem and team subscriber is reviewed for cost and failure behaviour before it ships.
## Why the cost lands on the request `ActiveSupport::Notifications` is synchronous. When the connection adapter runs a query, it calls `instrument("sql.active_record", ...)`; when the block finishes, the fanout calls every matching subscriber **on that same thread**, and only then does the query method return. Nothing is queued. A subscriber's time is therefore added to: - **every query** — `sql.active_record` fires once per statement, so a checkout with 150 queries pays the subscriber 150 times; - **every action** — `process_action.action_controller` subscribers add to each response time; - **every job** — the same events fire inside Active Job workers. Profilers show this as time "inside" Active Record, which makes a slow subscriber easy to misread as slow SQL. ## Why an error breaks the request The fanout iterates subscribers with a guard that collects exceptions, then re-raises after all of them have run: 1. **One** failing subscriber — its exception is re-raised as is. 2. **Several** — they are wrapped in `ActiveSupport::Notifications::InstrumentationSubscriberError`, with the first as `cause`. 3. Either way the exception surfaces where `instrument` was called — inside the query, the render or the action — so a `NoMethodError` in a metrics block turns a successful checkout into a 500. Two Rails base classes behave differently: `ActiveSupport::LogSubscriber#call` and `ActiveSupport::StructuredEventSubscriber#call` **rescue** errors and send them to `ActiveSupport.error_reporter` (the log subscriber also logs "Could not log ... event"). A plain block, a callable object, or a class built on `ActiveSupport::Subscriber` has no such guard. ## What makes a subscriber expensive | Cost | Where it comes from | |---|---| | The work itself | string building, JSON, logging, network calls, database queries | | Event objects | a one-argument subscriber gets an `Event` that reads CPU time, GC time and allocation counts at start and finish | | Broad patterns | `subscribe` with no pattern or a loose Regexp makes every event in the process call you | | Waking up silent events | `instrument` checks `listening?`; with no active subscriber it just yields, but any subscriber makes the event fully timed | | Churn | subscribing and unsubscribing at runtime clears the fanout's cached listener lists; the source warns to do it sparingly | In a typical Rails app `sql.active_record` is always timed, because `ActiveRecord::RuntimeRegistry` subscribes to it to compute `db_runtime`; your subscriber adds its own cost on top. ## The recursion trap A subscriber on `sql.active_record` that writes an audit row through an Active Record model runs an `INSERT`, which publishes **another** `sql.active_record` event, which calls the subscriber again. Without a guard this recurses until the stack overflows. Ship the data somewhere that is not the same database connection's instrumented path, or guard with a thread-local flag. ## Diagnosing a suspected subscriber 1. List what is subscribed: `ActiveSupport::Notifications.notifier.listeners_for("sql.active_record")` returns the active listeners for that name. 2. Profile a slow request and look for time attributed to Active Support's notification fanout or to a gem's subscriber class. 3. Temporarily detach suspects in a staging environment and compare response times. 4. Check error trackers for exceptions whose backtrace passes through the fanout, which point at a failing subscriber. ## Keeping subscribers safe 1. **Register at boot** in `config/initializers/`, with an exact String or a tight Regexp. 2. **Filter first**: return early on `payload[:cached]`, `"SCHEMA"` and sub-threshold durations before building anything. 3. **Do no I/O inline**: increment counters, or push a small hash to an in-memory buffer that a separate thread or the logger flushes. 4. **Rescue inside the subscriber**, or inherit `ActiveSupport::LogSubscriber`, so a bug cannot fail a request. 5. **Prefer the five-argument form** when you only need timing, to avoid building `Event` objects. 6. **Measure**: compare request time with and without the subscriber in a benchmark before shipping it to production.
- Why does wrapping a subscriber in ActiveSupport::LogSubscriber change what happens on an error?`ActiveSupport::LogSubscriber#call` rescues any `StandardError` from the handler method, reports it to `ActiveSupport.error_reporter` with the event name as source, and logs "Could not log ... event". The instrumented query or action continues. A plain block or an `ActiveSupport::Subscriber` lets the error reach the caller.
- How would you measure a subscriber's real cost before shipping it?Benchmark a representative request or job with and without the subscriber registered, using `ActiveSupport::Notifications.subscribed` to scope it, and compare total time and allocations. Also count events per request — `RuntimeRegistry` tracks queries — because the subscriber's cost multiplies by that count.
- Why is a subscriber with no pattern particularly risky?It matches every event in the process — every query, render, cache read and job event — so its cost multiplies across all of them. It also wakes up events that nobody else listens to: `instrument` skips timing when `listening?` is false, so an always-listening subscriber makes every event pay full instrumentation cost.
- Subscriber exceptions are logged and swallowed by ActiveSupport::Notifications
- Notifications subscribers run asynchronously, so their cost is off the request path
- Writing to the database from a sql.active_record subscriber is harmless
- A slow subscriber shows up as its own span, never as query time
- InstrumentationSubscriberError wraps even a single subscriber's failure