Managed Availability, Regions, Export and Recovery

Article · 7:00

What Google manages and what remains yours, regional and multi-region choices, export and import, backups and point-in-time recovery, and emulator-based testing.

This lesson has 1 runnable example. Press Try yourself! under any of them to open it in the editor.

Know what is managed and what is still your problem. Google manages replication, failover, patching, scaling and capacity. There is no instance to size, no failover to orchestrate and no replication lag to monitor - which removes most of the operational work in the other courses in this programme.

What remains yours is everything to do with your data and your design. A managed database does not protect you from a bad deployment that deletes documents, a Security Rule that lets a user write someone else's data, a Cloud Function in a loop, or a schema whose cost grows faster than your revenue. Managed availability is not managed correctness, and the capstone's recovery runbook exists for exactly these cases.

Location is chosen once and cannot be changed. A regional location (europe-west2) keeps data in one region: lower latency for nearby users, lower cost, and availability tied to that region. A multi-region location (eur3, nam5) replicates across regions: higher availability and higher cost. You cannot move a database between locations - migration means creating a new database and copying, so this decision deserves real thought, including data residency requirements, before the first document is written.

Export and import writes a database or selected collections to Cloud Storage and reads it back. The important properties: an export is not transactionally consistent unless you pin a snapshot-time; it bills one read per document exported; it can be scheduled; and import overwrites documents with matching IDs while leaving others untouched, which means an import is a merge rather than a restore to a point in time.

Managed backups and point-in-time recovery are the newer and better mechanism. Scheduled backups with a retention period, and PITR allowing a read at any microsecond within the retention window (seven days at the time of writing) - which lets you recover from a bad deployment by reading the data as it was before it. PITR must be enabled in advance, and it is the single most valuable reliability setting in Firestore. Enable it on day one.

Emulator-based testing is the reliability practice specific to this course. Because the emulator runs the real rules engine and a real Firestore implementation locally, you can test the things that actually break: Security Rules (with the rules unit testing library), Cloud Function triggers, transaction contention, and a full seed-and-verify cycle in CI. A Firestore project without emulator tests in CI has no regression protection on its authorisation layer, which is its most dangerous surface.

Laboratory exercise 5 - break it, then get it back.

Enable point-in-time recovery and configure a backup schedule.

Perform a destructive mistake at a recorded time - a script that deletes or corrupts a collection, which is a realistic incident. Then recover three ways and compare: a PITR read of the data as it was before, a restore from a managed backup, and an import from an export. Time each, and record RPO and RTO for each.

Then do the export properly: export with and without snapshot-time while writes are happening, and show the inconsistency in the unpinned one.

Demonstrate that an import is a merge: export, modify and add documents, import, and show which documents were overwritten and which survived.

Build an emulator-based CI test suite that seeds data, runs your rules tests, exercises your Cloud Function triggers, and verifies your invariants. Make it run on every commit.

Finally, produce the region design exercise: your location choice with its latency, cost, availability and data residency consequences, and what migration would cost if the choice were wrong.

Deliverable: the recovery runbook, measured RPO and RTO for all three methods, the export consistency demonstration, the import merge evidence, the CI suite with a passing run, and the region decision with its argument.

JS Example 1 110 lines
// ================= What is managed, and what is not ================
//   GOOGLE MANAGES:  replication, failover, patching, scaling,
//                    capacity. No instance to size, no failover to
//                    orchestrate, no replication lag to watch.
//
//   STILL YOURS:     a bad deployment that deletes documents
//                    a Security Rule that leaks data
//                    a Cloud Function in a loop
//                    a schema whose cost outgrows your revenue
//
// Managed availability is NOT managed correctness. The runbook is for
// these, not for hardware.

// ================= LOCATION: chosen once, CANNOT be changed ========
//   regional     europe-west2   lower latency nearby, lower cost,
//                               availability tied to one region
//   multi-region eur3 / nam5    replicated across regions, higher
//                               availability, higher cost
//
// You CANNOT move a database between locations. Migration means
// creating a new database and copying everything. Decide before the
// first document is written, and include DATA RESIDENCY in the
// argument - it is usually the constraint that settles it.

