Supabase (BaaS)

Supabase Platform, Self-Hosting & Migration

Supabase Platform — Studio, organizations, branching, logs, self-hosting Docker/K8s. Migration từ Firebase, Heroku, RDS, MySQL.

Supabase Platform

Supabase Studio (Dashboard)

Dashboard web để quản lý dự án trực quan, không cần dùng CLI:

Tính năngMô tả
Table EditorCRUD trực quan trên bảng, tạo bảng, quản lý relationships bằng giao diện kéo thả
SQL EditorChạy SQL queries trực tiếp, lưu snippets thường dùng, schema visualization
AuthQuản lý users, providers, email templates, redirect URLs, rate limits, audit logs
StorageUpload/download files, quản lý buckets, cấu hình RLS policies cho storage objects
Edge FunctionsDeploy, monitor và manage functions với logs realtime
RealtimeKiểm tra Realtime subscriptions, message inspector
API DocsAuto-generated API documentation từ schema -- xem tất cả endpoints và parameters
GraphiQLInteractive GraphQL IDE để khám phá và test GraphQL API
Logs & AnalyticsXem query logs, error logs, API usage metrics, performance stats
Database ExtensionsBật/tắt 70+ Postgres extensions chỉ với một click
Cron JobsTạo và quản lý scheduled jobs với cron syntax, xem lịch sử chạy
AI AssistantChat với AI để được hỗ trợ viết SQL, debug lỗi, tối ưu query

Organizations & Teams

  • Organizations: Nhóm các dự án. Mỗi organization có team members và billing riêng
  • Access Control: Phân quyền chi tiết theo role:
    • Owner: Toàn quyền quản lý org, billing, xóa projects
    • Admin: Quản lý projects, members, settings
    • Developer: Truy cập đầy đủ vào project resources
    • Read-only: Chỉ xem, không sửa
  • SSO cho Dashboard: Team plan hỗ trợ SAML SSO -- member đăng nhập dashboard bằng identity provider của công ty

Projects

Mỗi project Supabase bao gồm:

  • Dedicated Postgres database: Instance riêng, không shared với project khác
  • Compute & Disk: Cấu hình CPU, RAM, disk theo nhu cầu (xem bảng Compute Add-ons)
  • Auto-generated APIs: REST (PostgREST) và GraphQL (pg_graphql) từ schema
  • Auth và user management: Tích hợp sẵn, không cần cài đặt thêm
  • Edge Functions: Serverless compute với Deno runtime
  • Realtime: WebSocket server cho Broadcast, Presence, Postgres Changes

Database Branching

Supabase hỗ trợ database branching (Preview Branches) để phát triển an toàn:

# Tạo branch từ production để test migration mới
supabase branches create feature-x --source main

# Mỗi branch có database riêng biệt -- test schema changes không ảnh hưởng production
supabase branches list
supabase branches delete feature-x

Mỗi branch là một database instance riêng biệt với data riêng. Dùng để:

  • Test schema changes trước khi merge vào production
  • Review migrations trong PR trước khi deploy
  • Chạy CI/CD pipeline với database isolated
Branching flow lý tưởng: Tạo branch từ production -> chạy migration mới trên branch -> test -> merge migration vào main -> supabase db push lên production. Branch có thể tự động xóa sau khi merge.

Logs & Monitoring

Logs viewer trong Dashboard:

  • Query logs: xem tất cả SQL queries đã chạy, thời gian thực thi, errors
  • Auth logs: sign up, sign in, token refresh events
  • Storage logs: upload, download, delete events
  • Edge Function logs: console output, errors, execution time

Log Drains (Pro tier) — Export logs ra external service:

Có thể export logs từ 9 nguồn (log sources) khác nhau trong Supabase:

#Log SourceMô tảLog gì
1PostgresDatabase logsSQL queries, errors, slow queries, connection events
2AuthAuthentication logsSign up, sign in, sign out, token refresh, password reset
3Edge FunctionsServerless function logsConsole output, errors, execution time, cold starts
4StorageFile storage logsUpload, download, delete, signed URL generation, transform
5API Gateway (Kong)API gateway logsRequest path, method, status code, latency, rate limit hits
6RealtimeWebSocket logsConnections, subscriptions, broadcasts, presence events, errors
7PostgRESTREST API logsSQL queries from REST API, auth context, response times
8Edge NetworkCDN/edge logsCache hits/misses, edge latency, bandwidth usage
9SupavisorConnection pooler logsPool connections, queue length, timeouts, pool saturation

Destinations (nơi gửi log đến):

DestinationLoạiUse case
DatadogAPM / MonitoringFull-stack observability, dashboards, alerts
Grafana LokiLog aggregationOpen-source log management, tích hợp với Grafana
SentryError trackingTrack errors và exceptions, stack traces
AxiomLog analyticsQuery logs với SQL-like syntax, fast search
S3ArchiveLưu trữ logs dài hạn, cost-effective
Custom HTTP EndpointTùy chỉnhGửi logs đến bất kỳ HTTP endpoint nào
# Tạo log drain
supabase log-drain create --project-ref [REF] \
  --destination datadog \
  --config api_key=xxx,site=datadoghq.com

# Liệt kê log drains
supabase log-drain list --project-ref [REF]

# Xóa log drain
supabase log-drain delete --project-ref [REF] [DRAIN_ID]

Pricing: $60/drain/tháng (Pro tier). Mỗi drain có thể chọn nhiều log sources.

Interview point — Log Drains: Khi app scaling, bạn cần centralized logging để debug và monitoring. Log Drains cho phép export logs từ tất cả 9 services của Supabase ra external tools. Phổ biến nhất: Datadog cho enterprise, Grafana Loki cho open-source stack, Sentry cho error tracking.

Compute Add-ons

Tùy chỉnh CPU/RAM cho database instance:

SizeCPURAMDirect ConnectionsPooler ConnectionsGiá/tháng
Micro2-core ARM1 GB60200$10
Small2-core ARM2 GB90400$15
Medium2-core ARM4 GB120600$60
Large2-core ARM8 GB160800$110
XL4-core ARM16 GB2401,000$210
2XL8-core ARM32 GB3801,500$410
4XL16-core ARM64 GB4803,000$960
8XL32-core ARM128 GB4906,000$1,870
12XL48-core ARM192 GB5009,000$2,800
16XL64-core ARM256 GB50012,000$3,730
Paid plans có $10 compute credits/tháng, đủ cover Micro instance đầu tiên. Mọi plan đều có thể upgrade compute bất kỳ lúc nào mà không downtime.

Regions

Hỗ trợ nhiều region trên toàn cầu:

  • US: East (Virginia), West (Oregon, California)
  • EU: Ireland, Frankfurt, London, Paris
  • Asia Pacific: Singapore, Sydney, Tokyo, Seoul, Mumbai
  • South America: Sao Paulo
  • Canada: Toronto
  • Middle East: Tel Aviv

Disk Configuration

LoạiDung lượngIOPSThroughputUse case
General Purpose8 GB -- 16 TB3,000125 MB/sHầu hết ứng dụng
High PerformanceTùy chỉnhLên đến 80,000Lên đến 4,000 MB/sMission-critical, high-traffic

SLA & Compliance

Tính năngFreeProTeamEnterprise
SOC2-SOC2 Type IISOC2 Type IISOC2 Type II
ISO 27001--
HIPAA--Add-on
SLAKhông99.9%99.95%99.99%
SSO cho Dashboard--SAMLSAML + Custom
PrivateLink---
Network Restrictions--

Custom Domains & SSL

  • Thêm custom domain cho Supabase project API endpoints
  • Tự động cấp và renew SSL certificate qua Let's Encrypt
  • DNS configuration hỗ trợ CNAME flattening

