ArchitectureNo. 11

From Firebase to PostgreSQL while the stations kept billing

How FinyxWatt left Firestore for NestJS and PostgreSQL with stations live: an importer built to say no, 109 checksummed migrations, and releases that go back in one step.

In this article
  1. Make "no Firebase" a test, not a promise
  2. Keep the screens, replace what is under them
  3. An importer built to say no
  4. Give every migration a checksum and a lock
  5. Rehearse on the real database, then commit once
  6. Keep every change additive, so going back is one step
  7. What broke, and what each break changed
  8. The checklist for leaving a managed backend

The first version of FinyxWatt let a collector's phone write a bill straight into Firestore. What a phone was allowed to write lived in one file of security rules. On the day I retired it, that file was 2,731 lines long, and this was its rule for a bill:

text
match /bills/{billId} {
  allow read: if canReadThinOperationalData(resource.data);
  allow create: if canWriteThinOperationalData(request.resource.data)
    && isValidBillCreate(request.resource.data);
  allow update: if isSameCompanyData(resource.data)
    && canWriteThinOperationalData(resource.data)
    && (
      isValidBillPaymentSyncUpdate()
      || isValidBillNumberUpdate()
      || isValidBillEditUpdate()
      || isValidBillSmsDeliveryUpdate()
      || isValidBillZoneTransferUpdate()
    );
  allow delete: if canDeleteThinAdminLevelOperationalData(resource.data);
}

Five ways to change a bill and one way to delete it, each a function in the same file, every one reachable from a phone. A mistake in any of them was a mistake in the money.

Today no phone writes a bill into the database. It sends a command, a NestJS API decides, and PostgreSQL keeps the money in an append-only ledger. The move happened while the stations kept working, and by late October the schema stood at 109 migrations.

This is how the move was done: the rule that kept Firebase out, the layer that let staff keep their screens, the importer that was built to refuse, and the migration discipline that makes a live schema safe to change. By the end you will be able to move data you cannot fully trust, keep a migration history that cannot drift, and change a schema under live users with a way back that is one step long.

In short

  • The importer is built to say no: dry run by default, apply bound to the snapshot's SHA-256, production refused in code. On the last backup, its honest answer was "not ready".
  • Every migration runs once, in order, under an advisory lock, and its SHA-256 is stored. An edited file stops the deploy.
  • Every migration is additive: the previous API image must keep working on the new schema, so going back only swaps the image.

109

migrations, each with its SHA-256 in the database

46

of them shipped in scripted releases, 6 to 29 October

43,203

documents in the Firebase backup of 31 August

2,731

lines of Firestore rules retired

Make "no Firebase" a test, not a promise

The decision is dated 14 August 2026, in the platform's first architecture record: the new platform contains no Firebase runtime. Its reasons are the ones the rules file shows. Business rules lived in several clients and in security rules. The replacement had to run on a server I control, with one server-side authority for stations, permissions, money, SMS and the audit trail.

The record turns that into rules a reviewer can check. The server takes the station from the signed-in session, never from the request. Only the server sets timestamps, versions, counters, totals and ledger entries. Clients send intent as commands. Every write that may be retried carries an idempotency key, and every record that can be edited carries a version.

A rule nobody enforces decays, so CI enforces this one. A script scans every runtime folder for Firebase packages, configuration files, endpoints and API keys, and fails the build on any of them. One exception survived, and it is written into the gate with its reason:

js
// Since migration 0069 the platform sends push notifications itself through
// Firebase Cloud Messaging: plain HTTPS to the FCM HTTP v1 API from the
// worker process, without any Firebase SDK. Only that sender and its opt-in
// Compose override may name FCM or Firebase.
const pushSenderPaths = [/^backend\/src\/push\/[^/]+\.ts$/, /^infra\/compose\.push\.yaml$/];
const pushSenderLabels = new Set(['Firebase SDK or dependency', 'Firebase Cloud Messaging dependency']);

Push notifications on Android travel through Google's service, so the exception says exactly where it stops: two paths, two labels, no SDK. Every other rule still applies to those files, and a Firebase package is refused everywhere.

Keep the screens, replace what is under them

Station staff did not need a new app. They needed the same app on a new backend, so the move happened below the screens.

On 26 September one commit took the station app off the Firebase SDK. For the cutover, the class every screen called kept its old name, FirestoreService, but it became a REST client for the new API, with no Firebase code and no fallback. Handing it a Firebase dependency failed at once. Later it was renamed to what it had become, AppRepository.

The danger in such a swap is a screen that still looks as if it works. A button whose operation the new API did not support yet was not allowed to pretend. Each such operation went into a named registry, unavailableOperations, and its call failed with an explicit error. The release checker read that registry, and the cutover could not pass while it held a single entry. The handoff notes put the rule in one line: never replace a missing operation with a success stub.

