Hot Documents, Distributed Counters and Cost

Article · 7:00

The per-document write limit, sequential key hotspots, distributed counters, listener cost at scale, and modelling the bill before it arrives.

This lesson has 1 runnable example. Press Try yourself! under any of them to open it in the editor.

Firestore's performance problems are almost all one problem: a hot document or a hot key range.

The per-document write limit is about one sustained write per second. A single counter document that every user increments is therefore capped at roughly one increment per second regardless of how many users you have. This is the most common Firestore scaling failure and it presents as writes becoming slow and then failing with contention errors.

The fix is a distributed counter: shard the counter across N documents, write to a random shard, and read all N and sum. With 10 shards you get roughly 10 writes per second; with 100, roughly 100. The cost is N reads to read the total, so you choose N from your write rate and accept the read cost - or keep a periodically aggregated total for display and the shards for accuracy.

Sequential document IDs create a hot key range. Firestore's index is a sorted key space, so monotonically increasing IDs (a timestamp, a sequence) put every write at the same end of it, and the recommendation is a limit of about 500 writes per second to a sequential range. Auto-generated IDs are random by design and avoid this entirely. The same applies to an indexed field with a monotonically increasing value: a createdAt field you write with serverTimestamp() creates a hot index range, which is tolerable at moderate rates and a real limit at high ones.

Listener cost at scale deserves its own analysis. A listener on a document that changes frequently bills every client watching it, on every change. One room document updated on every message, watched by 100 members, is 100 reads per message. That is a design decision with a direct price, and the alternative - clients listening to the messages subcollection rather than the room summary - may cost less.

Cost modelling is an engineering skill in this course, not an afterthought. Firestore bills document reads, writes and deletes, stored data, and network egress. The free tier is genuinely generous and the paid rates are small per operation, which is exactly why the bill surprises people: a per-operation price of a fraction of a cent multiplied by a design that reads 60 documents per screen view at a million screen views per day is a real number. Build a spreadsheet, put your measured read counts into it, and multiply. Doing that before you build is the single highest-value hour in this course.

The specific things that generate unplanned cost: listeners without limits, listeners not unsubscribed, offset pagination, reading documents to count them instead of count(), a Cloud Function trigger that writes a document that triggers another function, and development with a seeding script against a live project rather than the emulator.

Laboratory exercise 4 - a measured improvement.

Load at least two million documents. Declare a baseline: five queries with p50, p95 and p99, and the read count for each.

Create a hot document deliberately: a single counter incremented by 100 concurrent clients. Record the achieved write rate and the errors. Then implement a distributed counter with 10 shards and then 100, and record the write rate and the read cost of the total at each.

Create a hot key range: write documents with sequential IDs at a high rate and record the throughput, then switch to auto-generated IDs and compare.

Measure listener cost at scale: one document watched by 100 clients and updated 100 times, versus 100 clients watching a limited subcollection query. Record total reads for each.

Apply the other techniques and re-measure: field index exemptions, a count() aggregation against reading documents, and cursor against offset pagination.

Then build the cost model: a spreadsheet with your measured read and write counts, projected to 10,000 and 100,000 daily active users, at current list prices.

Deliverable: the benchmark report with percentiles and read counts at each step, the hot document measurements at 1, 10 and 100 shards, the sequential ID comparison, the listener cost comparison, the cost model with both projections, and one change that did not help.

JS Example 1 120 lines
// ------------------------------------------------------------------
// THE PROBLEM: a hot document. ~1 sustained write per second.
// ------------------------------------------------------------------
// This is capped at ~1/s no matter how many users you have:
await updateDoc(doc(db, "stats", "global"), { messageCount: increment(1) });
//
// 100 concurrent clients doing this: writes slow, then fail with
// contention. The most common Firestore scaling failure, and it looks
// like "Firestore got slow" rather than "we hit a documented limit".

// ------------------------------------------------------------------
// THE FIX: a DISTRIBUTED COUNTER. Shard it.
// ------------------------------------------------------------------
const SHARDS = 10;      // ~10 writes/s. 100 shards -> ~100 writes/s.

async function incrementCounter(name, by = 1) {
  const shard = Math.floor(Math.random() * SHARDS);
  await setDoc(
    doc(db, "counters", name, "shards", String(shard)),
    { count: increment(by) },
    { merge: true }        // merge: creates the shard on first use
  );
}

