Skip to content

Firestore Pagination — Complete Guide

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about Firestore Pagination. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

You use offset() for pagination and your bill skyrockets because Firestore reads all documents up to the offset on every query.

Wrong Approach ❌

// Offset-based pagination — expensive!
db.collection("posts")
    .orderBy("createdAt")
    .limit(20)
    .offset(page * 20) // Firestore reads page*20 documents!
    .get()

Output: Reading page 10 reads 200 documents but only returns 20. Massive read costs.

Right Approach ✅

class PostRepository(private val db: FirebaseFirestore) {

    // Cursor-based pagination
    suspend fun loadPosts(
        lastVisible: DocumentSnapshot?, // null for first page
        pageSize: Long = 20
    ): Pair<List<Post>, DocumentSnapshot?> {
        var query: Query = db.collection("posts")
            .orderBy("createdAt", Query.Direction.DESCENDING)
            .limit(pageSize)

        // Start after the last document from previous page
        lastVisible?.let { query = query.startAfter(it) }

        val snapshot = query.get().await()
        val posts = snapshot.toObjects(Post::class.java)
        val lastDoc = snapshot.documents.lastOrNull()

        return Pair(posts, lastDoc)
    }

    // Paginated with real-time listener
    fun observePostsPaginated(
        pageSize: Long = 20
    ): Flow<List<Post>> = callbackFlow {
        var lastVisible: DocumentSnapshot? = null
        val allPosts = mutableListOf<Post>()

        // Initial load
        val query = db.collection("posts")
            .orderBy("createdAt", Query.Direction.DESCENDING)
            .limit(pageSize)

        val registration = query.addSnapshotListener { snapshot, error ->
            if (error != null) {
                cancel(error.message ?: "Error", error)
                return@addSnapshotListener
            }

            snapshot?.let { snap ->
                val newPosts = snap.toObjects(Post::class.java)
                allPosts.clear()
                allPosts.addAll(newPosts)
                lastVisible = snap.documents.lastOrNull()
                trySend(allPosts.toList())
            }
        }

        awaitClose { registration.remove() }
    }

    // Load more (next page)
    suspend fun loadMore(
        lastVisible: DocumentSnapshot,
        pageSize: Long = 20
    ): Pair<List<Post>, DocumentSnapshot?> {
        return loadPosts(lastVisible, pageSize)
    }
}

// Usage in ViewModel
class FeedViewModel(private val repo: PostRepository) : ViewModel() {
    private val _posts = MutableStateFlow<List<Post>>(emptyList())
    val posts: StateFlow<List<Post>> = _posts

    private var lastDoc: DocumentSnapshot? = null
    private var isLoading = false

    fun loadInitial() {
        viewModelScope.launch {
            val (posts, last) = repo.loadPosts(null)
            _posts.value = posts
            lastDoc = last
        }
    }

    fun loadMore() {
        if (isLoading) return
        isLoading = true
        viewModelScope.launch {
            lastDoc?.let { cursor ->
                val (newPosts, last) = repo.loadMore(cursor)
                _posts.value = _posts.value + newPosts
                lastDoc = last
            }
            isLoading = false
        }
    }
}

Output: Efficient cursor-based pagination. Only requested documents read.

Prevention

  • Use startAfter()/startAt() with document snapshots — never offset().
  • Always include orderBy() with pagination queries.
  • Use limit() to control page size.
  • Track the last visible document as the cursor.

Common Mistakes with firestore pagination

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. Non-exhaustive pattern matches that compile with warnings then crash at runtime

These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Why is offset() bad for pagination?

Firestore reads all documents up to the offset on the server. Reading page 10 with offset(200) reads 220 documents total. Cursor pagination reads only the requested page.

### What happens if a document is inserted between pages?

Cursor pagination based on orderBy ensures consistent ordering. New documents may shift positions, but you won't miss or duplicate items within a stable sort.

### Can I paginate by timestamp instead of document?

Yes. Use startAfter(timestamp) with the last document's timestamp value. This works but is less reliable than document cursors (duplicate timestamps can cause ambiguity).

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro