Skip to content

Firestore Batch Writes — Efficient Bulk Data Operations in Firestore

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about Firestore Batch Writes. We cover key concepts, practical examples, and best practices to help you master this topic.

Firestore batch writes allow executing multiple write operations (set, update, delete) atomically in a single request, ensuring all operations succeed or none are applied.

What You'll Learn

  • Creating and committing batch writes
  • Batch size limits and best practices
  • Error handling and retry strategies

Why It Matters

Batch writes reduce the number of network requests and ensure data consistency for related operations. Without batches, partial failures leave data in inconsistent states. DodaTech uses batch writes for device configuration updates across multiple documents.

flowchart LR
    A["Start Batch"] --> B["Add Operation 1: set"]
    A --> C["Add Operation 2: update"]
    A --> D["Add Operation 3: delete"]
    B --> E["Commit Batch"]
    C --> E
    D --> E
    E --> F["All succeed or all fail"]

Code Examples

// Batch write example
import { writeBatch, doc, collection } from 'firebase/firestore';

const batch = writeBatch(db);

// Add operations to the batch
const userRef = doc(db, 'users', 'alice@example.com');
batch.set(userRef, {
  name: 'Alice Johnson',
  email: 'alice@example.com',
  role: 'admin',
  updatedAt: new Date()
});

const settingsRef = doc(db, 'users', 'alice@example.com', 'settings', 'prefs');
batch.set(settingsRef, {
  theme: 'dark',
  notifications: true
});

const logRef = doc(collection(db, 'auditLogs'));
batch.set(logRef, {
  action: 'user_created',
  userId: 'alice@example.com',
  timestamp: new Date()
});

// Commit all operations atomically
try {
  await batch.commit();
  console.log('All operations completed successfully');
} catch (error) {
  console.error('Batch failed, no changes applied:', error);
}
// Batch update and delete
const batch2 = writeBatch(db);

// Update multiple documents
const userRef1 = doc(db, 'users', 'user1');
const userRef2 = doc(db, 'users', 'user2');
const userRef3 = doc(db, 'users', 'user3');

batch2.update(userRef1, { role: 'moderator' });
batch2.update(userRef2, { role: 'moderator' });
batch2.delete(userRef3);

await batch2.commit();
# Python Firestore batch writes
from google.cloud import firestore

db = firestore.Client()

# Create a batch
batch = db.batch()

# Get document references
user1 = db.collection('users').document('alice@example.com')
user2 = db.collection('users').document('bob@example.com')
log = db.collection('auditLogs').document()

# Add operations
batch.set(user1, {
    'name': 'Alice Johnson',
    'role': 'admin',
    'updatedAt': firestore.SERVER_TIMESTAMP
})

batch.update(user2, {'role': 'moderator'})

batch.set(log, {
    'action': 'batch_update',
    'users': ['alice@example.com', 'bob@example.com'],
    'timestamp': firestore.SERVER_TIMESTAMP
})

# Commit
batch.commit()

Common Mistakes

1. Exceeding the 500 Operation Limit

Batches are limited to 500 operations. Split large batches into multiple commits.

2. Mixing Batch Writes Across Multiple Databases

Batches can only operate on documents within the same Firestore database.

3. Not Handling Commit Errors

Batch failures must be caught. The entire batch is rolled back on failure.

4. Adding Dependent Operations Within the Same Batch

Operations in a batch are not ordered. Do not read a document written in the same batch.

5. Using Batches for Single Operations

Use setDoc, updateDoc, or deleteDoc for single operations. Batches are for multiple writes.

Practice Questions

  1. What is the maximum number of operations in a batch?
  2. Are batch operations atomic?
  3. Can you read documents inside a batch?
  4. What happens if one operation in a batch fails?
  5. Can a batch span multiple databases?

Answers:

  1. 500 operations.
  2. Yes. Either all operations succeed or none are applied.
  3. No. Batches are for writes only. Read operations are not allowed.
  4. The entire batch fails and no changes are applied.
  5. No. All operations must be in the same Firestore database instance.

Challenge: Build a user import script that reads a CSV file and creates user documents with associated settings and audit log entries in batch operations. Handle errors gracefully and report the status of each batch.

FAQ

How fast are batch writes compared to individual writes?

Batch writes are faster for bulk operations because they make a single network request instead of multiple requests. For 100 operations, batch is about 10x faster.

Can I use batch writes with custom claims?

No. Custom claims are set via the Firebase Admin SDK, not Firestore. They cannot be included in batch writes.

Do batch writes count as a single write or multiple writes?

Each operation in the batch counts individually toward your Firestore write quotas. The batch grouping does not reduce write costs.

Can I roll back a batch after commit?

No. Once committed, the batch operations are permanent. There is no rollback. Use transactions for read-then-write scenarios.

What happens to batch writes when the client goes offline?

Firestore stores pending batch writes locally and syncs them when connectivity is restored, just like individual writes.

Mini Project

Build a Firestore data Migration tool that reads documents from one collection, transforms them, and writes to another collection using batch writes. Include progress reporting, error handling, and rollback capability. Handle the 500-operation limit by splitting into multiple batches.

What's Next

Learn about Firestore transactions for read-then-write scenarios, then explore Firestore security rules for access control.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro