Skip to content

Firebase Without the Backend Sprawl: A Small-Team Architecture Blueprint

Design a small Firebase application around explicit Firestore access patterns, deny-by-default security rules, and transactional Cloud Functions, from local development through recovery.

Ekanatha Reddy Urivakili17 min2,916 words

1) Context and scale

Consider a shared task application for small businesses. Users sign in, open a workspace, and maintain its task list. Workspace members can read tasks; editors and owners can create them.

The architecture uses Firebase Authentication, a regional Cloud Firestore database, Firebase Hosting, and one second-generation Cloud Function. It deliberately avoids an API service, message broker, search engine, and separate administrative application.

The important split is:

  • Read directly from Firestore, with Security Rules enforcing tenant isolation.
  • Execute business commands through Cloud Functions, with authorization inside each command.
  • Keep privileged provisioning outside the browser.

This is not a universal Firebase pattern. Direct client writes are appropriate for simple user-owned data. Here, a command boundary makes role checks, idempotency, audit logging, and future workflow changes easier to reason about.

Planning assumptions

All capacity and budget figures below are assumptions, not observed performance or published service guarantees.

DimensionAssumption
Users800 registered users; 300 daily active users
Traffic2 application operations/s average during active hours; 20/s short peaks
Task creation30,000 commands/month, including retries
Firestore operations1.5 million reads and 150,000 writes/month
Data volume2 GiB including indexes and retained command receipts
TeamTwo engineers sharing development and operations
DeploymentOne production project; regional services in us-central1
BudgetTarget below $50/month, excluding labour and domain registration
AvailabilityBusiness application, not a safety-critical service

Use a supported Node.js 22 runtime for the functions in this blueprint. Commit dependency lockfiles and validate runtime support before upgrading; do not couple a small application to untested floating dependencies.

2) Requirements

Functional requirements

RequirementImplementation boundaryAcceptance condition
Sign inFirebase AuthenticationUnauthenticated requests cannot access workspace data
Open a workspaceFirestore SDK and rulesOnly active members can read it
List tasksBounded Firestore queryPages contain at most 50 tasks
Create a taskCallable Cloud FunctionOnly editors and owners succeed
Retry a commandTransactional command receiptSame request identifier returns the same task
Manage membershipTrusted provisioning tool initiallyBrowsers cannot grant roles

Membership management is intentionally operational at first. An engineer provisions the initial workspace and owner using an Admin SDK script with short-lived credentials. A self-service invitation flow can follow when product demand justifies it.

Non-functional requirements

ConcernTarget or constraint
IsolationEvery workspace read and mutation checks membership
ConsistencyTask creation and its command receipt commit atomically
LatencyServer-side task creation p95 below 1.5 seconds under normal load
Availability99.5% successful eligible commands over a rolling 30-day window
RecoveryTarget RPO of 24 hours and RTO of four hours
PrivacyNo task content, tokens, or email addresses in logs
MaintainabilityOne repository and one deployment pipeline
Cost controlBounded queries, instance limits, budget alerts, no minimum warm instances

Latency and recovery figures are engineering targets requiring validation. They are not consequences of selecting Firebase.

3) High-level design

flowchart LR
    Browser["Browser application"]
    Hosting["Firebase Hosting"]
    Auth["Firebase Authentication"]
    Firestore["Cloud Firestore"]
    Rules["Firestore Security Rules"]
    Functions["Cloud Functions for Firebase"]
    Observe["Cloud Logging and Cloud Trace"]

    Hosting --> Browser
    Browser --> Auth
    Browser -->|"Bounded task queries"| Firestore
    Rules -->|"Authorize SDK access"| Firestore
    Browser -->|"Callable createTask"| Functions
    Functions -->|"Admin SDK transaction"| Firestore
    Functions --> Observe

The browser reads through rules, while privileged commands execute inside a small server-side boundary.

Use Firebase Hosting for static assets. Authentication establishes identity; it does not establish workspace authorization.

The function uses the Admin SDK, which bypasses Firestore Security Rules. Its transaction must therefore check membership independently. Rules and application authorization protect different entry points.