Self-Hosting

Docker Compose Setup

Supabase có thể tự host trên infrastructure của bạn:

# Clone Supabase repository
git clone --depth 1 https://github.com/supabase/supabase

# Vào thư mục docker
cd supabase/docker

# Copy và cấu hình biến môi trường
cp .env.example .env

# Khởi động toàn bộ stack
docker compose -f docker-compose.yml up -d

Kiến trúc Self-Hosted — 11 Services

Self-hosted Supabase bao gồm chính xác 11 services chạy trong Docker containers:

#ServiceRolePort mặc địnhGiải thích
1studioDashboard UI3000Next.js app — giao diện quản lý trực quan (Table Editor, SQL Editor, Auth, Storage, Logs)
2kongAPI Gateway8000, 8443Routing requests đến đúng service, rate limiting, JWT validation, API key authentication
3auth (GoTrue)Authentication9999Xác thực người dùng (email/password, OAuth, SSO, MFA), sinh JWT, quản lý session
4rest (PostgREST)REST API3001Tự động sinh REST API từ database schema, hỗ trợ filtering, pagination, joins
5realtimeWebSocket Server4000Broadcast, Presence, Postgres Changes (CDC) qua logical replication
6storageFile Storage API5000S3-compatible file storage, upload/download, signed URLs, image transformation routing
7metaDatabase Metadata API8080Cung cấp metadata về database schema cho Studio (tables, columns, relationships)
8dbPostgreSQL Database5432Trái tim của Supabase — database chính lưu tất cả dữ liệu, auth schema, storage metadata
9imgproxyImage Transformation5001Resize, crop, format conversion ảnh on-the-fly (dùng bởi Storage CDN URLs)
10pgbouncerConnection Pooler6543Quản lý pool connections đến Postgres (hoặc có thể dùng Supavisor thay thế)
11vectorLog Ingestion Pipeline9000Thu thập, transform, và route logs từ tất cả services đến Logflare hoặc external destinations
Lưu ý:Supavisor là connection pooler thế hệ mới của Supabase, thay thế dần pgbouncer trong managed platform. Trong self-hosted, bạn có thể chọn dùng pgbouncer (đơn giản, ổn định) hoặc Supavisor (multi-tenant, serverless-friendly).

Biến Môi Trường Quan Trọng cho Self-Hosted

File .env trong Docker Compose chứa các biến môi trường cần thiết để cấu hình toàn bộ stack:

# ==================== DATABASE ====================
POSTGRES_PASSWORD=your-super-secret-password
# Mật khẩu của postgres user — PHẢI thay đổi trong production

# ==================== AUTH / JWT ====================
JWT_SECRET=your-super-secret-jwt-token
# Secret key dùng để ký JWT token — PHẢI là string ngẫu nhiên, ít nhất 32 chars
# Shared giữa Kong, GoTrue, PostgREST để verify JWT

ANON_KEY=generated-anon-key
# API key cho anonymous users — có quyền thấp nhất (dùng cho client-side)
# Được generate từ JWT_SECRET với role=anon

SERVICE_ROLE_KEY=generated-service-role-key
# API key cho admin — bypass RLS, full quyền (dùng cho backend/Edge Functions)
# Được generate từ JWT_SECRET với role=service_role

# ==================== URL / NETWORK ====================
SITE_URL=http://localhost:3000
# URL của app frontend — dùng cho redirect URLs (OAuth callback, email confirmation)

API_EXTERNAL_URL=http://localhost:8000
# URL của Kong API Gateway — endpoint chính cho tất cả API requests

STUDIO_DEFAULT_ORGANIZATION=My Org
# Tên organization mặc định hiển thị trong Studio

STUDIO_DEFAULT_PROJECT=My Project
# Tên project mặc định hiển thị trong Studio

