Lesson 9 of 9 · 27m
Transactions and the Relational Boundary
Multi-document transactions in MongoDB are real but not free; use them for genuine invariants and know when relational consistency is the better database.
MongoDB supports multi-document ACID transactions, and they are not a myth. The scar tissue is that teams hear this and stop designing documents well. Transactions are the emergency bridge across aggregate boundaries, not the road you drive every request over.
One document is already atomic
A single document write is atomic. That is why modeling matters: if the invariant lives inside one document, no transaction is needed.
db.accounts.updateOne(
{ _id: accountId, balance: { $gte: amount } },
{ $inc: { balance: -amount } }
)Embedding or co-locating related state can encode invariants directly in the document structure. That is faster and simpler than coordinating a transaction across collections.
Use transactions for cross-entity invariants
Transferring money between two accounts is a legitimate case:
const session = client.startSession();
try {
await session.withTransaction(async () => {
const debit = await accounts.updateOne({ _id: from, balance: { $gte: 10000 } }, { $inc: { balance: -10000 } }, { session });
if (debit.modifiedCount !== 1) throw new Error("insufficient funds");
await accounts.updateOne({ _id: to }, { $inc: { balance: 10000 } }, { session });
await ledger.insertOne({ transferId, from, to, amount: 10000, at: new Date() }, { session });
}, { readConcern: { level: "snapshot" }, writeConcern: { w: "majority" } });
} finally {
await session.endSession();
}Drivers and withTransaction retry transient transaction and commit errors, but retry exhaustion or manual transaction control can still leave the commit outcome ambiguous. Idempotency keys and unique constraints are how adults survive ambiguity.
Transactions have real costs
Transactions pin resources, increase write conflict surfaces, and have time limits. Long-running transactions are especially bad: they hold state, interact poorly with cache pressure, and turn ordinary contention into aborts. Keep them short, touch few documents, and avoid application round trips in the middle.
If everything needs a transaction, the aggregate boundaries are wrong or the domain is relational. Do not use transactions to recreate the normalized schema you secretly wanted.
When relational wins
MongoDB is a poor fit when the core problem is many-to-many relational integrity across independently evolving entities:
- highly normalized finance systems with complex joins and ad-hoc relational queries
- inventory allocation across many constraints
- access-control graphs and deep relationship traversal
- reporting models where the question changes weekly
PostgreSQL is boring in the way bridges are boring: it handles relational algebra, constraints, joins, triggers, and transactional consistency as first-class design. MongoDB wins when access-pattern-shaped aggregates, flexible document evolution, horizontal scale, and operational simplicity dominate.
Field notes
- The existence of multi-document transactions does not make cross-collection normalization a good default.
- Keep transaction callbacks small and deterministic; do not perform network calls to other services inside them.
- A unique index is often the cheapest correctness primitive in the entire system.
- Choosing MongoDB versus PostgreSQL is not a personality test. It is a workload statement.
Was this lesson helpful?