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.

Advanced · 180–240 minutesrequirements · SLOs · edition/mode · data model · retention · security · costNode 22+ · Firebase CLI course baseline 15.30.0 · JS SDK 12.19.0 · Admin SDK 14.4.0 · rules-unit-testing 5.0.2Mandatory capstone demo project + Emulator Suite/no-cost · managed production verification explicitly separatedLast reviewed: 17 September 2026

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.

Learning outcomes
  • 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.
Execution and safety note

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.

Chapter 27 reproducibility baseline · reviewed 17 September 2026

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

docs/adr-027-firestore-capstone.json
{  "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

AtlasMart document contracts
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

Broken design

“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

  1. Create capstone/adr.json from the decision record above.
  2. Create capstone/journeys.json with the six journeys and expected query/write/security path.
  3. Create capstone/known-limits.json with emulator index/limit/transaction gaps, transaction retry semantics, hotspot risk, TTL eventuality, vector no-listener boundary and recovery cloud-only evidence.
  4. Start Firestore/Auth emulators under demo-atlasmart-firestore.
  5. Seed five products, one cart, two inventory SKUs, one order and synthetic events.
  6. Run a script that validates every document has schemaVersion and every journey has an evidence owner.
Minimal architecture gate
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`);
Expected state

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

  1. Why is Enterprise not the automatic capstone choice?
  2. Which AtlasMart action may work offline, and which must remain online?
  3. Why does an SLO need a population and evidence source?
  4. Why is App Check absent from the core authorization decision?
  5. 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

Keep knowledge open

Help the academy stay free and grow.

If these tutorials save you time, a small donation supports new lessons, technical review, diagrams, examples, and long-term maintenance.

ETHEthereum / ERC-20 only
0x716c4Ab160C4B66F31a28AE2448BfF68fc3a2ef0

Send only Ethereum or ERC-20 compatible assets to this address.