Process Flow - Transaction basics
Start Transaction
Read Data Snapshot
Apply Update Logic
Attempt Commit
Commit
A transaction reads data, applies changes, tries to commit, and retries if conflicts occur.
db.runTransaction(transaction => {
return transaction.get(docRef).then(doc => {
const newCount = doc.data().count + 1;
transaction.update(docRef, { count: newCount });
});
});| Step | Action | Data Read | Update Applied | Commit Attempt | Result |
|---|---|---|---|---|---|
| 1 | Start transaction | N/A | N/A | No | Transaction started |
| 2 | Read document snapshot | {"count": 5} | N/A | No | Data read successfully |
| 3 | Calculate new count | 5 | count = 6 | No | Update prepared |
| 4 | Apply update | 5 | count = 6 | No | Update staged |
| 5 | Attempt commit | 5 | count = 6 | Yes | Commit successful |
| 6 | Transaction ends | N/A | N/A | No | Transaction complete |
| Variable | Start | After Step 2 | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|---|
| count | undefined | 5 | 6 | 6 | 6 |
| transactionState | not started | started | update prepared | update staged | committed |
Transaction basics in Firebase: - Start transaction - Read latest data snapshot - Apply update logic - Attempt commit - If commit fails, retry transaction - Ensures atomic, consistent updates