Keep functions and Firestore colocated. A single region reduces cross-region latency and operational complexity, but it also defines the regional failure boundary.

Start with one callable function and a small set of modules. Adding a function for every entity method would create deployment complexity without improving isolation.

For list screens, fetch a page and explicitly refresh it. Attach realtime listeners only where product behaviour needs them, and always detach them when the screen closes. A background listener is a continuing database workload, not a free local cache.

4) Cloud service mapping

These equivalents describe comparable responsibilities, not interchangeable APIs. Firestore’s client SDK and rules model does not map directly onto the other clouds.

ComponentChosen GCP serviceAWS equivalentAzure equivalentGCP equivalent
Static frontendFirebase HostingAmplify HostingStatic Web AppsFirebase Hosting
End-user identityFirebase AuthenticationAmazon CognitoMicrosoft Entra External IDFirebase Authentication
Document databaseCloud FirestoreDynamoDB, with different modellingAzure Cosmos DBCloud Firestore
Command executionCloud Functions for Firebase, second generationAWS LambdaAzure FunctionsCloud Run functions
Client data authorizationFirestore Security RulesIAM/AppSync resolver authorization, redesignedAPI authorization/Cosmos access controls, redesignedFirestore Security Rules
Logs and metricsCloud Logging and MonitoringCloudWatchAzure MonitorCloud Logging and Monitoring
TracesCloud TraceAWS X-RayApplication InsightsCloud Trace
CI federationWorkload Identity FederationIAM OIDC federationWorkload identity federationWorkload Identity Federation

Do not add API Gateway simply because another blueprint includes it. Firebase callable functions already supply the client protocol, authentication integration, and App Check integration needed here.

The trade-off is deliberate Firebase coupling. That coupling buys a smaller operational surface. Keep domain validation in ordinary TypeScript functions so migration does not require extracting business policy from transport handlers.

5) Data design

Model Firestore around the queries the application actually executes.

