Published on
How to migrate from Firebase to PostgreSQL: Firestore, Auth, Storage and realtime
Firebase is not relational: Firestore stores documents in collections, with no tables and no foreign keys. Moving to PostgreSQL is a project in stages. Export the collections to NDJSON with the Admin SDK, load them with COPY into a staging table and turn them into tables with SQL. Keep Firebase Auth at first, or migrate passwords by checking Firebase’s modified scrypt hash at login. Replace listeners with LISTEN/NOTIFY or Valkey Pub/Sub, move files to S3-compatible storage and turn Cloud Functions into routes, queues and scheduled Jobs. This guide has code for every step, a cutover plan with rollback and the bill before and after: an app that reads 10 million documents a day pays R$ 1,023.08 a month on Firestore in São Paulo, using the PTAX rate of 11/27/2026 and the 3.5% IOF, and R$ 236.70 with PostgreSQL and Valkey on Zenifra.
Is Firebase relational, and can you migrate from Firestore to PostgreSQL?
No, Firebase is not relational. The two Firebase databases most apps use are NoSQL. Firestore stores documents inside collections, with no tables, no foreign keys and no fixed schema, and the Realtime Database stores a single JSON tree in the cloud. You can migrate to PostgreSQL, and the safest path is in parts: first the Firestore data, then realtime, files and Cloud Functions, and last, if it makes sense, the Firebase Auth users.
This guide walks through every step with code that runs. There is a script that exports collections to NDJSON with the Admin SDK, a PostgreSQL table schema, a load with COPY, a check for Firebase password hashes, two ways to replace realtime listeners and a cutover plan with rollback. At the end, a before and after cost comparison uses the official prices of Firestore, Cloud Storage and Zenifra, all read on 11/28/2026.
Is there a Firebase with PostgreSQL? There is. SQL Connect is Firebase’s own service built on Cloud SQL for PostgreSQL, with schema and queries in GraphQL. It shows up in the section on when not to migrate, because it is the option for teams that want SQL without leaving Google. The rest of this guide covers moving to a regular PostgreSQL that you reach with any driver, ORM or BI tool.
Dollar prices were converted with the selling PTAX rate of 11/27/2026, published by Brazil’s Central Bank, of R$ 5.5430, plus the 3.5% IOF on international card purchases, which gives R$ 5.7370 per dollar. The card issuer’s own spread is not included, so the real bill tends to land a little higher.
Is it worth migrating from Firebase to PostgreSQL?
It is worth it when the document model already costs more than it saves. A few signs tend to show up together: every new screen needs a new composite index, the same data is duplicated across several documents to avoid chained queries, and reports depend on exporting everything to BigQuery or a spreadsheet. If the team spends more time working around the database than building the product, PostgreSQL solves those points with standard SQL.
Another sign is the bill. Firestore charges per document read, and every listener charges a read whenever a document in its result is added or changed. That is great early on, when usage is low, and it starts to hurt when a popular screen reads hundreds of documents every time it opens. With managed PostgreSQL, the price is the plan’s price, and the limits become CPU, memory and connections.
It is also fair to give Firestore its due. It scales without you running servers, the SDKs ship offline cache and listeners out of the box, and Firebase authentication is free up to 50 thousand monthly active users. A migration trades those conveniences for control, and much of this guide is about rebuilding what the SDK used to hand you. The table sums up the differences that weigh most in the decision.
| Aspect | Firestore (Standard edition) | PostgreSQL |
|---|---|---|
| Data model | Documents in collections, no fixed schema | Tables with typed columns and a schema enforced by the database |
| Relations | References and data duplicated across documents; Standard edition runs only basic reads, writes and queries | Foreign keys and JOIN in standard SQL |
| Queries | Every query needs an index; OR queries capped at 30 disjunctions and not-in at 10 values | Any SQL query; indexes are an optimization, not a requirement |
| Integrity | Enforced by app code and Security Rules | UNIQUE, CHECK, NOT NULL and FOREIGN KEY in the database itself |
| Transactions | ACID, with atomic batch operations | ACID, across any combination of tables |
| Realtime | Native listeners in the SDKs | LISTEN/NOTIFY or Valkey Pub/Sub, delivered over WebSocket or SSE |
| Offline mode | Offline cache in the mobile and web SDKs | No ready-made equivalent; it is up to the app |
| Billing | Per document read, written and deleted, plus storage | Fixed plan per instance, plus disk |
The query limits in the table come from the Firestore queries documentation, and the Standard edition scope from the editions page, both read on 11/28/2026. Transactions are not a reason to switch: Firestore has ACID transactions. The strong reasons are queries, integrity, reporting and cost per read.
How do you export data from Firestore?
There are two paths, and ideally you use both. The first is the managed export, with gcloud firestore export, which copies documents into a Cloud Storage bucket. It is a great backup before any change, but it produces files in the LevelDB log format, designed to be imported back into Firestore or loaded into BigQuery, not read by a migration script.
The export documentation has warnings that change the plan. The project must be on the Blaze plan. The export charges one read per exported document, and those reads do not show up in the console’s usage section. The result is not an exact snapshot of the database, because it may include changes made while the export was running. And when you use --collection-ids, subcollections are not included automatically: every collection group must be on the list.
The second path is an Admin SDK script that walks the collections page by page and writes one document per line to an NDJSON file. That is the easiest format to load into PostgreSQL. The script below converts the Firestore types JSON does not know about: Timestamp becomes ISO 8601 text in UTC, DocumentReference becomes the document path, GeoPoint becomes latitude and longitude, and bytes become base64. Each line keeps the full path, such as orders/A1/items/B2, which preserves the subcollection hierarchy without any extra rule.
Pagination uses orderBy(FieldPath.documentId()) with startAfter, in batches of 500, so a whole collection never sits in memory. For each document, listCollections() finds its subcollections and the script walks into them. One caveat: parent documents that do not exist but have subcollections appear in the console and do not appear in queries. If your app creates subcollections without creating the parent document, export those subcollections as well with db.collectionGroup("name").
The script’s reads are billed as regular reads. In São Paulo, above the free quota of 50 thousand reads a day, 1 million documents cost US$ 0.45, or R$ 2.58 with the PTAX rate and the 3.5% IOF. Run it first against a test project or a small collection, check the file, and only then run it on the whole database, preferably at a quiet hour.
# Official backup before any change (project on the Blaze plan)
gcloud firestore export gs://my-firestore-backup --database="(default)"
# Only some collection groups; subcollections must be listed as well
gcloud firestore export gs://my-firestore-backup --collection-ids=users,products,orders,items --database="(default)"import { createWriteStream } from "node:fs"
import { once } from "node:events"
import { initializeApp, applicationDefault } from "firebase-admin/app"
import { getFirestore, FieldPath, Timestamp, DocumentReference, GeoPoint } from "firebase-admin/firestore"
initializeApp({ credential: applicationDefault() })
const db = getFirestore()
const out = createWriteStream("firestore.ndjson")
const plain = v =>
v instanceof Timestamp ? v.toDate().toISOString()
: v instanceof DocumentReference ? v.path
: v instanceof GeoPoint ? { lat: v.latitude, lng: v.longitude }
: Buffer.isBuffer(v) ? v.toString("base64")
: Array.isArray(v) ? v.map(plain)
: v && typeof v === "object" ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, plain(x)]))
: v
async function dump(collection) {
let last
for (;;) {
let query = collection.orderBy(FieldPath.documentId()).limit(500)
if (last) query = query.startAfter(last)
const snap = await query.get()
if (snap.empty) return
for (const doc of snap.docs) {
const line = JSON.stringify({ path: doc.ref.path, data: plain(doc.data()) }) + "\n"
if (!out.write(line)) await once(out, "drain")
for (const sub of await doc.ref.listCollections()) await dump(sub)
}
last = snap.docs.at(-1)
}
}
for (const collection of await db.listCollections()) await dump(collection)
out.end()
await once(out, "finish")How do you turn collections and subcollections into tables?
The rule of thumb is that each collection becomes a table, each document becomes a row and the document ID becomes the primary key. Keep the Firestore IDs as text. Auto-generated IDs are 20 characters long and already live in URLs, email links and analytics events, and swapping them for numbers during the migration creates a second migration hidden inside the first one.
Subcollections become child tables with a foreign key to the parent document’s table. orders/{id}/items/{itemId} becomes order_items, with order_id pointing to orders. There is a behavioral difference worth noting here. In Firestore, deleting a document does not delete its subcollections, so it is common to find orphaned items after years of use. In PostgreSQL, ON DELETE CASCADE handles that in the database itself, and the load will reveal the orphans that already exist.
The most common question is when to use JSONB. Use regular columns for anything that shows up in WHERE, JOIN, ORDER BY or reports, and for fields that need a constraint, such as a unique email or a non-negative price. Use JSONB for variable-shape maps that the app reads whole and rarely filters, such as user preferences, product attributes that change by category or a raw webhook payload. If a JSONB field starts being filtered often, a GIN index with jsonb_path_ops serves queries that use the @> operator.
Arrays call for a case-by-case decision. An array of plain values queried with array-contains, such as tags, becomes a text[] column with a GIN index and the query WHERE tags @> ARRAY['promo']. An array of objects with a life of their own, such as order items, becomes a table. Denormalized counters, which Firestore forces you to maintain by hand to avoid reading a whole collection, can become a count(*) with an index or stay as a column updated in the same transaction that writes the record.
Finally, indexes. The composite indexes you created in the Firestore console are a good starting list of B-tree indexes in PostgreSQL, because each one matches a real query in the app. The difference is that in PostgreSQL a query without an index still works, just more slowly, and EXPLAIN ANALYZE shows where one is missing. Start with the indexes behind the most frequent queries and add the rest by watching the database in use.
CREATE TABLE staging_docs (
path text PRIMARY KEY,
collection text GENERATED ALWAYS AS (split_part(path, '/', -2)) STORED,
doc_id text GENERATED ALWAYS AS (split_part(path, '/', -1)) STORED,
data jsonb NOT NULL
);
CREATE INDEX staging_docs_collection ON staging_docs (collection);
CREATE TABLE users (
id text PRIMARY KEY,
email text UNIQUE NOT NULL,
name text,
preferences jsonb NOT NULL DEFAULT '{}',
created_at timestamptz NOT NULL
);
CREATE TABLE products (
id text PRIMARY KEY,
name text NOT NULL,
price_cents integer NOT NULL CHECK (price_cents >= 0),
tags text[] NOT NULL DEFAULT '{}',
attrs jsonb NOT NULL DEFAULT '{}'
);
CREATE TABLE orders (
id text PRIMARY KEY,
user_id text NOT NULL REFERENCES users(id),
status text NOT NULL,
created_at timestamptz NOT NULL
);
CREATE TABLE order_items (
order_id text NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
id text NOT NULL,
product_id text NOT NULL REFERENCES products(id),
quantity integer NOT NULL CHECK (quantity > 0),
unit_price_cents integer NOT NULL,
PRIMARY KEY (order_id, id)
);
CREATE INDEX orders_user_created ON orders (user_id, created_at DESC);
CREATE INDEX products_tags ON products USING gin (tags);
CREATE INDEX products_attrs ON products USING gin (attrs jsonb_path_ops);| In Firestore | In PostgreSQL | Note |
|---|---|---|
| Collection | Table | One table per collection or collection group |
| Document and ID | Row with a text primary key | Keep the original ID |
| Subcollection | Child table with a foreign key | ON DELETE CASCADE when children cannot exist without the parent |
Timestamp | timestamptz | The script exports in UTC |
DocumentReference | Foreign key | The script exports the path, such as users/abc |
| Variable-shape map | jsonb | GIN index if it starts being filtered |
| Array of plain values | text[] or a table | GIN for queries with @> |
| Array of objects | Child table | Order items, addresses, attachments |
GeoPoint | Two double precision columns | Or geography, if the database has the PostGIS extension |
| Composite index | Composite B-tree index | Same field order as the query |
| Denormalized counter | count(*) or a column in the same transaction | No more Cloud Function to keep it in sync |
The staging_docs table receives the NDJSON exactly as it came out of Firestore. The collection and doc_id columns are generated by the database from the path, with split_part and a negative position, a feature available since PostgreSQL 14 and therefore in every version from 15 to 18.
How do you load the NDJSON into PostgreSQL with Node.js?
With COPY, the fastest way to put many rows into PostgreSQL. Instead of one INSERT per document, the script opens a single stream and sends the whole file at once. The example uses the pg driver and the pg-copy-streams package, by the same author, and writes everything to the staging table, with each document in a jsonb column. The transformation into the final tables stays in SQL, where it is easier to review and rerun.
Loading into staging first has a practical upside: you run the load once and repeat the transformation as many times as you like, tweaking the SQL, without reading Firestore again and without paying for those reads twice. At the end, the script prints the count per collection, which is the first number to compare against Firestore.
After the load, each final table gets an INSERT ... SELECT from the JSON, in dependency order: users and products before orders, orders before items. This is where the schemaless model sends the bill. An order pointing to a deleted user, a price stored as text in some documents or a missing date makes the row fail on the foreign key, the CHECK or the NOT NULL. The first query in the SQL block lists those orphans before the load.
Handle each inconsistency with an explicit decision: fix it at the source, fill in a default value or move the row to a rejects table that someone will review. Letting the migration "pass" with constraints turned off only pushes the problem to the first screen that runs a JOIN.
On Zenifra, the connection URI copied from the Console already includes sslmode=require, and the pg driver turns on TLS from that alone. The DB-Starter plan accepts 15 concurrent connections, and one connection is enough for the load.
import { createReadStream } from "node:fs"
import { createInterface } from "node:readline"
import { Readable } from "node:stream"
import { pipeline } from "node:stream/promises"
import pg from "pg"
import { from as copyFrom } from "pg-copy-streams"
const csv = value => "\"" + value.replace(/"/g, "\"\"") + "\""
async function* rows(file) {
for await (const line of createInterface({ input: createReadStream(file) })) {
if (!line) continue
const { path, data } = JSON.parse(line)
yield csv(path) + "," + csv(JSON.stringify(data)) + "\n"
}
}
const client = new pg.Client({ connectionString: process.env.DATABASE_URL })
await client.connect()
const copy = client.query(copyFrom("COPY staging_docs (path, data) FROM STDIN WITH (FORMAT csv)"))
await pipeline(Readable.from(rows("firestore.ndjson")), copy)
const result = await client.query("SELECT collection, count(*) FROM staging_docs GROUP BY collection ORDER BY collection")
console.table(result.rows)
await client.end()-- Orders that point to users who no longer exist
SELECT o.path FROM staging_docs o
LEFT JOIN staging_docs u ON u.path = o.data->>'user'
WHERE o.collection = 'orders' AND u.path IS NULL;
BEGIN;
INSERT INTO users (id, email, name, preferences, created_at)
SELECT doc_id, data->>'email', data->>'name', coalesce(data->'preferences', '{}'), (data->>'createdAt')::timestamptz
FROM staging_docs WHERE collection = 'users';
INSERT INTO products (id, name, price_cents, tags, attrs)
SELECT doc_id, data->>'name', (data->>'priceCents')::int,
ARRAY(SELECT jsonb_array_elements_text(data->'tags')), coalesce(data->'attrs', '{}')
FROM staging_docs WHERE collection = 'products';
INSERT INTO orders (id, user_id, status, created_at)
SELECT doc_id, split_part(data->>'user', '/', 2), data->>'status', (data->>'createdAt')::timestamptz
FROM staging_docs WHERE collection = 'orders';
INSERT INTO order_items (order_id, id, product_id, quantity, unit_price_cents)
SELECT split_part(path, '/', 2), doc_id, split_part(data->>'product', '/', 2), (data->>'quantity')::int, (data->>'priceCents')::int
FROM staging_docs WHERE collection = 'items' AND path LIKE 'orders/%';
COMMIT;The field names in the example, such as email, createdAt, user, product and priceCents, are illustrative. Replace them with your app’s fields and run the whole transformation inside a transaction, so an error halfway through does not leave tables half filled.
How do you migrate Firebase Auth users?
The shortest path is not migrating users yet. The app keeps signing in with the Firebase SDK and sends the ID token to your API, which validates it with the Admin SDK’s verifyIdToken() and gets the uid. That uid is the key of the users table in PostgreSQL, the same one that already came over from Firestore. According to Firebase’s pricing page, authentication stays free up to 50 thousand monthly active users, with SMS sign-in billed separately, and you swap the database without touching sign-in, password recovery or social providers.
If you want to leave Firebase Auth as well, the command firebase auth:export users.json --format=JSON exports accounts with localId, email, emailVerified, passwordHash, salt, creation date and the linked providers in providerUserInfo. Passwords come out hashed with the modified scrypt variant Firebase uses. To verify those hashes outside Firebase, you need the project’s hash parameters, found in the console under Authentication, on the Users tab, in the three-dot menu above the user list: base64_signer_key, base64_salt_separator, rounds and mem_cost. Treat those values as secrets, because with them and the exported file someone can test passwords offline.
The algorithm is described in the firebase/scrypt repository, now archived. It runs scrypt with the password, the user’s salt concatenated with the project’s separator, N equal to 2 to the power of mem_cost, r equal to rounds and p equal to 1. The first 32 bytes of the result become the key of an AES-256-CTR cipher with a zeroed initialization vector, which encrypts the project’s signer_key. If the output matches the exported passwordHash, the password is correct. The function below uses only the Node.js crypto module and was checked against the official sample in the repository.
The strategy is to migrate at login. The users table gets a column with the hash algorithm. When a user signs in, the API checks the password with the Firebase function and, if it matches, stores a new hash with your auth library’s algorithm and updates the column. Over time, active users migrate on their own. Those who do not come back within a few months get a password reset email.
Accounts that sign in with Google or Apple have no password. Configure the same providers in the new authentication and link accounts by verified email or by the provider ID exported in providerUserInfo. There is also an edge case: accounts whose hash is not in Firebase’s variant, such as users imported from another system who never signed in on Firebase, come out with empty passwordHash and salt and will also need a reset.
import { scryptSync, createCipheriv, timingSafeEqual } from "node:crypto"
const b64 = s => Buffer.from(s.replace(/-/g, "+").replace(/_/g, "/"), "base64")
const hashConfig = {
signerKey: process.env.FIREBASE_HASH_SIGNER_KEY,
saltSeparator: process.env.FIREBASE_HASH_SALT_SEPARATOR,
rounds: Number(process.env.FIREBASE_HASH_ROUNDS),
memCost: Number(process.env.FIREBASE_HASH_MEM_COST),
}
export function verifyFirebasePassword(password, user, cfg = hashConfig) {
const salt = Buffer.concat([b64(user.salt), b64(cfg.saltSeparator)])
const key = scryptSync(password, salt, 32, { N: 2 ** cfg.memCost, r: cfg.rounds, p: 1, maxmem: 256 * 1024 * 1024 })
const cipher = createCipheriv("aes-256-ctr", key, Buffer.alloc(16, 0))
const hash = Buffer.concat([cipher.update(b64(cfg.signerKey)), cipher.final()])
const expected = b64(user.passwordHash)
return hash.length === expected.length && timingSafeEqual(hash, expected)
}What replaces Firestore’s realtime listeners?
An open connection between the app and your API, over WebSocket or Server-Sent Events, fed by an event channel. A Firestore listener does several things at once: it delivers the current state, notifies you when something changes and reconnects on its own. With your own backend, the app asks the API for the current state, opens the connection to receive changes and, on reconnect, asks for the state again. It is more code, but changes are no longer billed as reads.
With a single API instance, PostgreSQL itself is enough. A trigger calls pg_notify after each write, and the API keeps a dedicated connection with LISTEN to forward the event to connected clients. In the default configuration, the NOTIFY payload must be shorter than 8,000 bytes, so send only the ID and the type of change and let the app fetch the rest. The LISTEN connection must be a fixed session, outside any pool that swaps connections between queries, and it counts toward the plan’s connection limit.
With several API instances, each client is connected to one of them, and a change written by one instance has to reach the others. That is the job of Valkey Pub/Sub: after writing to PostgreSQL, the instance publishes to a channel, and every subscribed instance forwards the event to its own clients. On Zenifra, the Valkey Queues profile supports Pub/Sub and Streams, connections use TLS, and the queue-starter plan costs R$ 44.90 a month.
Choose between Pub/Sub and Streams based on what happens if a message is lost. In Pub/Sub, messages are not stored, and a disconnected consumer misses the event. For refreshing an open screen, that is acceptable, because the app reloads its state on reconnect. For tasks that must happen, such as sending an email or issuing an invoice, use Streams with consumer groups: the worker reads with XREADGROUP, acknowledges with XACK only after processing, and messages from a crashed worker can be claimed by another one with XAUTOCLAIM. Delivery is at least once, so processing must be idempotent.
Either way, the authorization that Security Rules used to do moves to the API. Before sending an event to a client, check that the user may see that record, the same way the HTTP route would. In the Valkey example, authenticate validates the Firebase ID token with verifyIdToken(), read from a cookie, because the browser’s EventSource does not send custom headers. The sendToUser function in the LISTEN example is the same one as in the Valkey example. On Zenifra, WebSocket and SSE go through the project’s regular HTTP port, custom domains included.
CREATE FUNCTION notify_order_change() RETURNS trigger AS $$
BEGIN
PERFORM pg_notify('order_changes', json_build_object('id', NEW.id, 'userId', NEW.user_id, 'status', NEW.status)::text);
RETURN NEW;
END
$$ LANGUAGE plpgsql;
CREATE TRIGGER orders_notify AFTER INSERT OR UPDATE ON orders
FOR EACH ROW EXECUTE FUNCTION notify_order_change();import pg from "pg"
const listener = new pg.Client({ connectionString: process.env.DATABASE_URL })
await listener.connect()
await listener.query("LISTEN order_changes")
listener.on("notification", msg => {
const change = JSON.parse(msg.payload)
sendToUser(change.userId, change)
})import http from "node:http"
import Redis from "iovalkey"
const url = new URL(process.env.VALKEY_URL)
const options = { tls: { servername: url.hostname } }
const sub = new Redis(process.env.VALKEY_URL, options)
const pub = new Redis(process.env.VALKEY_URL, options)
const connections = new Map()
function sendToUser(userId, event) {
for (const res of connections.get(userId) ?? []) res.write("data: " + JSON.stringify(event) + "\n\n")
}
await sub.subscribe("order_changes")
sub.on("message", (_channel, message) => {
const event = JSON.parse(message)
sendToUser(event.userId, event)
})
http.createServer(async (req, res) => {
if (!req.url.startsWith("/events")) return res.writeHead(404).end()
const userId = await authenticate(req)
if (!userId) return res.writeHead(401).end()
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" })
if (!connections.has(userId)) connections.set(userId, new Set())
connections.get(userId).add(res)
req.on("close", () => connections.get(userId).delete(res))
}).listen(process.env.PORT ?? 3000)
export async function publishOrderChange(order) {
await pub.publish("order_changes", JSON.stringify({ id: order.id, userId: order.user_id, status: order.status }))
}How do you move Cloud Storage files to S3-compatible storage?
With two command-line tools. gcloud storage rsync downloads the files from the Firebase bucket, and the AWS CLI uploads them to the S3-compatible destination. On Zenifra, the destination is Armazém, with the endpoint https://armazem.zenifra.com, region br-sp1 and virtual-hosted bucket addresses. For a large volume, do the full copy before the cutover and run the sync again on the day, which only transfers what changed.
The work people tend to forget is in the database, not in the files. Apps built on Firebase often store the full download URL in Firestore, with the firebasestorage.googleapis.com domain, the encoded object path and a token in the query string. Those URLs stop working once the old bucket is shut down. During the transformation, keep only the object key, such as photos/uid/123.jpg, and let the API generate a signed link when the file is displayed. The SQL example below handles the slash encoded as %2F; if names contain spaces or accents, decode the path in the export script.
Storage Rules move as well. Instead of rules on the bucket, the API decides who may upload and download and hands the app a signed upload or download link. The browser sends the file straight to Armazém, without going through the API server, and a signed link is valid for at most 7 days.
According to the Armazém documentation, read on 11/28/2026, storage costs R$ 0.18 per GB-month, the first 5 GB are always free per organization and the monthly allowance includes 50 thousand writes and listings and 500 thousand reads. Uploads and traffic between Armazém and applications on Zenifra are free. Transfer to the internet is free until 12/20/2026 and costs R$ 0.80 per GB from 12/21/2026.
# 1. Download the files from the Firebase bucket
gcloud storage rsync --recursive gs://my-project.firebasestorage.app ./files
# 2. Upload to Armazém (virtual-hosted addressing)
aws configure set default.s3.addressing_style virtual
aws --profile zenifra --endpoint-url https://armazem.zenifra.com --region br-sp1 s3 sync ./files s3://my-bucketUPDATE users
SET avatar_key = replace(split_part(split_part(avatar_url, '/o/', 2), '?', 1), '%2F', '/')
WHERE avatar_url LIKE 'https://firebasestorage.googleapis.com/%';How do you replace Cloud Functions with an API and scheduled Jobs?
Split the functions by trigger, because each kind has a different destination. Functions called over HTTP or from the SDK, with onRequest and onCall, become routes in your API. Functions triggered by Firestore writes, such as onDocumentCreated and onDocumentWritten, become code that runs right after the write, inside the API, or a message on a queue consumed by a worker. Scheduled functions, with onSchedule, become scheduled Jobs.
Database triggers need the most care. In Firebase, the function runs outside the transaction, after the document is already written, and it may run more than once for the same event. With PostgreSQL, you choose. If the effect must be atomic with the write, such as updating a balance, do it in the same transaction. If it can happen later, such as sending an email, write the task to an outbox table in the same transaction and let a worker publish it to the queue, the pattern known as outbox. That way no task is lost if the API crashes between writing and publishing.
For scheduled functions, Zenifra’s scheduled Jobs use a five-field cron expression, always in UTC, so midnight in Brasília becomes 0 3 * * *. Each run can take up to 60 minutes, the source can be a GitHub repository or a Docker image, and billing is per minute of execution, with build time left out. On the job-starter plan, with 0.1 vCPU and 128 MB, a minute costs R$ 0.0001666666, and a report that runs 5 minutes a day adds up to 150 minutes a month and costs R$ 0.02.
The API itself is a regular project, deployed from GitHub or a Docker image. On Zenifra, the Basic plan has 0.5 vCPU and 512 MB for R$ 29.90 a month, and Premium has 1 vCPU and 1 GB for R$ 62.90, with metrics and health checks. Unlike Cloud Functions, the process stays up: there is no cold start, and connections to the database and to Valkey are reused across requests, which also helps you stay within PostgreSQL’s connection limit.
On the Firebase side, the pricing page lists Cloud Functions as a Blaze plan feature, with 2 million invocations a month at no cost and US$ 0.40 per million after that, plus GB-seconds, CPU-seconds and outbound traffic billed separately.
| Firebase trigger | Destination after the migration | Watch out for |
|---|---|---|
onRequest (HTTP) | API route | Keeping the same URL behind your own domain makes the switch easier |
onCall (SDK) | API route with the ID token in the header | The app swaps the SDK call for fetch |
onDocumentCreated and onDocumentWritten | Code in the same transaction, or an outbox table with a worker | Idempotent processing, as in Firebase |
onSchedule | Scheduled Job with cron in UTC | Up to 60 minutes per run |
| Cloud Storage triggers | Queue message sent by the API after the upload | Direct uploads to Armazém need to notify the API |
| Auth triggers | Code in the API’s sign-up route | Only after migrating authentication |
How do you cut over without losing data?
In phases, with a clear point after which PostgreSQL becomes the source of truth. Up to that point, rolling back just means pointing the app at Firestore again. After it, rolling back means carrying back whatever was written to PostgreSQL, so the plan has to say how that would work before you start. The sequence below works for most apps.
- Run a managed export with
gcloud firestore exportas a backup before touching anything. - Run the full load in a rehearsal, check the counts and time it, because that number sets the size of the window.
- During the transition, mirror writes with an
onDocumentWrittenCloud Function that writes every change to staging withINSERT ... ON CONFLICT (path) DO UPDATE, or have the API write to both databases. - Ship the new API reading from PostgreSQL behind a flag and compare its responses with Firestore’s for a small group of users.
- In the window, freeze writes with Security Rules that deny
write, run the final reconciliation and check the counts again. - Point the app at the new API, keep Firestore read-only for a few weeks and only then turn off the mirror and the old listeners.
match /orders/{orderId} {
allow read: if request.auth.uid == resource.data.userId;
allow write: if false;
}for (const name of ["users", "products", "orders"]) {
const snap = await db.collection(name).count().get()
const { rows } = await client.query(
"SELECT count(*)::int AS n FROM staging_docs WHERE collection = $1 AND path LIKE $2",
[name, name + "/%"],
)
console.log(name, snap.data().count, rows[0].n)
}
const items = await db.collectionGroup("items").count().get()
console.log("items", items.data().count)To validate, compare the document count per collection in Firestore, taken with the count() aggregation, which charges one read per 1,000 index entries, against the count in staging and in the final tables. Equal counts do not guarantee equal content, so also compare a sample of documents field by field, picking random IDs.
When freezing writes, change only the write rules and leave the read rules as they are. The Admin SDK bypasses Security Rules, so the reconciliation script keeps working during the window. Older versions of the mobile app that still talk straight to Firestore will get a permission error when writing; warn users in advance and, if you can, require an app update before the cutover.
For a rollback after the cutover, log every write made to PostgreSQL in a table during the first few weeks. If you need to go back, a script replays that log into Firestore with the Admin SDK. Without that log, a rollback loses whatever users wrote after the cutover.
How much does Firebase cost before the migration?
It depends almost entirely on how many documents the app reads. According to the Firestore pricing page, read on 11/28/2026, the Standard edition in the São Paulo region (southamerica-east1) charges US$ 0.045 per 100 thousand reads, US$ 0.135 per 100 thousand writes, US$ 0.015 per 100 thousand deletes and US$ 0.135 per GiB stored per month. Each project gets one database with a daily free quota of 50 thousand reads, 20 thousand writes, 20 thousand deletes and 1 GiB stored, plus 10 GiB of outbound traffic a month.
The table works out two scenarios over 30 days, with the free quota already deducted. The mid-size app reads 1 million documents and writes 100 thousand a day, with 5 GiB in Firestore and 20 GiB of files. The larger app reads 10 million and writes 1 million a day, with 20 GiB in Firestore and 50 GiB of files. One million reads a day is, for example, a 500-document screen opened 2 thousand times.
Files live in Cloud Storage in São Paulo, at US$ 0.035 per GiB per month in the Standard class, with no free quota, because Firebase’s pricing page limits the no-cost quota for new buckets to the us-central1, us-west1 and us-east1 regions. Cloud Functions, authentication and outbound traffic stay within the free quotas in both scenarios, which keeps the Firebase bill at its lowest possible value.
| Item | Mid-size app | Larger app |
|---|---|---|
| Firestore reads | 28.5 million billed, US$ 12.825 | 298.5 million billed, US$ 134.325 |
| Firestore writes | 2.4 million billed, US$ 3.24 | 29.4 million billed, US$ 39.69 |
| Firestore storage | 4 GiB billed, US$ 0.54 | 19 GiB billed, US$ 2.565 |
| Cloud Storage (Standard, São Paulo) | 20 GiB, US$ 0.70 | 50 GiB, US$ 1.75 |
| Total in dollars | US$ 17.305 | US$ 178.33 |
| In reais, with the 11/27/2026 PTAX and 3.5% IOF | R$ 99.28 | R$ 1,023.08 |
At 100 thousand reads a day, the same app would pay US$ 0.675 a month for reads. Firestore is cheap at the start and grows in a straight line with usage, and the exchange rate comes on top: the same dollar bill has a different value in reais every month.
And how much does the same app cost on PostgreSQL after the migration?
It costs the price of the plans, which does not change with the number of reads. The table builds both scenarios with Zenifra’s plans, read from the public pricing API on 11/28/2026, in reais with no currency conversion, paid by PIX, boleto or card. The mid-size app runs on one API instance and uses LISTEN/NOTIFY for realtime, with no Valkey. The larger app runs on two API instances and uses Valkey Pub/Sub between them.
One million documents read a day on Firestore does not mean one million queries on PostgreSQL. A screen that lists 50 orders reads 50 documents on Firestore and runs one query on the relational database. That is why DB-Starter, with 0.3 vCPU, 256 MB and 15 connections, handles the mid-size app, and DB-Basic, with 1 vCPU, 1 GB and 72 connections, gives the larger one room to grow. PostgreSQL disk is billed separately, at R$ 0.20 per GB per instance, and the scenario reserves twice the volume that was in Firestore, for data, indexes and growth.
| Item | Mid-size app | Larger app |
|---|---|---|
| API | Basic, 0.5 vCPU and 512 MB, R$ 29.90 | 2 Premium instances, 1 vCPU and 1 GB each, R$ 125.80 |
| PostgreSQL | DB-Starter, R$ 11.90 | DB-Basic, R$ 49.90 |
| PostgreSQL disk | 10 GB, R$ 2.00 | 40 GB, R$ 8.00 |
| Realtime | LISTEN/NOTIFY in PostgreSQL itself, R$ 0.00 | Valkey queue-starter, R$ 44.90 |
| Files on Armazém | 20 GB, with 5 GB free and 15 GB at R$ 0.18, R$ 2.70 | 50 GB, with 5 GB free and 45 GB at R$ 0.18, R$ 8.10 |
| Monthly total | R$ 46.50 | R$ 236.70 |
| Firebase in the same scenario | R$ 99.28 | R$ 1,023.08 |
With a scheduled Job running 5 minutes a day on job-starter, add R$ 0.02 to each scenario. Both database plans include automatic backups: every 24 hours on DB-Starter and every 12 hours on DB-Basic, kept for 7 days.
The comparison favors migrating in both cases, but with very different weight. For the mid-size app, the difference is R$ 52.78 a month, which rarely pays for weeks of migration work on its own. For the larger app, the bill drops from R$ 1,023.08 to R$ 236.70 a month and pays for the project in a few months. For a small app within Firestore’s free quota, there is simply no cost argument, and the decision comes down to queries and integrity.
When is it not worth migrating from Firebase?
When the app relies on what the SDK hands you and the cost does not bother you. An offline-first app, which works without internet and syncs later, uses Firestore’s offline cache in a way that is hard to reproduce, and rebuilding that with your own API is a project of its own. A small app within the free quota has no savings to chase. And a team with nobody to look after a backend trades a predictable bill for an API to maintain.
If what bothers you is the document model, but you want to keep the BaaS experience, with an SDK in the front end and ready-made authentication and realtime, Supabase is a better fit than your own backend. It runs on PostgreSQL, has a São Paulo region and publishes a guide for migrating Firebase Auth users. According to its pricing page, read on 11/28/2026, Pro starts at US$ 25 a month per organization, R$ 143.43 with the PTAX rate and the 3.5% IOF, with US$ 10 of compute credits, and the Free plan pauses projects after a week of inactivity.
If you want SQL without leaving Google, Firebase SQL Connect uses Cloud SQL for PostgreSQL with Firebase Auth integration. According to Firebase’s pricing page, it includes 250 thousand operations a month at no cost and US$ 0.90 per million after that. The Cloud SQL instance has a 3-month no-cost trial and then starts at US$ 9.37 a month, with prices that vary by region and configuration.
You also do not have to migrate everything. Cloud Messaging, Crashlytics, Analytics and Remote Config keep working with the database somewhere else, and many teams keep Firebase Auth for years after replacing Firestore with PostgreSQL. Moving just the database already solves queries, reporting and cost per read, which are usually the reasons for the change.
Summing up
Firebase is not relational, and migrating from Firestore to PostgreSQL is a project in stages, not a single command. Export with the Admin SDK to NDJSON, load with COPY into staging, turn it into tables with SQL and let foreign keys surface the inconsistencies. Keep Firebase Auth at first, replace listeners with LISTEN/NOTIFY or Valkey Pub/Sub, move files to S3-compatible storage and turn Cloud Functions into routes, queues and Jobs. The cutover is safe when it has mirrored writes, checked counts and a log for rollback.
The math pays off when the app reads a lot: in the 10 million reads a day scenario, the bill drops from R$ 1,023.08 to R$ 236.70 a month. If that is your case, Zenifra’s managed databases run in São Paulo and bill in reais, and the calculator shows your scenario before you start.