Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 37 ยท Testing and Patterns

Transactions and Sessions in Mongoose

Use multi-document ACID transactions in Mongoose - sessions, withTransaction, passing the session to operations, replica set requirements, retries, and a runnable commit/rollback stand-in.

Some operations must happen all together or not at all: moving money between two accounts, placing an order while reducing stock, creating a user and their first workspace. If the app crashes between the two writes, you end with money that vanished or an order without a stock decrement. A transaction groups several operations into one atomic unit: either everything commits, or everything is rolled back.

MongoDB has always made a single document update atomic. Since version 4.0 it also supports multi-document ACID transactions, which Mongoose exposes through sessions.

First, do you need one?

Transactions cost performance and complexity. Often you can avoid them:

  • If the data that must change together lives in one document (embedding, see Embedding or referencing), a single updateOne is already atomic.
  • Atomic operators ($inc, $push, conditional updates such as updateOne({ _id, stock: { $gte: qty } }, { $inc: { stock: -qty } })) handle many "check then change" cases without a transaction.

Use a transaction when two or more documents (or collections) must change together and no single-document design fits.

Requirements

Transactions need a replica set or a sharded cluster, not a standalone mongod. Atlas clusters qualify; locally start mongod --replSet rs0 and run rs.initiate() once, or use the single-node replica set that many Docker images and mongodb-memory-server's MongoMemoryReplSet provide.

Using withTransaction

session.withTransaction(fn) starts a transaction, runs your function, commits, and retries automatically on transient errors (such as a write conflict) and on unknown commit results. The callback must be safe to run more than once.

JavaScript
import mongoose from 'mongoose';

async function transfer(fromId, toId, amount) {
  const session = await mongoose.startSession();
  try {
    await session.withTransaction(async () => {
      const from = await Account.findOneAndUpdate(
        { _id: fromId, balance: { $gte: amount } },
        { $inc: { balance: -amount } },
        { session, new: true },
      );
      if (!from) throw new Error('Insufficient funds');

      await Account.updateOne({ _id: toId }, { $inc: { balance: amount } }, { session });
      await Transfer.create([{ fromId, toId, amount }], { session });
    });
  } finally {
    await session.endSession();
  }
}

The crucial rule: pass { session } to every operation that belongs to the transaction. An operation without it runs outside, and will not roll back. Throwing inside the callback aborts the transaction. Notice create takes an array when you pass options: Model.create([doc], { session }).

Mongoose also offers connection.transaction(fn), which wraps the same flow and resets document state on abort:

JavaScript
await mongoose.connection.transaction(async (session) => {
  const order = new Order({ items });
  await order.save({ session });
  await Product.updateOne({ _id: itemId }, { $inc: { stock: -1 } }, { session });
});

Documents loaded in a session remember it: doc.$session() returns it, and doc.save() then uses it automatically.

A runnable commit and rollback stand-in

This stand-in keeps account balances in a Map. withTransaction snapshots the state, runs the callback on a working copy, and either commits (copy replaces state) or rolls back. It also retries once on a simulated transient error, the way the real driver helper does.

Node.js withTransaction: commit, rollback, retry (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Note that the total never changes: that is the "atomic" guarantee. If the callback has side effects outside the database (sending an email, calling an API), a retry repeats them, so keep the callback database-only and do side effects after the transaction commits.

What ACID means here

flowchart LR
  A["Atomic<br/>all or nothing"] --- C["Consistent<br/>rules still hold"] --- I["Isolated<br/>others see old or new, not half"] --- D["Durable<br/>survives a crash once committed"]

MongoDB transactions provide snapshot isolation inside the transaction.

Inside a transaction you read a consistent snapshot, writes are invisible to other clients until commit, and conflicting writes cause one transaction to abort with a TransientTransactionError (which withTransaction retries).

Limits and pitfalls

  • Keep them short. Default maximum lifetime is 60 seconds; long transactions hold resources and increase conflicts.
  • Create collections first. In older servers you could not create collections inside a transaction; call Model.createCollection() and Model.init() at startup.
  • Pass the session everywhere: queries, updates, save(), create(), deleteOne, aggregate().session(session). Forgetting one is the most common bug.
  • Do not share a session across concurrent operations in one transaction; run them sequentially, or at least do not interleave unrelated work.
  • Avoid hot documents. If every transaction updates the same counter document, they conflict and retry.
  • Plain find inside a transaction also needs { session } to read the snapshot and see your own uncommitted writes.

Without transactions: patterns that are enough

When a transaction is unavailable or too heavy:

  1. Conditional atomic update (above) to guard inventory.
  2. Two-phase / saga: record intent in a document with a status (pending, done, failed), perform steps, and have a job repair stuck states. Safe for cross-service flows.
  3. Idempotency keys: a unique index on (operationId) makes retries safe, because a repeated insert fails with 11000 instead of double-charging.
Node.js Idempotency key makes retries safe (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must every operation inside a Mongoose transaction include?

    Operations without { session } run outside the transaction and are not rolled back.
  2. 2. What does a transaction require from the MongoDB deployment?

    Multi-document transactions need a replica set (a single-node replica set is enough for development).
  3. 3. Why should the withTransaction callback avoid sending emails?

    withTransaction retries transient failures by re-running the callback, repeating any external side effects.
  4. 4. When is a transaction usually unnecessary?

    Single-document operations are atomic already; embedding or atomic operators can avoid transactions.

Summary

  • Transactions make multi-document changes atomic; they need a replica set.
  • Use session.withTransaction() or connection.transaction(); they retry transient errors.
  • Pass { session } to every operation and keep callbacks short and side-effect free.
  • Prefer single-document designs and atomic operators when they are enough.
  • Idempotency keys and status-based sagas help where transactions cannot.

Next: Discriminators and inheritance