Chapter 27 · Production Capstone: Design, Secure, Scale, Search, Recover, and Operate a Firestore Application
Define User Journeys, Data Model, Queries, Realtime / Offline Needs, Atomicity, Retention, Security, SLOs, and Cost Budget
Define AtlasMart journeys and SLOs first, then choose Firestore edition/mode, data model, security, retention, recovery and cost from explicit requirements.
1. AtlasMart capstone brief: choose a system before choosing features
The final chapter starts with a deliberately ordinary product requirement: AtlasMart needs public product browsing, a private cart, checkout with inventory protection, live order status, limited offline usefulness, operational analytics, retention, recovery, and predictable cost. That sounds like “use every Firestore feature from the course.” It is not. The architecture review must prove why each mechanism exists, what state it protects, and which requirement would make the team remove or replace it.
The first decision is deliberately conservative: Standard edition, Native mode, Core operations. It already provides the client-side realtime/offline model, Security Rules path, server SDKs, transactions, indexes and managed scale needed by this slice. Enterprise Pipeline, MongoDB compatibility and vector retrieval are not architectural badges; they are conditional tools evaluated later against measurable needs.
- Translate user journeys into document/query/listener/transaction/security/recovery contracts.
- Choose Standard versus Enterprise and Native versus MongoDB compatibility from requirements, not novelty.
- Define SLOs and cost budgets as measurable acceptance criteria rather than aspirational labels.
- Separate client cache/realtime/offline behavior from authoritative server business invariants.
- Produce an architecture decision record and known-limit register before implementation.
Use the Emulator Suite, a Firebase demo project, or an isolated test project for destructive, security-sensitive, billing-sensitive, migration, backup/restore, or write-heavy exercises unless the lesson explicitly marks managed verification as required. Treat shown output as expected evidence unless it is explicitly identified as captured output, and re-check current Firebase/Google Cloud edition, mode, quota, pricing, and security documentation before production execution.
AtlasMart keeps project ID
demo-atlasmart-firestore, Standard edition /
Native mode / Core operations, database
(default), Node.js 22+, Firebase CLI course
baseline 15.30.0, Firebase JavaScript SDK
12.19.0, Firebase Admin Node SDK
14.4.0,
@firebase/rules-unit-testing 5.0.2, Firestore
emulator 127.0.0.1:8080, Auth emulator
127.0.0.1:9099, and Emulator UI
127.0.0.1:4000. The mandatory capstone uses only
a demo- project and local tooling. Managed
location, production IAM/App Check, real composite/vector
indexes, Query Explain/Insights, billing, quotas, Key
Visualizer, scheduled backups/PITR, CMEK/network controls,
Enterprise/Pipeline, and MongoDB-compatibility validation are
optional managed evidence and are never inferred from emulator
success. Where a managed Standard example needs a concrete
location, this chapter uses us-central1 only as
an explicit example—not a universal recommendation.
2. Define the terms before the architecture diagram
| Term | Capstone meaning |
|---|---|
| Firebase project | The Firebase configuration surface associated with a Google Cloud project; it is not the database itself. |
| Firestore database |
A named managed database such as
(default) with its own
edition/mode/location/configuration.
|
| Standard / Enterprise | Firestore editions with materially different query/index/pricing behavior. Standard is the capstone default until evidence justifies Enterprise. |
| Native Core | The familiar document/query/listener/transaction interface used by Firebase client SDKs and server libraries. |
| Pipeline | Enterprise Native query interface for advanced composable server-side querying; not assumed to have the same client offline/realtime surface. |
| MongoDB compatibility | Enterprise serverless compatibility surface for MongoDB drivers/tools; it is not a MongoDB server process. |
| Security Rules | Authorization/data-validation policy for mobile/web client requests. Rules are not filters. |
| IAM / ADC | Google Cloud authorization and credential discovery used by trusted server libraries that bypass Security Rules. |
| App Check | App/device attestation that can reduce abuse; it is not user authorization. |
| Offline persistence | Client cache/synchronization behavior; it does not make a business invariant valid while disconnected. |
| Transaction | Atomic read-then-write unit that can retry; transaction callbacks must be retry-safe. |
| SLO | A measurable reliability/latency objective with a defined population and measurement window. |
3. User journeys become database contracts
| Journey | Firestore path | Consistency / offline decision | Security decision | Evidence |
|---|---|---|---|---|
| Browse products |
Query products where
active==true and category filter/order.
|
Realtime optional; cached browse acceptable with explicit stale UI. | Public reads only for public/active products; no client product writes. | Rules tests + query contract + managed index readiness. |
| Edit cart |
carts/{{uid}} +
items subcollection.
|
Optimistic/offline queue acceptable; server price is not trusted from cart. | Owner-only Rules; client cannot mint privileged price/inventory fields. | Offline/reconnect test + Rules allow/deny matrix. |
| Checkout | Trusted backend reads cart + inventory and creates order/reservation. | Online required; inventory/order invariant enforced transactionally/idempotently. | Backend verifies user token/business permission; Admin SDK uses IAM and bypasses Rules. | Transaction conflict test + duplicate-request idempotency. |
| Track order | Owner query/listener on orders. |
Realtime useful; cache may display last known state with source metadata. | Owner read Rules; backend-only state transitions. | Listener lifecycle + Rules + reconnect test. |
| Operations dashboard | Server aggregation/materialized summaries. | Freshness budget explicit; not a client authorization surface. | IAM + application-layer admin authorization. | Aggregation/cost evidence + audit log. |
| Retention / recovery |
events.expireAt, backups/PITR policy.
|
TTL is eventual; recovery has explicit RPO/RTO. | Legal holds excluded from automatic deletion; recovery operator least privilege. | Lifecycle simulation + optional managed restore drill. |
4. Architecture decision record: choose Standard Core deliberately
{ "decision": "Standard Native Core for AtlasMart transactional application slice", "date": "2026-09-17", "database": {"id":"(default)","edition":"STANDARD","mode":"NATIVE"}, "requirements": { "mobileWebRules": true, "realtimeOrderStatus": true, "offlineCart": true, "trustedCheckout": true, "advancedPipelineJoinRequired": false, "mongodbDriverDependency": false, "semanticSearchRequiredAtLaunch": false }, "managedProofStillRequired": [ "composite index readiness", "production p95/p99 and contention", "IAM/App Check enforcement", "billing and quota telemetry", "backup/PITR recovery drill" ], "revisitWhen": [ "Pipeline-only query materially reduces application complexity/cost", "MongoDB compatibility becomes a migration constraint", "measured Standard economics or query limits fail the workload" ]}
5. SLOs: define population, threshold and evidence
“Fast” and “highly available” are not testable. AtlasMart writes explicit targets, then labels which are local engineering targets versus managed production SLO evidence. Emulator latency is useful for regression inside one machine; it is not a regional service-latency forecast.
| Indicator | Capstone target | Evidence source | Important caveat |
|---|---|---|---|
| Product API latency | p95 < 250 ms, p99 < 500 ms for managed canary population. | Application timer + Cloud Monitoring/trace correlation. | Local emulator p95/p99 only detects code regressions. |
| Checkout correctness | No oversell; duplicate checkout key creates at most one committed order. | Transaction/idempotency tests + production canary logs. | A transaction may retry; side effects stay outside callback. |
| Order visibility | Client receives committed status within product UX budget. | Listener timestamp/correlation IDs. | Offline client can only show cached last-known state. |
| Recovery | RPO ≤ documented policy; RTO measured from incident declaration through validated app cutover. | Recovery drill report. | Multi-region availability is not logical-corruption recovery. |
| Cost | Base scenario stays within approved monthly envelope; worst case has alerts/controls. | Chapter 25 unit model + billing export/alerts. | Budget alerts are notifications, not hard shutdown. |
6. Data model from access patterns
products/{productId} tenantId, categoryId, name, active, visibility, priceCents, inventorySkuId, updatedAt, schemaVersioncarts/{uid} ownerUid, currency, updatedAt, schemaVersioncarts/{uid}/items/{productId} ownerUid, productId, quantity, observedPriceCents, updatedAtinventory/{skuId} available, reserved, version, updatedAtorders/{orderId} ownerUid, idempotencyKey, status, lineItems[], totalCents, createdAt, updatedAt, schemaVersionevents/{eventId} type, subjectId, occurredAt, expireAt, legalHold, schemaVersion
7. Wrong approach: feature checklist architecture
“Use Enterprise because it is newer; add Pipeline joins, vectors, MongoDB compatibility, App Check, TTL and PITR so the capstone is complete.” This creates multiple query/security/billing surfaces without a requirement, complicates testing, and makes launch-stage boundaries harder to audit.
The repair is a requirement-to-mechanism ledger. A feature is accepted only if its requirement, owner, test, cost surface, fallback and exit criterion are written down. Optional capabilities can still be taught—but they remain optional until the evidence changes the decision.
- No Enterprise/Pipeline without a query/economic requirement.
- No MongoDB compatibility without a MongoDB ecosystem/migration requirement and compatibility tests.
- No vector retrieval without a retrieval-quality target and server-side integration plan.
- No TTL for exact-time business actions; expiry is a policy boundary, not a scheduler.
- No managed recovery claim until a restore/cutover drill has been executed.
8. Mandatory local lab: architecture contract before code
-
Create
capstone/adr.jsonfrom the decision record above. -
Create
capstone/journeys.jsonwith the six journeys and expected query/write/security path. -
Create
capstone/known-limits.jsonwith emulator index/limit/transaction gaps, transaction retry semantics, hotspot risk, TTL eventuality, vector no-listener boundary and recovery cloud-only evidence. -
Start Firestore/Auth emulators under
demo-atlasmart-firestore. - Seed five products, one cart, two inventory SKUs, one order and synthetic events.
-
Run a script that validates every document has
schemaVersionand every journey has an evidence owner.
import fs from "node:fs";const adr = JSON.parse(fs.readFileSync("capstone/adr.json", "utf8"));const journeys = JSON.parse(fs.readFileSync("capstone/journeys.json", "utf8"));if (adr.database.edition !== "STANDARD") throw new Error("unexpected edition");for (const j of journeys) { if (!j.requirement || !j.mechanism || !j.evidence || !j.rollback) { throw new Error(`incomplete journey contract: ${j.name}`); }}console.log(`architecture gate: ${journeys.length} journeys complete`);
The capstone has an explicit Standard/Core decision, six user/operations journeys, measurable SLO definitions, a cost/recovery/security evidence owner, and a known-limit register before feature implementation begins.
Production judgment and bridge
Firestore is a fit only if the journeys can be implemented without hiding correctness, security, cost or operability debt. Lesson 2 now turns the contracts into documents, indexes, typed SDK access, Rules, listeners and a trusted checkout path while preserving the client/server trust boundary.
Knowledge check
- Why is Enterprise not the automatic capstone choice?
- Which AtlasMart action may work offline, and which must remain online?
- Why does an SLO need a population and evidence source?
- Why is App Check absent from the core authorization decision?
- What should trigger a database-choice review?
Review the answers
1. Because edition choice must follow required query/index/client/pricing behavior; Standard already satisfies the launch requirements.
2. Cart edits may queue offline; checkout must be online because it protects authoritative inventory/order invariants.
3. Without them, a number such as p95<250 ms cannot be reproduced or interpreted.
4. App Check attests app/device context and can reduce abuse; it does not replace user authorization or IAM.
5. Measured failure of workload fit—correctness, query expressiveness, scale, cost, recovery, governance or maintainability—not feature fashion.
Summary and next step
This lesson established the working contract for Define User Journeys, Data Model, Queries, Realtime/Offline Needs, Atomicity, Retention, Security, SLOs, and Cost Budget. Keep its edition/mode assumptions, trust boundary, verification evidence, and operational constraints explicit when reusing the pattern.
Next, continue to Implement Documents/Indexes/Queries/Listeners/Transactions, Typed SDK Access, Security Rules, and Trusted Backend Paths.
Authoritative references
- Firebase: Cloud Firestore documentation — Standard Native/Core application semantics.
- Firebase: Security Rules conditions — Rules are not filters and server libraries bypass Rules in favor of IAM/ADC.
- Firebase: Connect to the Cloud Firestore emulator — demo projects and emulator/production differences.
- Firebase: Transactions and batched writes — retries, atomicity and offline constraints.
- Firebase: Firestore best practices — hotspot avoidance and gradual traffic ramping.
- Firebase: Firestore pricing — document/index-entry/listener/aggregation billing in Standard.
- Firebase: Vector search — vector indexes, dimensions, query limits and supported server SDKs.
- Google Cloud: Firestore release notes — current Enterprise/Pipeline launch status and product changes.
- Google Cloud: Core and Pipeline query interfaces — Standard/Enterprise indexing and query-interface differences.
- Google Cloud: Firestore with MongoDB compatibility overview — serverless compatibility surface, not MongoDB itself.
- Google Cloud: Firestore backups and restore — managed recovery mechanisms.
- Google Cloud: Point-in-time recovery — historical recovery window and managed semantics.