async function readCounter(name) {
  const snap = await getDocs(collection(db, "counters", name, "shards"));
  return snap.docs.reduce((t, d) => t + (d.data().count || 0), 0);
  // COSTS N READS. That is the trade: pick SHARDS from your write
  // rate, and accept the read cost.
}

// Or both: shards for accuracy, a periodic aggregate for display.
//   exports.aggregate = onSchedule("every 5 minutes", async () => {
//     const total = await readCounter("messages");
//     await db.doc("counters/messages").set({total, at: FieldValue.serverTimestamp()});
//   });
// Clients read ONE document. Accuracy is 5 minutes stale, which for a
// displayed count is almost always fine.

// ------------------------------------------------------------------
// HOT KEY RANGE: sequential IDs.
// ------------------------------------------------------------------
// Firestore's index is a SORTED KEY SPACE. Monotonic ids put every
// write at the same end of it.
await setDoc(doc(db, "messages", `msg-${Date.now()}`), {...});    // BAD
await setDoc(doc(db, "messages", String(nextSequence++)), {...}); // BAD
//   recommended limit: ~500 writes/s to a sequential range

await addDoc(collection(db, "messages"), {...});                  // GOOD
//   auto-generated ids are RANDOM BY DESIGN. No hot range.

// The same applies to an INDEXED FIELD with a monotonic value: a
// createdAt written with serverTimestamp() creates a hot index range.
// Tolerable at moderate rates, a real limit at high ones. If you do
// not query on it, exempt it. If you do, consider a sharded prefix.

// ------------------------------------------------------------------
// LISTENER COST AT SCALE: a design decision with a price.
// ------------------------------------------------------------------
// One room document updated on EVERY message, watched by 100 members:
//   100 members x 1 read per update x 100 messages = 10,000 reads
//
// The same 100 members listening to the messages subcollection with
// limit(50) instead:
//   100 x 50 (attach, once) + 100 x 100 (one per new message)
//     = 5,000 + 10,000 = 15,000 reads
//
// MEASURE BOTH for your actual pattern - the answer depends on the
// ratio of attaches to messages, and the intuitive choice is often
// the more expensive one.

// ------------------------------------------------------------------
// COUNT instead of reading documents to count them.
// ------------------------------------------------------------------
const n = await getCountFromServer(
  query(collection(db, "rooms", "room-1", "messages"),
        where("authorId", "==", uid)));
n.data().count;
//   count():          1 read per 1,000 index entries scanned
//   reading them all: 1 read per DOCUMENT
// On 50,000 matching documents that is 50 reads against 50,000.

// ------------------------------------------------------------------
// THE COST MODEL. Build this BEFORE you build the app.
// ------------------------------------------------------------------
// Firestore bills: document reads, writes, deletes, stored data,
// network egress. The free tier is generous and the per-operation
// price is small - which is exactly why the bill surprises people.
//
//   measured, per screen view:
//     room list (denormalised)        20 reads
//     room list (normalised)          60 reads
//     open a room                     50 reads (listener attach)
//     each new message, per watcher     1 read
//     send a message                   2 writes (message + room)
//
//   10,000 DAU x 10 room-list views x 20 reads  = 2,000,000 reads/day
//   10,000 DAU x  5 room opens  x 50 reads      = 2,500,000 reads/day
//   10,000 DAU x 20 messages sent x 2 writes    =   400,000 writes/day
//   messages received: 20 x 10,000 x 8 watchers = 1,600,000 reads/day
//                                       TOTAL   = 6,100,000 reads/day
//
//   ... then x30 for a month, x10 for 100,000 DAU, at list price.
//   Put the real numbers in a spreadsheet and multiply. That hour is
//   the highest-value hour in this course.

// WHAT GENERATES UNPLANNED COST, every one of them seen in the wild:
//   * a listener with no limit()
//   * a listener never unsubscribed on navigation
//   * offset pagination
//   * reading documents to count them
//   * a Cloud Function trigger that writes a document that triggers
//     another function - an INFINITE LOOP that bills per hop
//   * seeding and load-testing against a LIVE project instead of the
//     emulator

// Monitor it, with an alert, from day one:
//   Firebase console -> Firestore -> Usage
//   Cloud Monitoring: firestore.googleapis.com/document/read_count
//   Budget alerts at 50%, 90%, 100% of your expected monthly spend

Open this example in the editor and change it. Nothing you type is saved.

Discussion

No questions on this topic yet. Sign in to ask the first one.