惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - Franky
N
Netflix TechBlog - Medium
宝玉的分享
宝玉的分享
Google DeepMind News
Google DeepMind News
腾讯CDC
G
Google Developers Blog
Martin Fowler
Martin Fowler
Microsoft Security Blog
Microsoft Security Blog
Recent Announcements
Recent Announcements
爱范儿
爱范儿
Engineering at Meta
Engineering at Meta
Microsoft Azure Blog
Microsoft Azure Blog
A
About on SuperTechFans
aimingoo的专栏
aimingoo的专栏
有赞技术团队
有赞技术团队
Jina AI
Jina AI
人人都是产品经理
人人都是产品经理
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
M
MIT News - Artificial intelligence
罗磊的独立博客
博客园 - 三生石上(FineUI控件)
美团技术团队
WordPress大学
WordPress大学
阮一峰的网络日志
阮一峰的网络日志

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Multi-tenant PostgreSQL: row-level security vs schema-per...
Jayanth · 2026-05-24 · via DEV Community

Jayanth

If you're building a multi-tenant SaaS, this is the first real architecture

decision that will haunt you if you get it wrong.
I've implemented both approaches in production. Here's the honest trade-off.

Option A: Shared schema with row-level security (RLS)

Every tenant's data lives in the same tables. A tenant_id column on every
row. PostgreSQL RLS policies enforce that queries only ever return rows
belonging to the current tenant.

-- Enable RLS on the table
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;

-- Policy: users only see their tenant's rows
CREATE POLICY tenant_isolation ON orders
    USING (tenant_id = current_setting('app.current_tenant_id')::uuid);

Enter fullscreen mode Exit fullscreen mode

# Set the tenant context before every query
async def set_tenant(conn, tenant_id: str):
    await conn.execute(
        "SELECT set_config('app.current_tenant_id', $1, true)",
        tenant_id
    )

Enter fullscreen mode Exit fullscreen mode

Works well when: You have many small tenants. Hundreds or thousands.
Schema-per-tenant at that scale is unmanageable — migrations alone would take hours.

Breaks when: A noisy tenant runs heavy queries and degrades performance for others. You can't easily move one tenant's data to a separate DB. You need different retention policies per tenant.

Option B: Schema per tenant

Each tenant gets their own PostgreSQL schema — effectively a namespace.
tenant_abc.orders, tenant_xyz.orders. Same tables, different schema.

-- Create schema for a new tenant
CREATE SCHEMA tenant_abc;

-- Set search path at connection time
SET search_path TO tenant_abc, public;

Enter fullscreen mode Exit fullscreen mode

# Alembic migration across all tenant schemas
from alembic import command
from alembic.config import Config

def migrate_all_tenants(tenant_schemas: list[str]):
    for schema in tenant_schemas:
        alembic_cfg = Config("alembic.ini")
        alembic_cfg.set_main_option("sqlalchemy.url", db_url)
        alembic_cfg.set_section_option("alembic", "version_table_schema", schema)
        command.upgrade(alembic_cfg, "head")

Enter fullscreen mode Exit fullscreen mode

Works well when: You have fewer, larger tenants. Enterprise customers
who need data isolation guarantees, custom retention, or the ability to
export their entire dataset cleanly.
Breaks when: You have 500+ tenants. Running migrations across 500
schemas sequentially is slow. Connection pool overhead grows.

What I actually use
For most SaaS products at early stage: start with RLS. It's simpler to
operate, migrations are trivial, and you can always move to schema-per-tenant
for specific large customers later by routing them to a dedicated schema
or even a dedicated database.
The hybrid approach — RLS for SMB tenants, dedicated schema for enterprise —
is what I've settled on. Your connection string is the router.

def get_db_url(tenant: Tenant) -> str:
    if tenant.tier == "enterprise":
        return tenant.dedicated_db_url
    return f"{shared_db_url}?options=-csearch_path={tenant.schema}"

Enter fullscreen mode Exit fullscreen mode

One thing nobody tells you: test your RLS policies with a superuser disabled.
PostgreSQL superusers bypass RLS by default. Your staging environment running
as a superuser will never catch a broken policy. Use a restricted role in tests.