Firestore transactions and batched writes both provide atomic updates, but they solve different problems. This guide shows when to use a transaction, a batched write, or a server-side operation; how to design retry-safe code; how to diagnose contention; and what to review as your schema, traffic, and SDKs change.
Overview
Use a Firestore transaction when the result depends on the current value of one or more documents. A transaction reads documents, calculates a result, and writes only if the documents have not changed during the transaction. If another write creates a conflict, Firestore may retry the transaction function with fresh data.
Use a batched write when you already know the values to write and need several creates, updates, or deletes to succeed as one atomic unit. A batch does not read documents as part of its operation and therefore cannot safely make a decision based on a value that might change concurrently.
Use a server-side operation, such as a callable or HTTP Cloud Function, when the workflow needs trusted credentials, payment-provider interaction, privileged validation, a durable idempotency record, or coordination that should not run in an untrusted client. Server-side code does not remove concurrency concerns; it gives you a controlled place to handle them.
| Requirement | Best starting point | Reason |
|---|---|---|
| Update a stock value only if enough inventory remains | Transaction | The decision depends on a current read. |
| Create an order, audit record, and status document with known values | Batched write | Several writes must commit together, with no read-dependent calculation. |
| Process a payment webhook or external API callback | Server-side operation | Secrets, retries, and idempotency belong on a trusted server. |
| Increment a counter without reading its current value | Atomic increment or server-side aggregation | A field transform can avoid a client read; high-contention counters may need sharding. |
| Apply a conditional multi-document change | Transaction, often server-side | The condition and writes must be evaluated against a consistent read set. |
Atomic does not mean unlimited or automatically retry-safe. A transaction or batch can prevent a partial commit, but your application still needs to handle rejected requests, duplicate invocations, authorization failures, and external side effects.
What to track
Transaction design
In the JavaScript modular SDK, a transaction commonly uses runTransaction:
import { runTransaction } from "firebase/firestore";
await runTransaction(db, async (transaction) => {
const ref = doc(db, "inventory", sku);
const snapshot = await transaction.get(ref);
const available = snapshot.data()?.available ?? 0;
if (available < quantity) {
throw new Error("INSUFFICIENT_STOCK");
}
transaction.update(ref, {
available: available - quantity
});
});
Keep the transaction callback deterministic. Firestore may invoke it more than once, so do not send an email, charge a card, publish a message, mutate global state, or append to a non-transactional system inside the callback. Throw a deliberate error for a business-rule failure, and let the caller decide whether to show a user-facing message or retry.
Read every document needed for the decision before issuing writes. Keep the read set small, avoid unnecessary document reads, and write only the fields that must change. Transactions are a poor fit for long-running work or code that depends on a network call inside the callback.
Batched writes
A batch is appropriate when the application has already computed the new values:
import { writeBatch, doc } from "firebase/firestore";
const batch = writeBatch(db);
const orderRef = doc(db, "orders", orderId);
const auditRef = doc(db, "orderAudits", orderId);
batch.set(orderRef, {
status: "submitted",
userId,
createdAt: serverTimestamp()
});
batch.set(auditRef, {
orderId,
action: "submitted",
userId,
createdAt: serverTimestamp()
});
await batch.commit();
All writes in the batch are committed together or rejected together. A batch cannot protect a rule such as “write this update only when the current status is pending” unless that condition is enforced by a transaction or by security rules that evaluate the request against the existing data. Validate input before constructing the batch, and surface commit errors rather than treating the local construction of a batch as success.
Limits and operational constraints
Before shipping, confirm the limits for the SDK and Firestore features used by your project. A batch or transaction is commonly limited to 500 write operations, and a transaction request has a maximum request size. Security Rules also impose limits on document-access calls during atomic operations. These constraints can be affected by writes that trigger rules, transforms, or additional document lookups.
Large imports should be chunked into bounded batches, with progress tracking and safe retry behavior. Do not assume that increasing the batch size improves throughput: request size, index work, security-rule evaluation, contention, and client memory can become bottlenecks first. Consult the current Firestore quotas and limits documentation when setting production thresholds.
Cadence and checkpoints
Review atomic-write behavior during development, then establish a monthly or quarterly checkpoint for systems with active traffic. Track the following variables:
- Aborted or contention errors: group them by document path or feature, not only by endpoint.
- Commit failures: separate permission, validation, size, quota, and transient failures.
- Transaction duration: longer callbacks increase the opportunity for conflicts and user-visible latency.
- Retry frequency: repeated retries can indicate a hot document or an overly broad read set.
- Batch size and request size: record the largest normal operation and the largest operation seen in tests.
- Duplicate business effects: compare payment, fulfillment, notification, and audit records against their initiating request.
At each checkpoint, run emulator or integration tests for concurrent updates, offline behavior, permission failures, and repeated requests. The Firebase Emulator Suite Testing Guide can help structure local seed data and CI test matrices. If rules are part of the atomic operation, include rule-access-call usage in the review; the Firebase Security Rules Audit provides a useful companion checklist.
How to interpret changes
When a transaction fails
An aborted result generally means the transaction could not complete because the documents it depended on changed or the operation encountered contention. It is not automatically evidence of a Firestore outage. First identify the contested document, then ask whether many users are updating one shared document, whether the transaction reads more documents than necessary, and whether the callback performs slow work.
If contention is expected, reduce the read set, move unrelated writes out of the transaction, distribute hot data across documents, or redesign a global counter as a sharded counter. Do not add an unbounded client retry loop. The SDK manages transaction retries within its behavior; your application should apply a bounded policy for the overall request and report a controlled failure when the operation remains unsuccessful.
Offline clients
Mobile and web clients can queue some writes while offline, but transaction behavior differs from ordinary writes because a transaction needs current document reads to make its decision. Test offline and reconnect scenarios on every supported platform. A UI should not label a transaction-dependent inventory or reservation action as complete merely because the user tapped a button. Confirm the committed result and design for a reconnect-time failure.
Idempotency template
For payments, inventory reservations, webhook handlers, and scheduled work, give each logical request an idempotency key. Store a record such as operations/{key} with the operation type, requester, status, result reference, and timestamps. On receipt, a server-side function should atomically claim the key or detect that it is already completed. If the key is complete, return the stored result; if it is in progress, apply a clear lease or recovery policy; if it failed safely, decide whether the same key may be retried.
The idempotency record prevents duplicate application-level effects, but it cannot make an external provider automatically idempotent. Pass the same key to providers that support idempotency, and record provider responses only after validating that the response belongs to the intended operation.
When to revisit
Revisit this design immediately when a schema changes, a new index or rule is added, traffic concentrates on a document, an SDK is upgraded, or a workflow gains an external side effect. Also review it on a monthly or quarterly schedule using production error data rather than assumptions.
Use this practical checklist:
- List every transaction and batch, including the documents each one reads and writes.
- Mark whether each operation depends on current data, known values, or privileged server logic.
- Test concurrent success, transaction aborts, permission denials, oversized requests, offline reconnects, and duplicate requests.
- Verify that transaction callbacks contain no irreversible side effects.
- Confirm that batches are chunked below the relevant limits and that failures are observable.
- Measure hot documents and repeated retries, then redesign before contention becomes a user-facing incident.
- Record the review date and the next trigger for reassessment.
The reliable choice is usually simple: use a transaction for a read-dependent decision, a batch for known multi-document writes, and a server-side operation for trusted or externally coordinated workflows. Recheck that choice as data volume, concurrency, and business consequences change.