多租戶
規則
- 行級隔離(預設):為每個租戶範圍的資料表添加
tenantId 欄位,並透過中介軟體或 RLS(資料列層級安全性)強制實施。
- 模式分隔租戶:當租戶需要自訂模式或嚴格的資料隔離時使用——此方法操作較複雜,但隔離性更佳。
- 子網域路由:從
{tenant}.app.com 解析租戶——在中介軟體中解析,並在請求上下文中設定 tenantId。
- 自訂域名:將 CNAME 指向您的應用程式,透過
Host 標頭查找租戶——使用 domains 資料表將自訂域名對應到租戶 ID。
- 每個租戶的配置:將主題(標誌、顏色)、功能標誌和限制儲存在
tenant_settings 資料表中——使用帶 TTL 的記憶體進行快取。
- RLS 模式(Postgres):
ALTER TABLE posts ENABLE ROW LEVEL SECURITY; CREATE POLICY tenant_isolation ON posts USING (tenant_id = current_setting('app.tenant_id'))
- 中介軟體:從子網域/標頭提取租戶,設定到上下文,並應用於所有資料庫查詢——絕不讓任何查詢在沒有租戶範圍的情況下執行。
- 資料分割:對於大型資料表,按
tenantId 進行分割——可改善查詢效能,並支援每個租戶的備份/還原。
行級隔離模式
function getTenantFromHost(host: string): string {
const subdomain = host.split(".")[0];
return subdomain;
}
prisma.$use(async (params, next) => {
if (TENANT_MODELS.includes(params.model)) {
params.args.where = { ...params.args.where, tenantId: context.tenantId };
}
return next(params);
});
子網域路由(Next.js 中介軟體)
export function middleware(request: NextRequest) {
const host = request.headers.get("host") ?? "";
const tenant = host.split(".")[0];
const response = NextResponse.next();
response.headers.set("x-tenant-id", tenant);
return response;
}
避免事項
- 遺漏租戶範圍的查詢——只要少了一個
WHERE tenantId = ? 就會跨租戶洩漏資料
- 在客戶端硬編碼租戶——應從伺服器端透過子網域/域名解析
- 未對
tenantId 建立索引——每個租戶範圍的資料表都需要一個以 tenantId 開頭的複合索引
- 在共用快取中混用租戶資料——快取鍵應以
{tenantId}:{key} 命名空間區隔