mongodb/mongoid · error · Mongoid::Errors::InvalidTransactionNesting
A transaction was started while another transaction was…
Error message
A transaction was started while another transaction was being used on this client.
What it means
transaction detected an already-open transaction on this client (via the session started by with_session). Transactions cannot be nested on the same client, so the overlapping call raises InvalidTransactionNesting.
Solutions
- Run the inner work inside the existing transaction instead of opening a new one
- Restructure so transaction blocks on the same client do not overlap
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at lib/mongoid/clients/sessions.rb:92 when the library encounters an invalid state.
Common situations: See trigger scenarios.
AI-assisted analysis of mongodb/mongoid@0da0e23d71 (2026-08-23).
Data as JSON: /api/errors/1bbcf946a5446500.
Report an issue: GitHub.
Appendix: source
Thrown at lib/mongoid/clients/sessions.rb:92
#
# @raise [ Mongoid::Errors::InvalidTransactionNesting ] If the transaction is
# opened on a client that already has an open transaction.
# @raise [ Mongoid::Errors::TransactionsNotSupported ] If MongoDB deployment
# the client is connected to does not support transactions.
# @raise [ Mongoid::Errors::TransactionError ] If there is an error raised
# by MongoDB deployment or MongoDB driver.
#
# @yield Provided block will be executed inside a transaction.
def transaction(options = {}, session_options: {}, &block)
with_session(session_options) do |session|
session.with_transaction(options, &block).tap { run_commit_callbacks(session) }
rescue *transactions_not_supported_exceptions
raise Mongoid::Errors::TransactionsNotSupported
rescue Mongoid::Errors::Rollback
run_abort_callbacks(session)
rescue Mongoid::Errors::InvalidSessionNesting
# Session should be ended here.
raise Mongoid::Errors::InvalidTransactionNesting.new
rescue Mongo::Error::InvalidSession, Mongo::Error::InvalidTransactionOperation => e
run_abort_callbacks(session)
raise Mongoid::Errors::TransactionError.new(e)
rescue StandardError => e
run_abort_callbacks(session)
raise e
end
end
# Sets up a callback is called after a commit of a transaction.
# The callback is called only if the document is created, updated, or destroyed
# in the transaction.
#
# See +ActiveSupport::Callbacks::ClassMethods::set_callback+ for more
# information about method parameters and possible options.
def after_commit(*args, &block)
set_options_for_callbacks!(args)
set_callback(:commit, :after, *args, &block)View on GitHub (pinned to 0da0e23d71)