MongoDB Transactions
Parent: MongoDB Expert Knowledge · researched 2026-05-28T15:34:27.680Z· 6 sources · 10 concepts · skill mongodb-transactions
---
1. Multi-Document Transactions Overview
- MongoDB added multi-document ACID transactions in 4.0 (replica sets) and extended them to sharded clusters in 4.2. Before 4.0, atomicity was limited to single-document operations (which remain the preferred approach for most use cases). [source]
- ACID guarantees provided: [source]
- Atomicity - all writes in the transaction commit together or all are rolled back [source]
- Consistency - data is moved from one valid state to another; session-level causal consistency is maintained [source]
- Isolation - snapshot isolation: the transaction sees a consistent snapshot of data as of the transaction start; no dirty reads, no non-repeatable reads [source]
- Durability - committed data survives node failures when w: "majority" is used [source]
- Snapshot isolation is the default isolation level since 4.0. Within a transaction, a client sees the data as it existed at transaction start, even if concurrent writers commit changes. This avoids dirty reads and non-repeatable reads but can cause write conflicts (two transactions modifying the same document - the second writer's commit or a read-write conflict will abort one of them). [source]
2. Replica Set Transactions
- All primary-based writes in a replica set transaction are routed to the primary. The session object carries the transaction state. [source]
withTransaction() callback API (recommended)
- withTransaction() handles commit retry and transient error retry automatically. Prefer this over the manual try/catch pattern. Available since Node.js driver 3.2+ and PyMongo 3.9+. [source]
3. Distributed Transactions on Sharded Clusters
- Since MongoDB 4.2, multi-document transactions work across shards using two-phase commit (2PC). [source]
Two-Phase Commit coordinator
- When a transaction touches multiple shards, the mongos router designates one of the participant shards as the coordinator (the shard that receives the first write). The coordinator: [source]
- Prepare phase - sends prepareTransaction to all participant shards; each shard locks its data and votes yes/no [source]
- Commit phase - if all shards vote yes, coordinator sends commitTransaction to all; if any vote no, sends abortTransaction [source]
- The coordinator's decision is durable in config.transactions so recovery is possible after coordinator failure. [source]
- Performance cost vs. replica set transactions: [source]
- 2PC adds at least one extra round-trip (prepare → commit) per participating shard [source]
- Each shard holds WiredTiger write locks during the prepare phase [source]
- Cross-shard transactions are 2–4× slower than replica set transactions under load [source]
- Prefer co-locating transactional data on the same shard (zone sharding, compound shard keys) to avoid cross-shard transactions [source]
4. Read Concern in Transactions
- The read concern set on startTransaction() applies to all reads within the transaction. [source]
- Snapshot isolation detail: [source]
- MongoDB picks a clusterTime at transaction start as the snapshot point [source]
- Reads within the transaction consistently see the state as of that clusterTime [source]
- If the snapshot falls behind the oldest in-use WiredTiger snapshot, MongoDB will abort the transaction with SnapshotTooOld (increase wiredTigerCacheSizeGB or reduce long-running transactions) [source]
5. Write Concern in Transactions
- Write concern on a transaction applies at commit time - it controls how many replica set members must acknowledge the commit before the driver considers it successful. [source]
- Write concern levels: [source]
- j: true (journaled): [source]
- Ensures the commit is written to the on-disk journal before returning success [source]
- Protects against data loss from process crash (but not disk failure) [source]
- Adds latency; omit only if you can tolerate potential data loss [source]
- If the majority acknowledgment isn't received within wtimeout milliseconds, the server returns a WriteConcernError (code 64 / wtimeout) [source]
- The driver wraps this as an error with the UnknownTransactionCommitResult label - the transaction may still have committed on the primary; the outcome is uncertain [source]
- Correct action: retry the commit only (not the full transaction body); withTransaction() does this automatically [source]
Operation count
- No fixed cap on the number of operations (reads + writes) per transaction; the practical limit is oplog size and WiredTiger cache pressure (see below). (A "1,000 per transaction" figure sometimes cited is the driver bulk-write batch-group size, not a transaction limit.) [source]
Oplog entry size
Transaction lifetime
WiredTiger cache pressure
7. Retryable Transactions
- MongoDB drivers classify transaction errors into two categories that require different retry strategies. [source]
Automatic retry via withTransaction()
- withTransaction() handles both TransientTransactionError (retries the callback) and UnknownTransactionCommitResult (retries commit) automatically. This is the recommended production pattern. [source]
Overhead measurement
- Compared to a non-transactional equivalent write, a 2-operation replica set transaction adds: [source]
- ~1–2 ms coordinator overhead on a local cluster [source]
- ~5–15 ms additional latency on a cross-datacenter replica set (round-trip for majority ack) [source]
- ~2–4× slower throughput under high concurrency due to write-conflict aborts [source]
Write conflict storms
- When many concurrent transactions attempt to modify the same document, MongoDB aborts all but the first writer, forcing retries. This is "hot document" contention. [source]
- Redesign schema to avoid hot documents (counters, queue heads) [source]
- Use $inc on a field that's rarely contended vs. an array that many writers append to [source]
- Rate-limit transactional writers at the application layer [source]
References
- https://www.mongodb.com/docs/manual/core/transactions/ [source]
- https://www.mongodb.com/docs/manual/core/transactions-in-applications/ [source]
- https://www.mongodb.com/docs/manual/core/transactions-production-consideration/ [source]
- https://www.mongodb.com/docs/manual/reference/method/Session.startTransaction/ [source]
- https://www.mongodb.com/docs/drivers/node/current/fundamentals/transactions/ [source]
- https://www.mongodb.com/docs/manual/core/read-isolation-consistency-recency/ [source]
Children
- Multi-Document Transactions (frontier)
- Replica Set Transactions (frontier)
- Distributed Sharded Transactions (frontier)
- Read Concern (frontier)
- Write Concern (frontier)
- Transaction Limits (frontier)
- Retryable Transactions (frontier)
- Driver Examples (frontier)
- Performance Impact (frontier)
- Transaction Anti-Patterns (frontier)
Frontier under this node: Distributed Sharded Transactions, Driver Examples, Multi-Document Transactions, Performance Impact, Replica Set Transactions, Retryable Transactions, Transaction Anti-Patterns, Transaction Limits