The data model has exactly three concepts. A collection holds documents and has no schema. A document is a map of fields - strings, numbers, booleans, timestamps, geopoints, arrays, nested maps, references and null - identified by a path like rooms/room-1/messages/msg-7. A subcollection is a collection nested under a document, which is how hierarchy is expressed.
The limits are not trivia; they are design constraints. Learn these four in Module 1 because every later module refers to them:
- A document may not exceed 1 MiB. With arrays and maps counting toward it, a document accumulating entries will eventually stop accepting writes.
- A single document may be written at most about once per second sustained. This is the limit people hit without understanding why, and it is why distributed counters exist.
- A collection has no size limit at all. A collection with a billion documents queries exactly as fast as one with a hundred, provided the query is indexed.
- A query's cost and latency scale with the result set, not the collection. This is Firestore's defining performance property and the reason for all the query restrictions.
Subcollections against root collections is the first real design decision. A subcollection is good for data that only makes sense within its parent (rooms/{id}/messages), gives natural path-based security rules, and has no size limit. A root collection is better when you need to query across all of it easily - though collection group queries (Module 2) let you query all subcollections of a name, which closes most of that gap. Note that deleting a document does not delete its subcollections - they become orphaned and still cost storage, which surprises everyone once.
The client SDK and the Admin SDK are profoundly different. The client SDK (browser, mobile) is subject to Security Rules and runs as the signed-in user. The Admin SDK bypasses Security Rules entirely - it runs with full access, as a service account, and is for servers and Cloud Functions. Using the Admin SDK is choosing to do your own authorisation, and the single most dangerous Firestore mistake is putting Admin SDK credentials somewhere a client can reach.
serverTimestamp() deserves a mention in Module 1. Client clocks are wrong; a createdAt set by the client is untrustworthy and can be set to any value by a malicious one. serverTimestamp() is written by the server and is the only timestamp you can order by or enforce rules on. It reads back as null locally until the server confirms, which is a UI case you must handle.
Laboratory exercise 1 - provision and verify.
Create a Firebase project and get the full Local Emulator Suite running - Firestore, Auth and the Emulator UI. Confirm you can read and write through the emulator and that resetting it clears everything.
Build a seeding script that loads at least 100,000 documents using batched writes, with a realistic shape for the capstone: rooms, members and messages.
Then demonstrate each of the four limits, with evidence: write a document until it exceeds 1 MiB and capture the error; write to one document in a tight loop and record the throughput ceiling you actually observe; query a collection at 1,000 documents and at 100,000 and show the latency is the same for the same result size; and delete a parent document and show its subcollection documents still exist.
Finally, demonstrate serverTimestamp() reading back as null before the server confirms.
Deliverable: a reproducible emulator setup with firebase.json, a seeding script, a README taking a colleague from a clean checkout to a loaded emulator, the four limit demonstrations with their actual output, and the pending-timestamp evidence.
// ------------------------------------------------------------------
// THE EMULATOR. Use it for everything you can. It is not a lesser
// version for learning - it is what professional Firestore
// development uses: no cost, no quota, instant reset, and the only
// sane way to test Security Rules.
// ------------------------------------------------------------------
// npm i -g firebase-tools
// firebase init emulators # Firestore, Auth, Functions
// firebase emulators:start
// UI: http://localhost:4000
//
// firebase.json:
// { "emulators": {
// "firestore": { "port": 8080 },
// "auth": { "port": 9099 },
// "ui": { "enabled": true, "port": 4000 } },
// "firestore": { "rules": "firestore.rules",
// "indexes": "firestore.indexes.json" } }
import { initializeApp } from "firebase/app";
import {
getFirestore, connectFirestoreEmulator,
collection, doc, addDoc, setDoc, getDoc, getDocs, updateDoc, deleteDoc,
writeBatch, serverTimestamp, Timestamp, increment, arrayUnion,
query, where, orderBy, limit
} from "firebase/firestore";
const app = initializeApp({ projectId: "demo-chat" });
const db = getFirestore(app);
if (location.hostname === "localhost") {
connectFirestoreEmulator(db, "localhost", 8080);
}
// ------------------------------------------------------------------
// The data model: collections, documents, SUBCOLLECTIONS.
// ------------------------------------------------------------------
// rooms/{roomId}
// rooms/{roomId}/members/{uid}
// rooms/{roomId}/messages/{messageId}
//
// Paths have an even number of segments for a document and an odd
// number for a collection. That is the whole addressing scheme.
await setDoc(doc(db, "rooms", "room-1"), {
name: "Engineering",
// serverTimestamp(): written by the SERVER. A client clock is
// wrong, and a malicious client can set createdAt to anything. This
// is the only timestamp you can order by or enforce rules on.
createdAt: serverTimestamp(),
createdBy: "uid-abc",
memberCount: 0,
// DENORMALISED for the room list screen - there is no join, so the
// alternative is a read per room. Module 2.
lastMessage: { text: "", at: null, by: "" }
});
const msgRef = await addDoc(collection(db, "rooms", "room-1", "messages"), {
text: "Hello",
authorId: "uid-abc",
authorName: "Ada", // denormalised: no join to fetch it
createdAt: serverTimestamp(),
editedAt: null
});
// serverTimestamp() reads back as NULL locally until the server
// confirms. A UI case you must handle, not an edge case:
const snap = await getDoc(msgRef);
snap.data().createdAt; // null, then a Timestamp a moment later
snap.metadata.hasPendingWrites; // true while unconfirmed
// ------------------------------------------------------------------
// THE FOUR LIMITS. Not trivia - design constraints.
// ------------------------------------------------------------------
// 1. A DOCUMENT MAY NOT EXCEED 1 MiB. Arrays and maps count.
// Demonstrate it:
try {
await setDoc(doc(db, "limits", "big"), { blob: "x".repeat(1100000) });
} catch (e) {
// INVALID_ARGUMENT: ... exceeds the maximum allowed size
}
// A document that accumulates entries WILL eventually stop
// accepting writes. Design the bound in from the start.
// 2. ONE DOCUMENT: ~1 SUSTAINED WRITE PER SECOND.
// The limit people hit without understanding why, and the reason
// distributed counters exist (Module 4). Measure your own ceiling:
// for (let i = 0; i < 200; i++)
// await updateDoc(doc(db,"limits","counter"), {n: increment(1)});
// Time it. You will see roughly 1/s, not 200/s.
// 3. A COLLECTION HAS NO SIZE LIMIT.
// 4. A QUERY SCALES WITH THE RESULT SET, NOT THE COLLECTION.
// Firestore's defining property, and the reason for every query
// restriction in Module 2. Prove it: the same query returning 20
// documents costs the same against 1,000 and against 1,000,000.
// ------------------------------------------------------------------
// DELETING A DOCUMENT DOES NOT DELETE ITS SUBCOLLECTIONS.
// ------------------------------------------------------------------
await deleteDoc(doc(db, "rooms", "room-1"));
// rooms/room-1/messages/* ALL STILL EXIST. They are orphaned,
// unreachable through the parent, and still billed as storage.
// Recursive delete is a Cloud Function or the CLI:
// firebase firestore:delete --recursive rooms/room-1
// Surprises everyone exactly once.
// ------------------------------------------------------------------
// Batched writes: how you seed. 500 operations per batch, maximum.
// ------------------------------------------------------------------
for (let b = 0; b < 200; b++) {
const batch = writeBatch(db);
for (let i = 0; i < 500; i++) {
const n = b * 500 + i;
batch.set(doc(collection(db, "rooms", "room-1", "messages")), {
text: `Message ${n}`, authorId: `uid-${n % 50}`,
authorName: `User ${n % 50}`,
createdAt: Timestamp.fromMillis(Date.now() - n * 1000)
// Timestamp.fromMillis, not serverTimestamp, when SEEDING -
// you want a controlled spread for the benchmarks.
});
}
await batch.commit();
}
// ------------------------------------------------------------------
// CLIENT SDK vs ADMIN SDK: the most important distinction here.
// ------------------------------------------------------------------
// CLIENT SDK (browser, mobile)
// * subject to SECURITY RULES
// * runs as the signed-in user
// * safe to ship: the API key is an identifier, not a secret
//
// ADMIN SDK (server, Cloud Functions)
// * BYPASSES SECURITY RULES ENTIRELY
// * runs as a service account with full access
// * using it means doing your OWN authorisation
//
// THE SINGLE MOST DANGEROUS FIRESTORE MISTAKE is putting Admin SDK
// credentials anywhere a client can reach - a service account JSON in
// a front-end bundle, a repository, or an environment variable
// exposed to the browser. There are no rules to save you.
//
// import { getFirestore } from "firebase-admin/firestore";
// // server only. Never in client code.
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.