Thay Supabase bằng Firebase: Khi nào nên chuyển, migrate an toàn

P P T P Chung

Thay thế Supabase bằng Firebase: khi nào nên chuyển và cách migrate an toàn

Supabase thường được gọi là “Firebase mã nguồn mở”: PostgreSQL, Auth, Realtime, Storage, Edge Functions. Với team thích SQL, cần quyền kiểm soát DB, Supabase rất hấp dẫn. Nhưng khi sản phẩm lớn hơn, req khác đi: mobile-first, analytics, push notification, offline sync, Google Cloud integration, quota ổn định, SDK trưởng thành. Khi đó Firebase có thể phù hợp hơn.

Chuyển từ Supabase sang Firebase không phải “đổi DB”. Đây là đổi mô hình dữ liệu, auth, realtime, security rule, storage, backend fn, observability. Làm sai → mất dữ liệu, lỗi auth, downtime, leak quyền truy cập. Làm đúng → app nhẹ hơn, vận hành dễ hơn, scale tốt hơn.

Bài này phân tích: khi nào nên chuyển, khi nào không, cách migrate an toàn.


Supabase vs Firebase: khác biệt cốt lõi

Supabase → SQL-first

Supabase dùng PostgreSQL. Điểm mạnh:

Schema rõ: bảng, khóa ngoại, index, constraint. – Query mạnh: join, aggregate, transaction, full-text search. – RLS: Row Level Security sát DB. – Dễ export/import: SQL, dump, migration. – Tự chủ hơn: có thể self-host.

Phù hợp app có dữ liệu quan hệ: CRM, ERP, marketplace, SaaS B2B, reporting phức tạp.

Firebase → app-first

Firebase xoay quanh app client, đặc biệt mobile/web realtime:

Firestore / Realtime Database: NoSQL document/tree. – Firebase Auth: nhiều provider, tích hợp tốt. – Cloud Functions: backend event-driven. – FCM: push notification mạnh. – Crashlytics, Analytics, Remote Config: mobile ops tốt. – Offline support: tốt cho mobile.

Phù hợp app consumer, realtime collaboration, chat, social, marketplace đơn giản, mobile-heavy.


Khi nào nên chuyển từ Supabase sang Firebase?

1. App mobile là trọng tâm

Nếu 70–90% traffic đến từ iOS/Android, Firebase có lợi thế rõ:

– Auth SDK mượt. – Push notification qua FCM. – Crashlytics để debug production. – Analytics/Remote Config/A/B test sẵn. – Offline cache Firestore tốt.

Supabase vẫn làm được nhiều phần, nhưng cần ghép thêm tool. Firebase → ít mảnh ghép hơn.

2. Cần offline-first

Firestore hỗ trợ local persistence. User có thể đọc/ghi khi mất mạng; sync lại khi online. Với app field service, ghi chú, chat, task, inventory mobile → rất hữu ích.

Supabase realtime + local cache cần tự thiết kế nhiều hơn.

3. Realtime đơn giản, traffic lớn

Nếu realtime pattern là:

– chat room, – presence đơn giản, – live comments, – trạng thái đơn hàng, – dashboard nhẹ,

Firestore/Realtime Database rất tiện. Listener client → ít backend code.

Nhưng nếu realtime cần query SQL phức tạp, filter động sâu, permission nhiều tầng → Supabase có thể vẫn tốt hơn.

4. Team muốn giảm vận hành backend

Firebase cung cấp nhiều dịch vụ managed:

– Auth, – DB, – Storage, – Functions, – Hosting, – Monitoring, – App Check, – Analytics.

Team nhỏ → ship nhanh. Ít DevOps. Ít config infra.

5. Cần tích hợp Google Cloud

Nếu đã dùng BigQuery, Cloud Run, Pub/Sub, Vertex AI, Google Ads, Analytics → Firebase nằm cùng hệ sinh thái. Export events sang BigQuery, chạy pipeline ML, phân tích hành vi → thuận.


Khi nào không nên chuyển?

1. Dữ liệu quan hệ phức tạp

Nếu app phụ thuộc nhiều vào:

– join nhiều bảng, – transaction phức tạp, – báo cáo tài chính, – lọc/search nâng cao, – dữ liệu chuẩn hóa cao,