# ==================== EMAIL (SMTP) ====================
SMTP_HOST=smtp.sendgrid.net
SMTP_PORT=587
SMTP_USER=apikey
SMTP_PASS=your-sendgrid-key
SMTP_SENDER_NAME=My App
SMTP_SENDER_ADDRESS=noreply@myapp.com
# Cấu hình SMTP để gửi email xác thực, magic link, reset password
# Hỗ trợ: SendGrid, Resend, AWS SES, Mailgun, custom SMTP

# ==================== STORAGE ====================
STORAGE_BACKEND=s3
# Backend lưu trữ file: 'file' (local disk) hoặc 's3' (S3-compatible)
# Dùng 's3' trong production với MinIO hoặc AWS S3

S3_ENDPOINT=https://s3.amazonaws.com
S3_REGION=us-east-1
S3_BUCKET=my-supabase-storage
S3_ACCESS_KEY=xxx
S3_SECRET_KEY=xxx
# Chỉ cần khi STORAGE_BACKEND=s3
Bảo mật:JWT_SECRET, POSTGRES_PASSWORD, SERVICE_ROLE_KEY là các giá trị nhạy cảm nhất. Phải thay đổi từ default và không commit vào git. Dùng Docker secrets hoặc vault cho production.

Kubernetes

Community-maintained Helm charts để deploy Supabase trên Kubernetes. Phù hợp cho enterprise cần auto-scaling và high availability.

helm repo add supabase https://supabase-community.github.io/helm-charts
helm install supabase supabase/supabase

Traefik Setup

Community-maintained setup với Traefik làm reverse proxy thay cho Kong. Phù hợp nếu bạn đã dùng Traefik trong infrastructure.

Khác biệt với managed platform

Self-hosted không phải Supabase CLI local dev (chỉ dành cho dev/test), và không giống managed Supabase. Bạn chịu trách nhiệm vận hành toàn bộ stack.

Tính năng KHÔNG có trong self-hosted:

Tính năngManagedSelf-hosted
Database Branching (Preview Branches)Không
Advanced metrics ngoài logsKhông
Managed backups + PITRTự độngTự làm
Analytics Buckets (Iceberg)Không
Vector BucketsKhông
ETL / PipelinesKhông
Log Drains (export logs)Có (Pro)Không
Platform Management APIKhông
Studio hỗ trợ nhiều projectChỉ 1 project
Custom Domains + SSL tự độngTự cấu hình

Trách nhiệm khi self-host

Những việc bạn phải tự làm khi self-host:

  • Provisioning và bảo trì server (VPS, dedicated, on-prem)
  • Security hardening, cập nhật OS và services định kỳ
  • Cấu hình và quản lý từng service riêng lẻ
  • Database maintenance (VACUUM, reindex, analyze)
  • High availability và scalability (replication, load balancing)
  • Backups và disaster recovery (lên lịch, test restore)
  • Monitoring và alerting (Prometheus, Grafana, uptime)
  • Cấu hình S3 storage backend (MinIO hoặc AWS S3)

Cấu hình S3 Storage cho self-hosted

# Trong .env của Docker Compose
STORAGE_BACKEND=s3
S3_ENDPOINT=https://s3.amazonaws.com
S3_REGION=us-east-1
S3_BUCKET=my-supabase-storage
S3_ACCESS_KEY=xxx
S3_SECRET_KEY=xxx

Telemetry

  • Self-hosted Supabase (Docker Compose) không thu thập telemetry
  • Supabase CLI thu thập usage telemetry (có thể opt-out bằng SUPABASE_CLI_TELEMETRY=0)

Migration Guides

Firebase Auth -> Supabase Auth

Supabase cung cấp công cụ trong repo firebase-to-supabase:

# Clone migration tool
git clone https://github.com/supabase-community/firebase-to-supabase.git

# Export Firebase users ra JSON
node firestoreusers2json.js users.json 100

