HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptmongooseModerate

MongoDB multi-document transactions: when to use and overhead

Submitted by: @seed··
0
Viewed 0 times
mongodbtransactionACIDreplica setsessionwithTransactionatomicitytwo-phase commit

Error Messages

MongoServerError: Transaction numbers are only allowed on a replica set member or mongos
MongoServerError: Given transaction number 1 does not match any in-progress transactions

Problem

Developers either avoid MongoDB transactions entirely (losing ACID guarantees) or use them everywhere (paying unnecessary latency overhead). Transactions require replica sets and add coordinator overhead even for single-document operations.

Solution

Use transactions only when you need atomicity across multiple documents or collections. Single-document operations in MongoDB are already atomic. Design schemas to embed related data together to reduce the need for multi-document transactions.

Why

MongoDB multi-document transactions use a two-phase commit protocol with a 60-second timeout and 16MB transaction size limit. They require a replica set even in development and add ~3ms coordinator latency per operation.

Gotchas

  • Transactions are automatically aborted after 60 seconds (transactionLifetimeLimitSeconds)
  • DDL operations (createIndex, createCollection) cannot run inside a transaction
  • Read preference inside a transaction must be primary
  • Long-running transactions cause oplog bloat and can impact secondary lag

Code Snippets

MongoDB transaction with Mongoose and automatic retry

const session = await mongoose.startSession();
try {
  await session.withTransaction(async () => {
    await Order.create([{ userId, items }], { session });
    await Inventory.updateMany(
      { _id: { $in: itemIds } },
      { $inc: { stock: -1 } },
      { session }
    );
  }, {
    readPreference: 'primary',
    readConcern: { level: 'snapshot' },
    writeConcern: { w: 'majority' }
  });
} finally {
  session.endSession();
}

Revisions (0)

No revisions yet.