Firestore có thể làm bạn đau. NoSQL cần denormalize. Một thay đổi dữ liệu có thể phải ghi nhiều nơi. Query bị giới hạn bởi index, cấu trúc collection.

2. Cần SQL analytics nội bộ

Supabase/Postgres rất mạnh cho admin dashboard, BI, ad-hoc query. Firebase thường cần export sang BigQuery hoặc duplicate data sang warehouse.

3. Vendor lock-in là rủi ro lớn

Firebase tiện nhưng gắn chặt Google ecosystem. Nếu sản phẩm cần portability, compliance đặc thù, hoặc self-host → Supabase thuận hơn.

4. Chi phí đọc/ghi khó dự đoán

Firestore tính phí theo read/write/delete, storage, network. Query sai → đọc quá nhiều doc → bill tăng. Với app nhiều list lớn hoặc polling/listener dày, cần tính kỹ.


Chuẩn bị trước migration

Audit toàn hệ thống

Lập bảng mapping:

| Supabase | Firebase | |—|—| | PostgreSQL tables | Firestore collections | | SQL rows | documents | | RLS policies | Firestore Security Rules | | Supabase Auth users | Firebase Auth users | | Storage buckets | Firebase Storage | | Edge Functions | Cloud Functions | | Realtime channels | Firestore listeners / RTDB |

Ghi rõ:

– bảng nào migrate, – trường nào đổi tên, – relation nào denormalize, – dữ liệu nào bỏ, – index nào cần, – quyền nào phải giữ.

Chọn DB Firebase đúng

Firestore: document DB, query tốt hơn, offline tốt, scale tốt. Nên dùng mặc định. Realtime Database: JSON tree, latency thấp, presence/chat đơn giản. Tốt cho trạng thái realtime cực nhanh.

Nhiều app dùng cả hai: Firestore cho dữ liệu chính, RTDB cho presence.


Thiết kế lại data model

SQL → NoSQL không nên copy 1:1.

Ví dụ Supabase:

userspostscommentslikes

Firestore có thể là:

users/{userId}
posts/{postId}
posts/{postId}/comments/{commentId}
posts/{postId}/likes/{userId}

Hoặc denormalize:

posts/{postId}
{
  authorId,
  authorName,
  authorAvatar,
  commentCount,
  likeCount,
  createdAt
}

Trade-off:

– đọc nhanh hơn, – UI đơn giản hơn, – nhưng update authorName/avatar cần sync nhiều doc.

Quy tắc thực tế: thiết kế theo màn hình đọc, không theo ERD.


Migrate Auth an toàn

Auth là phần nhạy nhất.

Firebase Admin SDK hỗ trợ import user với password hash, nhưng Supabase/GoTrue hash format có thể không map trực tiếp tùy cấu hình. Có 3 cách:

Cách 1: Import đầy đủ nếu hash tương thích

– export user từ Supabase Auth, – map email, uid, metadata, – import vào Firebase Auth, – giữ UID nếu app phụ thuộc user id.

Cần test login thật kỹ.

Cách 2: Forced password reset

An toàn, đơn giản:

– import email + metadata, – đánh dấu user cần reset password, – gửi email reset, – thông báo trước.

Nhược: friction cao.

Cách 3: Lazy migration

Khi user login lần đầu:

– verify qua Supabase legacy endpoint, – tạo Firebase user, – migrate profile, – sau đó dùng Firebase.

Cách này êm hơn, nhưng cần chạy song song 2 auth một thời gian.


Migrate dữ liệu

Quy trình đề xuất

1. Freeze schema Supabase: ngừng thay đổi DB. 2. Backup đầy đủ: SQL dump, storage, auth export. 3. Export dữ liệu: CSV/JSON theo bảng. 4. Transform: SQL rows → Firestore docs. 5. Import batch: dùng Firebase Admin SDK. 6. Verify count/checksum. 7. Dual-write tạm thời nếu cần zero downtime. 8. Cutover theo feature flag. 9. Monitor lỗi. 10. Rollback plan sẵn.

Ví dụ script Node.js:

import admin from "firebase-admin";
import fs from "fs";

admin.initializeApp(); const db = admin.firestore();

const users = JSON.parse(fs.readFileSync("./users.json", "utf8"));

const batchSize = 400;

