Supabase Platform, Self-Hosting & Migration
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ăng | Mô tả |
|---|---|
| Table Editor | CRUD trực quan trên bảng, tạo bảng, quản lý relationships bằng giao diện kéo thả |
| SQL Editor | Chạy SQL queries trực tiếp, lưu snippets thường dùng, schema visualization |
| Auth | Quản lý users, providers, email templates, redirect URLs, rate limits, audit logs |
| Storage | Upload/download files, quản lý buckets, cấu hình RLS policies cho storage objects |
| Edge Functions | Deploy, monitor và manage functions với logs realtime |
| Realtime | Kiểm tra Realtime subscriptions, message inspector |
| API Docs | Auto-generated API documentation từ schema -- xem tất cả endpoints và parameters |
| GraphiQL | Interactive GraphQL IDE để khám phá và test GraphQL API |
| Logs & Analytics | Xem query logs, error logs, API usage metrics, performance stats |
| Database Extensions | Bật/tắt 70+ Postgres extensions chỉ với một click |
| Cron Jobs | Tạo và quản lý scheduled jobs với cron syntax, xem lịch sử chạy |
| AI Assistant | Chat 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
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 Source | Mô tả | Log gì |
|---|---|---|---|
| 1 | Postgres | Database logs | SQL queries, errors, slow queries, connection events |
| 2 | Auth | Authentication logs | Sign up, sign in, sign out, token refresh, password reset |
| 3 | Edge Functions | Serverless function logs | Console output, errors, execution time, cold starts |
| 4 | Storage | File storage logs | Upload, download, delete, signed URL generation, transform |
| 5 | API Gateway (Kong) | API gateway logs | Request path, method, status code, latency, rate limit hits |
| 6 | Realtime | WebSocket logs | Connections, subscriptions, broadcasts, presence events, errors |
| 7 | PostgREST | REST API logs | SQL queries from REST API, auth context, response times |
| 8 | Edge Network | CDN/edge logs | Cache hits/misses, edge latency, bandwidth usage |
| 9 | Supavisor | Connection pooler logs | Pool connections, queue length, timeouts, pool saturation |
Destinations (nơi gửi log đến):
| Destination | Loại | Use case |
|---|---|---|
| Datadog | APM / Monitoring | Full-stack observability, dashboards, alerts |
| Grafana Loki | Log aggregation | Open-source log management, tích hợp với Grafana |
| Sentry | Error tracking | Track errors và exceptions, stack traces |
| Axiom | Log analytics | Query logs với SQL-like syntax, fast search |
| S3 | Archive | Lưu trữ logs dài hạn, cost-effective |
| Custom HTTP Endpoint | Tùy chỉnh | Gử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.
Compute Add-ons
Tùy chỉnh CPU/RAM cho database instance:
| Size | CPU | RAM | Direct Connections | Pooler Connections | Giá/tháng |
|---|---|---|---|---|---|
| Micro | 2-core ARM | 1 GB | 60 | 200 | $10 |
| Small | 2-core ARM | 2 GB | 90 | 400 | $15 |
| Medium | 2-core ARM | 4 GB | 120 | 600 | $60 |
| Large | 2-core ARM | 8 GB | 160 | 800 | $110 |
| XL | 4-core ARM | 16 GB | 240 | 1,000 | $210 |
| 2XL | 8-core ARM | 32 GB | 380 | 1,500 | $410 |
| 4XL | 16-core ARM | 64 GB | 480 | 3,000 | $960 |
| 8XL | 32-core ARM | 128 GB | 490 | 6,000 | $1,870 |
| 12XL | 48-core ARM | 192 GB | 500 | 9,000 | $2,800 |
| 16XL | 64-core ARM | 256 GB | 500 | 12,000 | $3,730 |
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ại | Dung lượng | IOPS | Throughput | Use case |
|---|---|---|---|---|
| General Purpose | 8 GB -- 16 TB | 3,000 | 125 MB/s | Hầu hết ứng dụng |
| High Performance | Tùy chỉnh | Lên đến 80,000 | Lên đến 4,000 MB/s | Mission-critical, high-traffic |
SLA & Compliance
| Tính năng | Free | Pro | Team | Enterprise |
|---|---|---|---|---|
| SOC2 | - | SOC2 Type II | SOC2 Type II | SOC2 Type II |
| ISO 27001 | - | - | Có | Có |
| HIPAA | - | - | Add-on | Có |
| SLA | Không | 99.9% | 99.95% | 99.99% |
| SSO cho Dashboard | - | - | SAML | SAML + Custom |
| PrivateLink | - | - | - | Có |
| Network Restrictions | - | - | Có | Có |
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:
| # | Service | Role | Port mặc định | Giải thích |
|---|---|---|---|---|
| 1 | studio | Dashboard UI | 3000 | Next.js app — giao diện quản lý trực quan (Table Editor, SQL Editor, Auth, Storage, Logs) |
| 2 | kong | API Gateway | 8000, 8443 | Routing requests đến đúng service, rate limiting, JWT validation, API key authentication |
| 3 | auth (GoTrue) | Authentication | 9999 | Xác thực người dùng (email/password, OAuth, SSO, MFA), sinh JWT, quản lý session |
| 4 | rest (PostgREST) | REST API | 3001 | Tự động sinh REST API từ database schema, hỗ trợ filtering, pagination, joins |
| 5 | realtime | WebSocket Server | 4000 | Broadcast, Presence, Postgres Changes (CDC) qua logical replication |
| 6 | storage | File Storage API | 5000 | S3-compatible file storage, upload/download, signed URLs, image transformation routing |
| 7 | meta | Database Metadata API | 8080 | Cung cấp metadata về database schema cho Studio (tables, columns, relationships) |
| 8 | db | PostgreSQL Database | 5432 | Trái tim của Supabase — database chính lưu tất cả dữ liệu, auth schema, storage metadata |
| 9 | imgproxy | Image Transformation | 5001 | Resize, crop, format conversion ảnh on-the-fly (dùng bởi Storage CDN URLs) |
| 10 | pgbouncer | Connection Pooler | 6543 | Quản lý pool connections đến Postgres (hoặc có thể dùng Supavisor thay thế) |
| 11 | vector | Log Ingestion Pipeline | 9000 | Thu thập, transform, và route logs từ tất cả services đến Logflare hoặc external destinations |
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
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
Tính năng KHÔNG có trong self-hosted:
| Tính năng | Managed | Self-hosted |
|---|---|---|
| Database Branching (Preview Branches) | Có | Không |
| Advanced metrics ngoài logs | Có | Không |
| Managed backups + PITR | Tự động | Tự làm |
| Analytics Buckets (Iceberg) | Có | Không |
| Vector Buckets | Có | Không |
| ETL / Pipelines | Có | Không |
| Log Drains (export logs) | Có (Pro) | Không |
| Platform Management API | Có | Không |
| Studio hỗ trợ nhiều project | Có | Chỉ 1 project |
| Custom Domains + SSL tự động | Có | Tự 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ứamem_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.usersvới password hash giữ nguyên - Tạo records trong
auth.identitiescho mỗi provider - Set
app_metadata,user_metadatatừ Firebase user data - Cấu hình scrypt parameters trong
auth.identitiesdata
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 Pattern | Postgres Equivalent | Cách xử lý |
|---|---|---|
Nested object {address: {city: "Hanoi"}} | Separate columns address_city TEXT | Flatten nested object thành columns riêng |
| Sub-collection | Separate 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.Timestamp | TIMESTAMPTZ | Convert qua new Date(ts._seconds * 1000) |
Reference DocumentReference | Foreign Key UUID | Extract ID và tạo FK constraint |
| GeoPoint | POINT type (PostGIS) | Cần extension postgis |
custom hooks để customize quá trình transform JSON.Firebase Storage -> Supabase Storage
Quy trình migrate files:
- 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
}
- Download files từ Firebase Storage:
const tempPath = `/tmp/${file.name}`
await file.download({ destination: tempPath })
- 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'
})
- 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
- Firebase:
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 Pattern | Postgres RLS Equivalent |
|---|---|
request.auth != null | auth.role() = 'authenticated' |
request.auth.uid == userId | auth.uid() = user_id |
request.auth.uid == resource.data.owner | auth.uid() = owner_id |
resource.data.published == true | published = true |
request.auth.uid in resource.data.members | auth.uid() = ANY(members) |
request.auth.token.role == 'admin' | auth.jwt()->>'role' = 'admin' |
allow read: if true | CREATE 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:
- Export MySQL schema và data qua
mysqldump - Dùng pgloader hoặc
mysql-to-postgresconverter - Điều chỉnh data types:
AUTO_INCREMENT->SERIAL/BIGSERIALTINYINT->SMALLINTDATETIME->TIMESTAMPTZTEXT->TEXT(giữ nguyên)ENUM->CREATE TYPE ... AS ENUM
- Convert stored procedures từ MySQL procedural SQL sang PL/pgSQL
- 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:
- Export schema definition từ SQL Server
- Convert data types:
NVARCHAR->TEXT,DATETIME->TIMESTAMPTZ,BIT->BOOLEAN - Convert stored procedures từ T-SQL sang PL/pgSQL
- Xử lý differences:
IDENTITY->SERIAL, computed columns -> generated columns - Dùng migration tool để import vào Supabase
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
Partner Gallery -- Integrations
- 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
- Cài đặt Supabase CLI và Docker Desktop
supabase initđể khởi tạo projectsupabase startđể khởi động toàn bộ stack local- Tạo migration cho schema blog (bảng posts, authors, comments)
- Thêm seed data với file
supabase/seed.sql - Generate TypeScript types từ schema local
- Tạo Edge Function test thử trên local
- Snapshot môi trường local với
supabase db dump
- 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/
supabase/config.toml:[db]
port = 54322
[studio]
port = 54323
[api]
port = 54321
- Firestore:
users,posts,comments,likes(nested trong posts),notifications - Firebase Auth: Email/Password + Google OAuth
- Firebase Storage: Avatar users, post images
- 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
- 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
Firestore collection -> Postgres table, xác định nested data cần flatten, và thiết kế foreign key relationships.