This chapter explores how MongoDB achieves ACID properties (Atomicity, Consistency, Isolation, and Durability) within a distributed environment. From the basic principles of ACID transactions to implementing these principles in MongoDB, we’ll cover essential topics for building reliable applications in distributed systems.
const session = client.startSession();
session.startTransaction();
try {
await db.collection("accounts").updateOne({ _id: 1 }, { $inc: { balance: -100 } }, { session });
await db.collection("accounts").updateOne({ _id: 2 }, { $inc: { balance: 100 } }, { session });
await session.commitTransaction();
console.log("Transaction committed successfully");
} catch (error) {
await session.abortTransaction();
console.error("Transaction aborted:", error);
} finally {
session.endSession();
}
const session = client.startSession();
session.startTransaction({
writeConcern: { w: "majority" }
});
"snapshot"
Read Concern: Provides an isolated snapshot of the data."majority"
Read Concern: Ensures that only majority-confirmed data is visible to transactions.
session.startTransaction({
readConcern: { level: "snapshot" }
});
WriteConcern
for DurabilitywriteConcern
settings (e.g., "majority"
) can be used to guarantee that writes are durable across replica sets.
session.startTransaction({
writeConcern: { w: "majority", j: true }
});
const session = client.startSession();
try {
session.startTransaction();
// Operations across collections or shards
await db.collection("users").insertOne({ userId: "A" }, { session });
await db.collection("orders").insertOne({ orderId: "1" }, { session });
await session.commitTransaction();
console.log("Transaction in sharded cluster committed successfully");
} catch (error) {
await session.abortTransaction();
console.error("Transaction aborted:", error);
} finally {
session.endSession();
}
startTransaction()
: Initializes a transaction.commitTransaction()
: Commits the transaction, making all changes permanent.abortTransaction()
: Aborts the transaction, discarding any changes.
async function runTransactionWithRetry(session, transactionFunction) {
while (true) {
try {
await transactionFunction(session);
break;
} catch (error) {
if (error.hasErrorLabel("TransientTransactionError")) {
console.log("Retrying transaction...");
} else {
throw error;
}
}
}
}
mongostat
, and mongotop
to monitor transaction health.ACID transactions ensure reliability and consistency in distributed systems but require careful implementation to handle challenges like network latency and failures. Balancing strict ACID compliance with scalability and performance is key to building robust and efficient distributed applications. Happy coding !❤️