mongodb/mongoid · error · Mongoid::Errors::InvalidSessionNesting

A session was started while another session was being used…

Error message

A session was started while another session was being used on this client.

What it means

with_session found a session already active on this client's thread/fiber storage. Sessions cannot be nested on the same client, so starting a second one before the first is ended raises InvalidSessionNesting.

Solutions

  1. Reuse the already-active session instead of opening another
  2. Ensure prior with_session blocks complete (no leaked sessions) before starting a new one
Defensive patterns

Strategy: try-catch

When it happens

Trigger: Thrown at lib/mongoid/clients/sessions.rb:39 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/6e8b5b70b02b4ce6. Report an issue: GitHub.

Appendix: source

Thrown at lib/mongoid/clients/sessions.rb:39

        # @example Execute some operations in the context of a session.
        #   Band.with_session(causal_consistency: true) do
        #     band = Band.create
        #     band.records << Record.new
        #     band.save
        #     band.reload.records
        #   end
        #
        # @param [ Hash ] options The session options. Please see the driver
        #   documentation for the available session options.
        #
        # @raise [ Errors::InvalidSessionUse ] If an operation is attempted on a model using another
        #   client from which the session was started or if sessions are nested.
        #
        # @return [ Object ] The result of calling the block.
        #
        # @yieldparam [ Mongo::Session ] The session being used for the block.
        def with_session(options = {})
          raise Mongoid::Errors::InvalidSessionNesting.new if Threaded.get_session(client: persistence_context.client)

          session = persistence_context.client.start_session(options)
          Threaded.set_session(session, client: persistence_context.client)
          yield(session)
        rescue Mongo::Error::InvalidSession => e
          raise Mongoid::Errors::SessionsNotSupported.new if e.is_a?(Mongo::Error::SessionsNotSupported)

          raise e
        rescue Mongo::Error::OperationFailure => e
          if (e.code == 40_415 && e.server_message =~ /startTransaction/) ||
             (e.code == 20 && e.server_message =~ /Transaction/)
            raise Mongoid::Errors::TransactionsNotSupported.new
          else
            raise e
          end
        rescue *transactions_not_supported_exceptions
          raise Mongoid::Errors::TransactionsNotSupported
        ensure

View on GitHub (pinned to 0da0e23d71)