The system. A realtime chat application. Rooms with members and admins, messages with editing, unread counts, offline support, and authorisation entirely in Security Rules with no backend except Cloud Functions for denormalisation.
Three invariants must hold:
- A non-member can read nothing from a room - proved by tests, not by inspection.
- Every room's
memberCountandlastMessagematch its subcollections, including after an offline client reconnects. - No message has an
authorIdother than the authenticated user who created it, enforced by rules rather than by client code.
What is assessed. 20% knowledge checks, 35% laboratory portfolio, 15% troubleshooting practical, 30% capstone. Three things carry the capstone, and the first is unusual for this programme.
A tested Security Rules suite. The rules are the backend, so the tests are the proof the system is secure. Every rule needs a positive and a negative test, running in CI against the emulator. A capstone with untested rules fails this criterion regardless of how well the application works, because "it works when I use it correctly" is not a security argument.
Measured performance and a cost model against a declared baseline. Declare it first: screens, the read count per screen measured rather than estimated, listener strategy, p50/p95/p99 for send and receive, and a projected monthly bill at 1,000, 10,000 and 100,000 daily active users. A capstone whose cost model is absent or hand-waved is incomplete - in a managed, per-operation database, cost is a functional requirement.
A defensible account of failure modes, operational limits and cost. The per-document write limit must be addressed where it applies. The offline conflict behaviour must be stated honestly - last write wins, silently - with its consequence for your UI. And the recovery runbook must cover a bad deployment, because that is the realistic Firestore incident.
Deliverables: architecture diagram; data model with every denormalisation argued and its maintenance mechanism named; source code including listeners with cleanup and the Cloud Function triggers; the complete rules test suite; reproducible test dataset and emulator setup; benchmark report with read counts; cost model with three projections; security review; recovery runbook with measured RPO and RTO; and a short design defence.
// ================= Invariants, as runnable assertions ==============
// Run these in CI against the emulator, and after every recovery.
// 1. A NON-MEMBER CAN READ NOTHING. Proved by TESTS, not inspection.
test("non-member is denied every path in a room", async () => {
await testEnv.withSecurityRulesDisabled(async (c) => {
const d = c.firestore();
await d.doc("rooms/r1").set({name:"P", memberIds:["alice"], adminIds:["alice"]});
await d.doc("rooms/r1/members/alice").set({uid:"alice"});
await d.doc("rooms/r1/messages/m1").set({text:"secret", authorId:"alice"});
});
const bob = testEnv.authenticatedContext("bob").firestore();
await assertFails(bob.doc("rooms/r1").get());
await assertFails(bob.doc("rooms/r1/messages/m1").get());
await assertFails(bob.doc("rooms/r1/members/alice").get());
await assertFails(bob.collection("rooms/r1/messages").get());
await assertFails(bob.collection("rooms/r1/messages").add({text:"x"}));
// And the collection group path, which people forget:
await assertFails(bob.collectionGroup("messages")
.where("authorId","==","alice").get());
});
// 2. Denormalised copies match their subcollections.
// (Admin SDK, server-side, scheduled.)
// for each room:
// memberCount === (await room.collection("members").count()).data().count
// lastMessage.text === newest message's text
// Expected: no mismatches. Check this AFTER an offline client
// reconnects, which is when it actually breaks.
// 3. authorId is always the authenticated creator - by RULE:
test("cannot write a message as someone else", async () => {
const bob = testEnv.authenticatedContext("bob").firestore();
await assertFails(bob.collection("rooms/r1/messages")
.add({text:"forged", authorId:"alice", createdAt: serverTimestamp()}));
});
// ================= The rules test suite IS the security argument ====
// Every rule gets a POSITIVE and a NEGATIVE test:
// read member yes / non-member no / unauthenticated no
// create member yes / non-member no / wrong authorId no /
// client timestamp no / empty text no / extra field no /
// text over 4000 chars no
// update author yes / other member no / changing authorId no /
// changing createdAt no / changing a field not in the
// allowed set no
// delete author yes / room admin yes / other member no
// members admin yes / member no
// group own messages yes / others' no
//
// A capstone with untested rules fails this criterion however well
// the app works. "It works when I use it correctly" is not a security
// argument, and the rules ARE the backend.
// ================= Declare the baseline BEFORE measuring ===========
//
// Screens and MEASURED reads (not estimated):
// room list (20 rooms, denormalised) 20 reads
// open a room (listener, limit 50) 50 reads
// each message received, per watcher 1 read
// send a message 2 writes (message + room via trigger)
//
// Listener strategy: one on the user's rooms
// (where memberIds array-contains uid, limit 50),
// one on the open room's messages (limit 50),
// BOTH unsubscribed on navigation.
//
// Claim:
// send -> own device renders p99 < 50 ms (latency compensation)
// send -> other device renders p99 < 500 ms
// room open to first paint p99 < 400 ms
// offline queue drain (50 msgs) p99 < 5 s
//
// COST MODEL - three projections, at list price:
// 1k DAU 10k DAU 100k DAU
// reads/day 610k 6.1M 61M
// writes/day 40k 400k 4M
// storage 2GB 20GB 200GB
// est. monthly $___ $___ $___
//
// A capstone whose cost model is absent or hand-waved is
// INCOMPLETE. In a per-operation managed database, cost is a
// functional requirement, and this is the number a stakeholder
// will actually ask about.
// ================= Hot document, where it applies ==================
// The room document is written on EVERY message. A busy room with 20
// messages a second hits the ~1 write/s per-document limit.
// mitigation 1: update lastMessage from a Cloud Function that
// DEBOUNCES - at most one write per second per room
// mitigation 2: shard unread counts into a subcollection per member
// rather than a map on the room
// mitigation 3: drop lastMessage and pay the extra read on the room
// list, which may be cheaper than the complexity
// State which you chose and why, with the numbers.
// ================= Failure modes ==================================
// rules mistake NOT A BUG - A BREACH. The reason the
// test suite is assessed.
// listener not unsubscribed read cost grows with navigation, not
// with usage. Invisible until the bill.
// offline conflict LAST WRITE WINS AT THE SERVER, SILENTLY.
// Your UI must not imply otherwise.
// busy room ~1 write/s per document on the room.
// Debounce or shard.
// Cloud Function loop a trigger that writes a document that
// triggers it again. Bills per hop until
// a quota or budget alert stops it.
// bad deployment THE realistic Firestore incident.
// PITR, enabled in advance, is the only
// answer that recovers from it.
// subcollection orphaned deleting a room leaves its messages.
// Recursive delete in a function.
// region chosen wrong cannot be changed. New database, copy
// everything, re-point every client.
//
// Verify after every recovery with the three assertions above. "The
// app loads" is not verification.
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.