# Firestore Unexpected Read Spike: Fix onSnapshot Loops & Bills

> Canonical URL: https://stackquota.com/guides/firestore-unexpected-read-spike-snapshot-listener-loop/
> Checked: 2026-12-04 · Published: 2026-12-04

Stop runaway Firestore Blaze bills ($0.06/100k multi-region reads). Fix unbounded onSnapshot queries, React useEffect loops, and Security Rules get().

## How much does an unbounded Firestore read spike actually cost on Blaze?

**Quick answer:** Beyond the `50,000` free daily reads on the Firebase Blaze plan, Firestore charges `$0.03` per `100,000` reads in single-region locations and `$0.06` per `100,000` reads in multi-region locations (`nam5`, `eur3`). A single React render loop re-subscribing to a `1,000`-document collection at `5 Hz` across `200` active browser tabs burns `3.6 billion` reads per hour, costing `$2,160/hour` on a multi-region database.

Firestore's unit pricing looks microscopic in isolation, which is why runaway read incidents catch teams off guard after routine frontend deploys. Unlike provisioned Postgres where a bad query pegs CPU and stalls, similar to [Supabase connection pool exhaustion](/guides/supabase-max-client-connections-pgbouncer-serverless-fix/): Firestore scales horizontally while metering every document serialized by the storage engine.

The December 2026 billing rates show how quickly read amplification compounds against fixed-tier Postgres alternatives:

| Cost & Quota Metric | Firestore Single-Region (`us-east1`) | Firestore Multi-Region (`nam5` / `eur3`) | Supabase Pro (Baseline) | Neon Launch (Serverless PG) |
| :--- | :--- | :--- | :--- | :--- |
| **Base Monthly** | `$0/mo` (Pay-as-you-go) | `$0/mo` (Pay-as-you-go) | `$25/mo` (`$10` compute credit) | `$19/mo` (`300` compute hrs) |
| **Free Reads** | `50,000` docs/day | `50,000` docs/day | Compute-bound SQL | `300` compute hrs incl. |
| **Read Overage** | `$0.03` / `100k` reads | `$0.06` / `100k` reads | `$0` (`$0.09/GB` egress > `250 GB`) | `$0` (`$0.16/hr` > `300` hrs) |
| **Write Overage** | `$0.09` / `100k` writes | `$0.18` / `100k` writes | `$8 GB` DB incl. (`$0.125/GB`) | `10 GB` DB incl. (`$0.35/GB`) |
| **Egress Rate** | `$0.12/GB` (> `10 GB/mo`) | `$0.12/GB` (> `10 GB/mo`) | `$0.09/GB` (> `250 GB/mo`) | `$0.09/GB` (> `100 GB/mo`) |
| **100M Reads/Mo** | `~$29.55` | `~$59.10` | `$25.00` (Micro `$10` covered) | `$19.00` |
| **5B Loop (24h)** | `~$1,500.00` | `~$3,000.00` | `$25.00` (throttled by CPU) | Throttled by compute cap |

Multi-region Firestore (`nam5` or `eur3`) doubles both read (`$0.06` vs `$0.03` per `100k`) and write (`$0.18` vs `$0.09` per `100k`) rates. Plug your active users and listeners per screen into our [Supabase vs Firebase vs Neon cost calculator](/calculators/supabase-vs-firebase-cost/) to find the exact crossover point, or compare edge SQLite behavior in our [Cloudflare D1 rows-read spike fix](/guides/cloudflare-d1-rows-read-spike-unindexed-query-fix/).

## Why does unbounded onSnapshot() multiply document reads?

**Quick answer:** Calling `onSnapshot(collection(db, "items"))` without an explicit `limit()` bills one read for every document in the collection on initial mount and re-bills the entire collection whenever a client reconnects after more than `30 minutes` offline. Enforcing `orderBy()` plus `limit(25)` with cursor pagination caps initial and resume snapshots to a predictable ceiling.

Real-time listeners are Firestore's sharpest double-edged sword. When a client attaches `onSnapshot()` to a query, Firestore bills you for:

