Atomicity and MongoDB

Faiz / 2024-02-03

As the world of databases evolves, the debate between SQL and NoSQL continues to gain momentum. One of the key factors that differentiate these two is the concept of atomicity. In this article, we will explore the significance of atomicity in databases, particularly in SQL, and how MongoDB, a popular NoSQL database, challenges the traditional perception by implementing atomicity. We will also take a code walkthrough to understand how atomic transactions can be implemented using MongoDB.

Atomicity in Databases: A Crucial Feature of SQL

SQL databases are known for their adherence to ACID properties, where atomicity plays a vital role. Atomicity refers to the concept of a set of operations being treated as a single indivisible unit, either succeeding entirely or failing entirely. In other words, if one part of a transaction fails, the entire transaction is rolled back, leaving the database in its original state. Consider a banking application where a user transfers funds from one account to another. Assuming enough balance in your account, the process involves 2 major steps: first, the deduction from your account, second the credit to another account. If the process is partially fulfilled i.e one of the steps fail while other succeed, it might lead to an inconsistent DB. 

The transaction must update the balance of both accounts simultaneously, ensuring that either both updates occur successfully or none at all. Atomicity ensures that if there is a failure during this operation, such as insufficient funds, the entire transaction is rolled back, preventing any inconsistencies in the database.

NoSQL and the Perception of Atomicity

NoSQL databases, on the other hand, are often perceived as sacrificing the ACID properties for greater scalability and flexibility. While this perception holds true in many cases, it is essential to understand that not all NoSQL databases handle atomicity in the same way. Many NoSQL databases trade strict atomicity for eventual consistency, where data may be temporarily inconsistent but eventually converges to a consistent state. This approach provides performance benefits for certain use cases, such as high write throughput, but may not be suitable for scenarios that require strong data integrity.

MongoDB: Challenging the Perception

MongoDB, a widely adopted NoSQL database, challenges the perception that NoSQL databases completely disregard atomicity. It introduces the concept of atomicity through features like multi-document transactions, which allow multiple operations to be executed atomically on different documents. By implementing multi-document transactions, MongoDB ensures that operations within a transaction are treated as an atomic unit. If any part of the transaction fails, all changes made within the transaction are rolled back, preventing any partial updates from affecting the overall system integrity.

Implementing Atomic Transactions in MongoDB: A Code Walkthrough

Let's dive into an example to understand how atomic transactions can be implemented using MongoDB. Consider a scenario where a user wants to update the quantity of multiple products in an e-commerce application. We will assume that the quantity must be reduced by 1 for each product.

const session = await db.startSession();        // Start a session
session.startTransaction();                     // Start a transaction
try {
  await Product.updateMany({}, { $inc: { quantity: -1 } });   // Update all products
  await session.commitTransaction();            // Commit the transaction
} catch (error) {
  await session.abortTransaction();             // Rollback the transaction on error
} finally {
  session.endSession();                         // End the session
}

In the code above, we create a session and start a transaction using MongoDB's session API. The updateMany operation reduces the quantity of all products by 1. If any error occurs during this process, the transaction is aborted, and all changes are rolled back. Finally, we end the session, ensuring proper cleanup.

Interesting reads:

1) What are ACID Properties in Database Management Systems?

2) DataStax CEO: Let's clear the air about NoSQL and ACID

3) Key Points from NoSQL Distilled

Hand crafted by Faiz Alam