Two details made testing on real phones safe. The test build had its own package name, com.moghalis.electricity.local, so it installed beside the production app on the same handset without touching it. And the new production app got its own name too, com.finyxwatt.company, so it installs next to the Firebase app instead of over it.

On FirebaseOn the platform
The phone writes documentsThe phone sends commands
2,731 lines of rules decide what a write may changeThe API and PostgreSQL decide, under tests
A bill can be changed five ways, or deletedMoney is append-only; corrections are new entries
Business rules repeated across clientsOne server-side authority
A Firebase project to operateA Compose stack on a server I control
The same station app, before and after the move

An importer built to say no

The data was the harder half. The last complete Firebase backup I could read was taken on 31 August: 43,203 documents in 28 collections. A fresh read-only export on 24 September failed, because Firestore answered HTTP 429 after bounded retries, so the newest data I could inspect was weeks old.

Most of those documents were not business records. 36,257 sat in collections with no place in the new schema: audit logs, SMS logs, the SMS queue, usage ledgers, device trust. The rest were the stations' real work: customers, meters, readings, bills and payments.

I wrote the importer to be hard to misuse:

  • Dry run is the default, and a dry run writes nothing.
  • The input file is hashed with SHA-256. An apply must repeat the exact digest the dry run printed, so it cannot run on a file nobody reviewed.
  • Each company goes in one transaction, with its checkpoint in that same transaction. A failed company leaves nothing behind, and an exact rerun skips a finished one.
  • Target ids are derived from the legacy ids, so a rerun produces the same rows, never a second copy.
  • It writes through a database role that cannot log in on its own, cannot bypass row-level security, and may only insert and read. A short-lived login borrows it and is dropped afterwards.
  • Production is refused in code.
js
export function uuidFor(namespace, legacyId) {
  const bytes = createHash('sha256').update(`electricity-platform/${namespace}/${legacyId}`).digest().subarray(0, 16);
  bytes[6] = (bytes[6] & 0x0f) | 0x50;
  bytes[8] = (bytes[8] & 0x3f) | 0x80;
  // … formatted as a UUID
}

if (normalizedEnvironment === 'production' || normalizedEnvironment === 'prod') {
  throw new Error('Production writes are hard-disabled in legacy importer v1.');
}
if (confirmDigest !== sourceDigest) {
  throw new Error('Apply requires --confirm-digest equal to the SHA-256 printed by dry-run.');
}

The guard does not trust the flag alone. A database whose host or name merely looks like production is refused as well.

On the August backup the dry run answered: no structural errors, 1,551 warnings, 26 manual actions, and readyToApply=false.

The warnings were the useful part. 1,153 payments carried fields that split one payment between the bill, older debt and credit. Mapping the gross amount alone would have kept every total and lost what each payment actually paid. 17 bill numbers and 29 receipt numbers repeated within a station. Six users had no verified identity in the new sign-in service yet.

Some things were never meant to cross. Passwords, tokens and device trust start fresh on the new platform, and the importer strips every key that looks like a credential. None of the 3,452 jobs in the old SMS queue crossed either: an imported job is a job a worker may send again, and a customer would receive an old bill twice.

I let the "no" stand. A tool that guesses which bill a payment paid is a tool that invents debt. So a station comes onto the platform from its subscriber list: each subscriber with a meter, the last reading and an opening balance. The import goes in slices. Each slice is one transaction, and each row sits behind its own savepoint:

ts
for (const row of rows) {
  const line = row.line, customerId = row.customerId;
  if (takenIds.has(customerId)) { results.push({ line, customerId, status: 'exists' }); continue; }
  // … subscriber number, zone and meter serial checked against the station
  await sql`SAVEPOINT customer_import_row`.execute(transaction);
  try {
    results.push(await this.importRow(transaction, actor, row, command.sendWelcome));
    await sql`RELEASE SAVEPOINT customer_import_row`.execute(transaction);
  } catch (error) {
    await sql`ROLLBACK TO SAVEPOINT customer_import_row`.execute(transaction);
    results.push({ line, customerId, status: 'failed', code: importFailureCode(error) });
  }
}

A bad row is rolled back alone and reported with its line number, and the rest of the slice is kept. The slice runs under an idempotency key, so a client that loses the answer and sends it again gets the first answer back. The opening balance becomes a ledger entry, and only for someone who holds the permission to adjust the ledger. The old history stays where it was safe: in the access-controlled backup.

Give every migration a checksum and a lock