for (let i = 0; i < users.length; i += batchSize) { const batch = db.batch(); const chunk = users.slice(i, i + batchSize);

for (const user of chunk) { const ref = db.collection("users").doc(user.id); batch.set(ref, { email: user.email, displayName: user.name ?? null, createdAt: admin.firestore.Timestamp.fromDate(new Date(user.created_at)) }); }

await batch.commit(); console.log(Imported ${i + chunk.length}); }

Firestore batch limit: 500 writes. Dùng 400 để an toàn.


Chuyển RLS sang Security Rules

Supabase RLS chạy ở DB. Firebase Security Rules chạy trên request client. Không copy logic máy móc.

Ví dụ rule cơ bản:

rules_version = '2';

service cloud.firestore { match /databases/{database}/documents { match /users/{userId} { allow read, update: if request.auth != null && request.auth.uid == userId; allow create: if request.auth != null; }

match /posts/{postId} { allow read: if true; allow create: if request.auth != null; allow update, delete: if request.auth != null && request.auth.uid == resource.data.authorId; } } }

Lưu ý:

– rules không thay thế backend validation hoàn toàn, – dùng Cloud Functions cho logic nhạy cảm, – test bằng Firebase Emulator, – tránh rule quá rộng như allow read, write: if true.


Storage migration

Supabase Storage → Firebase Storage:

– export object theo bucket, – giữ path nếu client đang dùng path, – upload sang Firebase Storage, – map metadata/content-type, – đổi URL trong DB nếu đang lưu public URL.

Khuyến nghị: lưu path, không lưu URL cứng. URL có thể đổi, path ổn hơn.

Rules mẫu:

service firebase.storage {
  match /b/{bucket}/o {
    match /avatars/{userId}/{fileName} {
      allow read: if true;
      allow write: if request.auth != null && request.auth.uid == userId;
    }
  }
}

Cutover không downtime

Có 2 chiến lược.

Big bang

Tắt app ghi Supabase → migrate → bật Firebase.

Phù hợp:

– app nhỏ, – downtime chấp nhận, – dữ liệu ít.

Phased migration

An toàn hơn:

– app version mới đọc Firebase, – bản cũ vẫn đọc Supabase, – backend dual-write, – sync job xử lý lệch, – feature flag chuyển từng nhóm user.

Phù hợp app production lớn.


Checklist kiểm thử

Trước go-live:

– Auth login/logout/reset password. – Permission từng role. – Count dữ liệu theo collection. – File download/upload. – Query index Firestore. – Offline mode. – Push notification. – Cloud Functions retry/idempotency. – Billing alert. – Crash/latency monitoring. – Rollback path.

Dùng Firebase Emulator Suite để test local. Dùng staging project tách production.


Rủi ro thường gặp

Query Firestore bị thiếu index

Giải pháp: chạy test luồng chính, tạo composite index trước.

Bill tăng do listener

Giải pháp: paginate, limit, detach listener khi unmount, tránh listen collection lớn.

Denormalization sai

Giải pháp: xác định source of truth, dùng Cloud Functions sync, viết script repair.

UID thay đổi

Giải pháp: giữ UID cũ nếu có thể. Nếu không, tạo bảng mapping oldUserId -> firebaseUid.

Rollback không rõ

Giải pháp: trong giai đoạn chuyển, giữ Supabase read-only hoặc dual-write đến khi ổn định.


Kết luận thực tế

Chuyển Supabase sang Firebase hợp lý khi app thiên về mobile, realtime đơn giản, offline-first, push notification, analytics, vận hành gọn. Không nên chuyển chỉ vì “Firebase phổ biến hơn”. Nếu dữ liệu quan hệ sâu, SQL reporting nặng, transaction phức tạp, Supabase/Postgres vẫn là lựa chọn mạnh.

Migration an toàn cần 4 nguyên tắc: backup trước, thiết kế lại data model, migrate auth cẩn thận, cutover có rollback. Đừng copy SQL schema sang Firestore. Đừng deploy rules lỏng. Đừng bỏ qua chi phí read/write.

Cách tốt nhất: migrate thử trên staging, chạy song song ngắn hạn, dùng feature flag, monitor sát. Khi metric ổn, mới tắt Supabase. Migration không phải cuộc đua tốc độ; là bài toán kiểm soát rủi ro.

Tác giả

P T P

Chia sẻ

Bài viết liên quan

Bình luận (0)

Email của bạn sẽ không được hiển thị công khai.

Chưa có bình luận. Hãy là người đầu tiên!