Rails 7.1 allows subscribing to Active Record transaction events for instrumentation

Vishnu M

By Vishnu M

on January 16, 2024

This blog is part of our  Rails 7 series.

The Active Support instrumentation API provides us with hooks which allows 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 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.

2  "transaction.active_record"
3) do |event|
4  MetricsLogger.record_transaction(event.payload)

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, 2 for more details.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.