Search code examples
node.jsgoogle-cloud-firestorefirebase-admin

How does Firestore handle Transactions involving queries


I'm working with Cloud Firestore transactions and I'm trying to understand how Firestore (server client libraries) handles transactions that involve queries. Specifically, the "locking" behavior when a transaction performs a query instead of directly getting a single document.

Does the transaction lock the entire collection (or collection group) from which the query is made, or does it only lock the specific documents that are returned by the query?

Example (NodeJs):

const db = admin.firestore();

const fireQuery = db.collectionGroup('my-collection')
                    .where('role', '==', 'user');

await db.runTransaction(async transaction => {
  // Query documents and lock them while performing the update.
  const querySnap = await transaction.get(fireQuery);

  // Perform write operations on the retrieved documents...
}

If it only locks the docs returned by the query, How does Firestore determine which documents to lock in advance, given that the results of a query might not be known until the query is executed?


Solution

  • Does the transaction lock the entire collection (or collection group) from which the query is made

    No.

    or does it only lock the specific documents that are returned by the query?

    Yes. You should be aware that there is a limit of 500 documents that may participate in a single batch or transaction. If the query returns more than that, it will result in an error.

    If it only locks the docs returned by the query, How does Firestore determine which documents to lock in advance, given that the results of a query might not be known until the query is executed?

    It doesn't have to know anything before the transaction occurs. The transaction will only lock documents that are read during the transaction, which includes any documents returned by a query or a single document get.