1. **Initial result set:** Every document currently matching the query (`N` documents = `N` reads, or a `1`-read minimum if `0` documents match).
2. **Incremental mutations:** `1` read every time a matching document is added, updated, or enters the query window while connected.
3. **30-minute disconnect penalties:** If a mobile app goes to the background or a laptop lid closes for more than `30 minutes`, Firestore invalidates the stream's resume token. When the tab wakes up, the SDK cannot request a cheap delta check, it executes a **full re-read** of every document matching the listener.

In early prototypes with `40` documents in `orders` or `chat_messages`, `onSnapshot(collection(db, "orders"))` feels instantaneous and free. Six months later, when that collection holds `18,000` documents, every browser refresh, tab wake-up, and route transition reads all `18,000` documents at once.

Replace every unbounded collection listener with a strictly bounded query and explicit cursor pagination for historical data:

```typescript
import {
  collection,
  query,
  where,
  orderBy,
  limit,
  startAfter,
  onSnapshot,
  getDocs,
  QueryDocumentSnapshot,
  DocumentData,
} from "firebase/firestore";
import { db } from "./firebase";

const PAGE_SIZE = 25;

// Live tail: strictly bounded to the 25 newest documents
export function subscribeRecentTickets(
  orgId: string,
  onData: (docs: QueryDocumentSnapshot<DocumentData>[]) => void,
  onError: (err: Error) => void
) {
  const ticketsQuery = query(
    collection(db, "tickets"),
    where("orgId", "==", orgId),
    orderBy("updatedAt", "desc"),
    limit(PAGE_SIZE) // Non-negotiable ceiling on live listeners
  );

  return onSnapshot(
    ticketsQuery,
    (snapshot) => {
      onData(snapshot.docs);
    },
    (error) => {
      console.error("Firestore listener failed:", error);
      onError(error);
    }
  );
}

// Historical pages: use one-shot getDocs() instead of expanding a live listener
export async function fetchOlderTicketsPage(
  orgId: string,
  lastCursor: QueryDocumentSnapshot<DocumentData>
) {
  const olderQuery = query(
    collection(db, "tickets"),
    where("orgId", "==", orgId),
    orderBy("updatedAt", "desc"),
    startAfter(lastCursor),
    limit(PAGE_SIZE)
  );

  const snapshot = await getDocs(olderQuery);
  return snapshot.docs;
}
```

Never paginate an `onSnapshot()` listener by incrementing `limit(25)` to `limit(50)`, `limit(75)`, and `limit(100)` inside state. Every time `limit()` changes, Firestore treats it as a brand-new query specification, re-evaluating the window from scratch. Keep your real-time listener pinned to the top `20–25` live items and load older history via one-time `getDocs()` calls.

## How do React useEffect dependency loops trigger Million-Read storms?

**Quick answer:** Passing inline objects or arrays into a React `useEffect` dependency array (or forgetting to return the `unsubscribe()` cleanup function) tears down and recreates `onSnapshot()` listeners on every render cycle. Stabilizing dependencies to primitive strings/numbers and enabling `persistentLocalCache` eliminates re-render subscription storms.

Roughly `70%` of emergency `$1,000+` weekend Firebase bills trace back to a single React hook anti-pattern. Consider what happens when a developer passes a filter object created during render into a custom hook, or updates React state inside `onSnapshot` while referencing that same state in the `useEffect` dependency list:

```tsx
// BROKEN: Triggers an infinite tear-down/re-subscribe loop on memory-cached clients
export function BrokenProjectFeed({ user }: { user: { orgId: string; roles: string[] } }) {
  const [projects, setProjects] = useState<Project[]>([]);

  // Inline object creates a brand-new memory reference on EVERY render
  const filterConfig = { orgId: user.orgId, allowedRoles: user.roles };

  useEffect(() => {
    const q = query(
      collection(db, "projects"),
      where("orgId", "==", filterConfig.orgId),
      limit(50)
    );

    // Bug 1: Missing `return unsubscribe;` leaks concurrent listeners!
    // Bug 2: setProjects triggers a re-render -> new `filterConfig` ref -> effect re-runs!
    onSnapshot(q, (snap) => {
      setProjects(snap.docs.map((d) => ({ id: d.id, ...(d.data() as Project) })));
    });
  }, [filterConfig]);

  return <ProjectTable items={projects} />;
}
```

