skip to content

In Rails 8.1, what does Rails.event add over ActiveSupport::Notifications, and how do notify, tagged and set_context shape a signup event?

level: middleimportance: nice to knowfreq 18%

answer

  1. new in Rails 8.1
  2. facts, not timed blocks
  3. subscribers implement emit(event)
  4. tags per block, context per request
  5. subscriber errors reported, not raised

basics

~10 s

Rails.event, new in Rails 8.1, reports structured, untimed events: notify("user.signed_up", user_id: 42) builds a hash with name, payload, tags, context, a nanosecond timestamp and source location, and passes it to every subscriber's emit method.

solid answer

~40 s

`Rails.event` is the 8.1 Event Reporter (`ActiveSupport::EventReporter`). Where Notifications times a block for in-process listeners, `Rails.event.notify("user.signed_up", user_id: 42, plan: "fan")` records a **fact** as a hash: `name`, `payload` (filtered through `filter_parameters`), `tags`, `context`, a `CLOCK_REALTIME` `timestamp` in nanoseconds and the caller's `source_location`. You can also pass an event object, whose class name becomes the name. `Rails.event.tagged("web") { ... }` adds `{ web: true }` to every event in the block; `Rails.event.set_context(request_id: ...)` merges request-wide data that the executor clears after each request or job. Subscribers are any objects with `emit(event)`, optionally with a filter block; their errors are reported to `Rails.error` and swallowed unless `raise_on_error` is on, which Rails ties to `consider_all_requests_local`. Rails' own frameworks re-emit events such as `action_controller.request_completed` through it.

code

ruby · 17 lines
ruby
class ApplicationController < ActionController::Base
  before_action { Rails.event.set_context(request_id: request.request_id) }
end

class RegistrationsController < ApplicationController
  def create
    @user = User.new(params.expect(user: [:email_address, :password]))
    if @user.save
      Rails.event.tagged("web") do
        Rails.event.notify("user.signed_up", user_id: @user.id, plan: "fan")
      end
      redirect_to root_path
    else
      render :new, status: :unprocessable_content
    end
  end
end

go deeper

for a junior

Recall that Rails 8.1 added Rails.event for structured events, that notify takes a name plus payload, and that subscribers implement emit.

for a middle

Explain the event hash, how tagged and set_context add metadata, payload filtering, and how it differs from timing with Notifications.

for a senior

Design the event flow: request context in a before_action, filtered payloads, error isolation in subscribers, and when framework structured events start costing anything.

for a principal

Decide which business facts become structured events, their naming and schema ownership, and how they leave the process for analytics and audit.

## A different job from Notifications Rails 8.1 added **structured event reporting**: `Rails.event` returns `ActiveSupport.event_reporter`, an `ActiveSupport::EventReporter`. It complements, rather than replaces, `ActiveSupport::Notifications`. | | `ActiveSupport::Notifications` | `Rails.event` | |---|---|---| | Unit | a **timed block** (`instrument`) | a **fact** that happened (`notify`) | | Timing | start, finish, duration | one `timestamp`, nanoseconds, real-time clock | | Subscriber contract | block or `call` with an `Event` or five arguments | any object with **`emit(event)`** | | Extra metadata | payload only | payload, **tags**, **context**, **source location** | | Subscriber error | re-raised into the instrumented code | reported to `Rails.error`, swallowed unless `raise_on_error` | | Typical use | performance hooks, logging internals | business and audit events shipped to a pipeline | ## Anatomy of an event `Rails.event.notify("user.signed_up", user_id: 42, plan: "fan")` builds: - `name` — `"user.signed_up"` (or the class name when you pass an event object); - `payload` — `{ user_id: 42, plan: "fan" }`, keys symbolized and passed through the app's **`filter_parameters`** mask, so a `password:` key is filtered; - `tags` — from enclosing `tagged` blocks; - `context` — from `set_context`; - `timestamp` — `Process.clock_gettime(Process::CLOCK_REALTIME, :nanosecond)`; - `source_location` — `filepath`, `lineno` and `label` of the caller. Pass **either** a payload hash **or** keyword arguments, not both; mixing them is reported (or raised in development) as an `ArgumentError`. An event object, such as `UserSignedUp.new(user_id: 42)`, is passed through as the payload unchanged. ## Tags and context - **`tagged(*tags, **kv) { ... }`** pushes tags for the block, fiber-scoped and nestable: a String or Symbol becomes `{ web: true }`, a Hash or keywords are merged, and any other object is stored under its class name. - **`set_context(request_id: ..., user_agent: ...)`** merges keys into a context that every later event carries. Rails clears it when the executor completes each request or job, and `clear_context` does it by hand. `config.active_support.event_reporter_context_store` swaps in a custom store. Set request-wide context in a `before_action`; use `tagged` for a narrower slice such as "this happened through the API". ## Subscribers ```ruby Rails.event.subscribe(SignupAnalytics.new) { |event| event[:name].start_with?("user.") } ``` - The object must respond to `emit`; otherwise `subscribe` raises `ArgumentError`. - The optional block is a **filter** evaluated per event. - `unsubscribe` accepts the instance or its class. - Each subscriber is called in turn; one raising does not stop the others. With `raise_on_error` off — Rails sets it from `config.consider_all_requests_local`, so off in production — the error goes to `Rails.error` as handled. `Rails.event.debug(...)` reports only in **debug mode**, which Rails enables in development, or inside `Rails.event.with_debug { ... }`. ## Framework events in 8.1 Each framework ships an `ActiveSupport::StructuredEventSubscriber` subclass that listens to its Notifications events and re-emits them as structured events: `action_controller.request_started`, `action_controller.request_completed` (with `status`, `duration_ms`, `gc_time_ms`), `action_controller.redirected`, and debug-only ones such as `active_record.sql`. They stay silent while `Rails.event` has no subscribers, so an app pays for them only once it subscribes. ## Testing structured events `ActiveSupport::TestCase` includes `ActiveSupport::Testing::EventReporterAssertions` in 8.1, so a test can assert that an event was reported with a partial payload match: ```ruby assert_event_reported("user.signed_up", payload: { plan: "fan" }) do post registrations_path, params: { user: { email_address: "[email protected]", password: "s3cret-pass" } } end ``` `assert_no_event_reported` and `assert_events_reported` cover the negative and multi-event cases. ## When to reach for which - Measuring how long checkout takes → Notifications `instrument`. - Recording that a fan signed up, with request context, for an analytics pipeline → `Rails.event.notify`. - Both at once → instrument for the timing and notify for the business fact; do not force one API to do the other's job.

  • Why does a password key in a Rails.event payload not leak into subscribers?
    When the payload is a Hash or keyword arguments, the reporter runs it through an `ActiveSupport::ParameterFilter` built from `filter_parameters`, replacing matching values with the filtered mask before any subscriber sees it. An event object passed instead of a hash is not filtered; it must avoid carrying secrets itself.
  • What happens to context set with Rails.event.set_context once the request finishes?
    The Active Support railtie registers an executor `to_complete` hook that calls `clear_context`, so context does not leak into the next request or job on the same thread. It is also cleared before classes are unloaded on reload. Within a request, later `set_context` calls merge keys rather than replace the whole hash.

  • Rails.event.notify times a block and reports its duration
  • Rails.event subscribers implement call(name, start, finish, id, payload)
  • Rails.event.tagged only adds tags to Rails.logger lines
  • Context set with set_context persists across requests on a thread
  • Rails.event replaces ActiveSupport::Notifications in Rails 8.1

Assumes Rails 8.1, which introduced Rails.event (ActiveSupport::EventReporter) and the framework structured event subscribers.