How to fix FAILED_PRECONDITION: The system is not in a state required for the operation in Firebase
The FAILED_PRECONDITION error occurs when a Firestore operation fails because necessary preconditions (like composite indexes or transaction constraints) are not met. Most commonly caused by missing indexes on compound queries combining where() and orderBy().
Quick fix
Fixes FAILED_PRECONDITION: The system is not in a state required for the operation
You can create a composite index by going to:
https://console.firebase.google.com/v1/...- Check browser console and Firebase Console for index creation link
- Manually create the composite index in Firebase Console
- For transactions, add retry logic with exponential backoff
- Verify Firestore security rules are not blocking the operation
You can create a composite index by going to:https://console.firebase.google.com/v1/...FAILED_PRECONDITION: The system is not in a state required for the operation
What this error means
Firebase Firestore returns this error when an operation is rejected because the system is not in the required state to complete it. This is Firestore's way of enforcing data consistency and preventing invalid operations. The error can occur in several contexts: (1) Composite indexes are missing for queries that combine multiple filters or sorting, (2) A transaction is attempting to modify a document that has changed since the transaction began (optimistic concurrency control), (3) A document is currently locked by another concurrent write operation, or (4) Security rules or emulator configuration is preventing the operation.
Typical symptoms
- Query with .where().orderBy() fails with error code 9 or "firestore/failed-precondition"
- Chaining multiple .where() clauses causes the operation to be rejected
- Collection group queries (.collectionGroup()) with filters fail
- Firestore transactions fail with "stored version does not match required base version" message
- Error appears in browser console or logcat without a link to create index
- Emulator returns FAILED_PRECONDITION when running simple transactions
Common causes
- Missing composite index for compound queries - Most common. Queries combining where() and orderBy(), or multiple where() clauses, require explicit indexes in Firebase Console.
- Transaction document conflict - Another client modified a document your transaction is trying to update, triggering optimistic concurrency control protection.
- Document locked by concurrent write - Attempting simultaneous writes to the same document while another operation has it locked.
- Collection group query without required index - Using collectionGroup() with filters requires a composite index across subcollections.
- Security rules blocking operation - Firestore security rules may silently reject operations, manifesting as FAILED_PRECONDITION.
- Incorrect query syntax - Chaining incompatible filters (like = with >=) on the same field can trigger the error.
- Firestore emulator state issue - Running transactions against a fresh or improperly configured emulator may fail.
How to fix "FAILED_PRECONDITION: The system is not in a state required for the operation"
When Firestore encounters a query that needs an index, it usually logs a direct link in the console:
You can create a composite index by going to:
https://console.firebase.google.com/v1/...If you see this link, click it to auto-create the required index. On Android (React Native), check adb logcat output for the index link instead of the browser console.
If no link appears, proceed to the next step.
If the automatic link did not appear:
1. Go to [Firebase Console](https://console.firebase.google.com)
2. Select your project and navigate to Firestore Database
3. Click on the Indexes tab (next to Collections)
4. Click Create Index
5. Select your collection name
6. Add the fields you're querying on:
- For .where("status", "==", "active").orderBy("createdAt", "desc"), add:
- Field: status (Ascending)
- Field: createdAt (Descending)
7. Click Create Index
The index will take 1-5 minutes to build. Your queries will work once the index status shows "Enabled".
If you're seeing FAILED_PRECONDITION on transactions, implement retry logic:
import { getFirestore, runTransaction, doc } from "firebase/firestore";
const db = getFirestore();
const maxRetries = 3;
let retries = 0;
async function updateWithRetry() {
while (retries < maxRetries) {
try {
await runTransaction(db, async (transaction) => {
const userRef = doc(db, "users", "user123");
const userDoc = await transaction.get(userRef);
if (!userDoc.exists()) throw new Error("Document not found");
transaction.update(userRef, {
score: userDoc.data().score + 10,
});
});
console.log("Transaction succeeded");
break;
} catch (error: any) {
if (error.code === "failed-precondition" && retries < maxRetries - 1) {
const delay = Math.pow(2, retries) * 100; // 100ms, 200ms, 400ms
await new Promise((resolve) => setTimeout(resolve, delay));
retries++;
} else {
throw error;
}
}
}
}This exponential backoff gives competing transactions time to complete before retrying.
FAILED_PRECONDITION can sometimes be a masked security rule denial. Check your rules:
1. Go to Firebase Console > Firestore > Rules tab
2. Ensure your rules allow the operation. Example:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
// Allow authenticated users to read/write their own documents
allow read, write: if request.auth.uid == userId;
}
match /posts/{postId} {
// Allow reads, require authentication for writes
allow read: if true;
allow write: if request.auth != null;
}
}
}3. Click Publish to apply rule changes
4. Retry your operation
If you're encountering FAILED_PRECONDITION in Cloud Functions:
1. Start the Firebase Emulator Suite:
firebase emulators:start2. Update your code to use the emulator:
import { connectFirestoreEmulator, getFirestore } from "firebase/firestore";
if (process.env.NODE_ENV === "development") {
connectFirestoreEmulator(getFirestore(), "localhost", 8080);
}3. Run your test against the emulator to see clearer error messages
4. Once tests pass locally, deploy to production:
firebase deploy --only functions,firestoreCollection group queries require explicit indexes:
1. Use collectionGroup() in your code:
const q = query(
collectionGroup(db, "comments"),
where("authorId", "==", userId),
orderBy("createdAt", "desc")
);2. Firestore will log an index creation link. Click it, or manually create it in:
- Firebase Console > Firestore > Indexes > Create Index
- Collection: Leave blank for collection group
- Fields: authorId (Ascending), createdAt (Descending)
3. Wait for the index to build (1-5 minutes), then retry the query.
Advanced notes
FAILED_PRECONDITION is Firestore's primary mechanism for enforcing consistency. Unlike some databases that silently ignore constraints, Firestore explicitly fails the operation rather than allowing corrupted state.
Transaction Internals: Firestore uses optimistic concurrency control. When you call runTransaction(), it reads documents at a snapshot in time, executes your transaction function, then tries to commit. If any read document changed between the read and commit, Firestore rejects the entire transaction with FAILED_PRECONDITION to prevent data inconsistency. Retrying with backoff is the correct pattern here.
Composite Index Performance: A missing index doesn't mean your query is impossible—Firestore could do a full collection scan, but that's expensive and slow. By requiring an index, Firestore guarantees O(log n) query performance and prevents runaway costs from accidental full scans.
Emulator Quirks: The Firebase Emulator Suite may have stale state from previous test runs. If you continue seeing FAILED_PRECONDITION after creating indexes, try restarting the emulator with firebase emulators:start --clear.
Frequently asked questions
- What does "FAILED_PRECONDITION: The system is not in a state required for the ope" mean?
- Firebase Firestore returns this error when an operation is rejected because the system is not in the required state to complete it. This is Firestore's way of enforcing data consistency and preventing invalid operations. The error can occur in several contexts: (1) Composite indexes are missing for queries that combine multiple filters or sorting, (2) A transaction is attempting to modify a document that has changed since the transaction began (optimistic concurrency control), (3) A document is currently locked by another concurrent write operation, or (4) Security rules or emulator configuration is preventing the operation.
- How do I fix "FAILED_PRECONDITION: The system is not in a state required for the ope"?
- The FAILED_PRECONDITION error occurs when a Firestore operation fails because necessary preconditions (like composite indexes or transaction constraints) are not met. Most commonly caused by missing indexes on compound queries combining where() and orderBy().
- What causes "FAILED_PRECONDITION: The system is not in a state required for the ope"?
- Missing composite index for compound queries - Most common. Queries combining where() and orderBy(), or multiple where() clauses, require explicit indexes in Firebase Console. Transaction document conflict - Another client modified a document your transaction is trying to update, triggering optimistic concurrency control protection. Document locked by concurrent write - Attempting simultaneous writes to the same document while another operation has it locked.
- Is the "FAILED_PRECONDITION: The system is not in a state required for the ope" error serious?
- It is a medium-severity error — more of a blocker than a risk. The steps above resolve it.
Official resources & further reading
- 📚Firebase Official Documentation
- 📖firebase.google.com - firestore(Official Docs)
- 📖firebase.google.com - Precondition(Official Docs)
- 🐙github.com - 5871(GitHub)
- 🐙github.com - 453(GitHub)
- 🐙github.com - 1866(GitHub)
- 🐙github.com - 515(GitHub)
- 🐙github.com - 3737(GitHub)