0Pricing
NestJS Enterprise Backend APIs · 강의

요청 범위 공급자와 그 트레이드오프

REQUEST 범위를 안전하게 사용하면서 성능과 주입 전파의 영향을 이해합니다.

요청 범위 공급자와 그 트레이드오프은(는) CoddyKit의 무료 NestJS Enterprise Backend APIs 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 NestJS Enterprise Backend APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. NestJS Enterprise Backend APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Scopes Exist

By default every NestJS provider is a singleton: one instance is created at bootstrap and shared across the whole application lifetime. This is fast and memory-efficient, and it is the right choice for the overwhelming majority of services.

But some scenarios need per-request state. In a multi-tenant backend you might want a provider that already knows which tenant the current request belongs to, so you do not pass the tenant id through every method call. NestJS solves this with injection scopes.

  • Scope.DEFAULT — singleton (the default)
  • Scope.REQUEST — a new instance per incoming request
  • Scope.TRANSIENT — a new instance for each consumer that injects it

Declaring a Request-Scoped Provider

You opt into request scope by passing { scope: Scope.REQUEST } to the @Injectable() decorator. NestJS will then instantiate a fresh copy of this provider for every HTTP request (or message, in microservices/WebSocket transports).

Because a new instance exists per request, it is safe to store request-specific mutable state on it — concurrent requests never share the same object.

import { Injectable, Scope } from '@nestjs/common';

@Injectable({ scope: Scope.REQUEST })
export class TenantContext {
  private tenantId: string | null = null;

  set(id: string): void {
    this.tenantId = id;
  }

  get(): string {
    if (!this.tenantId) {
      throw new Error('Tenant not resolved for this request');
    }
    return this.tenantId;
  }
}

Injecting the REQUEST Object

A request-scoped provider can inject the underlying request object using the REQUEST token. This is the canonical way to read headers, the resolved user, or a subdomain to determine the tenant.

Only providers that are themselves request-scoped (or transient) may inject REQUEST. Trying to inject it into a singleton is a design error — the request does not exist yet when a singleton is built.

import { Injectable, Scope, Inject } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';

@Injectable({ scope: Scope.REQUEST })
export class TenantContext {
  readonly tenantId: string;

  constructor(@Inject(REQUEST) private readonly req: Request) {
    const header = this.req.headers['x-tenant-id'];
    this.tenantId = Array.isArray(header) ? header[0] : (header ?? 'public');
  }
}

Scope Bubbling: The Core Trade-off

This is the single most important consequence to internalize: scope bubbles up the injection chain.

If a controller or service injects a request-scoped provider, that consumer also becomes request-scoped — even if you never marked it that way. The effect cascades transitively up every provider that depends on it.

  • A request-scoped TenantContext injected into OrdersService makes OrdersService request-scoped.
  • If OrdersController injects OrdersService, the controller is instantiated per request too.

One small request-scoped leaf can quietly turn a large subtree of your app non-singleton, which has real performance implications.

What Bubbling Looks Like in Code

Here neither OrdersService nor the controller declares a scope, yet both become request-scoped purely because of the transitive dependency on TenantContext. NestJS resolves the effective scope by taking the narrowest scope in the chain.

Keep this graph shallow: the deeper a request-scoped provider sits, the more of your tree it drags into per-request instantiation.

import { Injectable } from '@nestjs/common';
import { TenantContext } from './tenant.context';

// No scope declared, but it INHERITS Scope.REQUEST
@Injectable()
export class OrdersService {
  constructor(private readonly tenant: TenantContext) {}

  findAll() {
    return `orders for tenant ${this.tenant.get()}`;
  }
}

The Performance Cost

Request scope is not free. For every request, Nest must:

  • Walk the dependency subgraph and build a fresh instance of each request-scoped (and inheriting) provider.
  • Run their constructors and any lifecycle hooks on every request.
  • Garbage-collect those instances after the request ends.

Under high throughput this adds measurable latency and GC pressure. The official guidance is blunt: use request scope sparingly. The more providers turn request-scoped via bubbling, the larger the per-request allocation cost grows.

Lifecycle Hooks Run Per Request

A subtle gotcha: for request-scoped providers, lifecycle hooks like onModuleInit are not available, but request-scoped instances do go through construction on each request. Heavy setup in a constructor therefore runs on every single request.

If your provider opens a connection, parses a token, or hydrates config in its constructor, multiply that work by your request rate. Move expensive, request-independent setup into a singleton and inject it.

import { Injectable, Scope, Inject } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';
import { ConnectionPool } from './connection-pool'; // singleton

@Injectable({ scope: Scope.REQUEST })
export class TenantConnection {
  // pool is shared (singleton); only the cheap per-request pick is here
  constructor(
    @Inject(REQUEST) req: Request,
    private readonly pool: ConnectionPool,
  ) {
    const tenant = (req.headers['x-tenant-id'] as string) ?? 'public';
    this.client = pool.forTenant(tenant);
  }
  client: unknown;
}

Performance-Sensitive REQUEST Injection

For performance-critical request-scoped providers, Nest lets you avoid inheriting the full Request object payload. Passing { scope: Scope.REQUEST } still injects a lightweight context.

