Reference · Cheat sheet

Multi-document transactions

Lesson 0010 distilled — the escape hatch, snapshot isolation, the cost, and why schema design usually removes the need. Built to print.

From lesson 0010Context: MongoDB 4.2+ (sharded), 4.0+ (replica sets)

The default — single-document atomicity

Any write to a single document is all-or-nothing. No transaction needed. Free and always on.

Good schema design (embedding co-written data) removes most transaction use cases before they arise.

Reaching for a transaction is a signal to re-examine the schema first.

When you actually need one

Referencing was correct for schema reasons, but two writes must be atomic:

• Account transfers — debit + credit on separate documents

• Inventory + order — decrement stock + create order

• Audit consistency — status update + event log entry

Snapshot isolation

Transaction reads from a consistent snapshot taken at its start.

Concurrent writes from other sessions are invisible for the transaction's lifetime.

The transaction's own writes are buffered until commitTransaction().

Abort → all buffered writes vanish atomically.

Write conflicts

Two transactions try to write the same document → the second one encounters a write conflict and must abort and retry.

Optimistic concurrency — no pre-locking. Conflict detected at write time.

MongoDB drivers support automatic retry for transient errors.

The cost

Single-doc writeTransaction
CoordinationNoneTwo-phase commit
Snapshot lifetimeMillisecondsUntil commit/abort (max 60 s)
Write conflictsImpossiblePossible — must retry
MemoryMinimalBuffered until commit

Postgres contrast

Postgres: BEGIN … COMMIT is the primitive — trivial overhead, used constantly, expected by the planner.

MongoDB: single-document write is the primitive — transaction is the escape hatch, with real overhead.

Neither is better. They reflect design priorities: Postgres = normalized + free joins; MongoDB = embedded + free single-doc atomicity. The transaction overhead in each is the cost of crossing the engine's preferred pattern.