Are Mongoid transactions actually thread-safe? #5870
-
Our Rails app runs in a pretty common multi-threaded environment powered by Puma. After the recent upgrade to Mongoid v9, we'd like to start using this new block-syntax for transactions. However after reading the documentation, I've got a concern about feature's thread safety. Here are few quotes:
and
Does it mean that Mongoid transactions are not thread-safe and therefore should not be used in a multi-threaded setups, such as Puma? Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @arg , thank you for your question! Mongoid transactions API is thread safe. When you call The new Therefore, you are safe unless you explicitly pass the session to another thread. This won't work, and should be avoided. I would like to point out that I hope this clarifies the situation for you. Please reach us out if you still have question, or if you experience issues with the new transactions API. Thank you for using MongoDB and Mongoid! |
Beta Was this translation helpful? Give feedback.
Hi @arg , thank you for your question! Mongoid transactions API is thread safe. When you call
#with_session
method, it creates a new session for the current persistence context, and stores it in theThread.local
storage ( https://github.com/mongodb/mongoid/blob/master/lib/mongoid/clients/sessions.rb#L47). This session will be used inside the block.The new
#transaction
method uses#with_session
under the hood, so the same applies here.Therefore, you are safe unless you explicitly pass the session to another thread. This won't work, and should be avoided.
I would like to point out that
#with_session
method is not the new transaction API introduced in 9. If you were using transactions in 8…