Skip to content
LESSON 50 / 50Expertdistributed

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).

Interactive Engine Simulator

Horizontal Sharding, mongos Router & Chunk Balancer

Observe mongos single-shard routing vs scatter-gather queries and automatic chunk migration across replica sets.

mongos Query Router

Stateless routing daemon. Caches routing table from Config DB. Clients connect directly to mongos on port 27017.

Config Replica Set (CSRS)

Stores cluster catalog, database mappings, and chunk range boundaries in config.chunks with two-phase commit lock.

Chunk Balancer

Background round-robin process. Triggers migration when chunk difference between shards exceeds the migration threshold.

Shard 01 (Replica Set: rs-shard-01)3 Chunks
chunk-1Range: [MinKey .. 1000)
450 docs
chunk-2Range: [1000 .. 2000)
820 docs
chunk-3Range: [2000 .. 3000)
610 docs
Shard 02 (Replica Set: rs-shard-02)1 Chunks
chunk-4Range: [3000 .. MaxKey)
390 docs
MONGOS_LOG:Cluster balanced across 2 shards. Shard key: { user_id: 1 }.

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.

Sample BSON Documents:
Collection: db.accounts
{
  "_id": "acc_A",
  "balance": 1000
}
Collection: db.accounts
{
  "_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

Step 1: Execute atomic multi-document transaction in mongosh / Node.js
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();
}
Guarantees snapshot isolation across all affected collections.

5. Critical Engineering Rules

Rule / ConstraintUnderlying Reason & Impact
Time Limit (60s)Transactions have a default maximum lifetime of 60 seconds (transactionLifetimeLimitSeconds) to avoid pinning MVCC cache.
DDL Operations ProhibitedDDL operations that create collections, create indexes, or drop collections cannot run inside transactions.
TransientTransactionErrorDrivers 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
Production Warning: Overusing multi-document transactions in MongoDB indicates relational schema design flaws.

7. Architectural Trade-offs

Advantages
  • •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
Disadvantages & Gotchas
  • •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

Q1: Why does MongoDB recommend relying on single-document atomicity over multi-document transactions whenever possible?

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?