Document pathImportant fieldsAccess pattern
workspaces/{workspaceId}name, createdAtGet a known workspace
workspaces/{workspaceId}/members/{uid}role, activeMembership check by exact identity
workspaces/{workspaceId}/tasks/{taskId}title, status, createdBy, timestampsGet one; list by status and update time
workspaces/{workspaceId}/commands/{commandId}actorId, fingerprint, taskId, createdAtServer-only retry lookup
erDiagram
    WORKSPACE ||--o{ MEMBER : contains
    WORKSPACE ||--o{ TASK : contains
    WORKSPACE ||--o{ COMMAND : records
    MEMBER ||--o{ TASK : creates
    COMMAND ||--|| TASK : creates

    WORKSPACE {
        string workspaceId PK
        string name
    }
    MEMBER {
        string uid PK
        string role
        boolean active
    }
    TASK {
        string taskId PK
        string createdBy
        string status
        string title
    }
    COMMAND {
        string commandId PK
        string fingerprint
        string taskId
    }

Relationships are application invariants; Firestore does not enforce these foreign keys.

The following SQL DDL is an executable SQLite documentation mirror, not a database deployed alongside Firestore. It makes uniqueness and relationships explicit during design review.

PRAGMA foreign_keys = ON;

CREATE TABLE workspace (
    workspace_id TEXT PRIMARY KEY,
    name TEXT NOT NULL
);

CREATE TABLE member (
    workspace_id TEXT NOT NULL REFERENCES workspace(workspace_id),
    uid TEXT NOT NULL,
    role TEXT NOT NULL CHECK (role IN ('owner', 'editor', 'viewer')),
    active INTEGER NOT NULL CHECK (active IN (0, 1)),
    PRIMARY KEY (workspace_id, uid)
);

CREATE TABLE task (
    workspace_id TEXT NOT NULL,
    task_id TEXT NOT NULL,
    created_by TEXT NOT NULL,
    title TEXT NOT NULL CHECK (length(title) BETWEEN 1 AND 200),
    status TEXT NOT NULL CHECK (status IN ('open', 'done')),
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL,
    PRIMARY KEY (workspace_id, task_id),
    FOREIGN KEY (workspace_id, created_by)
        REFERENCES member(workspace_id, uid)
);

CREATE TABLE command (
    workspace_id TEXT NOT NULL,
    command_id TEXT NOT NULL,
    actor_id TEXT NOT NULL,
    fingerprint TEXT NOT NULL,
    task_id TEXT NOT NULL,
    PRIMARY KEY (workspace_id, command_id),
    FOREIGN KEY (workspace_id, task_id)
        REFERENCES task(workspace_id, task_id)
);

The task query is workspace-scoped, filters by status, orders by updatedAt, and uses a cursor for pagination. Avoid offsets: skipping records still consumes reads.

Commit its index definition:

{
  "indexes": [
    {
      "collectionGroup": "tasks",
      "queryScope": "COLLECTION",
      "fields": [
        { "fieldPath": "status", "order": "ASCENDING" },
        { "fieldPath": "updatedAt", "order": "DESCENDING" }
      ]
    }
  ],
  "fieldOverrides": [
    {
      "collectionGroup": "tasks",
      "fieldPath": "title",
      "indexes": []
    }
  ]
}

Store this as firestore.indexes.json.

Do not place an ever-growing array of tasks or members in the workspace document. Independent documents avoid unbounded document growth and unnecessary write contention. Do not maintain a global task counter on every creation unless the product actually needs one.

Command receipts remain durable in this version. Deleting them changes the idempotency contract; introduce retention only with an explicit retry horizon and corresponding client behaviour.

6) Low-level design

classDiagram
    class TaskScreen {
        loadPage()
        submitTask()
    }
    class FirestoreReader {
        listTasks()
    }
    class CallableClient {
        createTask()
    }
    class CreateTaskCommand {
        validate()
        executeTransaction()
    }
    class MembershipPolicy {
        canCreate()
    }

    TaskScreen --> FirestoreReader
    TaskScreen --> CallableClient
    CallableClient --> CreateTaskCommand
    CreateTaskCommand --> MembershipPolicy

The browser has separate read and command paths, but the backend remains one small module.

Minimal runnable example: prove the read boundary

Use deny-by-default rules. The helper reads a single membership document; a missing document fails authorization.

Save the following as firestore.rules:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    function activeMember(workspaceId) {
      return request.auth != null
        && get(/databases/$(database)/documents/workspaces/$(workspaceId)/members/$(request.auth.uid)).data.active == true;
    }

    match /workspaces/{workspaceId} {
      allow get: if activeMember(workspaceId);

      match /members/{uid} {
        allow get: if request.auth != null
          && request.auth.uid == uid;
      }

      match /tasks/{taskId} {
        allow get: if activeMember(workspaceId);
        allow list: if activeMember(workspaceId)
          && request.query.limit != null
          && request.query.limit <= 50;
      }
    }
  }
}

Unspecified writes and command-receipt access are denied.

Create the local configuration:

{
  "firestore": {
    "rules": "firestore.rules",
    "indexes": "firestore.indexes.json"
  },
  "functions": {
    "source": "functions"
  },
  "hosting": {
    "public": "public",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"]
  },
  "emulators": {
    "firestore": {
      "port": 8080
    }
  }
}

Install the test tools and use the Java version required by the installed Emulator Suite:

npm init -y
npm install --save-dev firebase-tools @firebase/rules-unit-testing
npm install firebase
mkdir -p test

# After saving the test below:
npx firebase emulators:exec \
  --project demo-taskboard \
  --only firestore \
  "node --test test/rules.test.mjs"

Save this test as test/rules.test.mjs:

import { readFileSync } from "node:fs";
import test from "node:test";
import {
  initializeTestEnvironment,
  assertFails,
  assertSucceeds
} from "@firebase/rules-unit-testing";
import {
  collection, doc, getDocs, limit, query, setDoc
} from "firebase/firestore";

test("members can read bounded pages, but cannot write tasks", async () => {
  const env = await initializeTestEnvironment({
    projectId: "demo-taskboard",
    firestore: {
      rules: readFileSync("firestore.rules", "utf8")
    }
  });

  try {
    await env.withSecurityRulesDisabled(async context => {
      const db = context.firestore();
      await setDoc(doc(db, "workspaces/w1/members/alice"), {
        active: true,
        role: "editor"
      });
      await setDoc(doc(db, "workspaces/w1/tasks/t1"), {
        title: "Review rules",
        status: "open"
      });
    });

    const alice = env.authenticatedContext("alice").firestore();
    const outsider = env.authenticatedContext("mallory").firestore();
    const path = "workspaces/w1/tasks";

    await assertSucceeds(getDocs(query(collection(alice, path), limit(50))));
    await assertFails(getDocs(collection(alice, path)));
    await assertFails(getDocs(query(collection(outsider, path), limit(50))));
    await assertFails(setDoc(doc(alice, `${path}/t2`), {
      title: "Bypass the command"
    }));
  } finally {
    await env.cleanup();
  }
});

Notice that the test proves both tenant isolation and the prohibition on direct writes.

Rules are not filters: a query must be authorized as a whole. The workspace path establishes the tenant boundary; the limit bounds each response. It does not rate-limit an attacker who repeatedly issues permitted queries.

Realistic runnable example: transactional task creation

Initialize the function package:

mkdir -p functions/src
cd functions
npm init -y
npm pkg set main=lib/index.js engines.node=22
npm pkg set scripts.build="tsc"
npm install firebase-admin firebase-functions \
  @opentelemetry/api @opentelemetry/sdk-trace-node \
  @opentelemetry/sdk-trace-base @opentelemetry/resources \
  @google-cloud/opentelemetry-cloud-trace-exporter
npm install --save-dev typescript @types/node
cd ..

Use this functions/tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "outDir": "lib",
    "strict": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*.ts"]
}