By default, the modular Firebase Web SDK uses an **in-memory cache** (`memoryLocalCache`) unless you explicitly configure IndexedDB persistence. When using the default memory-only cache without active listener sharing, detaching and re-attaching a query (or leaking dozens of parallel listeners because `unsubscribe()` was omitted) forces repeated server round-trips. Even on a `50`-document query, re-running `useEffect` `6 times` per second burns `300` reads/sec per open browser tab.

Fix both layers permanently: configure multi-tab IndexedDB persistence at SDK initialization, and lock your `useEffect` dependencies strictly to primitive values (`string`, `number`, `boolean`) with mandatory cleanup:

```typescript
// firebase.ts — Enable IndexedDB cache shared safely across browser tabs
import { initializeApp } from "firebase/app";
import {
  initializeFirestore,
  persistentLocalCache,
  persistentMultipleTabManager,
} from "firebase/firestore";

const app = initializeApp({
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
});

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

```tsx
// FIXED: Primitive dependencies, deterministic cleanup, zero leaked listeners
export function SafeProjectFeed({ orgId }: { orgId: string }) {
  const [projects, setProjects] = useState<Project[]>([]);

  useEffect(() => {
    if (!orgId) return;

    const q = query(
      collection(db, "projects"),
      where("orgId", "==", orgId),
      orderBy("createdAt", "desc"),
      limit(50)
    );

    const unsubscribe = onSnapshot(q, (snap) => {
      setProjects(snap.docs.map((d) => ({ id: d.id, ...(d.data() as Project) })));
    });

    return () => unsubscribe();
  }, [orgId]); // Primitive string: only re-subscribes if orgId actually changes

  return <ProjectTable items={projects} />;
}
```

In development, wrap your Firestore query factory with a lightweight counter attached to `window.__firestoreSubscriptions` and fail Playwright E2E tests if mounting a route creates more than one subscription per query key.

## Are open Firebase console tabs and security rules secretly billing reads?

**Quick answer:** Yes, every document rendered inside the Firebase Console Data viewer bills standard Blaze document reads, and every `get()` or `exists()` lookup inside Firestore Security Rules bills `1` additional read per unique document path evaluated. Close idle Console tabs and move tenant roles into Firebase Auth Custom Claims to drop rule-evaluation reads to zero.

When teams investigate a read spike and find zero client anomalies in frontend telemetry, the culprit is usually one of two server-side blind spots:

### 1. the open Firebase console trap
The Firestore Data viewer in the Firebase Console attaches live listeners directly to production collections to render trees, previews, and cell updates. Leaving the Console open on a high-churn `events` or `sessions` collection across multiple engineering laptops bills standard Blaze reads on every mutation and scroll. During an incident, inspect read rates in **Google Cloud Monitoring** (`firestore.googleapis.com/document/read_count`), never by browsing live collections in the Console.

### 2. security rules `get()` and `exists()` amplification
Firestore Security Rules bill `1` read per unique document path fetched via `get()` or `exists()` during a request (up to `10` calls for single-doc requests and `20` for queries/batches). Checking `exists(/databases/$(database)/documents/admins/$(request.auth.uid))` turns every `1`-doc read into `2` reads (`100%` overhead), while dynamic parent paths (`resource.data.parentProjectId`) multiply reads across list queries.

Eliminate Security Rules lookups by stamping `orgId` and `role` onto the user's JWT via Firebase Auth Custom Claims:

```javascript
// Admin SDK: Stamp claims when membership changes
await admin.auth().setCustomUserClaims(uid, { orgId: "org_9482", role: "editor" });
```

```javascript
// firestore.rules — Zero extra billable reads from signed JWT claims
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /projects/{projectId} {
      allow read: if request.auth != null && request.auth.token.orgId == resource.data.orgId;
      allow write: if request.auth != null
                   && request.auth.token.orgId == resource.data.orgId
                   && request.auth.token.role in ['admin', 'editor'];
    }
  }
}
```

Evaluating `request.auth.token.orgId` runs purely in memory for `$0.00` and `0 ms` of storage I/O.

## How do getCountFromServer() and Firestore bundles cut read volume by 99%?

**Quick answer:** Server-side aggregation (`getCountFromServer()`) charges `1` document read per `1,000` matched index entries instead of reading full documents, while **Firestore Data Bundles** serialize shared query snapshots onto a CDN so `100,000` users share a single backend read.

Two architectural upgrades cut mature Firestore bills by `80%–99%` without migrating databases:

1. **Replace `.size` counting with `getCountFromServer()`:** Never call `getDocs(q)` just to display `"4,210 unread logs"`. `getCountFromServer(q)` scans index entries on the backend and bills `1` read per up to `1,000` matched entries (`5` reads vs `4,210` reads, with zero document egress). Avoid polling `getCountFromServer()` rapidly on million-row collections, since `500,000` matched index entries still costs `500` reads per call.
2. **Cache shared feeds with Firestore Data Bundles:** If `50,000` daily visitors fetch the same `200` catalog items or leaderboard rows, direct queries burn `10,000,000` reads/day (`$18/mo` multi-region). Instead, build a bundle in an HTTP Cloud Function via `firestore.bundle("catalog-v1").add("active-catalog", snapshot).build()` and serve it behind Firebase Hosting CDN with `Cache-Control: public, max-age=60, s-maxage=600`. Clients call `loadBundle(db, res.body)` and `namedQuery(db, "active-catalog")` for zero direct Firestore reads per visitor, using the same edge caching principles detailed in our [Supabase cached vs uncached egress guide](/guides/supabase-egress-overage-cached-storage-cdn-fix/).

## How do you deploy a Google cloud budget alert and billing Kill-Switch function?

**Quick answer:** Because Google Cloud Budget Alerts only emit notifications and lag live traffic by `15–60 minutes`, pair a `1-minute` Cloud Monitoring read-rate alert with an automated Pub/Sub Cloud Function that detaches billing if monthly spend crosses your hard ceiling.

Protect every production Blaze project with two independent circuit breakers:

1. **Real-Time Spike Alert (< 2 Minutes):** In Google Cloud Monitoring -> **Alerting**, alert on `firestore.googleapis.com/document/read_count` (`1-minute` `SUM` alignment) at `5x` normal peak traffic to page Slack or PagerDuty within `120 seconds` of a broken `useEffect` deploy.
2. **Hard Dollar Kill-Switch via Budget Pub/Sub:** Connect a Google Cloud Budget to a `billing-alerts` Pub/Sub topic and deploy a 2nd-Gen Cloud Run Function with `roles/billing.projectManager`:

```typescript
import { CloudEvent } from "@google-cloud/functions-framework";
import { CloudBillingClient } from "@google-cloud/billing";

