Wiring an application
users-api registers the packages once, in three modules. A handler then only declares the behaviors specific to it, as in A command through every layer.
The order a request takes
Section titled “The order a request takes”CorrelationMiddlewaresets the correlation id;TenantSchemaMiddlewareruns the rest of the request inside the tenant named byx-tenant-schema(see Several tenants in one deployment).AuthSessionGuardresolves the principal;SessionPrincipalContextInterceptormakes it available to the application;HttpRouteInterceptornames the HTTP span by its route.StandardSchemaValidationPipevalidates the parameters declared with aschema.- The controller dispatches a command or query; the bus runs its pipeline: the global
beforebehaviors, the handler’s own, then the handler. - On the way out, the exception filters turn the packages’ framework-neutral errors into HTTP answers: 400 for validation, 403 for a disabled feature or a denied action, 429 for a rate limit, 409 or 422 for an idempotency conflict.
The root module
Section titled “The root module”/* Copyright (C) 2026-present Aristotelis — see repository license. */
import { contextSources } from '@common/context/context-sources.js';import { AuthSessionGuard } from '@common/guards/auth-session.guard.js';import { SessionPrincipalContextInterceptor } from '@common/interceptors/session-principal-context.interceptor.js';import { CorrelationMiddleware } from '@cqrs-ddd/nestjs/correlation';import { JobContextModule } from '@cqrs-ddd/nestjs/job-context';import { type MiddlewareConsumer, Module, type NestModule, StandardSchemaValidationPipe,} from '@nestjs/common';import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';import { CqrsModule } from '@nestjs/cqrs';import { TenantSchemaMiddleware } from '@persistence/middlewares/tenant-schema.middleware.js';import { persistenceConfig } from '@persistence/persistence.config.js';import { PersistenceModule } from '@persistence/persistence.module.js';import { AuthorizationModule } from './auths/authorization.module.js';import { AuthsModule } from './auths/auths.module.js';import { SessionJobPrincipal } from './auths/infrastructure/session-job-principal.js';import { DomainExceptionFilter } from './common/filters/domain-exception.filter.js';import { ObservabilityModule, ReliabilityModule,} from './common/modules/index.js';import { RolesModule } from './roles/roles.module.js';import { UsersModule } from './users/users.module.js';
/** * Root composition module of the Users API application. * * Orchestrates cross-cutting infrastructure concerns (Observability, Reliability, Persistence, * CASL Authorization, CQRS) alongside business domain modules (Users, Roles, Auths). * * ### Architectural Layout * - {@link ObservabilityModule}: Structured logging (Pino), OpenTelemetry tracing & metrics, global pipeline behaviors, and audit logging. * - {@link ReliabilityModule}: BullMQ queue engine, dead-letter storage, rate limiting, distributed idempotency, resilience policies, caching, and feature flags. * - {@link AuthorizationModule}: role- and attribute-based access control (`CaslBehavior`, `CaslAuthorizer`) on the application's permission source. * - {@link PersistenceModule}: MikroORM database connection, entity repositories, and tenant schema manager. * - {@link JobContextModule}: carries a request's tenant, correlation id and principal into the jobs it enqueues. * - `StandardSchemaValidationPipe`: validates every route parameter declared with a `schema`; NestJS answers 400 with its own body. * - {@link DomainExceptionFilter}: the one global filter; every error becomes a NestJS `HttpException`. * - {@link CorrelationMiddleware}: takes or creates the correlation id of every request. * - Domain Feature Modules: {@link UsersModule}, {@link RolesModule}, {@link AuthsModule}. */@Module({ imports: [ CqrsModule.forRoot(), ObservabilityModule, ReliabilityModule, AuthorizationModule, PersistenceModule, UsersModule, RolesModule, AuthsModule, JobContextModule.forRoot({ imports: [AuthsModule], principal: SessionJobPrincipal, tenants: () => persistenceConfig().tenants, sources: contextSources, }), ], providers: [ { provide: APP_GUARD, useClass: AuthSessionGuard }, { provide: APP_INTERCEPTOR, useClass: SessionPrincipalContextInterceptor }, { provide: APP_PIPE, useValue: new StandardSchemaValidationPipe() }, { provide: APP_FILTER, useClass: DomainExceptionFilter }, ],})export class AppModule implements NestModule { constructor( private readonly tenantSchemaMiddleware: TenantSchemaMiddleware, ) {}
configure(consumer: MiddlewareConsumer) { consumer .apply( CorrelationMiddleware, this.tenantSchemaMiddleware.use.bind(this.tenantSchemaMiddleware), ) .forRoutes('*'); }}Global behaviors and observability
Section titled “Global behaviors and observability”ObservabilityModule orders the global behaviors so that telemetry wraps everything a
handler adds: logging, then the span and metrics, then AttributesBehavior, which copies
the add-ons’ decisions onto the span, then validation. Commands and events also get
DeadLetterBehavior. It also connects the tenant of @nestjs-pipeline/tenant to
@cqrs-ddd/core’s tenant-scoped cache keys:
/* Copyright (C) 2026-present Aristotelis — see repository license. */
import { IncomingMessage } from 'node:http';import { AUDIT_MODULE_DEFAULTS } from '@common/audit/audit.options.js';import { HEADERS } from '@common/constants/headers.constants.js';import { contextSources } from '@common/context/context-sources.js';import { HttpRouteInterceptor } from '@common/interceptors/http-route.interceptor.js';import { setTenantResolver } from '@cqrs-ddd/core/application';import { PipelineModule } from '@cqrs-ddd/nestjs';import { LoggingBehavior, logging } from '@cqrs-ddd/pipeline';import { AuditBehavior, LogAuditSink } from '@cqrs-ddd/pipeline-audit';import { buildCacheAttributes } from '@cqrs-ddd/pipeline-cache';import { buildDeadLetterAttributes, DeadLetterBehavior,} from '@cqrs-ddd/pipeline-deadletter';import { buildFeatureFlagAttributes } from '@cqrs-ddd/pipeline-feature-flags';import { buildIdempotencyAttributes } from '@cqrs-ddd/pipeline-idempotency';import { AttributesBehavior, MetricsBehavior, TraceBehavior,} from '@cqrs-ddd/pipeline-opentelemetry';import { buildRateLimitAttributes } from '@cqrs-ddd/pipeline-rate-limit';import { currentTenantId } from '@cqrs-ddd/pipeline-tenant';import { ZodValidationBehavior } from '@cqrs-ddd/pipeline-zod';import { Logger, Module } from '@nestjs/common';import { APP_INTERCEPTOR } from '@nestjs/core';import { LoggerModule, NativeLogger } from 'nestjs-pino';
/** Credential headers redacted from structured HTTP logs. */const HTTP_LOG_REDACT_PATHS = [ 'req.headers.authorization', 'req.headers.cookie', `req.headers["${HEADERS.API_KEY}"]`, `req.headers["${HEADERS.API_ID}"]`, 'req.headers["set-cookie"]', 'res.headers["set-cookie"]',];
/** * Configures structured HTTP logging, correlation propagation, tracing, metrics, * request validation and operational audit recording. It places the global * behaviors of every handler's pipeline, and provides the logging, telemetry, * validation and audit behaviors under their behavior classes. Global pipeline * ordering keeps telemetry around handler-local behaviors so their outcomes * reach the span. * * HTTP server spans carry the matched route (`HttpRouteInterceptor`). * * HTTP credentials are redacted through `HTTP_LOG_REDACT_PATHS`. Auditing uses * a log sink on the Nest logger with `failOpen: true`; durable audit requirements need * a persistent sink and an explicit failure policy. * * It also makes the pipeline's tenant the tenant of `@cqrs-ddd/core`'s * tenant-scoped helpers (`cacheKey`, `cacheKeyTemplate`), before any * lifecycle hook can start work that reads it. * * @example Register application observability * ```ts * @Module({ imports: [ObservabilityModule] }) * export class AppModule {} * ``` */@Module({ imports: [ LoggerModule.forRoot({ pinoHttp: { autoLogging: true, level: process.env.NODE_ENV === 'production' ? 'info' : 'debug', redact: { paths: HTTP_LOG_REDACT_PATHS, censor: '[REDACTED]', }, transport: process.env.NODE_ENV !== 'production' ? { target: 'pino-pretty', options: { colorize: true, messageFormat: '[{context}] {msg}', translateTime: 'SYS:HH:MM:ss.l', }, } : undefined, customProps: (req: IncomingMessage) => ({ context: `${req.method} ${req.url}`, }), }, }), PipelineModule.forRoot({ sources: contextSources, globalBehaviors: [ { scope: 'all', before: [ logging({ requestResponseLogLevel: 'log' }), [TraceBehavior, { tracerName: 'users-api' }], [MetricsBehavior, { meterName: 'users-api' }], [ AttributesBehavior, { factories: [ buildFeatureFlagAttributes, buildCacheAttributes, buildIdempotencyAttributes, buildRateLimitAttributes, buildDeadLetterAttributes, ], }, ], ZodValidationBehavior, ], }, { scope: 'commands', before: [DeadLetterBehavior], }, { scope: 'events', before: [DeadLetterBehavior], }, ], }), ], providers: [ { provide: APP_INTERCEPTOR, useClass: HttpRouteInterceptor }, { provide: LoggingBehavior, inject: [NativeLogger], useFactory: (logger: NativeLogger) => new LoggingBehavior(logger), }, TraceBehavior, { provide: MetricsBehavior, useFactory: () => new MetricsBehavior(new Logger(MetricsBehavior.name)), }, AttributesBehavior, ZodValidationBehavior, { provide: AuditBehavior, useFactory: () => { const logger = new Logger(AuditBehavior.name); return new AuditBehavior( new LogAuditSink({ logger }), AUDIT_MODULE_DEFAULTS, logger, ); }, }, ], exports: [LoggerModule],})export class ObservabilityModule { constructor() { setTenantResolver(currentTenantId); }}Queues, limits and stores
Section titled “Queues, limits and stores”ReliabilityModule connects the add-ons to their infrastructure: BullMQ queues, the
dead-letter transport, the rate limiter, the idempotency store, resilience policies, the
response cache and feature flags:
/* Copyright (C) 2026-present Aristotelis — see repository license. */
import { RATE_LIMIT_CAPACITY, RATE_LIMITER } from '@common/constants/index.js';import { redisConfig } from '@common/environment/redis.config.js';import { buildCache, CacheBehavior } from '@cqrs-ddd/pipeline-cache';import { BullMqDeadLetterTransport, DeadLetterBehavior,} from '@cqrs-ddd/pipeline-deadletter';import { createFeatureFlagClient, FeatureFlagBehavior, releaseFeatureFlagProvider,} from '@cqrs-ddd/pipeline-feature-flags';import { IdempotencyBehavior, MemoryIdempotencyStore,} from '@cqrs-ddd/pipeline-idempotency';import { RateLimitBehavior, type RateLimiterLike,} from '@cqrs-ddd/pipeline-rate-limit';import { ResilienceBehavior } from '@cqrs-ddd/pipeline-resilience';import { BullModule, getQueueToken } from '@nestjs/bullmq';import { Inject, Logger, Module, type OnApplicationShutdown,} from '@nestjs/common';import { TypedInMemoryProvider } from '@openfeature/server-sdk';import type { Queue } from 'bullmq';import type { Cache } from 'cache-manager';import { RateLimiterMemory } from 'rate-limiter-flexible';import { DEAD_LETTER_DEFAULTS } from '../dead-letter/dead-letter.options.js';
/** Injection token of the store `CacheBehavior` caches handler responses in. */export const RESPONSE_CACHE = Symbol('RESPONSE_CACHE');
const FEATURE_FLAGS = { provider: new TypedInMemoryProvider({ 'user-registration': { disabled: false, variants: { on: true, off: false }, defaultVariant: 'on', }, 'role-creation': { disabled: false, variants: { on: true, off: false }, defaultVariant: 'on', }, }),};
/** * Wires BullMQ, and the behaviors that handlers place for reliability: dead * letters, rate limiting, idempotency, resilience, response caching and feature * flags. Each is a provider under its behavior class, built once here; the * pipeline takes these instances. * * Rate-limit quotas and idempotency records are process-local. Response caching * uses memory for local development and Redis when REDIS_HOST is configured or * NODE_ENV is production. Every Redis client takes its connection from * `redisConfig()`. Repository snapshot caching has its own adapters and * invalidation lifecycle; this module configures pipeline response caching. * On shutdown it stops the idempotency store's sweep, disconnects the response * cache and releases the feature-flag provider. * * @example Register the pipeline infrastructure alongside observability * ```ts * @Module({ imports: [ObservabilityModule, ReliabilityModule] }) * export class AppModule {} * ``` */@Module({ imports: [ BullModule.forRootAsync({ useFactory: () => { const { host, port } = redisConfig(); return { connection: { host, port } }; }, }), BullModule.registerQueue({ name: 'dead-letters', forceDisconnectOnShutdown: true, }), ], providers: [ { provide: DeadLetterBehavior, inject: [getQueueToken('dead-letters')], useFactory: (queue: Queue) => new DeadLetterBehavior( new BullMqDeadLetterTransport(queue), DEAD_LETTER_DEFAULTS, new Logger(DeadLetterBehavior.name), ), }, { provide: RATE_LIMITER, useFactory: () => new RateLimiterMemory(RATE_LIMIT_CAPACITY), }, { provide: RateLimitBehavior, inject: [RATE_LIMITER], useFactory: (limiter: RateLimiterLike) => new RateLimitBehavior( limiter, undefined, new Logger(RateLimitBehavior.name), ), }, { provide: MemoryIdempotencyStore, useFactory: () => new MemoryIdempotencyStore(), }, { provide: IdempotencyBehavior, inject: [MemoryIdempotencyStore], useFactory: (store: MemoryIdempotencyStore) => new IdempotencyBehavior( store, undefined, new Logger(IdempotencyBehavior.name), ), }, { provide: ResilienceBehavior, useFactory: () => new ResilienceBehavior(undefined, new Logger(ResilienceBehavior.name)), }, { provide: RESPONSE_CACHE, useFactory: () => { const redis = redisConfig(); return buildCache({ store: !redis.isConfigured && process.env.NODE_ENV !== 'production' ? { type: 'memory' } : { type: 'redis', url: redis.url }, ttl: 30_000, }); }, }, { provide: CacheBehavior, inject: [RESPONSE_CACHE], useFactory: (cache: Cache) => new CacheBehavior(cache, undefined, new Logger(CacheBehavior.name)), }, { provide: FeatureFlagBehavior, useFactory: async () => new FeatureFlagBehavior( await createFeatureFlagClient(FEATURE_FLAGS), undefined, { environment: process.env.NODE_ENV ?? 'development' }, new Logger(FeatureFlagBehavior.name), ), }, ], exports: [BullModule, RATE_LIMITER],})export class ReliabilityModule implements OnApplicationShutdown { constructor( private readonly idempotencyStore: MemoryIdempotencyStore, @Inject(RESPONSE_CACHE) private readonly responseCache: Cache, ) {}
async onApplicationShutdown(): Promise<void> { this.idempotencyStore.destroy(); await this.responseCache.disconnect(); await releaseFeatureFlagProvider(FEATURE_FLAGS); }}