Save the handler as functions/src/index.ts. The tracing helper is supplied in section 9.

import { createHash } from "node:crypto";
import { initializeApp } from "firebase-admin/app";
import { FieldValue, getFirestore } from "firebase-admin/firestore";
import { logger } from "firebase-functions";
import { HttpsError, onCall } from "firebase-functions/v2/https";
import { traceCommand } from "./telemetry.js";

initializeApp();
const db = getFirestore();

function hash(value: string): string {
  return createHash("sha256").update(value).digest("hex");
}

export const createTask = onCall(
  {
    region: "us-central1",
    memory: "256MiB",
    timeoutSeconds: 30,
    minInstances: 0,
    maxInstances: 3,
    concurrency: 20,
    enforceAppCheck: true
  },
  async request => traceCommand(request.rawRequest.headers, async () => {
    const uid = request.auth?.uid;
    if (!uid) throw new HttpsError("unauthenticated", "Sign in first.");

    const data = request.data;
    if (
      !data || typeof data !== "object" ||
      typeof data.workspaceId !== "string" ||
      !/^[A-Za-z0-9_-]{1,64}$/.test(data.workspaceId) ||
      typeof data.requestId !== "string" ||
      !/^[A-Za-z0-9_-]{16,80}$/.test(data.requestId) ||
      typeof data.title !== "string"
    ) {
      throw new HttpsError("invalid-argument", "Invalid command.");
    }

    const title = data.title.trim();
    if (title.length < 1 || title.length > 200) {
      throw new HttpsError("invalid-argument", "Invalid title.");
    }

    const workspaceId: string = data.workspaceId;
    const commandId = hash(`${uid}:${data.requestId}`);
    const fingerprint = hash(JSON.stringify({ title }));
    const base = db.doc(`workspaces/${workspaceId}`);
    const memberRef = base.collection("members").doc(uid);
    const commandRef = base.collection("commands").doc(commandId);
    const taskRef = base.collection("tasks").doc(commandId);
    const started = Date.now();

    const result = await db.runTransaction(async tx => {
      const [member, receipt] = await tx.getAll(memberRef, commandRef);
      const membership = member.data();

      if (
        membership?.active !== true ||
        !["owner", "editor"].includes(membership.role)
      ) {
        throw new HttpsError("permission-denied", "Editor access required.");
      }

      if (receipt.exists) {
        if (receipt.get("fingerprint") !== fingerprint) {
          throw new HttpsError(
            "already-exists",
            "Request identifier was used for another command."
          );
        }
        return { taskId: receipt.get("taskId") as string, replayed: true };
      }

      const timestamp = FieldValue.serverTimestamp();
      tx.create(taskRef, {
        title,
        status: "open",
        createdBy: uid,
        createdAt: timestamp,
        updatedAt: timestamp
      });
      tx.create(commandRef, {
        actorId: uid,
        fingerprint,
        taskId: taskRef.id,
        createdAt: timestamp
      });

      return { taskId: taskRef.id, replayed: false };
    });

    logger.info("task.create.completed", {
      commandId,
      workspaceId,
      taskId: result.taskId,
      replayed: result.replayed,
      durationMs: Date.now() - started
    });

    return result;
  })
);

