Write conflict in transaction

I have an application that tries to update the same row in a collection in 2 separate threads at the same time. Each thread has its own connection the MongoDB server and has started a transaction.

Thread 1 has altered the row and the 2nd thread tries to update the same row when MongoDB returns the write conflict error. The 2nd thread waits 5 millisecs and then tries to update the row again, when MongoDB returns transaction aborted.

Each thread is updating and inserting into multiple documents in the transaction.

This a major issue for us, is this a bug?

I changed the app to work as separate processes instead of multiple threads and I still get the same issue.

Write conflict can occur in following case:

  1. thread A reads a row
  2. thread B reads the same row
  3. thread B updates the row
  4. thread A updates the row.

the data read by A before A’s write is no longer valid (modified by B), so you get a conflict.

I understand your logic for explaining a write conflict, however in a multi-user transaction based environment that should not happen, thread B after updating the row should have it locked and blocking thread A until thread B commits/rollback or thread A gets a transaction timeout.

If MongoDB is not working as above then it cannot be used in a multi-user environment that requires updates in a transaction to block other users.

My understanding is that if you update a row in MongoDB it locks it.

Check this.

It looks like at least in mongo 4.0, other sessions attempting to modify the locked document (locks are only released upon transaction finish) will not block and will be aborted.

MongoDB 4.2 our code seemed to work fine, since 4.4, 5 and 6 it is broken.

I would expect any updates in a transaction to have their rows locked until committed/rollbacked and other reads/updates outside the transaction blocked.

I have seen many people asking about MongoDB transactions on the internet, it seems to be very confusing or not straight forward as expected.