Transactions
Use multi-document ACID transactions with sessions for consistent writes.
Session Management
Transactions in MongoDB require a client session. Start a session from your driver, then start a transaction within that session. All operations participating in the transaction must pass the session to read and write methods.
Sessions also enable causal consistency in replica sets when you read your own writes across connections using the same session token.
const session = client.startSession();
try {
await session.withTransaction(async () => {
const orders = db.collection("orders");
const inventory = db.collection("inventory");
await orders.insertOne({ /* ... */ }, { session });
await inventory.updateOne({ sku }, { $inc: { qty: -1 } }, { session });
});
} finally {
await session.endSession();
}Transaction Basics
Call startTransaction, perform operations, then commitTransaction on success or abortTransaction on failure. Drivers often provide withTransaction helper that retries transient errors automatically.
Transactions have a default time limit (60 seconds in many configurations). Keep transaction scope small—few documents, few operations—to avoid lock contention and timeouts.
session.startTransaction();
try {
// operations with { session }
await session.commitTransaction();
} catch (error) {
await session.abortTransaction();
throw error;
}Multi-Document Consistency
Use transactions when updating multiple documents or collections must succeed or fail together—transferring funds, order creation with inventory decrement, or account balance adjustments.
Prefer single-document atomic updates when all related data fits in one document. Transactions add overhead and require a replica set or sharded cluster; standalone instances support transactions only in recent versions with limitations.
- All collections involved must reside in the same replica set (or meet sharded transaction rules)
- Reads inside transactions use snapshot isolation
- Design idempotent transaction retries for duplicate client requests
Error Handling
TransientTransactionError labels indicate safe retry of the entire transaction. UnknownTransactionCommitResult means the commit outcome is uncertain—verify state before retrying commit.
Log transaction abort reasons and monitor transaction duration metrics. Long-running transactions block other writers on the same documents in WiredTiger.
catch (error) {
if (error.hasErrorLabel?.("TransientTransactionError")) {
// retry withTransaction
}
throw error;
}Alternatives to Transactions
Embedded documents and atomic single-document updates cover many consistency needs without multi-document transactions. Outbox patterns and eventual consistency via change streams suit high-throughput event-driven systems.
Evaluate whether your consistency requirement is truly ACID across documents or whether compensating actions and idempotent consumers are acceptable.
- Use findOneAndUpdate for atomic read-modify-write on one document
- Implement saga patterns for cross-service consistency in microservices
- Reserve multi-document transactions for short, high-value consistency boundaries