Notice that authorization, receipt lookup, task creation, and receipt creation share one transaction.

The handler may execute more than once; the durable outcome remains one task per actor, workspace, and request identifier. Reusing an identifier with different content fails instead of silently returning an unrelated result.

Firestore can rerun transaction callbacks. Never send email, publish external events, or emit business-success logs inside the callback.

The browser generates one request identifier per user action and retains it across retries. Deploy the callable only after configuring the frontend’s App Check provider; local integration tests use an appropriately configured emulator or registered debug token, never a production enforcement bypass.

7) Key flows

sequenceDiagram
    participant Browser
    participant Auth as Firebase Authentication
    participant DB as Cloud Firestore
    participant Rules as Security Rules

    Browser->>Auth: Sign in
    Auth-->>Browser: ID token
    Browser->>DB: Workspace task query with limit
    DB->>Rules: Evaluate identity and membership
    Rules-->>DB: Allow or deny
    DB-->>Browser: One page or permission denied

Task reads stay off the function path while retaining workspace authorization.

sequenceDiagram
    participant Browser
    participant Function as Create Task Function
    participant DB as Cloud Firestore

    Browser->>Function: Command with stable requestId
    Function->>Function: Verify identity and validate input
    Function->>DB: Transaction reads membership and receipt
    alt New command
        Function->>DB: Atomically create task and receipt
    else Existing command
        Function->>Function: Compare payload fingerprint
    end
    Function-->>Browser: Stable taskId

Retries repeat the request, not the business effect.

After a network timeout, the browser cannot know whether the transaction committed. It retries with the original identifier and exponential backoff with jitter. It must not generate a fresh identifier merely because the response was lost.

A membership revocation races safely with creation because membership is read inside the transaction. Once revocation wins, subsequent command attempts fail, including retries of previously completed commands.

8) Build and release

Use Terraform for durable platform configuration and Firebase CLI for rules, indexes, hosting, and functions. Do not let both tools manage the same database resource.

This focused Terraform excerpt assumes an existing billing-enabled Firebase project. API enablement, IAM, App Check registration, and CI federation belong in the surrounding infrastructure configuration.

terraform {
  required_providers {
    google = {
      source = "hashicorp/google"
    }
  }
}

variable "project_id" {
  type = string
}

provider "google" {
  project = var.project_id
}

resource "google_firestore_database" "primary" {
  project                     = var.project_id
  name                        = "(default)"
  location_id                 = "us-central1"
  type                        = "FIRESTORE_NATIVE"
  delete_protection_state     = "DELETE_PROTECTION_ENABLED"
  point_in_time_recovery_enablement = "POINT_IN_TIME_RECOVERY_ENABLED"

  lifecycle {
    prevent_destroy = true
  }
}

Commit Terraform’s provider lockfile. Import an existing database rather than trying to recreate one, and verify location before creation: moving regions is a migration.

A minimal GitHub Actions pipeline uses federation rather than a downloaded service-account key:

name: firebase-release

on:
  pull_request:
  push:
    branches: [main]

permissions:
  contents: read