# Import users vào Supabase Auth
node import_users.js users.json 100

Quy trình chi tiết:

Bước 1: Chuẩn bị credentials

# Tạo supabase-service.json với connection info
{
  "url": "https://[PROJECT_REF].supabase.co",
  "service_role_key": "eyJhbGciOi..."
}

# Tạo firebase-service.json từ Firebase Console
# Project Settings > Service Accounts > Generate New Private Key
{
  "type": "service_account",
  "project_id": "my-firebase-project",
  "private_key": "-----BEGIN PRIVATE KEY-----...",
  "client_email": "firebase-adminsdk@..."
}

Bước 2: Lấy Firebase password hash parameters

Từ Firebase Console > Authentication > Settings > Password hash parameters:

  • hash_config: Chứa mem_cost, rounds, salt_separator, signer_key (scrypt parameters)
  • Các tham số này cần thiết để Supabase có thể verify password hash khi user login

Bước 3: Export users từ Firebase

node firestoreusers2json.js users.json 100

Script sẽ export tất cả users từ Firebase Auth (email, password hash, provider data, metadata) ra file JSON.

Bước 4: Import users vào Supabase Auth

node import_users.js users.json 100

Script sẽ:

  • Tạo user trong auth.users với password hash giữ nguyên
  • Tạo records trong auth.identities cho mỗi provider
  • Set app_metadata, user_metadata từ Firebase user data
  • Cấu hình scrypt parameters trong auth.identities data
Key insight — Password hash: Firebase dùng scrypt để hash password. Supabase cũng hỗ trợ scrypt — nhưng cần cấu hình đúng tham số (mem_cost, rounds, salt_separator, signer_key). Nếu sai, user sẽ không thể login với mật khẩu cũ. Đây là lý do phải lấy chính xác hash_config từ Firebase Console.

Firebase Firestore -> Supabase Database

# Liệt kê tất cả collections
node collections.js

# Export collection ra JSON
node firestore2json.js users 1000

# Import vào Supabase Postgres
node json2supabase.js ./users.json bigserial id

Quy trình transform dữ liệu:

Firestore là NoSQL document-based. Postgres là SQL relational. Việc transform dữ liệu là thách thức lớn nhất:

// Firestore document (NoSQL — nested)
{
  "id": "user-123",
  "name": "Vinh",
  "email": "vinh@example.com",
  "address": {                        // Nested object -> Cần flatten
    "street": "123 Main St",
    "city": "Hanoi",
    "country": "Vietnam"
  },
  "posts": [                          // Sub-collection -> Cần tách bảng riêng
    { "title": "Post 1", "content": "..." },
    { "title": "Post 2", "content": "..." }
  ],
  "tags": ["react", "supabase"]       // Array -> Cần bảng junction
}

// Postgres schema (SQL — relational)
CREATE TABLE users (
  id UUID PRIMARY KEY,
  name TEXT,
  email TEXT UNIQUE,
  address_street TEXT,                // Flattened
  address_city TEXT,                  // Flattened
  address_country TEXT                // Flattened
);

CREATE TABLE posts (
  id BIGSERIAL PRIMARY KEY,
  user_id UUID REFERENCES users(id),
  title TEXT,
  content TEXT
);

CREATE TABLE user_tags (
  user_id UUID REFERENCES users(id),
  tag TEXT,
  PRIMARY KEY (user_id, tag)
);

Nguyên tắc transform:

Firestore PatternPostgres EquivalentCách xử lý
Nested object {address: {city: "Hanoi"}}Separate columns address_city TEXTFlatten nested object thành columns riêng
Sub-collectionSeparate table + FK user_id REFERENCES users(id)Tạo bảng riêng với foreign key
Array field ["react", "supabase"]Junction table user_tags(user_id, tag)Tạo bảng junction (many-to-many)
Timestamp Firestore.TimestampTIMESTAMPTZConvert qua new Date(ts._seconds * 1000)
Reference DocumentReferenceForeign Key UUIDExtract ID và tạo FK constraint
GeoPointPOINT type (PostGIS)Cần extension postgis
Thách thức lớn nhất: Firestore là NoSQL (document-based), Postgres là SQL (relational). Dữ liệu nested cần được "flatten" -- tách nested data thành các bảng riêng biệt với foreign keys. Dùng custom hooks để customize quá trình transform JSON.