// ================= POINT-IN-TIME RECOVERY ==========================
// MUST BE ENABLED IN ADVANCE. The single most valuable reliability
// setting in Firestore. Turn it on on day one.
//   gcloud firestore databases update --database='(default)' \
//       --enable-pitr
//
// Then read the data as it was, at any microsecond in the window
// (7 days at the time of writing):
//   gcloud firestore export gs://my-bucket/pitr-recovery \
//       --snapshot-time='2026-11-30T14:04:00.000000Z' \
//       --collection-ids='messages','rooms'
//
// This is what recovers you from a bad deployment: read the data from
// before it ran. No other mechanism here does that.

// Scheduled managed backups:
//   gcloud firestore backups schedules create \
//       --database='(default)' --recurrence=daily \
//       --retention=14d
//   gcloud firestore backups list --location=europe-west2
//   gcloud firestore databases restore \
//       --source-backup=projects/p/locations/l/backups/b \
//       --destination-database='restored-db'
// A restore creates a NEW database. It does not overwrite in place -
// which is safer, and means your runbook includes a cutover step.

// ================= EXPORT and IMPORT ===============================
//   gcloud firestore export gs://my-bucket/exports/$(date +%F) \
//       --collection-ids='rooms','messages'
//
// THREE properties that matter:
//   1. NOT transactionally consistent unless you pin --snapshot-time.
//      An export taken while writes happen can contain a room whose
//      lastMessage points at a message not in the export.
//      Demonstrate this in the lab.
//   2. It bills 1 READ PER DOCUMENT exported. A nightly full export
//      of 10,000,000 documents is 10,000,000 reads per night.
//   3. IMPORT IS A MERGE, NOT A RESTORE. Documents with matching ids
//      are OVERWRITTEN; documents not in the export are LEFT ALONE.
//      So importing yesterday's export does NOT undo today's
//      deletions - the deleted documents come back AND today's new
//      documents stay. That is rarely what "restore" means to the
//      person asking for one.
//   gcloud firestore import gs://my-bucket/exports/2026-11-29

// ================= EMULATOR-BASED CI: the practice that matters ====
// The emulator runs the REAL rules engine. So you can test the things
// that actually break, on every commit, for nothing.
//
// package.json:
//   "test": "firebase emulators:exec --only firestore,auth 'vitest run'"

import { initializeTestEnvironment, assertFails, assertSucceeds }
  from "@firebase/rules-unit-testing";

let testEnv;
beforeAll(async () => {
  testEnv = await initializeTestEnvironment({
    projectId: "demo-chat",
    firestore: { rules: readFileSync("firestore.rules", "utf8") }
  });
});
afterEach(() => testEnv.clearFirestore());

test("a non-member cannot read a room's messages", async () => {
  // Seed with rules DISABLED, so the fixture is not fighting them:
  await testEnv.withSecurityRulesDisabled(async (ctx) => {
    await ctx.firestore().doc("rooms/r1").set({ name: "Private" });
    await ctx.firestore().doc("rooms/r1/members/alice").set({ uid: "alice" });
    await ctx.firestore().doc("rooms/r1/messages/m1").set({ text: "secret" });
  });
  const bob = testEnv.authenticatedContext("bob").firestore();
  await assertFails(bob.doc("rooms/r1/messages/m1").get());

  const alice = testEnv.authenticatedContext("alice").firestore();
  await assertSucceeds(alice.doc("rooms/r1/messages/m1").get());
});
// A Firestore project without these tests in CI has NO regression
// protection on its authorisation layer - which is its most
// dangerous surface. This is not optional tooling.

// ================= Verify a recovery with assertions ===============
// "The database restored" is not verification. Run the invariants:
//   * every room's memberCount equals its members subcollection size
//   * every room's lastMessage exists in its messages subcollection
//   * no message has an authorId with no corresponding user

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.