jobs:
  verify:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - uses: actions/setup-node@v5
        with:
          node-version: "22"
          cache: npm
      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: "21"
      - run: npm ci
      - run: npm ci --prefix functions
      - run: npm run build --prefix functions
      - run: >
          npx firebase emulators:exec
          --project demo-taskboard
          --only firestore
          "node --test test/rules.test.mjs"

  deploy:
    if: github.event_name == 'push'
    needs: verify
    runs-on: ubuntu-latest
    environment: production
    permissions:
      contents: read
      id-token: write
    steps:
      - uses: actions/checkout@v5
      - uses: actions/setup-node@v5
        with:
          node-version: "22"
          cache: npm
      - uses: google-github-actions/auth@v3
        with:
          workload_identity_provider: ${{ vars.WIF_PROVIDER }}
          service_account: ${{ vars.DEPLOY_SERVICE_ACCOUNT }}
      - run: npm ci
      - run: npm ci --prefix functions
      - run: npm run build --prefix functions
      - run: >
          npx firebase deploy
          --project "${{ vars.FIREBASE_PROJECT_ID }}"
          --only firestore:indexes
          --non-interactive
      - run: >
          npx firebase deploy
          --project "${{ vars.FIREBASE_PROJECT_ID }}"
          --only firestore:rules,functions,hosting
          --non-interactive

Configure production environment approval and restrict the federation trust to the repository and deployment context. Pin actions to reviewed commit SHAs in the maintained repository.

The test strategy extends beyond the runnable smoke test:

LayerTests
UnitInput validation, role decisions, canonical payload fingerprint
Rules integrationOutsiders, inactive members, unbounded queries, direct writes, receipt access
Command integrationDuplicate submissions, conflicting payloads, revoked membership, concurrent retries
ContractCallable errors and response shape against the Firebase client SDK
LoadAssumed 20/s peak, cold starts, transaction retries, instance cap behaviour
RecoveryRestore data, redeploy rules/indexes, verify authorized access

The emulator does not prove production IAM, App Check configuration, or index readiness. Test those in a separate, disposable Firebase project before the first release and significant infrastructure changes.

Index creation is asynchronous. The pipeline submits definitions, but a release needing a new index must wait for it to become ready before exposing the corresponding query.

9) Observability

Log command outcomes, not document contents. Include command identifier, workspace identifier, replay status, duration, and trace correlation. Treat even opaque workspace identifiers as access-controlled operational data.

A useful structured entry looks like this:

{
  "severity": "INFO",
  "message": "task.create.completed",
  "commandId": "9f34...",
  "workspaceId": "w1",
  "taskId": "9f34...",
  "replayed": false,
  "durationMs": 184,
  "logging.googleapis.com/trace": "projects/example/traces/0123456789abcdef0123456789abcdef"
}

OpenTelemetry tracing

Save this as functions/src/telemetry.ts, completing the function example. It creates a command span and extracts W3C trace context when provided. It does not automatically instrument every Firestore RPC.

import {
  context, propagation, SpanKind, SpanStatusCode, trace
} from "@opentelemetry/api";
import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";
import { resourceFromAttributes } from "@opentelemetry/resources";
import { TraceExporter } from "@google-cloud/opentelemetry-cloud-trace-exporter";
import { logger } from "firebase-functions";

const provider = new NodeTracerProvider({
  resource: resourceFromAttributes({
    "service.name": "task-commands"
  }),
  spanProcessors: [
    new BatchSpanProcessor(new TraceExporter(), {
      maxQueueSize: 128,
      maxExportBatchSize: 32,
      scheduledDelayMillis: 500,
      exportTimeoutMillis: 1500
    })
  ]
});

provider.register();
const tracer = trace.getTracer("taskboard");

