Firestore Transactions — Complete Guide
In this tutorial, you'll learn about Firestore Transactions. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your Transaction fails with ABORTED because another client modified the data between your read and write, or your Transaction function throws an exception.
Wrong Approach ❌
// Non-atomic read-then-write — race condition!
val doc = db.collection("counters").document("visits").get().await()
val current = doc.getLong("count") ?: 0
db.collection("counters").document("visits").update("count", current + 1).await()
Output: If two clients run this simultaneously, one update is lost. Counter undercounts.
Right Approach ✅
class CounterRepository(private val db: FirebaseFirestore) {
// Transaction — atomic read-then-write
suspend fun incrementVisitCount(): Long {
return db.runTransaction { transaction ->
val docRef = db.collection("counters").document("visits")
val snapshot = transaction.get(docRef) // Read inside transaction
val newCount = (snapshot.getLong("count") ?: 0) + 1
transaction.update(docRef, "count", newCount)
newCount // Return value
}.await()
}
// Transaction with multiple documents
suspend fun transferPoints(fromUserId: String, toUserId: String, points: Long): Boolean {
return try {
db.runTransaction { transaction ->
val fromRef = db.collection("users").document(fromUserId)
val toRef = db.collection("users").document(toUserId)
val fromSnapshot = transaction.get(fromRef)
val fromPoints = fromSnapshot.getLong("points") ?: 0
if (fromPoints < points) {
throw FirebaseFirestoreException(
"Insufficient points",
FirebaseFirestoreException.Code.ABORTED
)
}
transaction.update(fromRef, "points", fromPoints - points)
transaction.update(toRef, "points",
(transaction.get(toRef).getLong("points") ?: 0) + points)
}.await()
true
} catch (e: FirebaseFirestoreException) {
if (e.code == FirebaseFirestoreException.Code.ABORTED) {
false // Transaction conflict — retry handled by SDK
} else {
throw e
}
}
}
// Using FieldValue.increment (no transaction needed for simple counters)
suspend fun simpleIncrement() {
// Transaction not needed for atomic increment!
db.collection("counters").document("visits")
.update("count", FieldValue.increment(1)).await()
}
}
Output: Atomic operations with conflict handling.
Prevention
- Use
runTransactionfor read-then-write operations. - Always read documents inside the Transaction lambda (not before).
- Use
FieldValue.increment()for simple counters — no Transaction needed. - Transactions retry automatically on conflict (up to a limit).
- Keep transactions small — max 10 document reads per Transaction.
Common Mistakes with firestore Transaction
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro