In ApsaraDB, operations on a single document are atomic. You can use an embedded document schema design to avoid transactions that span multiple documents or collections. If atomic operations and an embedded schema design do not meet your requirements, you can use transaction APIs to implement multi-document transactions.
Transaction details
A transaction executes completely or not at all. Partial success is not possible.
Before a transaction is committed, data updates within the transaction are invisible to operations outside of it. After the transaction is committed, if it modified multiple documents, changes to some documents may become visible before others. However, eventual consistency is guaranteed. If a transaction is rolled back, its changes are never visible outside the transaction.
Transactions use snapshot isolation. In snapshot isolation:
Read operations return a snapshot of an object, not the actual data.
Write operations modify the object's snapshot. This ensures that subsequent reads within the transaction see the same data.
Write operations place a transaction lock on an object. If an object is locked, write operations from other transactions fail. Non-transactional write operations are blocked until the transaction lock is released.
To avoid extensive lock conflicts, transactions currently support read and write operations on only a single document.
The following commands support transactions:
insertOne, findOne, updateOne, deleteOne, replaceOne, findOneAndUpdate, findOneAndReplace, findOneAndDelete.Transactions are supported only within cloud functions. They are not supported for direct database access from a client.
A transaction is valid for 10 s. If a transaction is not committed within this period, it is automatically rolled back.
Transaction APIs
Start a transaction.
const transaction = await ctx.mpserverless.db.startTransaction();You can operate on a single row of data in a transaction.
const findOneResult = await transaction.collection('user').insertOne( {name: 'xxxx', "age": 19}, );Commit the transaction.
await transaction.commit();Roll back the transaction.
await transaction.rollback();