skip to content

In Cloud Firestore on Android, how do snapshot listener metadata flags reveal unsynced writes and cached data, and how is offline persistence configured?

level: middleimportance: should knowfreq 55%

answer

  1. latency compensation
  2. pending versus cached
  3. metadata-only events are skipped
  4. persistent cache is the Android default
  5. settings before first use

basics

~10 s

Android snapshot listeners fire at once for local writes, flagged by hasPendingWrites, and mark cache-served data with isFromCache; metadata-only changes need MetadataChanges.INCLUDE. Persistence is on by default and tuned with setLocalCacheSettings and PersistentCacheSettings.

solid answer

~50 s

When the app writes a comment, Firestore applies it to the local cache and fires listeners at once. This is latency compensation, and the snapshot's `metadata.hasPendingWrites()` is true. When the backend confirms the write, only the metadata changes, so the listener stays silent unless it was attached with `MetadataChanges.INCLUDE`. That is how a Saving badge learns to clear. `metadata.isFromCache` true means the data came from the cache and may be stale or incomplete, which is the right signal for an offline banner. On Android, disk persistence is on by default with a 100 MB cache threshold. I configure it with `setLocalCacheSettings` and `PersistentCacheSettings` or `MemoryCacheSettings`, which replaced the deprecated `setPersistenceEnabled` and `setCacheSizeBytes` in firebase-firestore 24.6.0, and I apply settings before any other Firestore call. Default callbacks run on the main thread, and I remove the `ListenerRegistration` when the screen goes away.

code

kotlin · 31 lines
kotlin
import android.util.Log
import com.google.firebase.Firebase
import com.google.firebase.firestore.ListenerRegistration
import com.google.firebase.firestore.MetadataChanges
import com.google.firebase.firestore.firestore
import com.google.firebase.firestore.firestoreSettings
import com.google.firebase.firestore.persistentCacheSettings

private const val TAG = "Tasks"

fun configureFirestore() {
    // Must run before any other call on this FirebaseFirestore instance.
    Firebase.firestore.firestoreSettings = firestoreSettings {
        setLocalCacheSettings(persistentCacheSettings { setSizeBytes(200L * 1024 * 1024) })
    }
}

fun listenToTasks(projectId: String): ListenerRegistration =
    Firebase.firestore.collection("projects").document(projectId)
        .collection("tasks")
        .addSnapshotListener(MetadataChanges.INCLUDE) { snapshot, error ->
            if (error != null) {
                Log.w(TAG, "Listen failed; no further events", error)
                return@addSnapshotListener
            }
            val tasks = snapshot ?: return@addSnapshotListener
            Log.d(TAG, "offline banner: ${tasks.metadata.isFromCache}")
            for (doc in tasks.documents) {
                Log.d(TAG, "${doc.id} saving=${doc.metadata.hasPendingWrites()}")
            }
        }

go deeper

for a junior

Recall that a snapshot listener fires on every change, including your own writes before the server confirms them, and that you remove it when the screen goes away.

for a middle

Explain hasPendingWrites versus isFromCache, why metadata-only changes need MetadataChanges.INCLUDE, and how setLocalCacheSettings configures the Android cache.

for a senior

Show you build offline and saving states from these flags correctly, apply settings before first use, and handle a listener that dies on error.

for a principal

Weigh cache size and memory versus disk caching against device storage and stale-data risk, and set one team pattern for listener lifecycle and offline states.

