Multi-Document ACID Transactions & Distributed Two-Phase Commit
MongoDB provides fully compliant multi-document ACID transactions across replica sets and sharded clusters using snapshot isolation and distributed Two-Phase Commit (2PC).
Horizontal Sharding, mongos Router & Chunk Balancer
Observe mongos single-shard routing vs scatter-gather queries and automatic chunk migration across replica sets.
Stateless routing daemon. Caches routing table from Config DB. Clients connect directly to mongos on port 27017.
Stores cluster catalog, database mappings, and chunk range boundaries in config.chunks with two-phase commit lock.
Background round-robin process. Triggers migration when chunk difference between shards exceeds the migration threshold.
1. Formal Definition & Architecture Intent
MongoDB supports multi-document ACID transactions across replica sets (since 4.0) and sharded clusters (since 4.2). Transactions guarantee Atomicity, Consistency, Isolation (Snapshot Isolation), and Durability. Distributed transactions across shards are coordinated automatically via a distributed Two-Phase Commit (2PC) protocol.
2. Explain Like I'm 5 (Mental Model)
Transferring $100 from Alice to Bob: if you subtract $100 from Alice and the server catches fire before adding it to Bob, the money vanishes. A multi-document ACID transaction guarantees that BOTH updates happen together, or if anything goes wrong, EVERYTHING rolls back as if nothing happened.
3. Real-World Architecture Example
Atomic bank transfer between two independent account documents.
{
"_id": "acc_A",
"balance": 1000
}{
"_id": "acc_B",
"balance": 500
}Subtracting 200 from A and adding 200 to B occurs in a single atomic transaction block.
4. MQL Implementation Steps
const session = db.getMongo().startSession();
session.startTransaction({
readConcern: { level: "snapshot" },
writeConcern: { w: "majority" }
});
try {
const accColl = session.getDatabase("bank").accounts;
accColl.updateOne({ _id: "acc_A" }, { $inc: { balance: -200 } });
accColl.updateOne({ _id: "acc_B" }, { $inc: { balance: 200 } });
session.commitTransaction(); // Atomic commit!
} catch (error) {
session.abortTransaction(); // Rollback on any error!
throw error;
} finally {
session.endSession();
}5. Critical Engineering Rules
| Rule / Constraint | Underlying Reason & Impact |
|---|---|
| Time Limit (60s) | Transactions have a default maximum lifetime of 60 seconds (transactionLifetimeLimitSeconds) to avoid pinning MVCC cache. |
| DDL Operations Prohibited | DDL operations that create collections, create indexes, or drop collections cannot run inside transactions. |
| TransientTransactionError | Drivers provide automatic retry logic when write conflicts or network failovers occur. |
6. Deep Dive: Distributed 2PC Protocol Across Multiple Shards
When a transaction modifies documents spanning Shard 1 and Shard 2, the mongos router designates Shard 1 as the Transaction Coordinator. Phase 1 (Prepare): The coordinator asks all participant shards to acquire locks, flush preparation WAL logs, and vote PREPARED. Phase 2 (Commit): Once all shards agree, coordinator commands all shards to commit atomically.
// Transaction server status metrics: db.serverStatus().transactions; // "currentActive": active transactions holding snapshots
7. Architectural Trade-offs
- •Full ACID compliance for complex multi-entity business workflows (financial ledgers, checkout inventory)
- •Snapshot isolation guarantees zero dirty reads, non-repeatable reads, or phantom reads
- •Distributed 2PC handles shard cross-partition atomicity transparently
- •Incurs lock overhead and pins WiredTiger cache memory versions during transaction lifespan
- •Slower write throughput compared to single-document atomic updates
8. Technical Interview Questions
Single-document operations are inherently atomic in MongoDB and execute with zero distributed locking overhead. Multi-document transactions acquire locks, pin MVCC update chains in WiredTiger cache, increase dirty page pressure, and require distributed Two-Phase Commit across shards. Proper document embedding eliminates the need for 95% of transactions.
9. Staff-Level Ready Answer
"MongoDB supports multi-document ACID transactions across replica sets and sharded clusters using snapshot isolation and distributed Two-Phase Commit. Transactions have a default 60-second limit and require majority write concern. While powerful, document embedding should still be the primary design choice for atomic workflows."
10. Quick Knowledge Check
What is the default maximum lifespan of a MongoDB multi-document transaction before the server forcibly aborts it?