A NestJS application almost always starts the same way: a single AppModule, a handful of services, everything works. Six months and twenty features later, that same AppModule imports fifteen modules that import each other, two services reference one another through forwardRef, and adding a simple feature requires understanding a dependency graph that nobody on the team fully holds in their head anymore. The problem isn't NestJS, which actually provides the tools to avoid this drift: it's the absence of module boundaries enforced from the start.

The mechanism: modules, the DI container, and provider scope

NestJS organizes an application around modules, each declaring its providers (classes instantiated by the dependency injection container), its imports (modules whose exported providers it consumes), and its exports (providers it makes available to modules that import it). A provider that isn't exported stays strictly private to its own module, even if another module imports it.

// orders/orders.module.ts
@Module({
  imports: [CustomersModule],
  controllers: [OrdersController],
  providers: [OrdersService, OrdersRepository],
  exports: [OrdersService],
})
export class OrdersModule {}
// orders/orders.service.ts
@Injectable()
export class OrdersService {
  constructor(
    private readonly ordersRepository: OrdersRepository,
    private readonly customersService: CustomersService,
  ) {}

  async placeOrder(dto: CreateOrderDto): Promise<Order> {
    const customer = await this.customersService.findById(dto.customerId);
    return this.ordersRepository.create({ ...dto, customer });
  }
}

By default, a provider is singleton scoped: a single instance for the entire lifetime of the application, shared across every request. That's the desired behavior in the vast majority of cases, and it's also what makes NestJS performant compared to instantiating providers per request.

The most common symptom: the circular dependency

When two modules import each other, either directly or through a chain of intermediate modules, Nest can't determine in which order to instantiate them. The typical symptom is a startup error, or worse, a forwardRef() added as a workaround without the root cause ever being addressed:

// customers/customers.module.ts
@Module({
  imports: [forwardRef(() => OrdersModule)],
  providers: [CustomersService],
  exports: [CustomersService],
})
export class CustomersModule {}
// customers/customers.service.ts
@Injectable()
export class CustomersService {
  constructor(
    @Inject(forwardRef(() => OrdersService))
    private readonly ordersService: OrdersService,
  ) {}

  async getCustomerOrderCount(customerId: string): Promise<number> {
    return this.ordersService.countByCustomer(customerId);
  }
}

forwardRef resolves the technical instantiation problem, but it doesn't resolve the design problem: two modules depending on each other in both directions almost always signal a misplaced responsibility. Here, CustomersService needing to count a customer's orders depends on OrdersService, while OrdersService depends on CustomersService to validate a customer when an order is created. That's a sign that order-counting logic per customer shouldn't live inside CustomersService in the first place.

Diagnosing before reaching for forwardRef

Nest prints an explicit message at startup when it hits an unresolved circular dependency, along with the full chain of modules involved. Before adding a forwardRef by reflex, two checks are worth running:

npx madge --circular --extensions ts src/

madge maps the project's TypeScript imports and lists the actual cycles, independent of whichever one Nest happens to detect first at runtime. That surfaces the whole problem instead of just the first cycle the startup error points at.

On top of that, wiring dependency-cruiser or ESLint module-boundary rules (eslint-plugin-boundaries) into the lint step turns the convention of "no circular dependency between business modules" into a rule verified automatically in CI, rather than a team discipline that relies on individual vigilance.

The fix: invert the dependency, don't route around it

The structural fix is to extract the shared logic into a separate module, sitting lower in the dependency hierarchy, that both business modules can import without ever depending on each other:

// order-customer-stats/order-customer-stats.module.ts
@Module({
  providers: [OrderCustomerStatsService],
  exports: [OrderCustomerStatsService],
})
export class OrderCustomerStatsModule {}
// order-customer-stats/order-customer-stats.service.ts
@Injectable()
export class OrderCustomerStatsService {
  constructor(
    @Inject(ORDERS_READ_PORT) private readonly ordersReadPort: OrdersReadPort,
  ) {}

  async countByCustomer(customerId: string): Promise<number> {
    return this.ordersReadPort.countByCustomer(customerId);
  }
}

Using an injection token (ORDERS_READ_PORT) tied to an interface rather than to the concrete OrdersService class decouples this service from the real implementation, which lets OrdersModule provide that implementation without OrderCustomerStatsModule ever importing OrdersModule directly:

// orders/orders.module.ts
@Module({
  providers: [
    OrdersService,
    { provide: ORDERS_READ_PORT, useExisting: OrdersService },
  ],
  exports: [ORDERS_READ_PORT],
})
export class OrdersModule {}

The tradeoffs of request scope and shared modules

REQUEST scope lets you inject the current HTTP request's context (the authenticated user, a tenant id) directly into a provider, but it carries a real cost: a REQUEST-scoped provider gets re-instantiated on every request, and that scope propagates transitively to every provider that depends on it. A service sitting high up in the dependency graph, marked REQUEST by mistake, can turn a large chunk of the application into per-request instances, degrading performance in a way a shallow profiling pass won't immediately reveal the cause of.

@Injectable({ scope: Scope.REQUEST })
export class TenantContextService {
  constructor(@Inject(REQUEST) private readonly request: Request) {}

  getTenantId(): string {
    return this.request.headers['x-tenant-id'] as string;
  }
}

For lightweight request context (a tenant id, a trace id) without paying the REQUEST-scope cost across an entire chain of providers, a library like nestjs-cls, built on AsyncLocalStorage, propagates that context without involving the DI container at all, and stays singleton from Nest's point of view.

A catch-all SharedModule, exporting indiscriminately everything used by more than one business module, ends up recreating the same problem as a monolithic AppModule, just relocated: everything depends on it, nobody quite knows what it actually contains anymore. Prefer thin, responsibility-named shared modules (DatabaseModule, LoggingModule, AuthModule) over a generic CommonModule or SharedModule.

When splitting into modules isn't enough

For a complex business domain with rich validation rules and invariants, separating the domain layer (entities, business rules, ports) from the infrastructure layer (a Prisma or TypeORM repository, HTTP clients) inside a single module, following something close to hexagonal architecture, keeps business rules from becoming coupled to a particular ORM. The module exposes a port (an interface), and the concrete implementation gets injected through a custom provider, exactly like the ORDERS_READ_PORT example above, but applied systematically rather than as a one-off fix.

For domains with complex command and event flows (a multi-step business process with asynchronous side effects), the @nestjs/cqrs module explicitly structures the separation between commands, queries, and events, which clarifies the data flow in a module that would otherwise accumulate service methods with mixed responsibilities.

Finally, splitting a NestJS monolith into microservices through the @nestjs/microservices transports (TCP, Redis, NATS) is a distinct architectural decision, not to be confused with splitting into modules: a modular monolith with strictly respected module boundaries lends itself to a later extraction into separate services far more easily than a monolith riddled with circular dependencies, but the extraction itself answers organizational and scalability needs, not a code-readability problem.

Takeaway

A circular dependency between two NestJS modules is almost never a technical problem to solve with forwardRef, it's a design symptom pointing to a responsibility misplaced in the module graph. Explicit module boundaries, checked by a tool like madge in CI, cost less to maintain over time than a dependency graph that only a handful of developers can still reconstruct in their head.