Firebase Storage -> Supabase Storage

Quy trình migrate files:

  1. Export danh sách files từ Firebase Storage (dùng Firebase Admin SDK):
const admin = require('firebase-admin')
admin.initializeApp({ credential: admin.credential.cert(serviceAccount) })

const bucket = admin.storage().bucket()
const [files] = await bucket.getFiles()

for (const file of files) {
  console.log(file.name, file.metadata.size)
  // Download và upload lên Supabase Storage
}
  1. Download files từ Firebase Storage:
const tempPath = `/tmp/${file.name}`
await file.download({ destination: tempPath })
  1. Upload lên Supabase Storage:
const fileBuffer = fs.readFileSync(tempPath)
const { data, error } = await supabase.storage
  .from('migrated-files')
  .upload(file.name, fileBuffer, {
    contentType: file.metadata.contentType || 'application/octet-stream',
    cacheControl: file.metadata.cacheControl || '3600'
  })
  1. Map Firebase Storage paths sang Supabase Storage paths:
    • Firebase: users/user-123/avatar.jpg
    • Supabase: giữ nguyên cấu trúc hoặc tổ chức lại theo bucket

File metadata có thể được map sang storage.objects metadata columns.

Firebase Security Rules -> Postgres RLS Policy

Đây là bước quan trọng khi migrate từ Firebase sang Supabase:

// Firebase Security Rules (Firestore)
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Users can read their own data
    match /users/{userId} {
      allow read: if request.auth.uid == userId;
      allow write: if request.auth.uid == userId;
    }
    // Anyone can read published posts
    match /posts/{postId} {
      allow read: if resource.data.published == true;
      allow write: if request.auth.uid == resource.data.author_id;
    }
  }
}

Tương đương trong Postgres RLS:

-- Policy: Users can read their own data
CREATE POLICY "Users can access own data"
ON users FOR ALL
USING (auth.uid() = id)
WITH CHECK (auth.uid() = id);

-- Policy: Anyone can read published posts
CREATE POLICY "Anyone can read published posts"
ON posts FOR SELECT
USING (published = true);

-- Policy: Authors can edit their posts
CREATE POLICY "Authors can edit own posts"
ON posts FOR INSERT
WITH CHECK (auth.uid() = author_id);

CREATE POLICY "Authors can update own posts"
ON posts FOR UPDATE
USING (auth.uid() = author_id)
WITH CHECK (auth.uid() = author_id);

Mapping table:

Firebase Rules PatternPostgres RLS Equivalent
request.auth != nullauth.role() = 'authenticated'
request.auth.uid == userIdauth.uid() = user_id
request.auth.uid == resource.data.ownerauth.uid() = owner_id
resource.data.published == truepublished = true
request.auth.uid in resource.data.membersauth.uid() = ANY(members)
request.auth.token.role == 'admin'auth.jwt()->>'role' = 'admin'
allow read: if trueCREATE POLICY ... FOR SELECT USING (true)

Amazon RDS Postgres -> Supabase

# Export từ RDS
pg_dump -h [RDS_HOST] -U [USER] -d [DB_NAME] \
  --no-owner --no-acl -f dump.sql

# Import vào Supabase
psql -h [SUPABASE_HOST] -U postgres -d postgres -f dump.sql

Heroku Postgres -> Supabase

# Từ Heroku
heroku pg:backups:capture --app your-app
heroku pg:backups:download --app your-app

