0
0
Firebasecloud~5 mins

Transaction basics in Firebase - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you need to update data in a way that makes sure no one else changes it at the same time. Transactions help you do this by making sure your changes happen all at once or not at all.
When you want to increase a counter safely without losing updates from others.
When you need to read a value, change it, and save it back without conflicts.
When multiple users might try to update the same data at the same time.
When you want to keep data consistent, like updating a balance after a purchase.
When you want to retry your update automatically if someone else changed the data first.
Commands
This command runs a transaction that reads the current count from the 'clicks' document, adds one, and updates it safely. It retries if someone else changed the count meanwhile.
Terminal
firebase firestore:transaction 'db => db.runTransaction(transaction => {
  return transaction.get(db.collection("counters").doc("clicks")).then(doc => {
    const newCount = (doc.data().count || 0) + 1;
    transaction.update(db.collection("counters").doc("clicks"), { count: newCount });
  });
})'
Expected OutputExpected
Transaction successfully committed.
This command checks the current value of the 'clicks' counter to verify the transaction worked.
Terminal
firebase firestore:doc get counters/clicks
Expected OutputExpected
{ "count": 1 }
Key Concept

If you remember nothing else from this pattern, remember: transactions let you safely read and write data together so no updates get lost.

Common Mistakes
Trying to update data without a transaction when multiple users write at the same time.
This can cause lost updates because changes overwrite each other.
Use a transaction to read the current data and write the new data atomically.
Not handling retries inside the transaction function.
If data changes during your transaction, it will fail unless retried.
Write your transaction code so it can be retried automatically by the SDK.
Summary
Use transactions to read and update data safely in Firestore.
Run the transaction command to perform atomic updates that retry if needed.
Verify your changes by reading the updated document after the transaction.