const billing = new CloudBillingClient();
const PROJECT_NAME = `projects/${process.env.GCP_PROJECT_ID}`;

interface BudgetMessage {
  costAmount: number;
  budgetAmount: number;
}

export async function enforceHardBudgetCap(cloudEvent: CloudEvent<{ message: { data: string } }>) {
  const raw = Buffer.from(cloudEvent.data!.message.data, "base64").toString("utf8");
  const payload: BudgetMessage = JSON.parse(raw);

  if (payload.costAmount < payload.budgetAmount) {
    return;
  }

  const [info] = await billing.getProjectBillingInfo({ name: PROJECT_NAME });
  if (!info.billingEnabled) {
    return;
  }

  // Detaching billingAccountName immediately downgrades Firebase to Spark quotas
  await billing.updateProjectBillingInfo({
    name: PROJECT_NAME,
    projectBillingInfo: { billingAccountName: "" },
  });

  console.error(
    `CRITICAL: Detached billing on ${PROJECT_NAME} at $${payload.costAmount} (cap: $${payload.budgetAmount})`
  );
}
```

Keep production Firebase isolated in its own GCP project before enabling `updateProjectBillingInfo`: unlinking the billing account halts all paid GCP resources inside that project immediately, dropping Firestore back to Spark's free `50,000` reads/day ceiling instead of letting a Friday evening deploy turn into a `$4,000` Monday morning invoice.
