Should I create recursive method for retry in mongodb transaction to avoid document level lock error?

686 Views Asked by At

I am using mongodb transaction. Sometimes it may happen that for concurrent transaction in same document data update the second transaction will create transient transaction error which will abort the second concurrent update. In this case retry helps. My question is there better design for retry of the second transaction instead of recursive method call on error? Or retry is possible in mongodb query level ? Note: I am using it in scala playframework with reactivemongo.

1

There are 1 best solutions below

0
On

Every driver for MongoDB has two types of APIs:

  • Callback API, that incorporates logic to

    • retry the transaction as a whole if the transaction encounters a TransientTransactionError.
    • retry the commit operation if the commit encounters an UnknownTransactionCommitResult.
  • Core API, that does not incorporate retry logic for the above errors, instead applications should explicitly implement retry logic for the error.

The default implementation of retry logic for the NodeJS driver can be found here and is probably the best one in 90% of the cases. As you can see the attemptTransaction method is recursively called until MAX_WITH_TRANSACTION_TIMEOUT (fixed to 2 minutes) is reached.

Just for completeness, this approach of continuously rolling back and retrying the transaction is in line with the optimistic MVCC adopted by MongoDB, i.e. the snapshot isolation. The above errors are considered as transient errors, meaning that they are temporary and the transaction could be successful if restarted.

If you do not have any particular needs, then this implementation is good enough, otherwise your only choice is to use Core APIs and do it yourself. In this case you should provide additional info on why the default design available from Callback APIs is not suitable in your project.