Rails 7.1 Allows Subscribing To ActiveRecord Transaction Events For Instrumentation.

ActiveRecord transactions allow us to ensure that a series of database operations are executed together as a single unit. If any operation within the transaction fails, the entire transaction is rolled back, maintaining the integrity of our database.

The ActiveSupport instrumentation API provides hooks so that we can subscribe to notifications whenever specific events take place within our application.

Use ActiveSupport::Notifications.subscribe with a block to listen to for notifications. Depending on the amount of arguments the block takes, we will receive different data. The block can take different numbers of arguments, we will receive different data depending on how we define it.

Before

ActiveSupport::Instrumentation provides us many ActiveRecord hooks. Refer.

Tracking ActiveRecord transactions is crucial for effective debugging and monitoring. This includes understanding the transaction object, its outcome, and the associated connection details.

However, there are no instrumentation API hooks to track ActiveRecord transaction events.

After

Rails 7.1 allows subscribing to ActiveRecord transaction events for tracking/ instrumentation with the help of transaction.active_record.

The transaction.active_record event is emitted when a database transaction finishes and event payload includes connection, outcome, and timing details.

Key Value
:transaction Transaction object
:outcome :commit, :rollback, :restart, or :incomplete
:connection Connection object

The connection helps to identify the database involved, outcome indicates the transaction’s result and can be one of the following :commit, :rollback, :restart, or :incomplete and transaction objectis helpful for tracing database activity.

# config/initializers/events.rb

ActiveSupport::Notifications.subscribe("transaction.active_record") do |event|
  transaction = event.payload[:transaction]
  outcome = event.payload[:outcome]
  connection = event.payload[:connection]
  
  # Example logging or handling
  Rails.logger.info "Transaction: #{transaction.uuid}"
  Rails.logger.info "Outcome: #{outcome}"
  Rails.logger.info "Connection: #{connection.inspect}"
end

Refer

Need help on your Ruby on Rails or React project?

Join Our Newsletter