export async function traceCommand<T>(
  headers: Record<string, string | string[] | undefined>,
  work: () => Promise<T>
): Promise<T> {
  const parent = propagation.extract(context.active(), headers);

  return context.with(parent, () =>
    tracer.startActiveSpan(
      "task.create",
      { kind: SpanKind.SERVER },
      async span => {
        try {
          return await work();
        } catch (error) {
          const code = String(
            (error as { code?: unknown } | null)?.code ?? "internal"
          );
          span.setAttribute("app.error_code", code);

          const rejected = [
            "unauthenticated", "permission-denied",
            "invalid-argument", "already-exists"
          ].includes(code);

          if (!rejected) {
            span.setStatus({ code: SpanStatusCode.ERROR });
          }

          const project = process.env.GCLOUD_PROJECT;
          logger.write({
            severity: rejected ? "WARNING" : "ERROR",
            message: rejected ? "task.create.rejected" : "task.create.failed",
            errorCode: code,
            ...(project ? {
              "logging.googleapis.com/trace":
                `projects/${project}/traces/${span.spanContext().traceId}`
            } : {})
          });
          throw error;
        } finally {
          span.end();
          try {
            await provider.forceFlush();
          } catch {
            logger.warn("telemetry.flush.failed");
          }
        }
      }
    )
  );
}

Notice that export happens before the invocation finishes, reducing dependence on background execution after the response.

Grant the runtime identity Trace Agent permissions and enable the Cloud Trace API. The explicit flush adds latency; measure it. At this scale, straightforward reliable export is preferable to building a telemetry collector service. Configure sampling as traffic grows, while retaining error logs independently.

Metrics, objectives, and pages

Signal familyMeasure
RED: rateCommands/s and Firestore read/write operations
RED: errorsUnexpected command failures, separated from validation and authorization rejections
RED: durationCommand p50/p95/p99 and client-observed latency
USE: utilizationFunction memory and instance count relative to the configured cap
USE: saturationConcurrency pressure, throttling, quota consumption
USE: errorsOut-of-memory terminations, quota errors, transaction exhaustion

Firestore does not expose database CPU utilization as though it were a VM. Use its operation, latency, quota, and error signals rather than inventing a resource-utilization percentage.

SLISLOMeasurement
Eligible command success99.5% over 30 daysSuccessful commands divided by successful plus unexpected failed commands
Command latency95% below 1.5 secondsServer-side command duration
Authorized read journey99.5% successful synthetic journeysScheduled test identity querying an isolated fixture
Recovery readinessSuccessful restore exercise quarterlyRecorded exercise result and elapsed recovery time

Use one dashboard: command RED signals, Firestore operations, permission-denied trends, function instance/memory behaviour, and estimated spend.

Page on sustained unexpected failures with meaningful traffic, persistent synthetic journey failure, or repeated resource exhaustion. Use multi-window error-budget alerts to avoid paging on isolated cold starts. Authorization spikes, cost drift, and backup failures normally create urgent tickets rather than waking someone immediately.

10) Security and compliance

Use a dedicated runtime service account with only required database, logging, and tracing permissions. Firestore IAM is broader than document-level rules; avoid sharing this identity with unrelated workloads.

Additional controls are small but consequential:

  • Enforce App Check, while recognizing it is not user authorization or comprehensive rate limiting.
  • Deny browser access to command receipts.
  • Keep role assignments in membership documents rather than long-lived custom claims.
  • Restrict deployment credentials through federation and repository protections.
  • Validate strings and identifiers before constructing document paths.
  • Exclude tokens, task titles, and email addresses from logs.
  • Review authentication provider configuration and account-recovery flows.

A regional database is not a blanket data-residency guarantee for authentication, hosting, logs, or every supporting service. Map each service’s processing and storage commitments to the actual compliance requirement.

Define deletion behaviour explicitly. Removing a workspace document does not recursively remove subcollections. A trusted deletion job must enumerate and delete descendants, record completion, and account for backup retention.

11) Cost

The following is an assumption-based monthly estimate, not a price quote. Dollar allocations are planning allowances, not assertions about current unit rates. Validate with the Google Cloud pricing calculator and actual Firebase billing reports.

Cost areaAssumed monthly usagePlanning allowance
Firestore operations1.5M reads; 150K writes; limited deletes$4
Firestore storage and indexes2 GiB$1
PITR and scheduled backupsSmall database; short retention$4
Function compute and invocation30K commands; zero minimum instances$4
Hosting and transfer2 GiB assets; 15 GiB delivery$5
Logging and tracingSmall structured records; bounded retention$3
Builds and artifact storageModest release cadence; image cleanup$2
AuthenticationSelected non-SMS provider within applicable no-cost allowance$0
ContingencyReconnects, tests, retries, estimation error$12
Planning totalExcludes tax, support, domain, and labour$35

