Know the query limits exactly, because your schema is designed around them. In Firestore you can filter on equality, on in and array-contains, and on ranges, and you can order and limit. What you cannot do:
- No joins. None. There is no server-side way to fetch related documents in one query.
- No full-text search.
>=prefix tricks work for "starts with" and nothing more. Real search means Algolia, Typesense or Elasticsearch alongside. - Limited
OR.or()exists in recent SDKs and is constrained; the general pattern is still separate queries merged client-side, or a denormalised array field queried witharray-contains-any. - Range filters on multiple fields are supported in newer versions but have index implications; the classic rule - one field with an inequality - is still the safe mental model.
!=andnot-inare expensive and cannot be combined freely.- Aggregations are
count(),sum()andaverage()only. NoGROUP BY. Grouped aggregates mean maintaining counters on write.
Every query needs an index, and single-field indexes are automatic. Firestore indexes every field of every document ascending and descending by default. A query filtering or ordering on more than one field needs a composite index, which you declare in firestore.indexes.json. The practical workflow: run the query, read the error, and follow the link it gives you - the error contains a URL that creates exactly the right index.
Index fanout is the write cost nobody budgets for. Every index entry is written when the document is written. A document with 40 fields gets 80 single-field index entries by default, plus composites, plus array fields which index one entry per element. A document with a 100-element array in an indexed field writes 100 index entries. Exempting fields you never query is a real and underused optimisation, and it is configured per field.
Pagination is cursor-based. startAfter(lastDocument) continues from where you stopped. There is no offset worth using - skipping documents still reads and bills for them. Build pagination on cursors from the start.
Collection group queries query every subcollection with a given name across the whole database: all messages subcollections of all rooms, in one query. They need their own index and a rule written against the collection group path, and they are the answer to "I chose a subcollection and now I need to query across them".
Denormalisation is the normal way to model, not an optimisation. With no joins, rendering a room list with the last message means either a read per room or the last message stored on the room document. The cost is consistency: a denormalised copy must be maintained, and the two honest mechanisms are a transaction or batch at write time (consistent, more client complexity) or a Cloud Function trigger (simpler client, eventually consistent, and it costs a function invocation). Choose one, state it, and handle the failure case.
Laboratory exercise 2 - two models, measured in reads.
Design two schemas for the capstone chat application. The contrast: one normalised with references and client-side joins, and one denormalised with author names, last messages and unread counts stored where they are displayed.
Implement both. Write the representative queries: the room list with last message and unread count, a room's recent messages paginated, a user's rooms, a search for messages by author within a room, and message counts per room.
Measure both models in document reads, not milliseconds. Reads are the billable unit and the honest comparison - record the exact read count to render each screen in each model. Then convert to a monthly cost at 10,000 daily active users.
Implement one collection group query and the index and rule it needs.
Then measure index fanout: write a document with a 100-element indexed array, exempt the field, and compare write latency and the index entry count.
Deliverable: both models, all queries, a read-count table per screen per model, the monthly cost projection for both, the collection group query with its index and rule, the fanout measurement, and a page arguing for one model on reads and consistency.
// ------------------------------------------------------------------
// WHAT FIRESTORE CANNOT DO. Know this exactly - your schema is
// designed around it.
// ------------------------------------------------------------------
// * NO JOINS. None. No server-side way to fetch related documents.
// * NO FULL-TEXT SEARCH. Prefix matching only. Real search means
// Algolia / Typesense / Elasticsearch alongside.
// * LIMITED OR. or() exists and is constrained.
// * != and not-in are expensive and cannot be combined freely.
// * AGGREGATIONS: count(), sum(), average(). NO GROUP BY.
//
// These are not omissions. They are what guarantees that every
// indexed query is fast at any collection size.
// ------------------------------------------------------------------
// Queries, within the limits.
// ------------------------------------------------------------------
const recent = query(
collection(db, "rooms", "room-1", "messages"),
where("authorId", "==", "uid-abc"),
orderBy("createdAt", "desc"),
limit(20)
);
// Needs a COMPOSITE index on (authorId ASC, createdAt DESC).
// The workflow: run it, read the error, click the link in the error -
// it creates exactly the right index. Then commit it to
// firestore.indexes.json so it is reproducible:
// { "indexes": [{
// "collectionGroup": "messages", "queryScope": "COLLECTION",
// "fields": [ {"fieldPath":"authorId","order":"ASCENDING"},
// {"fieldPath":"createdAt","order":"DESCENDING"} ] }] }
// The OR workaround: a denormalised array, queried with
// array-contains-any. One query, one index:
await updateDoc(doc(db, "rooms", "room-1", "messages", "msg-7"), {
searchTags: arrayUnion("author:uid-abc", "type:text", "has:link")
});
const tagged = query(
collection(db, "rooms", "room-1", "messages"),
where("searchTags", "array-contains-any", ["type:image", "has:link"]),
orderBy("createdAt", "desc"), limit(20)
);
// array-contains-any takes at most 30 values, and only ONE
// array-contains clause is allowed per query.
// Aggregations - the three that exist:
import { getCountFromServer, getAggregateFromServer, sum, average }
from "firebase/firestore";
const c = await getCountFromServer(
collection(db, "rooms", "room-1", "messages"));
c.data().count;
// Billed at 1 read per 1,000 index entries scanned - MUCH cheaper
// than reading the documents, and not free. There is no GROUP BY:
// grouped aggregates mean maintaining counters on write.
// ------------------------------------------------------------------
// PAGINATION: cursors. Never offsets.
// ------------------------------------------------------------------
let page = await getDocs(query(
collection(db, "rooms", "room-1", "messages"),
orderBy("createdAt", "desc"), limit(20)));
const lastDoc = page.docs[page.docs.length - 1];
const next = await getDocs(query(
collection(db, "rooms", "room-1", "messages"),
orderBy("createdAt", "desc"),
startAfter(lastDoc), // the cursor
limit(20)));
// There is an offset-style API and it READS AND BILLS FOR every
// skipped document. Page 50 at 20 per page costs 1,000 reads to
// return 20. Build on cursors from the first line of code.
// ------------------------------------------------------------------
// COLLECTION GROUP: every subcollection of a name, database-wide.
// ------------------------------------------------------------------
import { collectionGroup } from "firebase/firestore";
const mine = query(
collectionGroup(db, "messages"), // ALL rooms' messages
where("authorId", "==", "uid-abc"),
orderBy("createdAt", "desc"), limit(50)
);
// Needs its own index with "queryScope": "COLLECTION_GROUP", AND a
// rule written against the collection group path, or every read is
// denied:
// match /{path=**}/messages/{messageId} { allow read: if ...; }
// The answer to "I chose a subcollection and now I need to query
// across them".
// ------------------------------------------------------------------
// DENORMALISATION IS NORMAL MODELLING HERE, not an optimisation.
// ------------------------------------------------------------------
// The room list screen needs each room's last message. With no joins
// the options are: a read per room, or store it on the room.
const roomDoc = {
name: "Engineering",
memberCount: 42,
memberIds: ["uid-abc", "uid-def"], // for array-contains queries
// DENORMALISED - 1 read for the whole room list row:
lastMessage: { text: "See you at 3", at: Timestamp.now(), by: "Ada" },
// DENORMALISED per member, so the badge needs no extra read:
unread: { "uid-abc": 0, "uid-def": 3 }
};
// Read cost to render a 20-room list:
// normalised: 20 rooms + 20 last messages + 20 authors = 60 reads
// denormalised: 20 reads
// At 10,000 DAU opening it 10 times a day that is 6,000,000 vs
// 2,000,000 reads/day. THAT is the comparison to put in the report.
// Keeping the copy consistent - two honest mechanisms, pick ONE:
// (a) A BATCH at write time: consistent, more client complexity.
const batch = writeBatch(db);
const newMsg = doc(collection(db, "rooms", "room-1", "messages"));
batch.set(newMsg, { text, authorId: uid, authorName: name,
createdAt: serverTimestamp() });
batch.update(doc(db, "rooms", "room-1"), {
"lastMessage.text": text,
"lastMessage.at": serverTimestamp(),
"lastMessage.by": name,
[`unread.${otherUid}`]: increment(1)
});
await batch.commit(); // all or nothing, max 500 operations
// (b) A CLOUD FUNCTION trigger: simpler client, EVENTUALLY consistent,
// and it costs an invocation per message.
// exports.onMessage = onDocumentCreated(
// "rooms/{roomId}/messages/{messageId}", async (event) => {
// await event.data.ref.parent.parent.update({ lastMessage: {...} });
// });
// Handle the failure case either way: a batch that fails leaves
// nothing written; a trigger that fails leaves the copy stale.
// ------------------------------------------------------------------
// INDEX FANOUT: the write cost nobody budgets for.
// ------------------------------------------------------------------
// Firestore indexes EVERY field ASCENDING and DESCENDING by default.
// 40 fields -> 80 index entries per write
// + composite indexes -> more
// + an indexed ARRAY field -> ONE ENTRY PER ELEMENT
// a 100-element array -> 100 index entries, one write
//
// EXEMPT what you never query. Real, underused, and configured per
// field in firestore.indexes.json:
// { "fieldOverrides": [{
// "collectionGroup": "messages", "fieldPath": "rawPayload",
// "indexes": [] // <- no indexes at all on this field
// }, {
// "collectionGroup": "messages", "fieldPath": "searchTags",
// "indexes": [{"arrayConfig":"CONTAINS","queryScope":"COLLECTION"}]
// // array-contains only: no ASC/DESC entries
// }] }
// Measure it: write a document with a 100-element indexed array,
// exempt the field, write again, compare. That is the lab.
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.