Cursor-based pagination (startAfter, endBefore) in Firebase - Time & Space Complexity
When using cursor-based pagination in Firebase, we want to know how the number of operations changes as we ask for more data pages.
We ask: How does fetching pages with cursors affect the work Firebase does?
Analyze the time complexity of the following operation sequence.
const pageSize = 10;
let lastVisible = null;
// Fetch first page
const firstPage = await firestore.collection('items')
.orderBy('createdAt')
.limit(pageSize)
.get();
lastVisible = firstPage.docs[firstPage.docs.length - 1];
// Fetch next page using cursor
const nextPage = await firestore.collection('items')
.orderBy('createdAt')
.startAfter(lastVisible)
.limit(pageSize)
.get();
This code fetches a page of items ordered by creation time, then fetches the next page starting after the last item of the previous page.
Identify the API calls, resource provisioning, data transfers that repeat.
- Primary operation: Querying Firestore with a cursor and limit to fetch a page of documents.
- How many times: Once per page requested by the user.
Each page fetch asks for a fixed number of documents, so the work per page stays about the same.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 (1 page) | 1 query fetching 10 documents |
| 100 (10 pages) | 10 queries each fetching 10 documents |
| 1000 (100 pages) | 100 queries each fetching 10 documents |
Pattern observation: The number of queries grows linearly with the number of pages requested, but each query fetches a fixed number of documents.
Time Complexity: O(p)
This means the total work grows linearly with the number of pages fetched, but each page fetch cost stays constant.
[X] Wrong: "Fetching the next page with startAfter means Firebase scans all previous documents again, so cost grows with total data size."
[OK] Correct: Firebase uses indexes and the cursor to jump directly to the start point, so each page fetch only reads the page size number of documents, not all before it.
Understanding how cursor-based pagination scales helps you design smooth user experiences and efficient data fetching in real apps.
"What if we changed from fixed page size to fetching all documents up to the cursor each time? How would the time complexity change?"
Practice
startAfter method do in Firebase cursor-based pagination?Solution
Step 1: Understand the purpose of
startAfterstartAftertells Firebase to begin loading documents after the given document snapshot, skipping that snapshot itself.Step 2: Compare with other cursor methods
endBeforestops before a snapshot, butstartAftermoves forward after it.Final Answer:
It starts loading documents after a specific document snapshot. -> Option DQuick Check:
startAfter= start after snapshot [OK]
- Confusing startAfter with endBefore
- Thinking startAfter includes the given document
- Assuming startAfter loads all documents from start
lastDoc in Firebase?Solution
Step 1: Recall Firebase query cursor methods
The correct method to start after a document isstartAfter().Step 2: Match method with snapshot variable
UsingstartAfter(lastDoc)correctly applies the cursor after thelastDocsnapshot.Final Answer:
query.startAfter(lastDoc) -> Option AQuick Check:
Correct method is startAfter() [OK]
- Using non-existent methods like endAfter or startBefore
- Mixing up startAfter and endBefore
- Forgetting to pass the snapshot as argument
const firstPage = await collection.orderBy('name').limit(3).get();
const nextPage = await collection.orderBy('name').startAfter(firstPage.docs[2]).limit(3).get();Solution
Step 1: Understand firstPage query
The first query orders by 'name' and limits to 3 documents, so it returns documents 1, 2, and 3.Step 2: Understand nextPage query with startAfter
UsingstartAfter(firstPage.docs[2])starts after the third document, so nextPage returns documents 4, 5, and 6.Final Answer:
Documents 1 to 3 on firstPage, documents 4 to 6 on nextPage -> Option AQuick Check:
startAfter skips last doc, nextPage continues [OK]
- Assuming startAfter includes the last document again
- Confusing document indexes (0-based vs 1-based)
- Not ordering consistently before pagination
const prevPage = await collection.orderBy('date').endBefore(lastDoc).limitToLast(3).get();
What is the likely cause?Solution
Step 1: Check cursor snapshot origin
The snapshotlastDocmust come from a query with the same ordering and filters.Step 2: Understand error cause
IflastDocis from a different query or unordered, Firebase throws an error.Final Answer:
ThelastDocsnapshot is not from the same query order -> Option CQuick Check:
Cursor snapshot must match query order [OK]
- Using snapshot from different query or order
- Mixing startAfter and endBefore incorrectly
- Ignoring need for consistent ordering
currentDoc. Which Firebase query correctly achieves this?Solution
Step 1: Understand backward pagination
To load documents beforecurrentDoc, useendBefore(currentDoc).Step 2: Use limitToLast for correct order
UsinglimitToLast(5)returns the last 5 documents beforecurrentDocin correct order.Final Answer:
collection.orderBy('timestamp').endBefore(currentDoc).limitToLast(5) -> Option BQuick Check:
Backward pagination uses endBefore + limitToLast [OK]
- Using startAfter for backward pagination
- Using limit instead of limitToLast when going backward
- Confusing endBefore with endAt
Ready to prove it?
Pass the test and this pattern moves unknown
