Back to journal

    Developer journal

    MongoDB Transactions Explained: ACID Operations and When to Use Them

    Understand MongoDB transactions, ACID guarantees, multi-document atomicity, and how to implement reliable transactions using Node.js and Mongoose with practical production examples.

    20 min read45 sections
    MongoDB Transactions Explained: ACID Operations and When to Use Them article cover
    In this article45 sectionsBrowse sections
    20 min read · 3,884 words

    MongoDB Transactions Explained: ACID Operations and When to Use Them

    When building a backend application, some operations involve changing multiple database documents.

    Consider a banking application where a user transfers money to another account. The application needs to:

    1. Deduct money from the sender's account.
    2. Add money to the recipient's account.
    3. Record the transaction.

    What happens if the sender's balance is updated successfully, but the server crashes before updating the recipient's balance?

    The database could end up with an inconsistent state: money has been deducted, but the recipient hasn't received it.

    This is where database transactions become important.

    MongoDB supports multi-document transactions that allow multiple database operations to succeed or fail as a single logical unit.

    In this guide, we'll understand MongoDB transactions, explore the ACID properties, implement transactions using Node.js and Mongoose, and discuss when they are appropriate for production applications.

    1. What Are MongoDB Transactions?

    A transaction is a group of database operations that are executed together.

    Instead of treating every operation independently, a transaction ensures that all participating operations either commit successfully or are rolled back.

    For example, consider transferring ₹1,000 between two bank accounts.

    Without a transaction:

    await Account.updateOne(
      { _id: senderId },
      { $inc: { balance: -1000 } }
    );
    
    await Account.updateOne(
      { _id: receiverId },
      { $inc: { balance: 1000 } }
    );
    
    await Transfer.create({
      sender: senderId,
      receiver: receiverId,
      amount: 1000
    });
    

    If the second operation fails, the first operation has already modified the database.

    A transaction solves this problem by grouping all three operations.

    await session.withTransaction(async () => {
      // Deduct money from sender
      // Add money to receiver
      // Record the transfer
    });
    

    If an operation fails and the error is propagated, the transaction is aborted and its database changes are rolled back.

    If every operation succeeds, the transaction commits.

    How a transaction works

    Start Transaction
           |
           v
    Execute Operation 1
           |
           v
    Execute Operation 2
           |
           v
    Execute Operation 3
           |
           v
    All Operations Successful?
           |
       +---+---+
       |       |
      Yes      No
       |       |
       v       v
     Commit   Abort
       |       |
       v       v
     Save     Roll Back
     Changes  Changes
    

    MongoDB supports transactions across multiple documents, collections, databases, and shards.

    However, transactions aren't necessary for every database operation. Understanding when to use them is just as important as knowing how to implement them.

    2. Understanding ACID Properties

    MongoDB transactions follow the ACID principles, subject to the transaction's configured read and write concerns.

    ACID represents:

    • Atomicity
    • Consistency
    • Isolation
    • Durability

    Let's understand each property.

    2.1 Atomicity

    Atomicity means that a transaction is treated as one logical unit.

    Either all its database changes are committed, or none of them are.

    Consider a money transfer:

    OperationResult
    Deduct from senderSuccessful
    Add to receiverFailed
    Record transferNot committed

    Because the transaction failed, the sender's deduction is also rolled back.

    The database doesn't leave behind a partially completed transfer.

    2.2 Consistency

    Consistency means that a transaction must preserve the application's required data invariants.

    For example, a banking application might enforce these rules:

    • An account balance cannot become negative.
    • A transfer must have a positive amount.
    • Both accounts must exist.
    • A completed transfer must have corresponding account updates.

    MongoDB transactions provide atomic execution, but developers are responsible for defining and enforcing application-level business rules.

    For example, the following update prevents an account from being debited below zero:

    await Account.updateOne(
      {
        _id: senderId,
        balance: { $gte: amount }
      },
      {
        $inc: {
          balance: -amount
        }
      },
      { session }
    );
    

    If the account doesn't have sufficient funds, the update won't match a document.

    The application must detect that result and abort the transaction.

    2.3 Isolation

    Isolation means that uncommitted changes inside a transaction aren't visible to ordinary operations outside that transaction.

    For example, while a transaction is transferring money between accounts, another database operation shouldn't observe the uncommitted intermediate changes as though the transfer had completed.

    MongoDB transactions use snapshot-based behavior depending on their read concern and deployment configuration.

    For applications requiring a consistent snapshot across a sharded cluster, the snapshot read concern is particularly important.

    Isolation doesn't mean that every transaction can execute without conflicts. Concurrent writes can still produce write conflicts, which applications must handle appropriately.

    2.4 Durability

    Durability means that committed changes are retained according to the configured write concern and deployment guarantees.

    For example, using writeConcern: { w: "majority" } requests acknowledgement after the write has been applied to a majority of voting members.

    The durability guarantees depend on the deployment, journaling configuration, and selected write concern.

    For important operations such as financial transactions, choosing appropriate write concern settings is essential.

    3. MongoDB Single-Document Atomicity vs Multi-Document Transactions

    One important MongoDB concept is that a write operation affecting a single document is already atomic.

    You don't need to create an explicit transaction for every update.

    Consider this user document:

    {
      _id: ObjectId("65f123456789abcdef123456"),
      name: "Robin",
      balance: 5000,
      status: "active"
    }
    

    You can update multiple fields in the same document atomically:

    await User.updateOne(
      { _id: userId },
      {
        $inc: { balance: -500 },
        $set: { status: "active" }
      }
    );
    

    Both modifications are part of one atomic document update.

    However, consider an operation that updates multiple documents:

    await User.updateOne(
      { _id: senderId },
      { $inc: { balance: -500 } }
    );
    
    await User.updateOne(
      { _id: receiverId },
      { $inc: { balance: 500 } }
    );
    

    These are separate atomic operations. The entire sequence isn't atomic.

    A transaction is necessary when the application requires all those changes to succeed or fail together.

    When single-document atomicity is enough

    Use a normal atomic update when:

    • All required changes belong to one document.
    • The application doesn't need multiple documents to change together.
    • A conditional update can enforce the required business rules.

    When a transaction is needed

    Consider a transaction when:

    • Multiple documents must be updated together.
    • Multiple collections must remain consistent.
    • A business operation must not be partially completed.
    • Multiple related database writes must commit or roll back together.

    4. MongoDB Transaction Requirements

    Before implementing transactions, understand an important deployment requirement.

    MongoDB transactions aren't supported on standalone MongoDB deployments.

    Multi-document transactions require a replica set or a sharded cluster.

    DeploymentMulti-document transactions
    Standalone MongoDBNot supported
    Replica setSupported
    Sharded clusterSupported

    This matters during local development.

    If you're running MongoDB through a simple standalone installation, transaction code may fail even when the application logic is correct.

    Configure a local replica set

    For a local development environment, you can configure a single-node replica set.

    Start MongoDB with a replica set name:

    mongod --replSet rs0 --dbpath ./data/db
    

    Connect using mongosh:

    mongosh
    

    Initialize the replica set:

    rs.initiate({
      _id: "rs0",
      members: [
        {
          _id: 0,
          host: "localhost:27017"
        }
      ]
    });
    

    Verify its status:

    rs.status();
    

    Your MongoDB connection string can then include the replica set name:

    MONGODB_URI=mongodb://localhost:27017/myapp?replicaSet=rs0
    

    A single-node replica set is useful for local development and testing transaction functionality. It does not provide the redundancy or fault tolerance of a production multi-member replica set.

    5. Implementing MongoDB Transactions Using Node.js and Mongoose

    Now let's implement a practical transaction.

    We'll use a banking example where one user transfers money to another.

    The operation needs to:

    1. Validate the sender's account.
    2. Deduct money from the sender.
    3. Credit the receiver.
    4. Create a transfer record.
    5. Commit all changes together.

    If any database operation fails, the transaction should roll back.

    Step 1: Create the Account model

    import mongoose from "mongoose";
    
    const accountSchema = new mongoose.Schema(
      {
        owner: {
          type: mongoose.Schema.Types.ObjectId,
          ref: "User",
          required: true
        },
    
        balance: {
          type: Number,
          required: true,
          min: 0
        },
    
        currency: {
          type: String,
          required: true,
          default: "INR"
        }
      },
      {
        timestamps: true
      }
    );
    
    export default mongoose.model("Account", accountSchema);
    

    For a financial system, store monetary amounts using integer minor units where practical. For example, ₹100.50 can be represented as 10050 paise. This avoids common floating-point precision problems.

    Step 2: Create the Transfer model

    import mongoose from "mongoose";
    
    const transferSchema = new mongoose.Schema(
      {
        sender: {
          type: mongoose.Schema.Types.ObjectId,
          ref: "Account",
          required: true
        },
    
        receiver: {
          type: mongoose.Schema.Types.ObjectId,
          ref: "Account",
          required: true
        },
    
        amount: {
          type: Number,
          required: true,
          min: 1
        },
    
        currency: {
          type: String,
          required: true
        },
    
        status: {
          type: String,
          enum: ["completed"],
          default: "completed"
        }
      },
      {
        timestamps: true
      }
    );
    
    export default mongoose.model("Transfer", transferSchema);
    

    Step 3: Connect to MongoDB

    import mongoose from "mongoose";
    
    export async function connectDatabase() {
      try {
        await mongoose.connect(process.env.MONGODB_URI);
    
        console.log("MongoDB connected successfully");
      } catch (error) {
        console.error("MongoDB connection failed:", error);
        process.exit(1);
      }
    }
    

    Make sure the connection string points to a replica set or supported sharded deployment.

    Step 4: Implement the transaction

    Mongoose provides transaction support through MongoDB sessions.

    Here's a complete transfer function using session.withTransaction():

    import mongoose from "mongoose";
    
    import Account from "../models/Account.js";
    import Transfer from "../models/Transfer.js";
    
    export async function transferMoney({
      senderId,
      receiverId,
      amount
    }) {
      if (!Number.isSafeInteger(amount) || amount <= 0) {
        throw new Error("Invalid transfer amount");
      }
    
      if (senderId.toString() === receiverId.toString()) {
        throw new Error("Cannot transfer to the same account");
      }
    
      const session = await mongoose.startSession();
    
      try {
        await session.withTransaction(
          async () => {
            // 1. Deduct money from the sender.
            const sender = await Account.findOneAndUpdate(
              {
                _id: senderId,
                balance: { $gte: amount }
              },
              {
                $inc: { balance: -amount }
              },
              {
                new: true,
                session
              }
            );
    
            if (!sender) {
              throw new Error(
                "Sender account not found or insufficient balance"
              );
            }
    
            // 2. Credit the receiver.
            const receiver = await Account.findByIdAndUpdate(
              receiverId,
              {
                $inc: { balance: amount }
              },
              {
                new: true,
                session
              }
            );
    
            if (!receiver) {
              throw new Error("Receiver account not found");
            }
    
            // 3. Verify that both accounts use the same currency.
            if (sender.currency !== receiver.currency) {
              throw new Error("Account currency mismatch");
            }
    
            // 4. Record the transfer.
            await Transfer.create(
              [
                {
                  sender: sender._id,
                  receiver: receiver._id,
                  amount,
                  currency: sender.currency,
                  status: "completed"
                }
              ],
              { session }
            );
          },
          {
            readPreference: "primary",
            readConcern: { level: "snapshot" },
            writeConcern: { w: "majority" }
          }
        );
    
        return {
          success: true,
          message: "Transfer completed successfully"
        };
      } finally {
        await session.endSession();
      }
    }
    

    Understanding the implementation

    There are a few important details in this example.

    1. Start a session

    const session = await mongoose.startSession();
    

    A session provides the context needed to execute transaction operations together.

    2. Start and manage the transaction

    await session.withTransaction(async () => {
      // Database operations
    });
    

    The helper manages transaction commit, abort, and supported retries for transient transaction errors.

    3. Pass the session to every database operation

    {
      session
    }
    

    This is extremely important.

    Every database operation that must participate in the transaction needs to use the same session.

    If an operation is accidentally executed without the session, it won't be part of that transaction.

    4. Throw an error when an operation fails

    if (!sender) {
      throw new Error("Insufficient balance");
    }
    

    Throwing the error causes the transaction callback to fail, allowing the transaction helper to abort the transaction.

    5. End the session

    await session.endSession();
    

    Always release the session when the operation finishes, whether it succeeds or fails.

    Step 5: Create an Express route

    import express from "express";
    import { transferMoney } from "../services/transferService.js";
    
    const router = express.Router();
    
    router.post("/transfer", async (req, res, next) => {
      try {
        const result = await transferMoney({
          senderId: req.body.senderId,
          receiverId: req.body.receiverId,
          amount: req.body.amount
        });
    
        res.status(200).json(result);
      } catch (error) {
        next(error);
      }
    });
    
    export default router;
    

    In a real application, obtain the sender's account through the authenticated user's identity rather than trusting a client-provided sender ID. Also validate the request, enforce authorization, and implement transfer idempotency to prevent duplicate processing.

    6. Understanding the Two Transaction APIs in Mongoose

    Mongoose supports two useful approaches for managing transactions.

    Option A: session.withTransaction()

    This method comes from the MongoDB driver and is available through the Mongoose session.

    const session = await mongoose.startSession();
    
    try {
      await session.withTransaction(async () => {
        await User.updateOne(
          { _id: userId },
          { $set: { status: "active" } },
          { session }
        );
      });
    } finally {
      await session.endSession();
    }
    

    It handles:

    • Transaction execution.
    • Commit on success.
    • Abort when the callback fails.
    • Retries for supported transient transaction errors.

    Option B: mongoose.connection.transaction()

    Mongoose also provides a transaction wrapper:

    await mongoose.connection.transaction(
      async (session) => {
        await User.updateOne(
          { _id: userId },
          { $set: { status: "active" } },
          { session }
        );
      }
    );
    

    This wraps the driver's transaction functionality and integrates with Mongoose's document change tracking.

    For example, when a Mongoose document is modified and saved inside a transaction that later aborts, this wrapper helps restore Mongoose's internal change-tracking state.

    Both approaches are useful. Choose one that fits your application's implementation style and Mongoose version.

    7. Manual Transaction Management

    You can also manage transactions manually.

    This approach gives you explicit control over starting, committing, and aborting transactions.

    const session = await mongoose.startSession();
    
    try {
      session.startTransaction();
    
      await User.updateOne(
        { _id: senderId },
        { $inc: { balance: -500 } },
        { session }
      );
    
      await User.updateOne(
        { _id: receiverId },
        { $inc: { balance: 500 } },
        { session }
      );
    
      await session.commitTransaction();
    
      console.log("Transaction committed");
    } catch (error) {
      await session.abortTransaction();
    
      console.error("Transaction aborted:", error);
    
      throw error;
    } finally {
      await session.endSession();
    }
    

    The manual approach requires you to manage transaction lifecycle and retry behavior correctly.

    For most application-level operations, withTransaction() or mongoose.connection.transaction() is a better starting point because they handle important transaction-management behavior for you.

    8. Common MongoDB Transaction Mistakes

    Transactions introduce additional complexity. Avoid these common mistakes when implementing them.

    1. Forgetting to pass the session

    Consider this example:

    await session.withTransaction(async () => {
      await User.updateOne(
        { _id: userId },
        { $set: { status: "active" } },
        { session }
      );
    
      // This operation is outside the transaction.
      await Order.updateOne(
        { _id: orderId },
        { $set: { status: "completed" } }
      );
    });
    

    The second update doesn't participate in the transaction because it doesn't receive the session.

    Solution: Pass the same session to every operation that must be atomic with the others.

    2. Using Promise.all() inside a transaction

    Avoid parallel operations inside a transaction:

    await session.withTransaction(async () => {
      await Promise.all([
        User.updateOne(
          { _id: userId },
          { $set: { status: "active" } },
          { session }
        ),
    
        Order.updateOne(
          { _id: orderId },
          { $set: { status: "completed" } },
          { session }
        )
      ]);
    });
    

    Mongoose documents parallel operations inside a transaction as unsupported behavior.

    Solution: Execute transaction operations sequentially:

    await session.withTransaction(async () => {
      await User.updateOne(
        { _id: userId },
        { $set: { status: "active" } },
        { session }
      );
    
      await Order.updateOne(
        { _id: orderId },
        { $set: { status: "completed" } },
        { session }
      );
    });
    

    3. Forgetting to end the session

    Always release the session after transaction processing.

    finally {
      await session.endSession();
    }
    

    This ensures that the session is cleaned up even when an operation fails.

    4. Performing unnecessary operations inside transactions

    Transactions have additional overhead.

    Avoid including unrelated queries or operations that don't need to participate in the same atomic unit.

    Solution: Keep transactions focused on the database changes that must succeed or fail together.

    5. Assuming transactions automatically prevent business logic errors

    Transactions guarantee atomic execution, but they don't automatically validate business rules.

    For example, a transaction doesn't automatically prevent an account from having a negative balance.

    Solution: Use conditional updates, schema validation, unique indexes, and appropriate application-level validation.

    6. Making external API calls inside transactions

    Consider this implementation:

    await session.withTransaction(async () => {
      await Order.create(
        [{ status: "completed" }],
        { session }
      );
    
      await paymentProvider.capturePayment();
    });
    

    This is dangerous.

    A transaction callback can be retried after certain errors. An external payment request isn't rolled back when MongoDB aborts its transaction.

    The payment could be captured more than once or succeed even though the database changes were rolled back.

    Solution: Keep external side effects outside the transaction. Use idempotency keys and a reliable workflow such as the transactional outbox pattern when coordinating database changes with external services.

    9. Transaction Performance Considerations

    Transactions are powerful, but they aren't free.

    Compared with individual single-document operations, multi-document transactions generally introduce additional overhead.

    Common performance considerations include:

    • Transaction duration.
    • Number of documents modified.
    • Number of collections involved.
    • Write conflicts.
    • Network latency.
    • Sharded cluster communication.
    • Locking and resource contention.
    • Retry behavior.

    Keep transactions short

    Avoid performing unnecessary calculations, waiting for user input, or making external API calls while a transaction is active.

    The longer a transaction remains open, the greater the chance of resource contention and operational problems.

    Avoid unnecessary multi-document writes

    If a business operation can be represented as one atomic document update, consider using that instead of a multi-document transaction.

    Use appropriate indexes

    Queries inside transactions still need efficient query execution.

    For example:

    db.accounts.createIndex({ owner: 1 });
    

    An appropriate index can reduce the amount of work required to locate documents.

    For more on index selection and query performance, read MongoDB Indexing Explained: How Indexes Improve Query Performance.

    Be careful with sharded transactions

    Transactions that span multiple shards generally have higher performance costs than transactions targeting a single shard.

    Design your data distribution and access patterns carefully before introducing cross-shard transactional workflows.

    10. Handling Transaction Retries and Idempotency

    One important production consideration is retry behavior.

    MongoDB transactions can encounter transient errors, including write conflicts.

    The withTransaction() helper handles supported retry scenarios, but your application must still be designed to handle repeated execution safely.

    Consider this example:

    await session.withTransaction(async () => {
      await Order.create(
        [{ status: "processing" }],
        { session }
      );
    });
    

    The transaction callback may execute again when the driver retries a transaction.

    Database writes inside the transaction are handled through the transaction mechanism, but operations outside MongoDB are different.

    For example, this should not be placed inside a retryable transaction callback:

    await session.withTransaction(async () => {
      await sendEmail();
    });
    

    An email might be sent more than once if the callback is retried.

    Use idempotency keys for important operations

    An idempotency key allows an application to identify repeated requests representing the same logical operation.

    For example, a payment request can include a unique key:

    {
      idempotencyKey: "payment_abc123",
      amount: 1000,
      currency: "INR"
    }
    

    Create a unique index:

    db.payments.createIndex(
      { idempotencyKey: 1 },
      { unique: true }
    );
    

    The application can then prevent duplicate payment records for the same key.

    A complete idempotency implementation should also define how concurrent requests are handled, how previous results are returned, and how failed or pending operations are represented.

    For workflows involving MongoDB and external services, consider the transactional outbox pattern:

    1. Write the business change and an outbox event in the same MongoDB transaction.
    2. A separate worker reads pending outbox events.
    3. The worker sends the event to the external service.
    4. The event is marked as processed.
    5. Retries use an idempotent event identifier.

    This avoids pretending that a MongoDB transaction can roll back an external service operation.

    11. When Should You Use MongoDB Transactions?

    Not every application needs multi-document transactions.

    Use them when multiple database changes must remain consistent as one business operation.

    Here are some practical examples.

    Use caseTransaction needed?
    Updating multiple fields in one documentUsually no
    Transferring money between accountsYes
    Creating an order and reducing inventoryOften yes
    Updating a user's profile documentUsually no
    Creating a booking and reserving related resourcesOften yes
    Updating multiple independent analytics recordsDepends on consistency requirements
    Creating a post with embedded metadataUsually no
    Updating several documents that must remain synchronizedYes

    Example: E-commerce order processing

    Consider an e-commerce application where an order requires:

    1. Creating an order document.
    2. Reducing available product inventory.
    3. Creating an inventory movement record.

    If these database changes must succeed together, a transaction can help maintain consistency.

    However, external payment processing, email delivery, and shipping-provider requests should be handled through a separate reliable workflow.

    Example: Booking system

    Consider a booking application where multiple users may attempt to reserve the same resource.

    A transaction alone isn't a complete solution to concurrency problems.

    The application should also use conditional updates or unique constraints to prevent conflicting reservations.

    Transactions can then ensure that related database changes are committed together.

    12. When Should You Avoid Transactions?

    Transactions aren't always the best solution.

    Consider avoiding them when:

    • All required changes fit inside a single document.
    • The operations don't require all-or-nothing behavior.
    • Data can be safely updated independently.
    • A better schema design can eliminate the need for multiple writes.
    • The transaction would contain unnecessary long-running operations.
    • A distributed workflow is better handled through an event-driven architecture.

    MongoDB's document model is designed to support denormalization and embedding.

    A good schema design can often eliminate the need for multi-document transactions.

    For more on choosing the right document structure, read MongoDB Schema Design: Embedding vs Referencing — When to Use Each.

    13. Production Checklist

    Before deploying MongoDB transactions in a production application, review the following:

    • MongoDB runs as a replica set or supported sharded cluster.
    • Every participating database operation receives the same session.
    • Business rules are validated before committing.
    • Conditional updates prevent invalid concurrent changes.
    • Transactions are kept short.
    • No unsupported parallel operations are used inside transactions.
    • Sessions are properly released.
    • Retry behavior is considered.
    • External API calls are kept outside transaction callbacks.
    • Idempotency is implemented for operations that may be retried.
    • Appropriate indexes exist for transaction queries.
    • Read and write concern settings match application requirements.
    • Failure scenarios are tested, including concurrent requests and write conflicts.

    Conclusion

    MongoDB transactions provide a reliable way to execute multiple database operations as one logical unit.

    By understanding ACID properties and using sessions correctly, you can build safer operations for banking applications, e-commerce platforms, booking systems, and other applications that require multi-document consistency.

    However, transactions shouldn't replace good schema design.

    MongoDB already provides atomicity for individual document operations, and embedding related information can often eliminate the need for multi-document transactions.

    The best approach is to design your data around application access patterns, use single-document atomic operations wherever possible, and introduce transactions only when multiple database changes genuinely need all-or-nothing behavior.

    Remember: Transactions help protect database consistency, but good schema design, business validation, conditional updates, and idempotent workflows are equally important for production-ready applications.


    Official References

    Enjoyed this read?

    Keep the conversation going.

    Follow along for more practical development notes, or reach out to talk about a project.

    Keep exploring

    Related articles

    More guides connected by the topics in this article.

    Browse the journal