---
title:
  "Rails 7.1 allows subscribing to Active Record transaction events for
  instrumentation"
description:
  "Rails 7.1 allows subscribing to Active Record transaction events for
  instrumentation."
canonical_url: "https://www.bigbinary.com/blog/rails-7-1-allows-subscribing-to-active-record-transaction-events"
markdown_url: "https://www.bigbinary.com/blog/rails-7-1-allows-subscribing-to-active-record-transaction-events.md"
---

# Rails 7.1 allows subscribing to Active Record transaction events for instrumentation

Rails 7.1 allows subscribing to Active Record transaction events for
instrumentation.

- Author: Vishnu M
- Published: January 16, 2024
- Categories: Rails, Rails 7

The Active Support instrumentation API provides us with hooks that allow us to
choose to be notified when certain events occur inside our application. Rails
provides a set of built-in events that we can subscribe to.
[Here](https://edgeguides.rubyonrails.org/active_support_instrumentation.html#rails-framework-hooks)
is the list of framework hooks.

One of the recent additions to this is the `transaction.active_record` event
That is triggered when Active Record-managed transactions occur. This is
particularly useful if you want to build a monitoring system like NewRelic,
where you need to track and analyze database transactions for performance
monitoring and optimization purposes.

The event payload contains the connection, outcome, and the timing details. The
connection helps us identify the database where the transaction occurred, which
is particularly valuable in a multi-database environment. The outcome, which may
be one of the following: `:commit`, `:rollback`, `:restart`, or `:incomplete`
signifies the transaction's result.

To make use of this, we can subscribe to the event in an initializer
`config/initializers/events.rb` like this.

```ruby
ActiveSupport::Notifications.subscribe(
  "transaction.active_record"
) do |event|
  MetricsLogger.record_transaction(event.payload)
end
```

In the above example, `MetricLogger` is responsible for recording the
transaction details. It then analyzes and reports slow transactions so that
proper action can be taken. You can modify this to suit your instrumentation
needs.

Please check out these pull requests -
[1](https://github.com/rails/rails/pull/49192),
[2](https://github.com/rails/rails/pull/49262) for more details.

## Links

- [Human page](https://www.bigbinary.com/blog/rails-7-1-allows-subscribing-to-active-record-transaction-events)