## Latency compensation and hasPendingWrites A **snapshot listener** (`addSnapshotListener` on a `DocumentReference` or `Query`) delivers an initial snapshot and then a new one each time the result changes. When your own app writes, Firestore does not wait for the server. It applies the write to the local cache and **fires listeners immediately**. The documentation calls this **latency compensation**. Every snapshot carries `SnapshotMetadata`: - `hasPendingWrites()`: true when the snapshot includes local writes the backend has not yet confirmed; - `isFromCache()`: true when the data came from the local cache and *might be stale or incomplete*; false when it is current with the server. The two flags answer different questions. `hasPendingWrites` is about **your unconfirmed writes**. `isFromCache` is about **where the data came from**. A snapshot can be from the cache with no pending writes, for example the first snapshot after the app starts offline. ## Metadata-only events Consider a member adding a comment in the team task app: 1. A snapshot fires at once with the new comment, and `hasPendingWrites()` is true. 2. The write reaches the backend. 3. The backend confirms it. The data has not changed, but `hasPendingWrites()` is now false. That is a **metadata-only change**. **By default, listeners are not notified of metadata-only changes.** A UI that shows a Saving label from `hasPendingWrites()` would never clear it. Attach with `MetadataChanges.INCLUDE`, or use `SnapshotListenOptions.Builder().setMetadataChanges(MetadataChanges.INCLUDE)`, to receive that event. The same applies when you need `isFromCache` to flip from true to false once the server answers. If you only need to know that one write finished, the write's own `Task` is simpler. ## Reading from the cache on purpose | API | Behaviour | |---|---| | `get()` (`Source.DEFAULT`) | tries the server, falls back to cached data | | `get(Source.SERVER)` | server only; errors if unreachable | | `get(Source.CACHE)` | cache only; a missing document errors, a query returns an empty snapshot | | listener with `ListenSource.DEFAULT` | initial snapshot from cache, then server updates | | listener with `ListenSource.CACHE` | cache only; fires on local writes, never fetches | ## Configuring persistence on Android - On Android, offline persistence is **on by default**: a persistent disk cache with a **100 MB** threshold. Past the threshold, the SDK periodically cleans up documents that have not been used recently. The minimum is 1 MB, and `CACHE_SIZE_UNLIMITED` disables cleanup. - Since **firebase-firestore 24.6.0**, configure the cache with `FirebaseFirestoreSettings.Builder.setLocalCacheSettings`, passing either `PersistentCacheSettings` (with `setSizeBytes`) or `MemoryCacheSettings`. The older `setPersistenceEnabled` and `setCacheSizeBytes` are **deprecated**. Mixing old and new APIs throws. - Settings must be applied **before any other call** on the `FirebaseFirestore` instance. Changing them afterwards throws `IllegalStateException`, unless the new settings are identical to the current ones. - While offline, the app can read, write, listen and query against the cache. On reconnect, local changes sync, and for several changes to one document the last write wins. Designing an offline-first app around this, with outboxes and conflict policies, belongs to mobile system design. ```kotlin val db = Firebase.firestore db.firestoreSettings = firestoreSettings { setLocalCacheSettings(persistentCacheSettings { setSizeBytes(200L * 1024 * 1024) }) } ``` ## Listener lifecycle and threads - With no executor argument, callbacks run on the **main thread**. Pass an `Executor` to move heavy mapping elsewhere. - `addSnapshotListener` returns a `ListenerRegistration`. Call `remove()` when the screen goes away, or use the overload that takes an `Activity`, which removes the listener in `onStop`. - The Kotlin `snapshots()` extension returns a `Flow`. It attaches the listener when collection starts and removes it when collection ends. - If a listen fails, for example on a permission error or an invalid query, the callback receives a `FirebaseFirestoreException` and **the listener gets no further events**. Re-attach once the cause is fixed. ## Mistakes that show up in code review - Reading `hasPendingWrites() == false` as *this came from the server*. It only says the snapshot holds no unconfirmed local writes; `isFromCache` answers the freshness question. - Attaching a listener every time a screen starts without removing the old one. Each return to the screen adds another live listener, and with it more network traffic and duplicate callbacks. - Setting `firestoreSettings` from a later screen after an earlier one has already queried. That throws, so configure Firestore once, at app start. - Treating an empty `get(Source.CACHE)` query result as *there are no tasks*, when it may only mean *nothing is cached yet*.

  • Why does a Saving badge driven by hasPendingWrites never clear on some screens?
    When the backend confirms the write, the document data is unchanged and only `hasPendingWrites()` flips to false. Listeners skip metadata-only changes by default, so no new snapshot arrives and the UI keeps the stale flag. Attach the listener with `MetadataChanges.INCLUDE`, or watch the write's own `Task` when only that one write matters.
  • What happens to a task listener when the query is denied by security rules?
    The callback receives a `FirebaseFirestoreException`, in this case with code `PERMISSION_DENIED`, and after an error the listener receives no more events, so there is nothing to detach. Fix the cause, for example wait for sign-in, then attach a new listener. Which reads the rules allow is a question for Firestore's security rules.
  • How do you read the task list without touching the network?
    For a one-off read, `get(Source.CACHE)` answers from the cache immediately. A document that is not cached returns an error, while a query returns an empty snapshot. For a live view, pass `SnapshotListenOptions.Builder().setSource(ListenSource.CACHE).build()` to `addSnapshotListener`. The listener then reacts to local writes and cache updates and never fetches from the server, so its data may be stale.

  • hasPendingWrites false means the snapshot came from the server and is current.
  • On Android you must enable Firestore persistence before anything is cached offline.
  • setPersistenceEnabled(true) is the current way to configure Firestore's Android cache.
  • Firestore settings can be changed at any time, even after the first query.
  • A Firestore listener that hits an error retries and resumes on its own.

Assumes firebase-firestore 24.6.0 or later, where setLocalCacheSettings replaced the deprecated setPersistenceEnabled and setCacheSizeBytes.