Working with Transactions
1. Starting Transaction
| API | Form |
|---|---|
| Core | session.startTransaction(opts) |
| Callback | session.withTransaction(async () => {...}) (auto-retry) |
2. Committing Transaction
| Method | Detail |
|---|---|
| commitTransaction() | Atomic apply across all docs |
| Retryable | Drivers auto-retry on transient errors |
3. Aborting Transaction
| Method | Detail |
|---|---|
| abortTransaction() | Discard all uncommitted ops |
| Implicit abort | On unhandled exception in withTransaction |
4. Using Transaction Options
| Option | Default |
|---|---|
| readConcern | snapshot |
| writeConcern | majority |
| readPreference | primary |
| maxCommitTimeMS | Override max commit duration |
5. Handling Transaction Errors
| Label | Meaning |
|---|---|
| TransientTransactionError | Retry entire transaction |
| UnknownTransactionCommitResult | Retry commit |
| WriteConflict | Most common transient |
6. Implementing Retry Logic
| Pattern | Detail |
|---|---|
| withTransaction | Built-in retry with backoff (recommended) |
| Manual | Check errorLabels for TransientTransactionError |
| Max time | Server kills txn after 60s (txnLifetimeLimitSeconds) |
await session.withTransaction(async () => {
await db.accounts.updateOne({_id: a}, {$inc:{balance:-100}}, {session});
await db.accounts.updateOne({_id: b}, {$inc:{balance: 100}}, {session});
}, { readConcern: { level: "snapshot" }, writeConcern: { w: "majority" } });
7. Using Multi-Document Transactions
| Scope | Supported |
|---|---|
| Replica set | Since 4.0 |
| Sharded cluster | Since 4.2 |
| Multiple collections | Yes |
| Cross-DB | Yes |
8. Understanding Transaction Limitations
| Limitation | Detail |
|---|---|
| 60s lifetime | txnLifetimeLimitSeconds |
| 16MB oplog entry | Limits total txn write size |
| No DDL Relaxed in 4.4+ | Some collection creation in txn supported |
| No $out / $merge | Cannot output stages |
9. Setting Transaction Timeout
| Setting | Default | Scope |
|---|---|---|
| transactionLifetimeLimitSeconds | 60s | Server-wide |
| maxCommitTimeMS | None | Per txn |
10. Using Callback API for Transactions
| Benefit | Detail |
|---|---|
| Auto-retry | Transient errors handled |
| Auto-commit | Callback success → commit; exception → abort |
| Recommended | Use over manual start/commit |
11. Understanding Transaction Performance
| Aspect | Impact |
|---|---|
| Locks | Document-level; conflicts → WriteConflict |
| Snapshot | Holds storage snapshot for txn duration |
| Cost | Avoid for high-throughput single-doc updates |
| Tip | Embed related data to avoid needing txn at all |