skip to content

In Rails, how do ActiveSupport::Notifications.instrument and ActiveSupport::Notifications.subscribe work together, and what does a subscriber receive?

level: juniorimportance: should knowfreq 32%

answer

  1. a named, timed block
  2. event.library naming
  3. one-argument block gets an Event
  4. five args: name, start, finish, id, payload
  5. runs after the block, same thread

basics

~20 s

ActiveSupport::Notifications.instrument(name, payload) { ... } runs and times a block, then calls every subscriber whose pattern matches the name. A one-argument subscriber block gets an Event (name, payload, duration in ms); a five-argument block gets name, start, finish, id and payload.

solid answer

~40 s

`ActiveSupport::Notifications` is Rails' in-process publish/subscribe bus. `instrument("checkout.ticketing", order_id: 7) { ... }` yields the payload hash to the block, times it, and when the block finishes notifies every subscriber whose pattern matches — synchronously, on the same thread — then returns the block's value. If the block raises, the payload gains `:exception` and `:exception_object`, subscribers are still notified, and the exception is re-raised. `subscribe` takes an exact String, a Regexp, or nothing (all events); a Symbol raises `ArgumentError`. A block with one parameter receives an `ActiveSupport::Notifications::Event` (`name`, `payload`, `duration` in milliseconds, `allocations`); a block with five receives `name, start, finish, id, payload`. Rails' own events follow the `event.library` naming convention, such as `sql.active_record`, and your own should too.

code

ruby · 13 lines
ruby
# app/models/order.rb (ticketing platform)
def place!
  ActiveSupport::Notifications.instrument("checkout.ticketing", order_id: id) do |payload|
    transaction { reserve_seats!; charge! }
    payload[:tickets] = tickets.size
  end
end

# config/initializers/ticketing_events.rb
ActiveSupport::Notifications.subscribe("checkout.ticketing") do |event|
  Rails.logger.info("checkout order=#{event.payload[:order_id]} " \
                    "tickets=#{event.payload[:tickets]} ms=#{event.duration.round(1)}")
end

go deeper

for a junior

Recall the pair: instrument publishes a named, timed block with a payload, subscribe registers a block for a name or Regexp, and a one-argument block gets an Event with duration in milliseconds.

for a middle

Explain ordering and threading: subscribers run synchronously after the block, still run when it raises, and see :exception in the payload. Know the three subscriber shapes.

for a senior

Design custom events for a feature: event.library names, small payloads, boot-time subscriptions, and what each subscriber costs on the hot path.

for a principal

Decide which business events the platform publishes on this bus, which go to a structured event pipeline, and who owns the subscribers that ship them out of the process.

## What the bus is for `ActiveSupport::Notifications` is a small **in-process publish/subscribe API** that Rails uses to report what its frameworks are doing: every SQL query, every controller action, every template render and job enqueue is published as a named event. Log lines, `db_runtime` in the request log and most third-party monitoring hooks are built by **subscribing** to those events. Your application can publish its own events the same way. ## Publishing with instrument ```ruby ActiveSupport::Notifications.instrument("checkout.ticketing", order_id: order.id) do |payload| order.place! payload[:tickets] = order.tickets.size # the payload is mutable inside the block end ``` What happens, in order: 1. If no subscriber is listening to `"checkout.ticketing"`, the block simply runs — no timing, no event object. 2. Otherwise the instrumenter records the start, yields the **payload hash** to the block, and records the finish. 3. If the block raises, the payload gains `:exception` (`[class_name, message]`) and `:exception_object`, subscribers are **still notified**, and the exception is re-raised. 4. `instrument` returns whatever the block returned. Calling `instrument` without a block publishes an instantaneous event, which is handy for "this happened" signals. ## Subscribing `subscribe` takes a pattern and either a block or an object that responds to `call`: - an **exact String** — `"checkout.ticketing"`; - a **Regexp** — `/\.ticketing\z/` matches every event in your namespace; - **nothing** — every event in the process (use with care); - a **Symbol** raises `ArgumentError` ("pattern must be specified as a String, Regexp or empty"). It returns a subscriber object; pass it to `ActiveSupport::Notifications.unsubscribe` to stop. `unsubscribe("checkout.ticketing")` removes every subscription with that exact name. ## What a subscriber receives | Subscriber shape | Receives | |---|---| | block or callable with **one** parameter | an `ActiveSupport::Notifications::Event` | | block with **five** parameters | `name, start, finish, id, payload` (`start` and `finish` are `Time` objects with `subscribe`) | | object responding to `start` and `finish` | separate `start(name, id, payload)` and `finish(name, id, payload)` calls | The `Event` object offers `name`, `payload`, `duration` (milliseconds), `cpu_time`, `idle_time`, `allocations`, `gc_time` and `transaction_id` (the instrumenter's id). ## When subscribers run - **Synchronously**, on the thread that called `instrument`, after the block has finished. There is no queue and no background thread. - **All** matching subscribers run before `instrument` returns to the caller. - Their cost therefore adds to the instrumented code's own latency, which is why subscriber cost is a production topic. ## A worked ticketing example A fan clicks "Buy" for two seats. `Order#place!` wraps its work in `instrument("checkout.ticketing", order_id: 7)`. Inside the block the seats are reserved, the card is charged and `payload[:tickets] = 2` is added. When the block returns, the fanout builds an `Event` for the one-argument subscriber in `config/initializers/ticketing_events.rb`, which logs the order id, ticket count and duration. If the card charge had raised, the same subscriber would have run with `payload[:exception]` set, and the exception would then have continued up to the controller. Common misreadings to avoid: - The subscriber is not a callback on the model; it hears every `checkout.ticketing` event from anywhere in the process. - Nothing is persisted or sent anywhere unless a subscriber does it. - The event name is just a string; Rails does not validate the `event.library` shape, it is a convention. ## Naming and payload habits - Follow the guide's **`event.library`** convention: `checkout.ticketing`, `refund.ticketing`, just as Rails uses `sql.active_record` and `process_action.action_controller`. - Keep payloads to plain values (ids, counts, names); subscribers may log or ship them. - Register long-lived subscribers once, at boot, in `config/initializers/`; Rails' own documentation warns that temporary subscriptions wipe internal caches and hurt performance. - Prefer `ActiveSupport::Notifications.subscribed(callback, "checkout.ticketing") { ... }` when a subscription must exist only for a block, such as in a test.

  • What does a subscriber see when the instrumented block raises an exception?
    It is still called. The payload contains `:exception`, a two-element array of the exception class name and message, and `:exception_object`, the exception itself. After the subscribers run, `instrument` re-raises the original exception to the caller, so instrumentation never swallows errors.
  • How do you subscribe to every event your own application publishes under one namespace?
    Pass a Regexp, such as `ActiveSupport::Notifications.subscribe(/\.ticketing\z/) { |event| ... }`, and branch on `event.name`. Alternatively, write a class inheriting `ActiveSupport::Subscriber` and call `attach_to :ticketing`, so each public method handles one event of that namespace.

  • Notifications subscribers run later on a background thread
  • Subscribers are skipped when the instrumented block raises
  • subscribe(:checkout) subscribes to every event starting with checkout
  • A one-argument subscriber block receives only the payload hash
  • instrument returns the Event object instead of the block's value