Process Flow - Batch writes
Start Batch Write
Add Write Operation 1
Add Write Operation 2
Commit Batch
All Writes Applied Atomically
End
Batch writes collect multiple write operations and apply them all at once atomically.
const batch = db.batch(); const doc1 = db.collection('users').doc('user1'); batch.set(doc1, {name: 'Alice'}); const doc2 = db.collection('users').doc('user2'); batch.update(doc2, {age: 30}); await batch.commit();
| Step | Action | Batch State | Result |
|---|---|---|---|
| 1 | Create batch object | Empty batch | Batch initialized |
| 2 | Add set operation for doc1 | Batch with 1 write (set user1) | Operation queued |
| 3 | Add update operation for doc2 | Batch with 2 writes (set user1, update user2) | Operation queued |
| 4 | Commit batch | Batch with 2 writes | Writes applied atomically |
| 5 | Batch cleared after commit | Empty batch | Ready for new writes |
| Variable | Start | After Step 2 | After Step 3 | After Step 4 | After Step 5 |
|---|---|---|---|---|---|
| batch | undefined | 1 write queued | 2 writes queued | writes committed | empty batch |
Batch writes let you queue multiple write operations. Use db.batch() to start. Add writes with batch.set(), batch.update(), etc. Call batch.commit() to apply all writes atomically. Batch resets after commit; create new batch for more writes.