Skip to content

MongoDB Transactions ​

Multi-Document Transactions (4.0+) ​

  • Trước 4.0: chỉ atomic trên một document.
  • Từ 4.0 (2018): transaction nhiều document, ACID, snapshot isolation, chạy trên replica set (từ 4.2 cả sharded cluster). Doc transactions chỉ liệt kê replica set và sharded cluster, không nêu standalone.

Transaction cơ bản (withTransaction tự chạy lại toàn bộ callback khi gặp TransientTransactionError, nên callback không được có tác dụng phụ ngoài DB):

javascript
// Node.js (mongodb 6.x) — cần replica set; tạo dữ liệu mẫu ngay trong khối
import { MongoClient } from 'mongodb'

const client = new MongoClient('mongodb://localhost:27017/?replicaSet=rs0')
const accounts = client.db('bank').collection('accounts')
await accounts.deleteMany({})
await accounts.insertMany([{ _id: 'A', balance: 500 }, { _id: 'B', balance: 0 }])

const session = client.startSession()
try {
  await session.withTransaction(async () => {
    // Mọi thao tác trong khối này là một đơn vị atomic
    await accounts.updateOne({ _id: 'A' }, { $inc: { balance: -100 } }, { session })
    await accounts.updateOne({ _id: 'B' }, { $inc: { balance: 100 } }, { session })
  })
  console.log('Transaction committed')   // A = 400, B = 100
} finally {
  await session.endSession()
}

Điều khiển tay (không tự retry; chỉ abort một lần, abortTransaction lần hai báo lỗi Cannot call abortTransaction twice):

javascript
// Node.js (mongodb 6.x) — chạy sau khối tạo `accounts` ở trên
const session = client.startSession()
try {
  session.startTransaction({
    readConcern: { level: 'snapshot' },
    writeConcern: { w: 'majority' },
    readPreference: 'primary'
  })

  await accounts.updateOne({ _id: 'A' }, { $inc: { balance: -1000 } }, { session })
  const balanceA = await accounts.findOne({ _id: 'A' }, { session })
  if (balanceA.balance < 0) {
    throw new Error('Insufficient balance')   // vào catch, abort đúng một lần
  }

  await accounts.updateOne({ _id: 'B' }, { $inc: { balance: 1000 } }, { session })
  await session.commitTransaction()
} catch (error) {
  if (session.inTransaction()) await session.abortTransaction()
  console.log('Transaction aborted:', error.message)
} finally {
  await session.endSession()
}

Read Concerns ​

Mặc định: readConcern là local, writeConcern là w: "majority" (replica set có arbiter có thể mặc định w: 1; đã đo trên MongoDB 8.x bằng getDefaultRWConcern).

javascript
// mongosh — chạy trên replica set; collection users đã có dữ liệu
// local: đọc dữ liệu mới nhất của nút này (có thể bị rollback)
db.users.find().readConcern('local')

// majority: chỉ đọc dữ liệu đã được đa số nút xác nhận (không bị rollback)
db.users.find().readConcern('majority')

// linearizable: mạnh nhất, đọc thấy mọi ghi majority trước đó; chỉ đọc từ primary, lọc theo một document
db.users.find({ _id: 123 }).readConcern('linearizable')

snapshot chỉ dùng trong transaction: session.startTransaction({ readConcern: { level: 'snapshot' } }) cho một góc nhìn nhất quán qua nhiều lần đọc (đã đo: document chèn bởi client khác sau khi transaction bắt đầu không hiện trong transaction).

Write Concerns ​

javascript
// mongosh — chạy trên replica set
// w: 1: chỉ primary xác nhận (nhanh nhất, ghi có thể bị rollback khi failover)
db.users.insertOne({ name: 'a' }, { writeConcern: { w: 1 } })

// w: "majority": đa số nút xác nhận (khuyên dùng)
db.users.insertOne({ name: 'b' }, { writeConcern: { w: 'majority' } })

// j: true: chờ ghi vào journal (bền trên đĩa)
db.users.insertOne({ name: 'c' }, { writeConcern: { w: 'majority', j: true } })

// wtimeout: quá hạn (ms) thì trả lỗi; w: 3 cần ≥ 3 nút mang dữ liệu
// (replica set 1 nút báo MongoWriteConcernError: Not enough data-bearing nodes)
db.users.insertOne({ name: 'd' }, { writeConcern: { w: 3, wtimeout: 5000 } })

Transaction Limitations ​

⚠️ Giới hạn:

  • Thời gian tối đa mặc định: 60 giây, chỉnh bằng transactionLifetimeLimitSeconds; quá hạn thì bị huỷ (đã đo với giới hạn 2 giây: NoSuchTransaction kèm nhãn TransientTransactionError).
  • Không còn giới hạn tổng kích thước từ 4.2; mỗi oplog entry vẫn ≤ 16 MB (doc: "each oplog entry still must be within the BSON document size limit of 16MB"). Giữ transaction nhỏ, số document sửa tối đa đo bằng workload của bạn.
  • Hai transaction cùng sửa một document: transaction sau nhận WriteConflict (code 112) kèm nhãn TransientTransactionError (đã đo); chạy lại toàn bộ transaction, không chạy lại từng lệnh.
  • DDL: từ 4.4 tạo collection và index trong transaction được (đã đo: createCollection + insertOne trong cùng transaction chạy OK); DDL khác bị chặn, và DDL phải chờ transaction đang chạy.
  • Chậm hơn thao tác đơn.

Best practices:

  • ✅ Giữ transaction ngắn nhất có thể
  • ✅ Chỉ dùng khi cần atomic nhiều document
  • ✅ Dùng $inc/$set atomic thay vì đọc-sửa-ghi (đã đo: hai tiến trình đọc 500 rồi cùng ghi 400 ⇒ mất một lần trừ; hai $inc -100 ⇒ 300)
  • ❌ Không dùng cho thao tác hàng loạt

Phải nhớ

  • Transaction cần replica set; dùng withTransaction để được retry TransientTransactionError.
  • Mặc định readConcern: local, writeConcern: majority; w: 1 có thể mất ghi khi failover.
  • Giữ ngắn (60 giây mặc định), tránh đọc-sửa-ghi khi $inc đủ dùng.