docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를 Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류. - 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로 자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거, 동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거. - 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming, Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business, Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로, 나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는 title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백). 원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지. - 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서. - 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는 지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지. - Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경. - 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
This commit is contained in:
@@ -0,0 +1,190 @@
|
||||
---
|
||||
id: backend-multi-tenant-architecture
|
||||
title: Multi-tenant — Pool / Silo / Bridge 모델
|
||||
category: Coding
|
||||
status: draft
|
||||
source_trust_level: B
|
||||
verification_status: conceptual
|
||||
created_at: 2026-05-09
|
||||
updated_at: 2026-05-09
|
||||
tags: [backend, multi-tenant, saas, vibe-coding]
|
||||
tech_stack: { language: "TS / SQL", applicable_to: ["Backend"] }
|
||||
applied_in: []
|
||||
aliases: [multi-tenant, SaaS, tenant isolation, pool model, silo model, RLS]
|
||||
---
|
||||
|
||||
# Multi-tenant Architecture
|
||||
|
||||
> 한 시스템 + 여러 고객 (조직). **Pool (공유 DB) / Silo (고객별 DB) / Bridge (혼합)**. 격리 강도 vs 운영 비용.
|
||||
|
||||
## 📖 핵심 개념
|
||||
- Tenant: 사용자가 속한 조직.
|
||||
- Pool: 모든 tenant 한 DB, tenant_id 컬럼.
|
||||
- Silo: tenant 별 DB / namespace.
|
||||
- Bridge: 큰 tenant 만 silo, 나머지 pool.
|
||||
|
||||
## 💻 코드 패턴
|
||||
|
||||
### Pool model (가장 단순)
|
||||
```sql
|
||||
CREATE TABLE orders (
|
||||
id UUID PRIMARY KEY,
|
||||
tenant_id UUID NOT NULL,
|
||||
...
|
||||
);
|
||||
|
||||
-- 모든 query 에 tenant_id 필수
|
||||
CREATE INDEX orders_tenant ON orders(tenant_id, created_at DESC);
|
||||
```
|
||||
|
||||
```ts
|
||||
// 강제 — request context 에서
|
||||
async function ordersForTenant(req: Request) {
|
||||
return db.orders.findMany({ where: { tenantId: req.tenantId, ...rest } });
|
||||
}
|
||||
```
|
||||
|
||||
### RLS (Row Level Security)
|
||||
```sql
|
||||
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
CREATE POLICY tenant_isolation ON orders
|
||||
USING (tenant_id = current_setting('app.tenant_id')::UUID);
|
||||
```
|
||||
|
||||
```ts
|
||||
// 매 트랜잭션 시작 시
|
||||
await db.execute(`SET LOCAL app.tenant_id = '${ctx.tenantId}'`);
|
||||
// 이제 모든 query 가 자동 필터
|
||||
```
|
||||
|
||||
→ 코드 실수해도 다른 tenant 못 봄.
|
||||
|
||||
### Schema-per-tenant (Postgres)
|
||||
```sql
|
||||
CREATE SCHEMA tenant_acme;
|
||||
CREATE TABLE tenant_acme.orders (...);
|
||||
-- 모든 테이블 동일 schema, tenant 별 분리
|
||||
```
|
||||
|
||||
```ts
|
||||
const schema = `tenant_${tenantId}`;
|
||||
await db.execute(`SET search_path TO ${schema}, public`);
|
||||
// 이후 query 가 자동 그 schema
|
||||
```
|
||||
|
||||
### Database-per-tenant (Silo)
|
||||
```ts
|
||||
const tenantPools = new Map<string, Pool>();
|
||||
|
||||
async function getPool(tenantId: string): Promise<Pool> {
|
||||
if (!tenantPools.has(tenantId)) {
|
||||
const cfg = await getTenantDbConfig(tenantId);
|
||||
tenantPools.set(tenantId, new Pool(cfg));
|
||||
}
|
||||
return tenantPools.get(tenantId)!;
|
||||
}
|
||||
|
||||
const db = await getPool(req.tenantId);
|
||||
const orders = await db.query('SELECT * FROM orders');
|
||||
```
|
||||
|
||||
### Tenant 식별
|
||||
```ts
|
||||
// 1. Subdomain
|
||||
const tenant = req.hostname.split('.')[0]; // acme.example.com
|
||||
|
||||
// 2. Header (API)
|
||||
const tenant = req.headers['x-tenant-id'];
|
||||
|
||||
// 3. JWT claim
|
||||
const { tenantId } = verifyJwt(token);
|
||||
|
||||
// 4. Path
|
||||
// /tenants/:slug/api/...
|
||||
```
|
||||
|
||||
### Migration (모든 tenant)
|
||||
```ts
|
||||
// Pool: 한 번만 (모든 tenant 영향)
|
||||
await runMigrations();
|
||||
|
||||
// Schema-per-tenant: 각 schema 마다
|
||||
const tenants = await db.query('SELECT id FROM tenants');
|
||||
for (const t of tenants) {
|
||||
await db.execute(`SET search_path TO tenant_${t.id}`);
|
||||
await runMigrations();
|
||||
}
|
||||
|
||||
// DB-per-tenant: 각 DB
|
||||
for (const t of tenants) {
|
||||
const pool = await getPool(t.id);
|
||||
await runMigrationsOn(pool);
|
||||
}
|
||||
```
|
||||
|
||||
### Backup / restore (silo 강점)
|
||||
```bash
|
||||
# Per-tenant backup
|
||||
pg_dump -d tenant_acme > acme.sql
|
||||
|
||||
# 한 tenant 만 restore — 다른 영향 X
|
||||
psql -d tenant_acme < acme.sql
|
||||
```
|
||||
|
||||
→ Pool 모델은 row 단위 backup 어려움.
|
||||
|
||||
### Quota / limit (per-tenant)
|
||||
```ts
|
||||
const QUOTAS: Record<Plan, { storageGB: number; usersMax: number }> = {
|
||||
free: { storageGB: 1, usersMax: 5 },
|
||||
pro: { storageGB: 100, usersMax: 50 },
|
||||
enterprise: { storageGB: 1000, usersMax: -1 },
|
||||
};
|
||||
|
||||
async function checkQuota(tenantId: string, type: 'storage' | 'users') {
|
||||
const t = await db.tenants.find(tenantId);
|
||||
const q = QUOTAS[t.plan];
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### Noisy neighbor 방지
|
||||
- Rate limit per tenant.
|
||||
- Connection pool per tenant (silo) 또는 limit per tenant (pool).
|
||||
- Job queue: tenant 별 partition / fair scheduler.
|
||||
|
||||
```ts
|
||||
const queue = new BullMQ('jobs');
|
||||
queue.add('process', data, { jobId: `${tenantId}:${jobId}`, priority: priorityFor(plan) });
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준
|
||||
| 상황 | 모델 |
|
||||
|---|---|
|
||||
| 작은 SaaS, 많은 작은 tenant | Pool + RLS |
|
||||
| Compliance 강함 (HIPAA, GDPR) | Silo (DB-per-tenant) |
|
||||
| 큰 enterprise + small tenants 혼합 | Bridge (큰 = silo, 작은 = pool) |
|
||||
| Customization 강함 | Schema-per-tenant 또는 silo |
|
||||
| 자원 분리 필요 | Silo |
|
||||
| 운영 단순 | Pool |
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **모든 query 에 tenant_id 누락 가능**: RLS 또는 ORM scope 강제.
|
||||
- **Cross-tenant join 가능**: pool 의 위험. 권한 분리.
|
||||
- **Silo + 비싼 idle pool**: connection 폭발. lazy / share.
|
||||
- **Tenant context global mutable**: race. AsyncLocalStorage.
|
||||
- **모든 tenant 동시 migration — 큰 lock**: 점진 / 병렬.
|
||||
- **Plan 정보 매 query DB hit**: cache.
|
||||
- **Tenant 삭제 = 못 함**: hard delete + cascade 또는 soft + 보존.
|
||||
|
||||
## 🤖 LLM 활용 힌트
|
||||
- Pool + RLS = 단순한 안전.
|
||||
- Silo = compliance / 큰 customer.
|
||||
- Bridge = 두 세계.
|
||||
- AsyncLocalStorage 로 tenant context 안전 전달.
|
||||
|
||||
## 🔗 관련 문서
|
||||
- [[DB_Sharding_Strategies]]
|
||||
- [[DB_Soft_Delete_Patterns]]
|
||||
- [[Backend_Rate_Limiting]]
|
||||
Reference in New Issue
Block a user