database concurrency_error ai_generated true

pymongo.errors.OperationFailure: WriteConflict error: this operation conflicted with another operation.

ID: database/mongo-write-conflict

Also available as: JSON · Markdown
87%Fix Rate
89%Confidence
42Evidence
2023-06-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7 active

Root Cause

Two operations attempted to modify the same document concurrently within a multi-document transaction. MongoDB uses optimistic concurrency control for transactions and raises WriteConflict when a conflict is detected. The operation is aborted and should be retried. This is expected behavior under high write concurrency to the same documents.

generic

Workarounds

  1. 90% success Implement transaction retry logic using the MongoDB driver's built-in retry support
    Use the driver's withTransaction() callback API which automatically retries on TransientTransactionError. In Python: with client.start_session() as session: session.with_transaction(callback). The driver handles retry with backoff. Limit retries to 3-5 attempts.
  2. 82% success Reduce transaction scope and duration to minimize conflict windows
    Keep transactions as short as possible. Move read operations outside the transaction. Avoid transactions that modify many documents across multiple collections. If the same documents are always contended, consider restructuring the schema to reduce the number of documents modified per transaction.

Dead Ends

Common approaches that don't work:

  1. Catching the WriteConflict and retrying only the failed operation instead of the entire transaction 90% fail

    When a WriteConflict occurs inside a transaction, the entire transaction is aborted, not just the single operation. Retrying only the failed operation within the aborted transaction session will fail with 'transaction has been aborted'. The entire transaction must be retried from the start.

  2. Removing multi-document transactions to avoid WriteConflict errors 70% fail

    Without transactions, individual operations succeed but you lose atomicity guarantees. If your business logic requires multiple documents to be updated together consistently, removing transactions leads to data inconsistency that is harder to fix than implementing retry logic.

Error Chain

Leads to:
Preceded by:
Frequently confused with: