Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 31 Β· Firebase Cloud Firestore

Realtime Listeners and Offline Support

Use Firestore onSnapshot for live updates, understand the local cache, pending writes and unsubscribing, count listener cost, and enable offline persistence.

The feature that made Firebase famous is that the database pushes changes to your app. Instead of asking "has anything changed?" on a timer, you register a listener on a document or a query. Firestore calls it once with the current data and again every time that data changes, on any device. Chat apps, live dashboards and shared to-do lists become a few lines of code.

Listeners also change how writes feel. Firestore keeps a local cache on the device, so your own writes show up in the UI immediately, before the server confirms them, and the app keeps working with no connection. This lesson explains listeners, the metadata that tells you what is confirmed, the cost of listening, and offline mode. You should already know queries and writes.

The real SDK needs a Firebase project, so its code here is read-only. The runnable examples are small stand-ins (an observer pattern and an offline queue) that show the behaviour. They are not Firestore's network protocol or cache.

onSnapshot

getDoc and getDocs fetch once. onSnapshot subscribes:

JavaScript
import { getFirestore, doc, collection, query, where, orderBy, onSnapshot } from "firebase/firestore";

const db = getFirestore();

// Listen to one document
const unsubscribeDoc = onSnapshot(doc(db, "rooms", "general"), snap => {
  console.log("Room is now:", snap.data());
});

// Listen to a query
const q = query(collection(db, "messages"), where("room", "==", "general"), orderBy("createdAt"));
const unsubscribeQuery = onSnapshot(q, snapshot => {
  snapshot.docChanges().forEach(change => {
    // change.type is "added", "modified" or "removed"
    console.log(change.type, change.doc.id, change.doc.data());
  });
});

The first call delivers the full current result. After that, each call delivers the new state of the whole result, and docChanges() tells you which documents were added, modified or removed. If you only need to update a list incrementally, use docChanges(); if you just re-render, snapshot.docs is enough.

onSnapshot returns a function. Call it to stop listening, for example when a component unmounts or a user leaves a screen:

JavaScript
unsubscribeDoc();
unsubscribeQuery();

Forgetting to unsubscribe is the most common listener bug. The connection stays open, callbacks keep firing on screens nobody sees, and you pay for the updates.

Try it: an observer stand-in

The stand-in below stores documents and calls every subscriber when a document changes. It also counts "delivered updates" as a rough model of listener cost, and shows what happens after you unsubscribe.

JS A listener with unsubscribe and a delivery counter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Listener A received the initial empty state, then three changes. B stopped after two changes and never saw "Retro". Once both unsubscribed, writes cost nothing in deliveries.

Metadata: what is confirmed?

Every snapshot carries metadata with two flags:

  • hasPendingWrites is true when the snapshot includes a local write that the server has not confirmed yet.
  • fromCache is true when the data came from the local cache rather than the server.
JavaScript
onSnapshot(doc(db, "tasks", "t1"), snap => {
  const status = snap.metadata.hasPendingWrites ? "saving..." : "saved";
  console.log(snap.data().title, status, snap.metadata.fromCache ? "(cache)" : "(server)");
});

This is how apps show a small "Saving…" indicator or grey out a message until it is confirmed.

Optimistic writes and latency compensation

When you call setDoc or updateDoc, the SDK applies the change to the local cache at once and fires your listeners with hasPendingWrites: true. It then sends the write to the server in the background. When the server accepts it, listeners fire again with hasPendingWrites: false. If a security rule rejects the write, the SDK rolls the local change back, and your listener fires again with the old data. This pattern is called latency compensation or an optimistic update: the UI feels instant, and rare failures correct themselves.

One consequence: a listener can fire twice for one write, once for the local change and once for confirmation. Do not run side effects (like a notification) on every callback; check the metadata or use a server-side trigger instead.

Offline support

On mobile SDKs (Android and iOS) the local cache is persisted to disk by default. On the web, it is memory-only unless you turn on persistence when you initialize Firestore:

JavaScript
import { initializeApp } from "firebase/app";
import { initializeFirestore, persistentLocalCache, persistentMultipleTabManager } from "firebase/firestore";

const app = initializeApp(firebaseConfig);

const db = initializeFirestore(app, {
  localCache: persistentLocalCache({ tabManager: persistentMultipleTabManager() }),
});

With persistence, reads that were cached before still work with no connection, and writes made offline are queued on the device and sent when the connection returns. Listeners fire with fromCache: true while offline. Behaviours to design for:

  • Reads of uncached data return nothing, or an error for getDoc on a document that was never cached.
  • Write promises do not resolve offline. await setDoc(...) waits for server confirmation, so an offline write can seem to hang. For responsive UIs, update the UI from the listener rather than awaiting the write.
  • Order and conflicts: queued writes are applied in order. Two devices editing the same field offline resolve by "last write wins" per field, so use increment and arrayUnion where merging matters.
  • Cache size is limited, and old data is garbage collected.

Try it: an offline write queue

This stand-in has a local cache, a queue of pending writes and an online switch. Watch how the metadata flags change as the client goes offline, writes, and reconnects.

JS Pending writes, cache flags and reconnecting

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first write was confirmed instantly because the client was online. The offline write showed up in the UI with pending: true, stayed out of the server, and was delivered after reconnecting.

Listener cost and good habits

Firestore bills one read for each document a query returns the first time, and one more read for each document that changes afterwards and is delivered to your listener. Practical rules:

  • Limit the query. A listener on an unbounded collection downloads everything. Use limit(), a date filter, or a room filter.
  • Prefer narrow listeners. Listen to the single document a screen shows, not the whole collection.
  • Unsubscribe when the screen closes. A listener that was disconnected for a long time (about 30 minutes or more) may have to fetch its whole result again, which bills those reads again.
  • Share listeners. Two components listening to the same query can use one listener and a shared store.
  • Avoid hot documents. A single document that thousands of clients listen to and many people write to will be slow and expensive; split it up.
  • Use a cached read first (getDocFromCache) for data that rarely changes.

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. What does onSnapshot return?

    It returns an unsubscribe function. Call it when the screen or component goes away.
  2. 2. You call updateDoc while online. How many times can your listener fire for that one write?

    Latency compensation applies your change locally first, then fires again when the server confirms.
  3. 3. What does hasPendingWrites: true tell you?

    It marks local, unconfirmed writes. It is how you show a saving indicator.
  4. 4. On the web, how do you make Firestore data survive reloads and work offline?

    The web cache is memory-only unless you configure persistentLocalCache. Mobile SDKs persist by default.

Summary

  • onSnapshot listens to a document or query and calls you with the current state and every later change.
  • Always call the returned unsubscribe function when you stop caring.
  • metadata.hasPendingWrites and fromCache show what the server has confirmed.
  • Writes apply locally first (optimistic updates) and roll back if rejected.
  • Offline mode queues writes and serves cached reads; enable persistence explicitly on the web.
  • Listeners are billed per delivered document, so limit queries and stay narrow.

Next: Supabase and Postgres Fundamentals.