Firestore Batch Writes — Efficient Bulk Data Operations in Firestore
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
- What is the maximum number of operations in a batch?
- Are batch operations atomic?
- Can you read documents inside a batch?
- What happens if one operation in a batch fails?
- Can a batch span multiple databases?
Answers:
- 500 operations.
- Yes. Either all operations succeed or none are applied.
- No. Batches are for writes only. Read operations are not allowed.
- The entire batch fails and no changes are applied.
- 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
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