Skip to content

Are Mongoid transactions actually thread-safe? #5870

Answered by comandeo-mongo
arg asked this question in Q&A
Discussion options

You must be logged in to vote

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 the Thread.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…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@arg
Comment options

Answer selected by arg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants