MongoDB has supported multi-document ACID transactions since 4.0, yet many MEAN apps still do "debit one document, credit another" with two unguarded writes. This tutorial shows how to use transactions correctly with Mongoose 8, Express 5 and Node 24: when you need one, how to write it, how to handle retries, and how to test it.
When you actually need a transaction
MongoDB guarantees atomicity for a single document, including embedded arrays and subdocuments. Before reaching for a transaction, ask whether you can model the data so one write is enough. You need a transaction when an invariant spans several documents or collections, for example:
- Moving credits between two accounts.
- Creating an order and decrementing inventory.
- Creating a user and the workspace they own.
Transactions require a replica set or sharded cluster. Atlas gives you one by default. For local development, run a single-node replica set, otherwise startSession().withTransaction() will fail.
# docker-compose.yml (development only)
services:
mongo:
image: mongo:8
command: ["--replSet", "rs0", "--bind_ip_all"]
ports: ["27017:27017"]
healthcheck:
test: ["CMD", "mongosh", "--quiet", "--eval", "try { rs.status().ok } catch (e) { rs.initiate({_id:'rs0',members:[{_id:0,host:'localhost:27017'}]}).ok }"]
interval: 5s
retries: 10
Connect with mongodb://localhost:27017/app?replicaSet=rs0&directConnection=true.
The transfer example
Two models: an Account with a balance in integer cents, and a Transfer ledger record.
// models/account.ts
import { Schema, model } from 'mongoose';
const accountSchema = new Schema({
owner: { type: String, required: true },
balanceCents: { type: Number, required: true, min: 0 },
});
export const Account = model('Account', accountSchema);
const transferSchema = new Schema({
from: { type: Schema.Types.ObjectId, ref: 'Account', required: true },
to: { type: Schema.Types.ObjectId, ref: 'Account', required: true },
amountCents: { type: Number, required: true, min: 1 },
requestId: { type: String, required: true, unique: true },
}, { timestamps: true });
export const Transfer = model('Transfer', transferSchema);
Use withTransaction, not manual commit
session.withTransaction(fn) automatically retries the callback on TransientTransactionError and retries the commit on UnknownTransactionCommitResult. Hand-rolled startTransaction/commitTransaction code usually misses one of those cases. Mongoose also offers connection.transaction(fn), which wraps the same behaviour and resets document state on retry.
// services/transfer.ts
import mongoose from 'mongoose';
import { Account, Transfer } from '../models/account';
export class InsufficientFunds extends Error {}
export async function transfer(from: string, to: string, amountCents: number, requestId: string) {
return mongoose.connection.transaction(async (session) => {
const debited = await Account.findOneAndUpdate(
{ _id: from, balanceCents: { $gte: amountCents } },
{ $inc: { balanceCents: -amountCents } },
{ session, new: true },
);
if (!debited) throw new InsufficientFunds('Insufficient funds or unknown account');
const credited = await Account.findOneAndUpdate(
{ _id: to },
{ $inc: { balanceCents: amountCents } },
{ session, new: true },
);
if (!credited) throw new Error('Destination account not found');
const [record] = await Transfer.create(
[{ from, to, amountCents, requestId }],
{ session },
);
return record;
});
}
Key points:
- Pass
sessionto every operation. Any query missing it runs outside the transaction, and Mongoose will not warn you. This is the most common transaction bug we see in code reviews. - The callback must be safe to run more than once. Do not send emails, call payment APIs or push to queues inside it. Do those after it returns, or use an outbox collection written in the same transaction.
- Guard in the filter.
balanceCents: { $gte: amountCents }makes the debit conditional, so the check and the write are one atomic operation. - Use an idempotency key. The unique
requestIdmeans a client retry after a timeout hits a duplicate key error rather than moving money twice.
Note that Model.create with a session needs the array form, as shown.
The Express 5 route
Express 5 forwards rejected promises from async handlers to the error middleware, so no wrapper is required.
// routes/transfers.ts
import { Router } from 'express';
import { z } from 'zod';
import { transfer, InsufficientFunds } from '../services/transfer';
const body = z.object({
from: z.string().length(24),
to: z.string().length(24),
amountCents: z.number().int().positive(),
});
export const router = Router();
router.post('/transfers', async (req, res) => {
const requestId = req.get('Idempotency-Key');
if (!requestId) return res.status(400).json({ error: 'Idempotency-Key header required' });
const input = body.parse(req.body);
const record = await transfer(input.from, input.to, input.amountCents, requestId);
res.status(201).json(record);
});
// error middleware
import type { ErrorRequestHandler } from 'express';
import { ZodError } from 'zod';
export const errors: ErrorRequestHandler = (err, _req, res, _next) => {
if (err instanceof ZodError) return res.status(400).json({ error: err.flatten() });
if (err instanceof InsufficientFunds) return res.status(409).json({ error: err.message });
if (err?.code === 11000) return res.status(200).json({ status: 'duplicate request ignored' });
console.error(err);
res.status(500).json({ error: 'Internal error' });
};
Returning 200 for a duplicate key is a simple approach. A stricter version looks up and returns the original Transfer.
Keep transactions short
Transactions have a default transactionLifetimeLimitSeconds of 60, and long ones hold locks and cache pressure on the server. Practical rules:
- Do reads that do not need isolation, validation and external calls before you open the transaction.
- Touch few documents. If you are updating thousands, batch them in separate transactions.
- Create collections and indexes ahead of time. Since MongoDB 4.4 you can create collections inside a transaction, but index builds on existing collections are not allowed.
- Pick a write concern of
majorityand a read concern ofsnapshotwhen you need strict guarantees:connection.transaction(fn, { readConcern: { level: 'snapshot' }, writeConcern: { w: 'majority' } }).
Handle write conflicts
If two transactions modify the same document, one fails with a WriteConflict labelled TransientTransactionError. withTransaction retries it for you, up to a time limit of about 120 seconds. Hot documents, such as a single global counter, will turn that into a queue, so shard counters across several documents if you see conflict storms.
Test it
Test with a real replica set, for example using Testcontainers, rather than mocks. Check the invariant under concurrency:
import { test } from 'node:test';
import assert from 'node:assert/strict';
test('concurrent transfers never overdraw', async () => {
const a = await Account.create({ owner: 'a', balanceCents: 1000 });
const b = await Account.create({ owner: 'b', balanceCents: 0 });
const results = await Promise.allSettled(
Array.from({ length: 20 }, (_, i) => transfer(String(a._id), String(b._id), 100, `req-${i}`)),
);
const ok = results.filter((r) => r.status === 'fulfilled').length;
const [fa, fb] = await Promise.all([Account.findById(a._id), Account.findById(b._id)]);
assert.equal(ok, 10);
assert.equal(fa!.balanceCents, 0);
assert.equal(fb!.balanceCents, 1000);
});
Also test that a failure after the debit (for example a thrown error in the credit step) leaves both balances unchanged.
Checklist
- Can a single-document write solve it? If so, skip the transaction.
- Replica set in dev, test and production.
sessionpassed to every query in the callback.- No side effects inside the callback.
- Idempotency key with a unique index.
- Short transactions, with conflict-prone hot documents avoided.
- Concurrency test in CI.
If your MEAN app has data-integrity bugs you cannot reproduce, or you need a second pair of eyes on a data model before it hardens, StackPilots consultants can review it. Get in touch through our contact page.