mongodb runtime_error ai_generated true

MongoServerError: Transaction 1234 was aborted due to a write conflict

ID: mongodb/transaction-abort-due-to-write-conflict

Also available as: JSON · Markdown · 中文
85%Fix Rate
88%Confidence
1Evidence
2023-06-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
mongodb-5.0 active
mongodb-6.0 active
mongodb-7.0 active
mongodb-8.0 active

Root Cause

Two concurrent transactions attempted to modify the same document, causing one to abort due to optimistic concurrency control.

generic

中文

两个并发事务尝试修改同一文档,导致一个事务因乐观并发控制而中止。

Official Documentation

https://www.mongodb.com/docs/manual/core/transactions-production-consideration/#write-conflicts

Workarounds

  1. 85% success Implement a retry loop in the application: catch the write conflict error and re-run the transaction up to 3 times with exponential backoff.
    Implement a retry loop in the application: catch the write conflict error and re-run the transaction up to 3 times with exponential backoff.
  2. 75% success Reduce transaction scope by accessing fewer documents or using smaller batch sizes to minimize contention.
    Reduce transaction scope by accessing fewer documents or using smaller batch sizes to minimize contention.
  3. 80% success Use a deterministic ordering for document updates within transactions to prevent deadlocks and conflicts.
    Use a deterministic ordering for document updates within transactions to prevent deadlocks and conflicts.

中文步骤

  1. Implement a retry loop in the application: catch the write conflict error and re-run the transaction up to 3 times with exponential backoff.
  2. Reduce transaction scope by accessing fewer documents or using smaller batch sizes to minimize contention.
  3. Use a deterministic ordering for document updates within transactions to prevent deadlocks and conflicts.

Dead Ends

Common approaches that don't work:

  1. 50% fail

    Disabling transactions entirely removes atomicity guarantees for multi-document operations.

  2. 50% fail

    Increasing wtimeoutMS does not resolve write conflicts; it only affects write concern timeouts.

  3. 50% fail

    Setting retryWrites=true does not apply to transactions; transactions must be retried manually.