Skip to content

Firestore Transactions — Complete Guide

DodaTech Updated 2026-06-24 2 min read

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 runTransaction for 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

  1. Using foldl instead of foldl' causing stack overflow on large lists
  2. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  3. 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

### What causes a Transaction to abort?

Concurrent modification of documents read in the Transaction. The SDK retries automatically. If it fails after multiple retries, ABORTED is thrown.

### How many documents can I read in a Transaction?

Maximum 10 document reads per Transaction. Exceeding this causes the Transaction to fail. For more reads, use a batch write instead.

### What is the difference between a Transaction and FieldValue.increment?

FieldValue.increment() is a server-side atomic operation that doesn't need a Transaction. Use it for simple counter updates. Use transactions when you need to read current data and conditionally update.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro