Is it okay to modify application state in a firestore transaction on the server?

Viewed 119

The docs state

Do not modify application state inside of your transaction functions. Doing so will introduce concurrency issues, because transaction functions can run multiple times and are not guaranteed to run on the UI thread.

When using the admin SDK there'll be pessimistic concurrency control and I don't need to think about a UI thread. Does that mean its okay to modify state in admin SDK transactions?

1 Answers

Transactions may fail to commit for various reasons. In such cases the SDK can retry the transaction up to 5 times, causing the update function to execute multiple times (see API docs). So it's still not a good idea to do state changes in the body of the transaction update. It's best to observe the transaction commit status before making a state change:

try {
  await db.runTransaction(async (t) => {
    const doc = await t.get(cityRef);
    const newPopulation = doc.data().population + 1;
    t.update(cityRef, {population: newPopulation});
  });

  console.log('Transaction success!');
  // DO STATE CHANGES HERE
} catch (e) {
  console.log('Transaction failure:', e);
}
Related