Reads are the first cost to investigate. Membership checks in rules, reconnecting listeners, and repeated page loads all contribute. Transaction retries also repeat work.

Budget alerts are notifications, not spending caps. Function instance limits constrain compute expansion, but direct Firestore clients can still generate database charges. Combine bounded queries, App Check, usage monitoring, and an incident procedure for disabling abusive access.

12) Failure modes, resilience and disaster recovery

FailureBehaviourResponse
Response lost after commitBrowser sees uncertaintyRetry original request identifier
Transaction conflictSDK retries transactionKeep callback side-effect-free
Function cold startIncreased latencyShow progress; measure before buying warm instances
Function cap reachedRejections or increased waitingBackoff; investigate before raising cap
Broken rules releaseReads denied or exposedRoll back rules immediately
Missing indexQuery failsBuild index before enabling query
Regional disruptionCore application unavailableCommunicate outage; follow recovery decision
Accidental deletionMissing documentsRestore and validate before cutover

Enable scheduled backups in addition to PITR, with retention aligned to the recovery target. Check that they actually execute.

A restore is not merely clicking a button. The runbook must cover the destination database, SDK configuration, rules, indexes, IAM, fixture checks, and application cutover. If restoring into another project, authentication users and provider configuration need a separate plan.

Practice recovery with a representative workspace. Measure elapsed time, verify task/receipt consistency, and confirm that unauthorized reads still fail. The four-hour target remains aspirational until demonstrated.

This blueprint does not promise automatic cross-region failover. Accepting a single-region dependency is reasonable at this scale when the business understands the trade-off.

13) Evolving to the next scale

Change architecture in response to measured limits, not user-count milestones alone.

TriggerNext change
Repeated command latency missesTune execution and dependencies; consider one warm instance
Reads dominated by unnecessary refreshTighten screen lifecycle and query strategy
Required email or external side effectsTransactional outbox plus an idempotent worker
Large membership administration workloadAdd audited invitation and role-management commands
Search exceeds Firestore query capabilitiesAdd a dedicated search index with explicit synchronization
Hot aggregate documentRemove synchronous counter updates or introduce sharded aggregation
Compliance requires regional recoveryDesign and rehearse a separate regional recovery architecture
Server IAM boundary becomes too broadSeparate privileged workloads and service identities

Do not introduce an event bus merely to update the same database after a successful command. Conversely, do not call an external payment or email API inside a transaction.

A Firestore trigger is not an exactly-once workflow engine. When asynchronous processing arrives, assume retries and potentially out-of-order delivery, and design durable processing state accordingly.

14) Phased implementation plan

Phase 1: establish the access boundary

  • Create the project and regional database.
  • Configure Authentication and App Check.
  • Implement membership documents and deny-by-default rules.
  • Make tenant-isolation tests pass before building the main interface.

Phase 2: ship one complete workflow

  • Implement bounded task reads and the callable command.
  • Test concurrent retries and conflicting request identifiers.
  • Provision one workspace through a trusted script.
  • Exercise the real client SDK against a disposable project.

Phase 3: make releases and operations repeatable

  • Add federated CI deployment and production approval.
  • Deploy indexes ahead of dependent queries.
  • Add command logs, traces, the dashboard, and actionable alerts.
  • Establish budgets, artifact cleanup, and backup retention.

Phase 4: prove readiness

  • Run the assumed peak workload.
  • Perform a restore exercise and rules rollback.
  • Verify deletion and membership-revocation behaviour.
  • Record ownership, incident steps, and measured recovery time.

The resulting architecture is intentionally modest: direct authorized reads, one transactional command boundary, and a managed regional database. Its strength is not the number of services. It is that data access, authorization, retries, release safety, and recovery each have an explicit owner and a testable contract.

Official references


This article was generated with AI. #AIGenerated