Query optimization in Firebase - Time & Space Complexity
When using Firebase to get data, how fast the query runs matters a lot. We want to know how the time it takes changes when we ask for more data or add filters.
We ask: How does the number of operations grow as we change the query?
Analyze the time complexity of the following operation sequence.
const db = firebase.firestore();
const query = db.collection('users')
.where('age', '>=', 18)
.orderBy('age')
.limit(50);
const snapshot = await query.get();
This code fetches up to 50 users who are 18 or older, sorted by age.
Identify the API calls, resource provisioning, data transfers that repeat.
- Primary operation: The query.get() call that fetches documents from the database.
- How many times: This call happens once per query, but internally it may scan multiple documents to find matches.
As the number of matching documents grows, the query scans more data to find the right results.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | Scans about 10 documents to find matches |
| 100 | Scans about 50 documents to find matches |
| 1000 | Scans about 50 documents to find matches |
Pattern observation: The number of documents scanned grows roughly linearly with the number of matching documents up to the limit (50), then remains constant.
Time Complexity: O(1)
This means the time to run the query is constant, bounded by the fixed limit of 50 documents checked.
[X] Wrong: "Adding a limit means Firebase scans all matching documents before applying the limit."
[OK] Correct: Firebase applies the limit during query execution, stopping after reading up to 50 matching documents.
Understanding how queries scale helps you design better apps and answer questions about performance clearly and confidently.
"What if we added an index on the 'age' field? How would the time complexity change?"
Practice
Solution
Step 1: Understand query optimization purpose
Query optimization aims to improve performance and reduce costs by limiting data fetched.Step 2: Identify correct benefit
Only "It makes your app faster and reduces costs by fetching only needed data." describes faster app and cost reduction by fetching needed data.Final Answer:
It makes your app faster and reduces costs by fetching only needed data. -> Option AQuick Check:
Query optimization = faster app and lower cost [OK]
- Thinking optimization backs up data
- Assuming optimization increases database size
- Confusing optimization with security settings
Solution
Step 1: Check correct method order
In Firebase, orderBy must come before limit to sort then limit results.Step 2: Validate syntax correctness
db.collection('games').orderBy('score').limit(10) uses correct chaining: orderBy('score').limit(10). Others misuse order or parameters.Final Answer:
db.collection('games').orderBy('score').limit(10) -> Option AQuick Check:
orderBy then limit = correct syntax [OK]
- Placing limit before orderBy
- Using where instead of limit for count
- Passing number as second orderBy argument
db.collection('users').where('age', '>=', 18).orderBy('age').limit(3)What will this query return?
Solution
Step 1: Analyze where and orderBy fields
Both where and orderBy use 'age', which is allowed and required for range filters.Step 2: Understand limit effect
Limit(3) returns only first 3 documents matching criteria ordered by age ascending.Final Answer:
The first 3 users aged 18 or older, ordered by age ascending. -> Option CQuick Check:
where and orderBy on same field + limit = first 3 matching [OK]
- Thinking it returns users younger than 18
- Assuming error due to different fields
- Ignoring limit effect
db.collection('orders').where('status', '==', 'shipped').orderBy('date')But it throws an error about missing index. What should you do?
Solution
Step 1: Understand composite index requirement
Queries with where and orderBy on different fields need a composite index in Firebase.Step 2: Fix error by creating index
Creating a composite index on 'status' and 'date' fields resolves the error.Final Answer:
Create a composite index on 'status' and 'date' fields in Firebase console. -> Option BQuick Check:
Missing index error = create composite index [OK]
- Removing orderBy instead of indexing
- Changing operators incorrectly
- Using limit to bypass index requirement
Solution
Step 1: Check correct chaining and order
db.collection('users').where('active', '==', true).where('score', '>', 50).orderBy('score', 'desc').limit(5) correctly chains where filters first, then orderBy with descending, then limit.Step 2: Validate query logic
It filters active users with score > 50, orders by score descending, and limits to 5 results as required.Final Answer:
db.collection('users').where('active', '==', true).where('score', '>', 50).orderBy('score', 'desc').limit(5) -> Option DQuick Check:
Filter then orderBy desc then limit = optimized query [OK]
- Placing limit before where
- Incorrect orderBy direction
- Missing one of the filters
Ready to prove it?
Pass the test and this pattern moves unknown
