테넌트별 스키마 데이터베이스 연결
확인된 테넌트에 따라 데이터베이스 스키마나 연결을 동적으로 전환합니다.
테넌트별 스키마 데이터베이스 연결은(는) CoddyKit의 무료 NestJS Enterprise Backend APIs 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 NestJS Enterprise Backend APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. NestJS Enterprise Backend APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Schema-per-Tenant: The Big Picture
In a multi-tenant API, every tenant's data must stay isolated. The schema-per-tenant model keeps one physical database but gives each tenant its own PostgreSQL schema (e.g. tenant_acme, tenant_globex). Tables have identical structures across schemas.
- Pool of tables (shared schema): one set of tables, isolation by a
tenant_idcolumn. Simple, but leaks are one missed WHERE clause away. - Schema-per-tenant: stronger isolation, easy per-tenant backup, but you must switch the active schema per request.
- Database-per-tenant: maximum isolation, heaviest operational cost.
This lesson focuses on dynamically routing each request to the correct schema or connection once the tenant has been resolved.
Resolving the Tenant per Request
Before you can switch schemas, you need the tenant. Resolution typically comes from a subdomain, a header, or a JWT claim. A lightweight middleware extracts it and attaches it to the request so downstream providers can read it.
Keep resolution dumb and cheap here; validation of whether the tenant exists happens when you build the connection.
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
@Injectable()
export class TenantMiddleware implements NestMiddleware {
use(req: Request, _res: Response, next: NextFunction) {
// Prefer an explicit header; fall back to subdomain.
const headerTenant = req.headers['x-tenant-id'] as string | undefined;
const host = req.headers.host ?? '';
const subdomain = host.split('.')[0];
const tenantId = headerTenant ?? subdomain;
(req as any).tenantId = tenantId;
next();
}
}Why REQUEST Scope Is the Natural Fit
The active schema changes on every request. NestJS providers are singletons by default, so a singleton cannot safely hold a per-request schema. The clean answer is a request-scoped provider that receives the current REQUEST.
Scope.REQUESTcreates a fresh provider instance per incoming request.- Any provider that injects a request-scoped provider becomes request-scoped too (it bubbles up the chain).
- Trade-off: instantiation per request has overhead, so keep request-scoped providers thin and cache the heavy bits (connections) outside.
Switching Schema with SET search_path
The simplest schema switch on a single Postgres connection is SET search_path. It tells Postgres which schema to resolve unqualified table names against for the rest of that session.
Critical caveat: with a connection pool, a connection may be handed to another tenant's request next. You must scope the switch to the work and reset it, or use a transaction-local variant.
import { DataSource } from 'typeorm';
export async function withTenantSchema<T>(
dataSource: DataSource,
schema: string,
work: () => Promise<T>,
): Promise<T> {
const runner = dataSource.createQueryRunner();
await runner.connect();
try {
// SET LOCAL is transaction-scoped and auto-resets on commit/rollback.
await runner.startTransaction();
await runner.query('SET LOCAL search_path TO $1', [schema]);
const result = await work();
await runner.commitTransaction();
return result;
} catch (err) {
await runner.rollbackTransaction();
throw err;
} finally {
await runner.release();
}
}Sanitizing the Schema Name
Schema names are identifiers, not values. You cannot safely parameterize an identifier in SET search_path the way you parameterize data. A malicious or malformed tenant id could become SQL injection.
Always validate the resolved schema against a strict allow-list pattern (and ideally against a registry of known tenants) before interpolating it.
const SCHEMA_PATTERN = /^[a-z][a-z0-9_]{1,62}$/;
export function tenantSchema(tenantId: string): string {
const candidate = `tenant_${tenantId.toLowerCase()}`;
if (!SCHEMA_PATTERN.test(candidate)) {
throw new Error(`Invalid tenant schema: ${candidate}`);
}
return candidate;
}
console.log(tenantSchema('Acme')); // tenant_acme
try {
tenantSchema('acme; DROP SCHEMA x'); // throws
} catch (e) {
console.log((e as Error).message);
}Per-Tenant Connections Instead of search_path
An alternative to mutating search_path on a shared pool is to keep a dedicated DataSource (and pool) per tenant schema. Each DataSource is configured once with its schema and reused.
- Pro: no per-request schema mutation, no pool cross-contamination risk.
- Con: connection count multiplies by active tenants — you must cap pool sizes and evict idle tenants.
This is where a connection manager that lazily builds and caches DataSources shines.
A Tenant Connection Manager
The manager owns the lifecycle: build a DataSource the first time a tenant is seen, cache it, and reuse it afterwards. It is a singleton — only the lookup is per-request, the heavy connections are shared safely because each is bound to its own schema.
Note the cache key is the schema, and concurrent first-hits must not build twice (store the promise, not just the resolved value).
import { Injectable } from '@nestjs/common';
import { DataSource } from 'typeorm';
@Injectable()
export class TenantConnectionManager {
private readonly pools = new Map<string, Promise<DataSource>>();
get(schema: string): Promise<DataSource> {
let pool = this.pools.get(schema);
if (!pool) {
pool = this.build(schema);
this.pools.set(schema, pool); // cache the promise to dedupe races
}
return pool;
}
private async build(schema: string): Promise<DataSource> {
const ds = new DataSource({
type: 'postgres',
url: process.env.DATABASE_URL,
schema,
entities: [__dirname + '/**/*.entity.{ts,js}'],
poolSize: 5,
});
await ds.initialize();
return ds;
}
}Exposing the Tenant DataSource as a Provider
Now wire a request-scoped factory provider that reads the tenant from REQUEST, computes its schema, and asks the manager for the right DataSource. Services inject this token instead of a fixed connection.
Because the factory injects REQUEST, the provider is request-scoped — but the manager it calls is a singleton, so connection reuse is preserved.
import { Scope, Provider } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';
import { DataSource } from 'typeorm';
export const TENANT_DATA_SOURCE = 'TENANT_DATA_SOURCE';
export const tenantDataSourceProvider: Provider = {
provide: TENANT_DATA_SOURCE,
scope: Scope.REQUEST,
inject: [REQUEST, TenantConnectionManager],
useFactory: (req: Request, manager: TenantConnectionManager): Promise<DataSource> => {
const tenantId = (req as any).tenantId as string | undefined;
if (!tenantId) {
throw new Error('No tenant resolved for this request');
}
const schema = tenantSchema(tenantId);
return manager.get(schema);
},
};Using the Tenant DataSource in a Service
A request-scoped service injects the resolved DataSource by token. Every query it runs already targets the correct schema — there is no tenant_id filter and no manual schema switch in business code.
The factory returns a Promise<DataSource>, so await it (or have the factory await before returning) before opening repositories.
import { Inject, Injectable, Scope } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { Invoice } from './invoice.entity';
@Injectable({ scope: Scope.REQUEST })
export class InvoiceService {
constructor(
@Inject(TENANT_DATA_SOURCE) private readonly dataSource: DataSource,
) {}
findAll(): Promise<Invoice[]> {
// Already bound to tenant_<x> schema — no tenant filter needed.
return this.dataSource.getRepository(Invoice).find();
}
}Dynamic Modules for Configurable Tenancy
Reusable tenancy logic belongs in a dynamic module so apps can configure resolution strategy, schema prefix, and pool size via forRoot/forRootAsync. The module exports the manager and the request-scoped DataSource provider.
This is the multi-tenancy + dynamic-module pairing: configuration is static (set once at boot), while the resolved connection is dynamic (per request).
import { DynamicModule, Module } from '@nestjs/common';
export interface TenancyOptions {
schemaPrefix: string;
poolSize: number;
}
@Module({})
export class TenancyModule {
static forRoot(options: TenancyOptions): DynamicModule {
return {
module: TenancyModule,
global: true,
providers: [
{ provide: 'TENANCY_OPTIONS', useValue: options },
TenantConnectionManager,
tenantDataSourceProvider,
],
exports: [TenantConnectionManager, TENANT_DATA_SOURCE],
};
}
}Lifecycle, Eviction, and Migrations
Per-tenant pools are a resource leak waiting to happen. Manage them deliberately:
- Cap concurrency: small
poolSizeper tenant; many tenants × big pools exhausts Postgresmax_connections. - Evict idle tenants: track last-used time and
destroy()DataSources that go cold (an LRU keeps memory bounded). - Shut down cleanly: implement
OnModuleDestroyto close every cached DataSource. - Migrations: a new tenant means
CREATE SCHEMA+ run migrations against it before first use; loop migrations across all tenant schemas on deploy.
Treat schema provisioning as an explicit onboarding step, never an accident of the first query.
Quick Check: Avoiding Cross-Tenant Leaks
You switch schemas using SET search_path on connections borrowed from a shared TypeORM pool. Occasionally tenant A sees tenant B's rows. What is the most likely root cause and the correct fix?
Recap: Dynamic Schema Routing
You learned to route each request to the right tenant schema:
- Resolve the tenant early (header/subdomain/JWT) in middleware and attach it to the request.
- Switch schemas either via transaction-scoped
SET LOCAL search_pathon a shared pool, or via a dedicated DataSource per tenant cached in a singleton manager. - Wire a request-scoped factory provider that reads
REQUEST, validates the schema name, and returns the correct DataSource — services stay tenant-agnostic. - Configure the whole thing through a dynamic module (
forRoot), keeping config static while the connection is dynamic. - Operate safely: validate identifiers, cap and evict pools, close on shutdown, and provision/migrate schemas as an explicit onboarding step.
자주 묻는 질문
“테넌트별 스키마 데이터베이스 연결” 강의는 무료인가요?
네 — “테넌트별 스키마 데이터베이스 연결” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 NestJS Enterprise Backend APIs 강의 전체를 잠금 해제할 수 있습니다. NestJS Enterprise Backend APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
“테넌트별 스키마 데이터베이스 연결”에서 뭘 배우나요?
확인된 테넌트에 따라 데이터베이스 스키마나 연결을 동적으로 전환합니다. 브라우저에서 직접 실행하는 실습 코드로 NestJS Enterprise Backend APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
NestJS Enterprise Backend APIs을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 NestJS Enterprise Backend APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“테넌트별 스키마 데이터베이스 연결” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 NestJS Enterprise Backend APIs 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 NestJS Enterprise Backend APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 미들웨어와 AsyncLocalStorage를 통한 테넌트 확인
- 테넌트별 스키마 데이터베이스 연결
- 구성 가능한 동적 모듈 구축
- 요청 범위 공급자와 그 트레이드오프