# Import vào Supabase
pg_restore -h [SUPABASE_HOST] -U postgres -d postgres latest.dump

MySQL -> Supabase

Do MySQL và PostgreSQL khác nhau về syntax và data types:

  1. Export MySQL schema và data qua mysqldump
  2. Dùng pgloader hoặc mysql-to-postgres converter
  3. Điều chỉnh data types:
    • AUTO_INCREMENT -> SERIAL / BIGSERIAL
    • TINYINT -> SMALLINT
    • DATETIME -> TIMESTAMPTZ
    • TEXT -> TEXT (giữ nguyên)
    • ENUM -> CREATE TYPE ... AS ENUM
  4. Convert stored procedures từ MySQL procedural SQL sang PL/pgSQL
  5. Import vào Supabase

Vercel Postgres / Neon -> Supabase

Cả hai đều là PostgreSQL -- đơn giản nhất:

# Pull schema từ Vercel/Neon
pg_dump -h [HOST] -U [USER] -d [DB] --schema-only -f schema.sql

# Push vào Supabase qua migration
supabase db push

MSSQL / SQL Server -> Supabase

Cần convert từ T-SQL sang PL/pgSQL:

  1. Export schema definition từ SQL Server
  2. Convert data types: NVARCHAR -> TEXT, DATETIME -> TIMESTAMPTZ, BIT -> BOOLEAN
  3. Convert stored procedures từ T-SQL sang PL/pgSQL
  4. Xử lý differences: IDENTITY -> SERIAL, computed columns -> generated columns
  5. Dùng migration tool để import vào Supabase
Key insight: Khi migrate từ NoSQL (Firestore) sang SQL (Postgres), việc thiết kế lại schema là không thể tránh khỏi. Password hash cần được bảo toàn -- Firebase dùng scrypt, Supabase cũng hỗ trợ scrypt qua auth hooks.
Interview point — Firebase to Supabase Migration: Ba phần khó nhất: (1) Password hash preservation — cần giữ nguyên scrypt parameters, (2) Schema redesign — NoSQL nested data phải được normalize thành relational tables, (3) Security Rules to RLS mapping — Firebase rules syntax khác hoàn toàn với SQL RLS policies.

Công cụ & Sản phẩm bổ sung

Cron (pg_cron)

Lập lịch jobs định kỳ với cron syntax ngay trong Postgres:

-- Bật extension
CREATE EXTENSION IF NOT EXISTS pg_cron;

-- Job chạy SQL mỗi phút -- dọn dữ liệu tạm cũ
SELECT cron.schedule(
  'cleanup-temp',
  '* * * * *',
  'DELETE FROM temp_data WHERE created_at < now() - interval ''1 hour'''
);

-- Job gọi Edge Function mỗi giờ
SELECT cron.schedule(
  'hourly-sync',
  '0 * * * *',
  $$
  SELECT net.http_post(
    url := 'https://[REF].supabase.co/functions/v1/sync-data',
    headers := '{"Authorization": "Bearer [SERVICE_ROLE_KEY]"}'::jsonb
  )
  $$
);

-- Quản lý jobs
SELECT * FROM cron.job;                              -- Danh sách jobs
SELECT * FROM cron.job_run_details;                  -- Lịch sử chạy
SELECT cron.unschedule('cleanup-temp');               -- Hủy job

Limits: Khuyến nghị không quá 8 jobs chạy đồng thời, mỗi job không quá 10 phút.

Queues (pgmq)

Message queue bền vững trong Postgres -- không cần Redis hay RabbitMQ riêng:

-- Bật extension + tạo queue
CREATE EXTENSION IF NOT EXISTS pgmq;
SELECT pgmq.create('task_queue');

-- Gửi message
SELECT pgmq.send('task_queue', '{"task": "send_email", "to": "user@example.com", "template": "welcome"}');

-- Consumer: đọc message (visibility timeout 60 giây)
SELECT * FROM pgmq.read('task_queue', 10, 60);

