Transactions
Perform multiple mutations on one or more documents in an atomic manner for better performance at scale.
Transactions are useful in scenarios where you need to ensure that a series of mutations are performed as a single atomic unit of work. For example, you might want to update multiple documents as part of a single transaction to ensure that the data remains consistent across all documents.
To perform a transaction in Squid, you can use the runInTransaction
method provided by the squid
object. This method
takes a callback
function as a parameter, which will be executed within the context of a transaction.
await squid.runInTransaction(async (transactionId: string) => {
const user1 = squid.collection<User>('users').doc('user_1_id');
const user2 = squid.collection<User>('users').doc('user_2_id');
await user1.update({ name: 'Alice' }, transactionId);
await user2.update({ name: 'Bob' }, transactionId);
});
To perform this transaction with a database integration, include the integration ID with the collection method and ensure that your document IDs are objects.
await squid.runInTransaction(async (transactionId: string) => {
const user1 = squid
.collection<User>('users', 'MY_INTEGRATION_ID')
.doc({ userId: 'user_1_id' });
const user2 = squid
.collection<User>('users', 'MY_INTEGRATION_ID')
.doc({ userId: 'user_2_id' });
await user1.update({ name: 'Alice' }, transactionId);
await user2.update({ name: 'Bob' }, transactionId);
});
For more information, see the documentation on Collection references and Document IDs.
When applying changes inside a transaction, these changes will not reflect immediately, but they will reflect
optimistically once the callback
returns. This is in contrast to applying a mutation without a transaction, where
changes are applied immediately and optimistically. Any mutation that is applied as part of a transaction will resolve
immediately. In order to make sure the changes are applied on the server, you should wait for the promise returned from
runInTransaction
to resolve.
When applying a transaction on multiple integrations, each integration will be updated atomically. However, it may be that one integration updated and the other one failed. There is no support for cross-integration atomic updates.