MongoDB Transactions: What 4.0 Changed—and Why Transactions Don't Replace Good Document Modeling
Multi-document transactions in MongoDB provide ACID guarantees when required, but treating a document database like a relational engine by wrapping distributed workflows in long-running transactions guarantees storage engine starvation.
TL;DR
- Problem: Holding multi-document transactions open—especially across external HTTP/RPC calls or hot counter documents—pins old MVCC snapshots in
WiredTigerHS.wt, drives dirty cache past 20%, and triggers optimisticWriteConflictretry storms.- Answer: Model for single-document atomicity first by co-locating bounded state, isolate multi-document transactions to minimal sub-second mutations with external RPCs executed beforehand, and co-locate sharded documents to avoid Two-Phase Commit (2PC).
- Watch out: Never execute network calls inside
withTransaction(), never share hot accumulator documents across concurrent transactions, and always setmaxCommitTimeMSwith bounded exponential-backoff retries.
Production Scope: MongoDB 4.2 – 8.0 on AWS EC2
Situation
When MongoDB added multi-document ACID transactions for replica sets in version 4.0 and extended them to sharded clusters in 4.2, many engineering teams migrating from PostgreSQL or Oracle treated transactions as permission to import normalized multi-table schemas directly into MongoDB. Foreign keys, split parent-child tables, and multi-step workflows were wrapped in session.startTransaction() blocks assuming row-level lock queues would serialize contention cleanly.
In low-concurrency staging environments, those transactions pass functional tests without issue. Under production concurrency on AWS EC2, however, high-throughput services—financial ledgers, inventory reservation engines, and order state machines—encounter WriteConflict retry storms, WiredTigerHS.wt disk bloat, and cascading latency spikes across unrelated non-transactional queries. The root surprise for teams coming from PostgreSQL or Oracle is lock semantics: relational SELECT ... FOR UPDATE queues competing writers behind row locks and surfaces contention as tail latency, whereas MongoDB’s optimistic concurrency immediately aborts the losing writer with WriteConflict, converting modest hot-document contention into exponential client retry amplification.
The Problem
Storage Engine MVCC and Locking Bottlenecks
Unlike relational engines with pessimistic row-lock queues and dedicated undo logs, MongoDB’s transaction model relies on WiredTiger’s Multi-Version Concurrency Control (MVCC) snapshot isolation and optimistic concurrency control. Overusing or prolonging transactions triggers four compounding bottlenecks:
- WiredTiger History Store Pinning (
WiredTigerHS.wt): A transaction opened withreadConcern: "snapshot"pins anoldest_timestampin WiredTiger. While that transaction remains open, WiredTiger cannot discard intermediate document versions modified by any concurrent writer in the cluster; it must retain those prior versions in the History Store (WiredTigerHS.wt). Consider a cluster processing 20,000 updates per second averaging 2 KB per prior document version (~40 MB/s of historical deltas): a single stalled session holding a snapshot open for 55 seconds (just under the 60-second abort limit) pins ~2.2 GB of history store versions from unrelated collections, competing directly with the ~31.5 GB WiredTiger cache on anr6g.2xlargeand spilling pages onto EBSgp3. - Cache Eviction Stalls and DDL Lock Queuing: Because open snapshots pin historical page versions in memory, background eviction threads fall behind. Tracked dirty cache rises toward the 20%
eviction_dirty_triggerthreshold, conscripting application worker threads into synchronous page eviction and spilling history store pages to EBS disk. Simultaneously, active transactions hold intent locks (IS/IX) on collections and databases for their entire lifetime; if a schema migration issuescollModorcreateIndex(requiring an exclusiveXlock), the DDL statement queues behind the stalled transaction and blocks all subsequent reads and writes behind it. - Optimistic
WriteConflictRetry Storms: MongoDB does not queue competing writes inside transactions. If Transaction $T_1$ modifies document $D$ and concurrent Transaction $T_2$ attempts to modify $D$, $T_2$ aborts immediately with aWriteConflict(TransientTransactionError). When dozens of application threads retry simultaneously against a hot document, CPU consumption spikes while effective throughput collapses. - Hard Lifetime & Cache Ceilings (
60s): Every transaction is bounded bytransactionLifetimeLimitSeconds(default 60 seconds). Even though MongoDB 4.2 lifted the 4.0 single-16-MB-oplog-entry cap by splitting large transactions across multiple linked oplog entries (prevOpTime), oversized uncommitted transactions still abort withTransactionTooLargeForCacheif they exceed WiredTiger’s cache budget.
The core architectural question is: Why do overused multi-document transactions degrade WiredTiger throughput, and how should teams combine single-document atomicity with bounded transactions to preserve both ACID correctness and latency?
Options Considered
| Modeling & Transaction Strategy | WiredTigerHS.wt Pinning | Contention / WriteConflict Risk | Cross-AZ 2PC Cost | Decision |
|---|---|---|---|---|
| Normalized Schema + Txns Everywhere | High; every workflow pins snapshots | High on shared parent/counter docs | Paid on every cross-shard write | Rejected: Starves WiredTiger cache under load |
| External RPCs Inside Transactions | Severe; pins history for seconds | Extreme; holds locks during HTTP waits | Amplifies 60s lifetime aborts | Rejected: Turns downstream latency into DB outage |
| Bounded Multi-Doc Txn (0 RPCs) | Minimal (milliseconds) | Low when sharded key co-located | Paid only on rare cross-shard ops | Chosen for Multi-Doc: Use strictly for multi-entity invariants |
| Single-Document Atomicity | Zero snapshot pinning | Single-document atomic update only | Zero 2PC overhead | Chosen Default: Embed bounded state for 1-op ACID |
Using transactions everywhere with normalized schemas forces WiredTiger to maintain multi-version history for operations that could be a single atomic document update, while placing external HTTP calls inside a transaction turns every downstream microservice hiccup into a database-wide cache stall. Defaulting to single-document atomicity and reserving short, RPC-free multi-document transactions for genuine multi-entity invariants (like cross-account transfers) keeps snapshot lifetimes in milliseconds.
Lowering a transaction’s read concern from "snapshot" to "local" or "majority" does not rescue long-running workflows: uncommitted writes inside an active session still hold document locks and dirty WiredTiger cache pages until commit or abort, and reading without "snapshot" sacrifices point-in-time consistency across statements. When a workflow must coordinate a database state change with an external API or message broker, use the Transactional Outbox Pattern—commit the domain state and an outbox event document together in a sub-10 ms transaction (or inside a single parent document), then publish asynchronously after commit.
The Transaction Architecture: WiredTiger MVCC, Snapshots, and 2PC
Tracing a transaction through WiredTiger MVCC and sharded Two-Phase Commit (2PC) shows why keeping transaction duration in single-digit milliseconds is critical.
flowchart TD
Client["Application Worker — Client Session"] --> Start["session.startTransaction()"]
Start --> ReadSnap["Acquire Snapshot Timestamp t0"]
ReadSnap --> Mutate["Execute Mutations — Intent Locks"]
Mutate --> PinHS["Pin Oldest Timestamp in WiredTigerHS.wt"]
Mutate --> ExtCheck{"External RPC in Transaction?"}
ExtCheck -->|Yes — Anti-Pattern| Delay["Session Open for Seconds"]
Delay --> Abort60["Breach 60s Limit — Forced Abort"]
ExtCheck -->|No — Best Practice| Commit["session.commitTransaction()"]
Commit --> Conflict{"WriteConflict?"}
Conflict -->|Yes| Retry["Rollback & Retry with Backoff"]
Conflict -->|No| Oplog["Oplog w:majority Commit — Unpin HS"]
1. WiredTiger History Store (WiredTigerHS.wt)
When a document is updated, the latest committed value stays on the active in-memory B-tree page while the previous version moves to WiredTigerHS.wt. Concurrent readers with an older snapshot timestamp reconcile the active page against WiredTigerHS.wt to read a consistent point-in-time image. As soon as all transactions referencing timestamp $t_0$ commit or abort, WiredTiger reclaims those historical entries.
If a stalled session holds oldest_timestamp open, background eviction workers still push modified pages out of RAM by writing their prior MVCC versions to WiredTigerHS.wt on disk—causing WiredTigerHS.wt to grow continuously on EBS even when memory appears steady. Worse, once that stalled transaction finally aborts at 60 seconds, WiredTiger marks the freed history blocks for internal reuse rather than truncating WiredTigerHS.wt back to the OS, leaving elevated disk consumption on the EBS volume. Keeping multi-document batches under 500 documents prevents both history-store spikes and TransactionTooLargeForCache aborts.
2. Distributed Two-Phase Commit (4.2+)
When a transaction modifies documents on two or more shards, mongos delegates coordination to a coordinator shard:
- Prepare Phase: The coordinator sends
prepareTransactionto each participant shard. Participants lock the modified documents, write a durable prepare entry to their local oplog (replicated to majority), and vote ready. - Commit Phase: Once all participants prepare, the coordinator writes
commitTransactionand instructs participants to commit and release locks.
Because documents stay locked across both cross-AZ network round-trips, cross-shard transactions hold locks significantly longer than single-shard operations, increasing WriteConflict probability under concurrency. Furthermore, if a primary stepdown or network timeout interrupts commitTransaction() after the prepare phase, the driver receives UnknownTransactionCommitResult. Using the driver’s callback API (withTransaction) automatically retries the commit command idempotently using the same logical session ID (lsid) and transaction number (txnNumber), whereas hand-rolled startTransaction() loops often mishandle UnknownTransactionCommitResult and leave applications uncertain whether the transfer committed.
3. Single-Document Atomicity and Oplog Commit Buffering
Every single-document write in MongoDB (updateOne, findOneAndUpdate, and each individual item inside bulkWrite, even with ordered: false) is atomic at the WiredTiger row level, including all embedded subdocuments and arrays, so partial-document updates are never visible to concurrent readers. Conditional updates such as updateOne({ _id: "ACC_1001", balance: { $gte: 250.00 } }, { $inc: { balance: -250.00 } })—or findOneAndUpdate with returnDocument: "after" to read the updated state—execute an atomic compare-and-swap without opening a multi-document snapshot or pinning WiredTigerHS.wt.
By contrast, a multi-document transaction writes nothing to local.oplog.rs until commitTransaction() executes. On commit, MongoDB records all mutations together as an atomic applyOps oplog entry (or a linked chain of entries via prevOpTime in MongoDB 4.2+ when the transaction exceeds 16 MB), and secondaries apply the entire batch atomically at the commit timestamp so readConcern: "majority" readers never see partial state. However, because all uncommitted writes stay buffered in the primary’s WiredTiger cache until commit, a bulk transaction touching 50,000 documents consumes gigabytes of dirty cache and risks aborting with TransactionTooLargeForCache before commit ever runs.
Diagnostic Telemetry: serverStatus().transactions and currentOp
Inspect active transactions, abort ratio, WriteConflict totals, and WiredTigerHS.wt size:
const ss = db.serverStatus();
const txns = ss.transactions;
const hs = ss.wiredTiger?.["history-store"];
print(`active=${txns.currentActive} committed=${txns.totalCommitted} aborted=${txns.totalAborted}`);
print(`writeConflicts=${ss.metrics.operation.writeConflicts}`);
if (hs) print(`hsMB=${(hs["bytes currently in the history store"] / 1048576).toFixed(2)}`);
Catch sessions holding transactions open (secs_running >= 2) and compare timeActiveMicros vs timeInactiveMicros:
db.currentOp({ transaction: { $exists: true }, secs_running: { $gte: 2 } }).inprog.forEach((op) => {
print(`opid=${op.opid} secs=${op.secs_running} activeMs=${(op.transaction.timeActiveMicros / 1000).toFixed(1)} inactiveMs=${(op.transaction.timeInactiveMicros / 1000).toFixed(1)}`);
});
High timeInactiveMicros relative to timeActiveMicros proves the application client is idle—typically waiting on an external HTTP call or slow application logic—while pinning WiredTiger history.
Safe Remediation: Single-Document Atomicity & Bounded Clients
In MongoDB, every single-document write is atomic by default. When an account balance and a bounded recent-ledger array can live in one document (respecting array bounds via the Outlier/Bucket patterns), one updateOne replaces a multi-document transaction entirely:
db.accounts.updateOne(
{ "_id": "ACC_1001", "balance": { $gte: 250.00 } },
{
$inc: { "balance": -250.00 },
$push: { "recent_ledger": { $each: [{ "txn_id": "TXN_99182", "amt": -250.00 }], $slice: -20 } }
}
);
When two distinct documents must be updated atomically, execute external RPCs first and wrap the pure DB mutations in withTransaction with bounded retries and maxCommitTimeMS:
def execute_transfer(client, src, dst, amount, max_retries=5):
if not call_external_fraud_check(src, amount):
raise RuntimeError("Fraud check failed")
backoff = 0.05
for attempt in range(max_retries):
try:
with client.start_session() as s:
def cb(sess):
accts = sess.client.banking.accounts
r = accts.update_one({"_id": src, "balance": {"$gte": amount}}, {"$inc": {"balance": -amount}}, session=sess)
if r.modified_count == 0:
raise ValueError("Insufficient funds")
accts.update_one({"_id": dst}, {"$inc": {"balance": amount}}, session=sess)
s.with_transaction(cb, read_concern=ReadConcern("snapshot"), write_concern=WriteConcern("majority", wtimeout=5000), max_commit_time_ms=5000)
return True
except (ConnectionFailure, OperationFailure) as exc:
if exc.has_error_label("TransientTransactionError"):
time.sleep(backoff)
backoff *= 2.0
elif exc.has_error_label("UnknownTransactionCommitResult"):
raise # Verify idempotently before retrying
else:
raise
raise RuntimeError("Circuit breaker: exceeded max transaction retries")
How It Rolls Out
- Phase 1 — Audit Open Transactions & History Store: Monitor
db.serverStatus().transactions,wiredTiger.history-store, andcurrentOptimeInactiveMicrosto locate long-running sessions and high-abort endpoints. - Phase 2 — Externalize Network I/O: Refactor application handlers so all HTTP calls, fraud checks, and message-queue publishes run before
startTransaction()or asynchronously via an outbox pattern after commit. In the outbox pattern, write the domain update and anoutboxevent document inside the same sub-10 ms transaction, then tail theoutboxcollection with a Change Stream (watch()persistingresumeAftertokens) to publish downstream messages without holding WiredTiger snapshots open. - Phase 3 — Refactor to Single-Doc Atomicity & Co-Located Shard Keys: Consolidate bounded 1-to-few invariants into single documents, and align sharded collection shard keys (e.g.,
tenant_idoraccount_group_id) so related documents reside on the same shard, avoiding 2PC. - Phase 4 — Enforce
maxCommitTimeMS& Circuit Breakers: Cap commit waits, boundTransientTransactionErrorretries with jittered exponential backoff, and alert ifWiredTigerHS.wtbytes exceed 2 GB. KeepmaxTransactionLockRequestTimeoutMillisat its5ms default so transactions fail fast instead of piling up behind DDL exclusive locks. On sharded clusters, also alert whendb.serverStatus().transactions.currentPreparedstays non-zero for more than a few seconds, as an orphaned 2PC coordinator can leave participant document locks pinned until the coordinator recovers.
In Practice
Documented MongoDB and WiredTiger behaviors explain why transaction scope and schema locality govern production stability:
- Snapshot Pinning in
WiredTigerHS.wt: Per MongoDB’s transaction production considerations, open transactions prevent WiredTiger from advancing the oldest active timestamp, forcingWiredTigerHS.wtto retain every intermediate document version created by concurrent writers. Short micro-transactions release snapshots in milliseconds, whereas holding a session open across an external RPC spills gigabytes of history store pages to EBS and triggers dirty-cache eviction stalls once dirty pages approach 20% of WiredTiger cache. - 2PC Lock Duration on Sharded Clusters: Per MongoDB’s sharded transaction architecture, multi-shard transactions require both a
prepareTransactionmajority-oplog round-trip and acommitTransactionround-trip across shards while holding document locks. Co-locating related entities under a shared shard key converts cross-shard 2PC into single-shard commits, cutting lock hold time andWriteConflictprobability. - MongoDB 7.0+ and 8.0 Transaction Improvements: MongoDB 7.0+ improved WiredTiger History Store eviction behavior, and MongoDB 8.0 converted internal
config.transactionsmetadata to a clustered collection alongside general write and replication throughput optimizations—reducing baseline transaction overhead, though long open snapshots and hot-document contention still trigger the same MVCC andWriteConflictlimits. - Primary-Only Routing and the 120-Second Driver Retry Window: Every operation inside a multi-document transaction must use
readPreference: "primary"; routing a transaction to a secondary fails immediately because snapshot coordination and write-conflict detection occur on the primary. In addition, MongoDB’s officialwithTransaction()helper retriesTransientTransactionErrorandUnknownTransactionCommitResultfor up to 120 seconds by default. Under a hot-documentWriteConflictstorm, leaving that 120-second retry loop uncapped stalls application worker threads for minutes per request—which is why production services should wrapwithTransaction()with explicitmaxCommitTimeMS, bounded retry counts, or a circuit breaker.
Where It Breaks
| Operational Action | Physical Failure Mechanism | Architectural Consequence | Safe Mitigation Protocol |
|---|---|---|---|
| External RPCs Inside Session | Network wait holds snapshot open for seconds. | Pins WiredTigerHS.wt, stalls eviction, hits 60s abort. | Run all HTTP/RPC calls before startTransaction(). |
| Hot Monolithic Counter Docs | Concurrent txns update one shared document. | Optimistic WriteConflict retry storms exhaust CPU. | Shard hot counters or use single-doc $inc outside txns. |
| Long Txns During Balancer | Multi-shard txns hold locks during chunk moves. | Blocks chunk migrations and raises mongos latency. | Co-locate data on 1 shard and schedule batches off-peak. |
| Massive 50,000-Doc Batches | Uncommitted writes fill WiredTiger cache. | Aborts with TransactionTooLargeForCache or 60s timeout. | Chunk bulk updates into <= 500 doc batches. |
| Orphaned 2PC Prepared Locks | Coordinator partitioned after prepareTransaction. | Participant docs stay locked until coordinator recovers. | Set maxCommitTimeMS and alert transactions.currentPrepared. |
WiredTigerHS.wt Disk Bloat | Long snapshots spill history store pages to EBS. | Consumes EBS IOPS and risks disk exhaustion. | Alert when bytes currently in the history store > 2 GB. |
| Infinite Driver Retry Loops | Unbounded retries on TransientTransactionError. | Exhausts maxIncomingConnections on primary. | Cap retries with jittered backoff and circuit breakers. |
| DDL During Active Txns | createIndex or collMod requests exclusive lock. | Queues behind open txns and stalls incoming reads. | Restrict DDL to maintenance windows with short txns. |
Key Takeaways
- Single-document writes are already ACID: Co-locating bounded state in one document eliminates MVCC snapshot pinning,
WriteConflictstorms, and 2PC overhead. - Never make network calls inside a transaction: Any external wait pins
WiredTigerHS.wtfor the entire cluster and risks hitting the 60-secondtransactionLifetimeLimitSecondsabort. - Co-locate sharded data to avoid 2PC: Cross-shard transactions hold document locks across
prepareTransactionandcommitTransactionround-trips, multiplyingWriteConflictrates. - Bound every multi-document transaction: Keep batches small (
<= 500docs), setmaxCommitTimeMS, and capTransientTransactionErrorretries with exponential backoff.
What to Do Next
- Problem: Production clusters suffer
WriteConflictaborts,WiredTigerHS.wtgrowth, or cache eviction stalls from overused or long-running transactions. - Solution: Prioritize single-document atomicity, move all external RPCs outside
startTransaction(), and co-locate sharded transactional entities. - Proof: Inspect
db.serverStatus().transactions(totalAborted / totalStarted),wiredTiger["history-store"], andcurrentOptimeInactiveMicrosunder peak load. - Action: Audit your top three transactional services this week for external calls inside
withTransaction(), enforcemaxCommitTimeMS, and add an alert onWiredTigerHS.wtexceeding 2 GB.