In some transports (e.g. GraphQL, microservices) the REQUEST token actually resolves to the execution context, not an HTTP request. Write your provider to read only what it needs, and guard for the shape differences across transports rather than assuming Express.

import { Injectable, Scope, Inject } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';

interface MaybeHttp {
  headers?: Record<string, string | string[] | undefined>;
}

@Injectable({ scope: Scope.REQUEST })
export class RequestMeta {
  readonly correlationId: string;

  constructor(@Inject(REQUEST) ctx: MaybeHttp) {
    const raw = ctx.headers?.['x-correlation-id'];
    this.correlationId = (Array.isArray(raw) ? raw[0] : raw) ?? 'n/a';
  }
}

Durable Providers: Scaling Multi-Tenancy

For multi-tenant apps where you would otherwise make many providers request-scoped, Nest offers durable providers. The idea: instead of one instance per request, keep one instance per tenant and reuse it across that tenant's requests.

You define a ContextIdStrategy that maps a request to a stable sub-tree id (e.g. the tenant id). Nest then caches durable sub-trees keyed by that id, dramatically cutting instantiation cost while preserving per-tenant isolation.

import { Injectable, Scope } from '@nestjs/common';

// durable: true tells Nest these instances can be reused across
// requests that share the same context id (e.g. the same tenant).
@Injectable({ scope: Scope.REQUEST, durable: true })
export class TenantRepository {
  // resolved once per tenant context, not once per request
}

Resolving Scoped Providers Manually

Outside the normal injection flow — for example inside a singleton that occasionally needs a request-scoped provider — you cannot just inject it (that would bubble the singleton). Instead resolve it manually against the current context id using ModuleRef.

You must pass the request's ContextId so Nest returns the instance bound to that specific request, not a brand-new orphan instance.

import { Injectable } from '@nestjs/common';
import { ModuleRef, ContextIdFactory } from '@nestjs/core';
import { TenantContext } from './tenant.context';

@Injectable() // stays a SINGLETON
export class AuditService {
  constructor(private readonly moduleRef: ModuleRef) {}

  async logFor(req: unknown): Promise<string> {
    const contextId = ContextIdFactory.getByRequest(req as object);
    const ctx = await this.moduleRef.resolve(TenantContext, contextId);
    return `audited tenant ${ctx.get()}`;
  }
}

When NOT to Use Request Scope

Reach for request scope only when per-request state is genuinely needed and cannot be passed as a parameter. Common safer alternatives:

  • AsyncLocalStorage (Node's node:async_hooks) to carry request context without making providers request-scoped — the whole graph stays singleton.
  • Method parameters — just pass the tenant id explicitly.
  • Durable providers — when you need per-tenant isolation at scale.

This snippet shows the AsyncLocalStorage pattern, which keeps services as fast singletons while still exposing per-request data.

import { AsyncLocalStorage } from 'node:async_hooks';

type Store = { tenantId: string };
const als = new AsyncLocalStorage<Store>();

function handleRequest(tenantId: string, work: () => string): string {
  return als.run({ tenantId }, work);
}

function currentTenant(): string {
  return als.getStore()?.tenantId ?? 'public';
}

console.log(handleRequest('acme', () => `serving ${currentTenant()}`));
console.log(handleRequest('globex', () => `serving ${currentTenant()}`));

Quick Check

Consider what happens to the dependency graph when you introduce a request-scoped provider deep in your application.

Recap

Key takeaways for using request scope safely:

  • Default to singletons. Request scope exists for genuine per-request state like tenant context.
  • Scope bubbles up. One request-scoped leaf turns every dependent provider request-scoped, transitively.
  • It costs performance. Per-request construction, lifecycle work, and GC pressure scale with throughput.
  • Keep request-scoped providers shallow and cheap. Push heavy, request-independent setup into singletons.
  • Prefer alternatives when you can: AsyncLocalStorage for context, explicit parameters, and durable providers for per-tenant reuse at scale.
  • Resolve manually via ModuleRef.resolve with the request's ContextId when a singleton must reach a scoped instance.

자주 묻는 질문

“요청 범위 공급자와 그 트레이드오프” 강의는 무료인가요?

네 — “요청 범위 공급자와 그 트레이드오프” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 NestJS Enterprise Backend APIs 강의 전체를 잠금 해제할 수 있습니다. NestJS Enterprise Backend APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

“요청 범위 공급자와 그 트레이드오프”에서 뭘 배우나요?

REQUEST 범위를 안전하게 사용하면서 성능과 주입 전파의 영향을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 NestJS Enterprise Backend APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

NestJS Enterprise Backend APIs을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 NestJS Enterprise Backend APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.

“요청 범위 공급자와 그 트레이드오프” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 NestJS Enterprise Backend APIs 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 NestJS Enterprise Backend APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 미들웨어와 AsyncLocalStorage를 통한 테넌트 확인
  2. 테넌트별 스키마 데이터베이스 연결
  3. 구성 가능한 동적 모듈 구축
  4. 요청 범위 공급자와 그 트레이드오프
← NestJS Enterprise Backend APIs(으)로 돌아가기