Now the schema. FinyxWatt's migrations are numbered SQL files, from 0001_identity_and_delivery_foundation.sql to 0109_carried_entries_settlements.sql, and a small runner applies them. Its core:

js
// The lock is held by this one physical connection for the whole migration
// run. A second deployment waits instead of racing a partially upgraded DB.
await client.query("SELECT pg_advisory_lock(hashtext('electricity-platform-migrations-v1'))");

for (const migrationName of migrations) {
  const source = await readFile(join(migrationDirectory, migrationName), 'utf8');
  const checksum = createHash('sha256').update(source).digest('hex');
  await client.query('BEGIN');
  const applied = await client.query(
    'SELECT checksum_sha256 FROM public.schema_migrations WHERE migration_name = $1 FOR UPDATE',
    [migrationName],
  );
  if (applied.rowCount === 1) {
    if (applied.rows[0].checksum_sha256 !== checksum) {
      throw new Error(`Applied migration checksum changed: ${migrationName}`);
    }
  } else {
    await client.query(source);
    await client.query(
      'INSERT INTO public.schema_migrations (migration_name, checksum_sha256) VALUES ($1, $2)',
      [migrationName, checksum],
    );
  }
  await client.query('COMMIT');
}

Before that loop runs, three refusals happen without touching the schema. A file whose name does not match ^\d{4}_[a-z0-9_]+\.sql$ stops the run. Two files with the same number stop it, which catches two branches that each added their own 0042. And a migration recorded in the database but missing from the image stops it, so a renamed file can never run a second time.

The checksum is the rule that matters most. An applied migration is history. If it changes, the deploy stops, and the fix is the next numbered file, never an edit.

That rule has a trap for anyone who writes code on Windows. A checksum is computed over bytes, and Git may turn line endings into CRLF on checkout. The same migration would then hash differently on my machine and in CI. One line in .gitattributes closes it:

