Learn how to perform atomic transactions in Firestore for web and Android apps, ensuring reliable data consistency with our step-by-step guide.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Introduction
Firestore is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud. Transactions in Firestore allow you to perform multiple read and write operations atomically. This ensures that either all modifications occur, or none do, in scenarios where data consistency is critical.
Step 1: Set Up Firestore in Your Project
To perform transactions in Firestore, you first need to set it up in your project. This typically involves:
Adding Firebase to your app:
// Include Firebase SDK in your project
// For the web:
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-firestore.js"></script>
// Initialize Firebase
firebase.initializeApp({
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID"
});
// Initialize Firestore through Firebase
const db = firebase.firestore();
Ensure you have configured Firebase in your Android or iOS app as per the Firebase documentation.
Step 2: Understand Firestore Transaction Flow
Firestore transactions are used for batch reads and writes, with the guarantee that all or none of the operations are executed. The flow for using transactions typically involves:
Step 3: Implement Firestore Transaction in JavaScript
Below is a sample implementation of a Firestore transaction using JavaScript. Ensure that you have initialized Firestore as shown in Step 1.
// Define an async function to run the transaction
async function performTransaction() {
const docRef = db.collection('yourCollection').doc('yourDocument');
try {
// Run a Firestore transaction
await db.runTransaction(async (transaction) => {
// Perform a read operation
const doc = await transaction.get(docRef);
if (!doc.exists) {
throw new Error("Document does not exist!");
}
// Decide what calculation or change you may need
const newValue = doc.data().field + 1;
// Perform a write operation
transaction.update(docRef, { field: newValue });
});
console.log("Transaction successfully committed!");
} catch (error) {
console.error("Transaction failed: ", error);
}
}
// Call the function to perform the transaction
performTransaction();
Replace 'yourCollection', 'yourDocument', and 'field' with your specific collection name, document ID, and field name. This code reads a field value, increments it, and updates it inside a transaction.
Step 4: Implement Firestore Transaction in Java (For Android)
Use the following code snippet to implement a transaction in an Android application:
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference docRef = db.collection("yourCollection").document("yourDocument");
db.runTransaction((Transaction.Function) transaction -> {
// Read the document and get its current value
DocumentSnapshot snapshot = transaction.get(docRef);
Long newValue = snapshot.getLong("field") + 1;
// Update the document
transaction.update(docRef, "field", newValue);
// Success
return null;
}).addOnSuccessListener(aVoid -> {
Log.d(TAG, "Transaction success!");
}).addOnFailureListener(e -> {
Log.w(TAG, "Transaction failure.", e);
});
Replace "yourCollection", "yourDocument", and "field" with your collection name, document ID, and field name.
Conclusion
Firestore transactions are an essential part of managing consistent and reliable updates to your Firestore collections and documents. By following these steps, you can confidently implement transactions in your web or Android applications using Firebase Firestore. For more advanced transaction capabilities, consult the Firebase and Firestore documentation.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.