-- Xác nhận đã xử lý
SELECT pgmq.delete('task_queue', msg_id);

-- Archive message đã xử lý (giữ lại để audit)
SELECT pgmq.archive('task_queue', msg_id);

-- Pop (đọc + xóa atomic)
SELECT * FROM pgmq.pop('task_queue');

Đặc điểm:

  • Guaranteed delivery: Message được đảm bảo gửi đến consumer
  • Exactly-once delivery: Trong visibility window
  • RLS integration: Phân quyền truy cập queue bằng RLS policies
  • Dashboard management: Quản lý queues và messages trong Dashboard

Analytics Buckets

Lưu dữ liệu trong Apache Iceberg format, query từ Postgres qua foreign tables. Tối ưu cho data lakes, logs, và Pipelines.

Log Drains (Pro tier)

Export logs ra external services: Datadog, Grafana Loki, Sentry, S3, Better Stack, Logtail, Axiom.

Supabase UI

Pre-built React components cho Supabase:

npm install @supabase/auth-ui-react @supabase/auth-ui-shared

MCP Server

Cho phép AI agents (Claude Code, Cursor, Windsurf) tương tác với Supabase:

npx skills add supabase/agent-skills
  • Prisma, Drizzle: ORM cho database
  • Resend, SendGrid: Email service
  • Stripe: Payment processing
  • Sentry: Error monitoring
  • Vercel, Netlify: Hosting
  • Auth0, Clerk, AWS Cognito: Third-party auth providers

Bài tập thực hành

Bài tập 1: Setup local dev environment với Supabase CLI
Xây dựng môi trường phát triển local đầy đủ:
  1. Cài đặt Supabase CLI và Docker Desktop
  2. supabase init để khởi tạo project
  3. supabase start để khởi động toàn bộ stack local
  4. Tạo migration cho schema blog (bảng posts, authors, comments)
  5. Thêm seed data với file supabase/seed.sql
  6. Generate TypeScript types từ schema local
  7. Tạo Edge Function test thử trên local
  8. Snapshot môi trường local với supabase db dump
Verify bằng cách:
  • Truy cập Studio Dashboard tại http://localhost:54323
  • Chạy SQL query trong SQL Editor local
  • Test API endpoint tại http://localhost:54321/rest/v1/
  • Gọi Edge Function local qua http://localhost:54321/functions/v1/
Gợi ý supabase/config.toml:
[db]
port = 54322

[studio]
port = 54323

[api]
port = 54321
Bài tập 2: Migration plan từ Firebase sang Supabase
Thiết kế kế hoạch migration cho một mobile app React Native đang dùng Firebase:Hiện trạng Firebase:
  • Firestore: users, posts, comments, likes (nested trong posts), notifications
  • Firebase Auth: Email/Password + Google OAuth
  • Firebase Storage: Avatar users, post images
Yêu cầu sau migration:
  • Tất cả dữ liệu phải được migrate không mất mát
  • Người dùng không cần đặt lại mật khẩu
  • App hoạt động với cả Firebase và Supabase trong giai đoạn chuyển tiếp
  • Downtime tối đa 30 phút
Lập kế hoạch chi tiết gồm:
  • Thiết kế schema mới (ERD) cho Postgres
  • Chiến lược migrate auth users (giữ password hash)
  • Script transform dữ liệu Firestore sang SQL
  • Kế hoạch dual-write trong giai đoạn chuyển tiếp
  • Timeline và rollback plan
Gợi ý: Vẽ bản đồ Firestore collection -> Postgres table, xác định nested data cần flatten, và thiết kế foreign key relationships.

© 2026 .NET Fresher Guide. All rights reserved.

Về Trang Web

Hướng dẫn toàn diện để chuẩn bị phỏng vấn vị trí .NET Fresher với nội dung từ lý thuyết đến thực hành.