text
# Migration checksums are byte-based; pin line endings across Windows and CI.
platform/database/migrations/*.sql text eol=lf

Rehearse on the real database, then commit once

In production I do not run migrations by starting a container and hoping. Each release is a package with a manifest of SHA-256 sums, and a script refuses to go on if any file differs from it. The script compares the pending migrations with what the database has applied, checksums included. Then it runs all pending migrations as one transaction, twice: first ending in ROLLBACK, then ending in COMMIT.

python
statements = ['BEGIN;',
              "SELECT pg_advisory_xact_lock(hashtext('electricity-platform-migrations-v1'));",
              # Never queue behind a long query while holding table locks.
              "SET LOCAL lock_timeout = '5s';",
              "SET LOCAL statement_timeout = '120s';",
              f'SET LOCAL ROLE "{owner}";']
for name, source, checksum in pending:
    statements += [source, f"INSERT INTO schema_migrations(migration_name,checksum_sha256) VALUES ('{name}','{checksum}');"]
statements += ["SELECT 'MIGRATIONS_APPLIED_IN_TRANSACTION';", 'COMMIT;' if commit else 'ROLLBACK;']

The rehearsal runs against the live data, which a test database cannot imitate. A new NOT NULL or CHECK that every test row satisfies can fail on one real row from a station's past, and the rehearsal finds it with nothing changed.

The lock timeout guards the stations during the real run. An ALTER TABLE waits for its lock, and every query that arrives after it waits behind it. A migration stuck behind one long report becomes an outage for every collector. With five seconds as the limit, the transaction fails instead, and nothing has changed.

Before both runs comes a pg_dump, and the script accepts it only if pg_restore --list can read it back. Its comment says why: "A dump that pg_restore can read back is a backup; anything else is not."

  1. Packageevery file matches the manifest's SHA-256
  2. Checkapplied migrations unchanged, runtime settings unchanged
  3. Backuppg_dump, kept only if pg_restore can list it
  4. Rehearsalall pending migrations in one transaction, then ROLLBACK
  5. Applythe same transaction, with COMMIT
  6. Switchthe new API image, checked for readiness, or the old image back
One release's path to production. A failure at any step leaves the live system as it was.

Keep every change additive, so going back is one step

The release script of 6 October states the rule in its opening lines: "The migrations are additive: the previous image keeps working on the new schema, so a rollback restores the image only." All 48 release scripts since carry it into their failure message: the previous images are restored, and the additive migration remains. A bad release never rolls the database back. It rolls the code back, and that is one Compose command.

That rule shapes how each migration is written, and the headers say how they keep it. This is 0096, which taught the platform about water stations:

sql
-- Nothing changes for the stations that exist: every one is electricity, its
-- fee 0, its bills' unit «ك.و.س». Every change here is additive, with
-- defaults the previous image satisfies: it inserts bills without a fee and
-- without a label, and the equation total = charge + fee + arrears holds
-- with a fee of 0 exactly as the old equation did. A rollback is safe.

Others follow the same pattern. A new column in a function's result goes last, so "what the previous image reads keeps its place" (0082). A trigger that wakes listeners after a commit is harmless to the old API, because "with nobody listening (the previous image) the notifications are simply dropped" (0086).

The API never migrates. Every service runs with RUN_MIGRATIONS=false, and the release check refuses a Compose configuration that would switch it on. The schema changes once, from one place, before any new code starts.

The phones are the slowest part of any release, because a collector updates the app when he updates it. So the server speaks to each version in terms it understands. Since 0109 a closed period's opening entry goes only to apps that declare, in an X-Client-Features header, that they understand it: an older app would count the carried balance twice on its statements. The JSON types are part of the same contract. When a bill's fixed fee did not arrive as a JSON number, station apps 1.5.0 and 1.5.1, which read it only as a number, showed no bills at all. The API now sends a number, and 1.5.2 reads it either way.

What broke, and what each break changed

Three breaks taught me more than the plan did.

Forced security applies to the owner too. In the main test database, migrations ran as a superuser, and a superuser skips row-level security. In production they run as a migration login without superuser, and FORCE ROW LEVEL SECURITY exempts no owner. Policy helper functions owned by that login read tables whose policies called the same helpers, and PostgreSQL stopped with SQLSTATE 54001, stack depth exceeded. Migration 0061 moved those functions to five roles that cannot log in, are members of nothing, and skip row-level security only inside those fixed functions. CI now applies the whole schema in a throwaway container with a production-like non-superuser login and the real runtime logins. Test migrations as the login production uses.

A clause only a superuser may write. Early migrations restate each runtime role's limits with ALTER ROLE platform_api NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS. PostgreSQL 18 lets only a superuser write those clauses, even when they change nothing. Editing the applied files would break their checksums, so the runner changes how the statement runs and leaves the file alone:

js
const executable = source.replace(
  /ALTER ROLE (platform_(?:api|worker|control|auditor|sms_enrollment|legacy_import))\s+NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS( NOINHERIT)?;/g,
  (_, role, noInherit) => `IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${role}' AND
    (rolsuper OR rolcreatedb OR rolcreaterole OR rolreplication OR rolbypassrls)) THEN
    RAISE EXCEPTION 'Migration role ${role} has unsafe privileges';
  END IF;${noInherit ? ` ALTER ROLE ${role} NOINHERIT;` : ''}`,
);

The file still matches its checksum, and the run still stops if a role ever holds an unsafe attribute. The statement went from setting the guarantee to proving it.

A new read for an old role. Migration 0095 made every bill in a list show what it still asks, through a function that reads the ledger. The control plane, which the developer console uses, is not allowed to read the ledger. Every platform list of a station's bills answered 403 until 0098 gave the platform its own guarded function. When a migration changes what a function reads, call it as every role that uses it.

Two more breaks belong to the billing story and are told in the article on offline billing: 0015 made an idempotency key single-use across endpoints, and 0080 stopped one debt from being collected twice. The roles, row-level security and secrets that every migration here assumes are in the six security layers.

The checklist for leaving a managed backend

  • Write the authority rules down: who sets stations, totals, versions and timestamps.
  • Make the boundary a CI check, and name every exception inside the check.
  • Replace the client's data layer under the screens; list unsupported operations and make them fail loudly.
  • Give test builds and the new production build their own package names.
  • Hash the snapshot, bind every apply to that hash, and refuse production in code.
  • Derive target ids from legacy ids, so a rerun cannot duplicate.
  • Never import credentials, sessions, device trust or queued messages.
  • When the data cannot say what a payment paid, start from opening balances and keep the history archived.
  • Number migrations, store their SHA-256, refuse edits, duplicates and unknown applied names, and hold an advisory lock.
  • Pin line endings for migration files.
  • Rehearse pending migrations on the live database and roll back; then apply in one transaction with a lock timeout.
  • Keep every migration additive, so the previous image runs on the new schema.
  • In CI, run migrations as the login production uses.

Firebase did not fail the stations. It put the rules of their money in a file every phone could reach. Moving those rules into one server took 109 migrations, and after every one of them, going back was one image away.

The whole platform, its four apps and its backend, is on the FinyxWatt case study.

Mohamed Moghalis

Full-stack software engineer

Portfolio

Get the next article

New articles go to RSS and to my accounts first.

Keep reading

Architecture

372 tests passed. No sale could reach the ledger.

How I keep a 322,000-line accounting system correct on my own: one save gate, append-only money, a hash-chained audit trail, real-database tests, and the audit that caught what they missed.