A conflict occurred during a write operation
This error occurs when two or more write operations conflict with each other. In a replica set, it can happen if a write is committed on a primary that subsequently gets rolled back. Within a transaction, it occurs if two operations in the transaction conflict with an external write.
- 1In a transaction, reading a document that is then modified by another transaction before the first one commits
- 2An operation in a transaction tries to modify a document that has already been modified by a committed, concurrent transaction
- 3A write operation succeeds on a primary, but that primary steps down and the write is rolled back before it replicates
- 4Using snapshot read concern and trying to read a document that was modified by a transaction committed after the snapshot was taken.
Two transactions attempt to modify the same document, causing a conflict.
// Start a transaction in Shell 1
const session1 = db.getMongo().startSession();
session1.startTransaction();
const coll1 = session1.getDatabase('test').getCollection('wc');
coll1.updateOne({ _id: 1 }, { $set: { x: 1 } });
// Start a transaction in Shell 2
const session2 = db.getMongo().startSession();
session2.startTransaction();
const coll2 = session2.getDatabase('test').getCollection('wc');
// This will block, waiting for the lock from Shell 1
coll2.updateOne({ _id: 1 }, { $set: { x: 2 } });
// Commit transaction in Shell 1
session1.commitTransaction();
// Transaction in Shell 2 will now fail with a WriteConflict error.
session2.commitTransaction();expected output
MongoServerError: WriteConflict error
Fix 1
Retry the Transaction
WHEN This error occurs within a transaction.
// Application logic should catch this specific error and retry the entire transaction.
try {
await session.withTransaction(async () => {
// ... transaction operations ...
});
} catch (error) {
if (error.hasErrorLabel("TransientTransactionError")) {
console.log("Retrying transaction due to write conflict...");
// ... retry logic ...
}
}Why this works
Write conflicts are expected in concurrent systems using transactions. The correct response is for the application to catch the error and retry the entire transaction from the beginning. MongoDB drivers often provide a helper API to automate this.
Fix 2
Investigate Rollbacks
WHEN The error occurs outside a transaction.
Why this works
If you receive a write conflict outside of a client-side transaction, it may be due to a replica set rollback. Check the `mongod` logs for rollback events. This is a rare and serious event that requires investigation of your replica set's health and stability.
✕ Assume the write failed and do nothing
The application's intended change was not applied. If the business logic requires this change, it must be retried to ensure data consistency.
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev