Limit and pagination in Firebase - Time & Space Complexity
When fetching data from Firebase, using limits and pagination helps control how much data you get at once.
We want to understand how the number of data fetches grows as we ask for more pages.
Analyze the time complexity of fetching paged data with limits.
const pageSize = 10;
let lastVisible = null;
async function fetchNextPage() {
let query = firestore.collection('items').orderBy('name').limit(pageSize);
if (lastVisible) {
query = query.startAfter(lastVisible);
}
const snapshot = await query.get();
lastVisible = snapshot.docs[snapshot.docs.length - 1];
return snapshot.docs.map(doc => doc.data());
}
This code fetches items in pages of 10, starting after the last item from the previous page.
- Primary operation: Firestore query with limit and startAfter to fetch a page.
- How many times: Once per page requested by the user.
Each page fetch makes one query call that returns a fixed number of items.
| Input Size (pages requested) | Approx. Api Calls/Operations |
|---|---|
| 1 | 1 query call |
| 10 | 10 query calls |
| 100 | 100 query calls |
Pattern observation: The number of query calls grows linearly with the number of pages requested.
Time Complexity: O(n)
This means if you want to see more pages, the number of queries grows directly with how many pages you fetch.
[X] Wrong: "Fetching page 10 is just one query, so it takes the same time as page 1 regardless of previous pages."
[OK] Correct: Each page requires a separate query call, so fetching page 10 means you have made 10 queries in total, one for each page.
Understanding how pagination affects query calls helps you design apps that load data smoothly and efficiently.
What if we changed the page size from 10 to 100? How would the time complexity change?
Practice
limit() function do in Firebase queries?Solution
Step 1: Understand the purpose of
Thelimit()limit()function is used to control how many documents are returned in a query result.Step 2: Compare options with
Only It restricts the number of documents returned by the query. correctly describes thatlimit()behaviorlimit()restricts the number of documents returned.Final Answer:
It restricts the number of documents returned by the query. -> Option AQuick Check:
limit() controls result count = B [OK]
- Confusing limit() with orderBy()
- Thinking limit() filters data
- Assuming limit() deletes data
Solution
Step 1: Recall correct method chaining order
In Firebase,orderBy()must come beforelimit()to sort then limit results.Step 2: Check each option's method order and parameters
db.collection('posts').orderBy('timestamp').limit(5) correctly orders by 'timestamp' then limits to 5 documents. Others have wrong order or invalid parameters.Final Answer:
db.collection('posts').orderBy('timestamp').limit(5) -> Option BQuick Check:
orderBy before limit = C [OK]
- Placing limit() before orderBy()
- Passing limit a field name
- Using orderBy with a number parameter
const firstPage = await db.collection('items').orderBy('name').limit(3).get();
const lastVisible = firstPage.docs[firstPage.docs.length - 1];
const nextPage = await db.collection('items').orderBy('name').startAfter(lastVisible).limit(3).get();
console.log(nextPage.docs.length);What will be printed if the collection has 7 documents?
Solution
Step 1: Analyze first page query
The first query orders by 'name' and limits to 3 documents, so it gets documents 1 to 3.Step 2: Analyze next page query
The next query starts after the last document of the first page and limits to 3 documents. Since total is 7, remaining documents are 4 (docs 4 to 7), but limit(3) returns 3 documents.Final Answer:
3 -> Option AQuick Check:
7 total - 3 first page = 4 remaining, limit(3) = 3 [OK]
- Assuming next page always has same limit count
- Ignoring startAfter effect
- Counting all documents again
const firstPage = await db.collection('users').limit(5).orderBy('age').get();What is the error and how to fix it?
Solution
Step 1: Identify method order error
Firebase requiresorderBy()beforelimit()to sort data before limiting.Step 2: Fix by swapping method calls
Change code todb.collection('users').orderBy('age').limit(5).get()to fix the error.Final Answer:
Error: orderBy must come before limit; fix by swapping the methods. -> Option CQuick Check:
orderBy before limit fixes error = A [OK]
- Calling limit before orderBy
- Passing field name to limit
- Calling get() too early
Solution
Step 1: Calculate documents fetched in first two pages
Each page shows 5 documents, so first two pages fetch 5 + 5 = 10 documents.Step 2: Calculate remaining documents for third page
Total documents are 12, so remaining are 12 - 10 = 2 documents.Step 3: Consider limit on third page
Limit is 5, but only 2 documents remain, so third page returns 2 documents.Final Answer:
2 -> Option DQuick Check:
12 - 10 = 2 documents left for page 3 [OK]
- Assuming all pages have full 5 documents
- Ignoring total document count
- Confusing page number with document count
Ready to prove it?
Pass the test and this pattern moves unknown
