skip to content

In Cloud Firestore on Android, when do you use runTransaction instead of a WriteBatch, and what rules must a transaction function follow?

level: middleimportance: must knowfreq 66%

answer

  1. both all-or-nothing
  2. reads before writes
  3. the function may run again
  4. five attempts by default
  5. offline: one queues, one fails

basics

~20 s

Use runTransaction when a write depends on data you read, such as claiming an unassigned task; use a WriteBatch for atomic writes that need no reads. A transaction function reads before writing, may rerun, must avoid side effects, and fails offline.

solid answer

~50 s

Both are atomic: every write applies or none does. A transaction is for read-modify-write. Inside `db.runTransaction { tx -> ... }` I make every `tx.get()` call first, then `tx.update`, `set` or `delete`. If another client changes a document I read before the commit, the SDK reruns the whole function, up to five attempts by default; `TransactionOptions.Builder().setMaxAttempts()` changes that. So the function must have no side effects (no UI updates, no changes to app state) and should return its outcome instead. On Android it runs on a background thread pool, which is why `tx.get()` may block. Transactions fail when the device is offline. A `WriteBatch` has no reads and is never retried, and it works offline: its writes are applied locally and sent when the connection returns. Claiming a task is a transaction; archiving a set of finished tasks is a batch.

code

kotlin · 23 lines
kotlin
import com.google.android.gms.tasks.Task
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.FieldValue
import com.google.firebase.firestore.FirebaseFirestore

// Read-modify-write: a transaction. May run up to 5 times; fails offline.
fun claimTask(db: FirebaseFirestore, taskRef: DocumentReference, uid: String): Task<Boolean> =
    db.runTransaction { tx ->
        val task = tx.get(taskRef)
        if (task.getString("assigneeId") != null) {
            false
        } else {
            tx.update(taskRef, "assigneeId", uid, "status", "in_progress")
            true
        }
    }

// Blind writes: a batch. Never retried; queued while offline.
fun archive(db: FirebaseFirestore, project: DocumentReference, done: List<DocumentReference>): Task<Void> =
    db.runBatch { batch ->
        done.forEach { batch.update(it, "archived", true) }
        batch.update(project, "archivedCount", FieldValue.increment(done.size.toLong()))
    }

go deeper

for a junior

Recall that both transactions and batched writes are all-or-nothing, and that only a transaction can read before it writes.

for a middle

Explain the retry loop: reads first, writes buffered, rerun on conflicting edits up to five attempts, and why the function must be free of side effects.

for a senior

Show that you design offline behaviour around these tools: batches and increments for writes that must queue, transactions only where a read decides the write.

for a principal

Weigh client-side transactions against moving contested logic to trusted server code, considering offline users, retry storms and rule-lookup limits per atomic operation.

## Two atomic tools Cloud Firestore offers two **atomic** operations. In each, either every write succeeds or none is applied: - a **transaction**: a set of reads and writes on one or more documents; - a **batched write**: a set of writes only, on one or more documents. The deciding question is whether any write **depends on a value you read**. In a team task app, *claim this task if nobody owns it* depends on the current `assigneeId`, so it is a transaction. *Mark these twelve finished tasks archived and update the project's summary* needs no reads, so it is a batch. ## How a client transaction runs On Android you call `FirebaseFirestore.runTransaction` with a function that receives a `Transaction`: 1. The SDK invokes your function on a **background thread pool**, not the main thread. That is why `Transaction.get()` can return a `DocumentSnapshot` synchronously. 2. Reads inside the transaction come from the **backend**, not from the local cache. 3. Writes (`set`, `update`, `delete`) are buffered. Nothing is written until the function returns. 4. At commit, if any document the function read was **modified outside the transaction**, Firestore rejects the commit and the SDK **runs the whole function again** on fresh data. 5. After **5 attempts** (the default failure limit) the transaction fails. You can change the limit with `TransactionOptions.Builder().setMaxAttempts(n)` and pass it to `runTransaction(options, function)`. A failed transaction writes nothing, and you never roll back by hand. To abort deliberately, throw a `FirebaseFirestoreException`; the documentation's own example uses code `ABORTED`. ## Rules for the transaction function - **Reads before writes.** A transaction that reads after it has written fails. - **No side effects.** Because the function can run more than once, it must not change app state, update the UI or fire analytics. Return a value and act on the returned `Task`'s result. - **No offline use.** Transactions fail when the client is offline, so a claim button needs an offline state. - **Read through the transaction.** Use `tx.get(ref)`, not `ref.get()`. Only the transaction's own reads are checked for conflicting changes. ```kotlin fun claimTask(db: FirebaseFirestore, taskRef: DocumentReference, uid: String): Task<Boolean> = db.runTransaction { tx -> val task = tx.get(taskRef) if (task.getString("assigneeId") != null) { false // someone else already owns it; no write } else { tx.update(taskRef, "assigneeId", uid, "status", "in_progress") true } } ``` ## Batched writes - Create one with `db.batch()` and finish with `commit()`, or use `db.runBatch { batch -> ... }`. - A batch performs **no reads**, so it has no conflict check and is **never retried**. It also has fewer ways to fail. - Batches **work offline**. The writes go into the local cache at once, so listeners see them, and they are sent when the connection returns. - Combine a batch with server-side transforms such as `FieldValue.increment(1)` or `FieldValue.serverTimestamp()` when a write needs the current value but the app does not. ## Limits that apply to both | Limit | Value | |---|---| | Request size | 10 MiB, counting documents and the index entries they change | | Transaction time | 270 seconds, with 60 seconds idle expiry | | Lock deadline | 20 seconds | | Field transforms on one document | 500 | | Security-rule document lookups | 20 per atomic operation, 10 per single write | The Android SDK's javadoc for `batch()` still states a maximum of 500 writes per batch, with each `FieldValue` transform counting as an extra write. The current limits page frames the ceiling as request size instead. Either way, a batch with hundreds of documents is a smell. The guidance is to split it, and to do bulk loads from a server client library with parallel writes rather than from a phone. ## Choosing in the task-list app | Operation | Tool | Why | |---|---|---| | Claim an unassigned task | Transaction | The write depends on the current owner | | Move a task and update both projects' summaries | Transaction, if summaries are recomputed from reads | Values derive from current data | | Archive finished tasks | Batch | Blind writes, and it should work offline | | Add a comment and bump `commentCount` | Batch with `FieldValue.increment` | No read needed |

  • Why must a transaction function avoid showing a toast or updating a ViewModel?
    The SDK reruns the function whenever a document it read changed before the commit, up to five attempts by default. A side effect inside it could fire several times, or fire for an attempt that never committed. It also runs on a background thread pool, not the main thread. Return the outcome from the function and act on the `Task` result once.
  • What does the user see if they tap Claim while offline?
    The transaction fails, because transactions need the backend to read current data and check conflicts. The app should catch the failure and show that claiming needs a connection, or disable the action while offline. A batch would behave differently: its writes apply to the local cache at once and sync later.
  • When is a batch with FieldValue.increment a better fit than a transaction?
    When the app only needs the counter to change, not to know its value. The server applies the increment, so the client sends a write with no read, no conflict check and no retry loop, and the batch still works offline. A transaction is needed only when the write depends on what you read, such as refusing to go below zero.

  • A Firestore transaction can read a document after it has already written one.
  • A transaction function runs exactly once, so it is safe to update the UI inside it.
  • A batched write is retried automatically when another client edits the same document.
  • Transactions queue offline and commit when the connection returns, like batched writes.
  • Calling ref.get() inside the transaction function is as good as tx.get(ref).