PrepStack › Backend › NestJS

NestJS interview cheat sheet

Modules, DI, the request pipeline, data, microservices and testing

NestJS interviews check that you understand how the framework is wired, not just its decorators. Expect questions on modules and encapsulation, the DI container and provider types, injection scopes, the exact request lifecycle (middleware, guards, interceptors, pipes, filters), validation with DTOs, auth with guards, and testing. Senior rounds add dynamic modules, circular dependencies, microservices, CQRS and Express vs Fastify. The runnable snippets are small plain-TypeScript models of what Nest does inside, so you can explain the mechanism, not just the API.

15-minute revision

  1. Nest = opinionated Node framework on top of Express (default) or Fastify. Building blocks: modules group code, controllers handle routes, providers (services, repos, factories) hold logic and are injected.
  2. The IoC container reads constructor parameter types (via emitDecoratorMetadata), builds the dependency graph at startup and creates singletons by default. Interfaces cannot be tokens; use a class, string, symbol or InjectionToken.
  3. A provider is visible only inside its module unless the module exports it and the consumer imports the module. @Global() removes the import step; use it sparingly.
  4. Custom providers: useClass (swap implementation), useValue (constants, mocks), useFactory (+ inject, can be async), useExisting (alias to the same instance).
  5. Scopes: DEFAULT (singleton), REQUEST (new per request, and it bubbles up to every consumer), TRANSIENT (new per consumer). Request scope costs performance; prefer singletons.
  6. Dynamic modules return { module, providers, exports } from a static method. Conventions: forRoot (configure once), register (per use), forFeature (per feature module), *Async variants take useFactory + inject.
  7. Request lifecycle: middleware → guards → interceptors (before) → pipes → handler → interceptors (after) → exception filters (only on errors). Guards, interceptors and pipes run global → controller → route.
  8. Pipes transform or validate arguments. ValidationPipe + class-validator DTOs; use whitelist, forbidNonWhitelisted and transform. DTOs must be classes, because interfaces disappear at runtime.
  9. Guards return true/false to allow a request (auth, roles). They get an ExecutionContext, so they know the handler and class and can read metadata with Reflector. Middleware cannot.
  10. Interceptors wrap the handler with RxJS: log timing, map the response, cache, add timeouts, or map errors. They are the only piece that runs both before and after the handler.
  11. Exception filters turn thrown errors into responses. HttpException subclasses (NotFoundException, ...) become JSON automatically; unknown errors become 500. The closest filter wins (route → controller → global).
  12. Bind globally with app.useGlobalX() (no DI) or with APP_GUARD / APP_PIPE / APP_INTERCEPTOR / APP_FILTER providers (DI works).
  13. Circular dependency: fix the design first (extract a shared service or use events). Otherwise forwardRef(() => X) on both sides, or ModuleRef lazy lookup.
  14. Testing: Test.createTestingModule({...}).overrideProvider(X).useValue(mock).compile() for unit tests; createNestApplication() + supertest on app.getHttpServer() for e2e.
  15. Microservices: same controllers with @MessagePattern (request/response, client.send) or @EventPattern (fire-and-forget, client.emit) over TCP, Redis, NATS, MQTT, RabbitMQ, Kafka or gRPC.
  16. Versions: Nest 11 made Express 5 the default HTTP engine. Nest 12 ships ESM packages and adds Standard Schema (Zod, Valibot) validation next to the class-validator ValidationPipe.

Core building blocks

What NestJS is & its architecture

A TypeScript-first Node.js framework that adds Angular-style modules and dependency injection on top of Express or Fastify.

  • Nest gives Node backends a fixed architecture: modules, controllers and providers, wired by a DI container. Express alone gives you routing and middleware but no structure.
  • It is platform-agnostic: the HTTP layer is an adapter (@nestjs/platform-express by default, or @nestjs/platform-fastify). The same building blocks also run microservices, WebSockets and GraphQL.
  • Entry point: NestFactory.create(AppModule) scans the module graph, creates all singleton providers, registers routes and returns an app you listen() on.
  • Heavy use of decorators (@Module, @Controller, @Get, @Injectable) that attach metadata. Nest reads that metadata at startup. It uses TypeScript's legacy experimentalDecorators plus emitDecoratorMetadata.
  • The CLI (nest new, nest g resource users) scaffolds modules, controllers, services, DTOs and spec files, so projects look alike.
  • Recent versions: Nest 11 (2025) uses Express 5 by default. Nest 12 ships ESM packages (CommonJS apps still work through require(esm)), lets new projects pick CJS or ESM, and adds Standard Schema validation.

Interview questions

  • What is NestJS and why would you choose it over plain Express?
  • What are the three main building blocks of a Nest app?
  • Is Nest tied to Express?

Modules & encapsulation

A module is a box of providers and controllers. Nothing leaves the box unless it is exported, and nothing enters unless the module is imported.

  • @Module({ imports, controllers, providers, exports }). imports: modules whose exported providers you need. providers: classes this module creates. exports: the subset others may inject.
  • Modules are singletons: if UsersModule is imported by five modules, they all share the same UsersService instance.
  • A shared module is just a module that exports providers. A module can also re-export a module it imports (exports: [CommonModule]).
  • @Global() makes exported providers available everywhere without importing. Use it for true infrastructure (config, logger, DB), registered once in the root module.
  • Organise by feature (users, orders, billing), each with its own module, controller, service and DTOs. The root module only composes them.

Interview questions

  • What does exports do in a module?
  • What is a global module and when should you use one?
  • Are providers shared between modules that import the same module?

Controllers & routing

Controllers map HTTP verbs and paths to methods, and use parameter decorators to pull data out of the request.

  • @Controller('cats') sets a path prefix. Method decorators @Get(), @Post(), @Put(), @Patch(), @Delete(), @All() add routes such as @Get(':id').
  • Parameter decorators: @Param('id'), @Query(), @Body(), @Headers(), @Ip(), @Req(), @Res(). Pipes can be attached to them: @Param('id', ParseIntPipe).
  • Return a value (object, array, promise or Observable) and Nest serialises it as JSON. Default status is 200, or 201 for POST. Change it with @HttpCode(204).
  • Other decorators: @Header(), @Redirect(), @Version('2') (URI, header or media-type versioning), @Sse() for server-sent events.
  • Injecting @Res() switches the route into library-specific mode: you must send the response yourself. Use @Res({ passthrough: true }) to set cookies or headers and still return a value.
  • Keep controllers thin: validate input, call a service, return the result. Business logic belongs in providers.

Interview questions

  • How do you read path params, query strings and the body?
  • What happens when you inject @Res()?
  • What status codes does Nest send by default?

Providers, DI & the IoC container

You declare what a class needs in its constructor. The container builds the graph at startup and hands each class its dependencies.

  • A provider is anything the container can create and inject: usually an @Injectable() class, but also values and factories.
  • Inversion of Control: classes do not new their dependencies. The framework creates and wires them. This gives loose coupling and easy mocking in tests.
  • Constructor injection is the norm: constructor(private readonly users: UsersService) {}. Property injection with @Inject() exists but is rarely used.
  • The token is the class itself. Nest learns parameter types from the design:paramtypes metadata that TypeScript emits. For non-class tokens use @Inject('TOKEN').
  • At bootstrap Nest resolves the graph depth-first and creates each singleton once. Missing providers fail fast at startup, not at request time.
  • @Optional() lets a dependency be missing (it becomes undefined).

Interview questions

  • What is dependency injection, and how does Nest implement it?
  • Why can't you inject an interface?
  • What does the error "Nest can't resolve dependencies of X (?, Y)" mean?
  • When are providers instantiated?

Dependency injection in depth

Custom providers: useClass, useValue, useFactory, useExisting

The long form { provide, useX } lets you control what gets injected for a token.

  • providers: [CatsService] is short for { provide: CatsService, useClass: CatsService }.
  • useClass: pick an implementation for a token, for example by environment (ConfigService → DevConfigService).
  • useValue: inject a constant, a config object, or a mock in tests.
  • useFactory: build the value in a function. inject: [ConfigService] lists the factory's arguments. The factory may be async, and Nest waits for it before bootstrap continues.
  • useExisting: an alias. Two tokens resolve to the same instance.
  • Non-class tokens are strings, symbols or InjectionTokens. Inject them with @Inject(TOKEN). Keep tokens in a constants file to avoid typos.

Interview questions

  • Difference between useClass and useExisting?
  • How do you provide something that needs async setup, like a DB connection?
  • How would you inject an implementation behind an interface, like a payment gateway?

Injection scopes: default, request, transient

Singleton by default. REQUEST creates one instance per request and bubbles up the chain; TRANSIENT gives each consumer its own instance.

  • Set with @Injectable({ scope: Scope.REQUEST }) or scope in a custom provider. Controllers can be scoped too.
  • DEFAULT: one instance for the whole app, created at startup. Safe in Node because a single thread serves all requests. Do not keep per-request state in fields.
  • REQUEST: new instance per incoming request, garbage-collected afterwards. Inject the raw request with @Inject(REQUEST) (or CONTEXT in GraphQL).
  • Scope bubbles up: anything that depends on a request-scoped provider becomes request-scoped too, up to the controller. One request-scoped logger can make a large part of the graph per-request.
  • TRANSIENT: each consumer gets its own dedicated instance, but the consumer keeps its own scope. Typical use: a logger that stores the consumer's class name as context.
  • Durable providers (durable: true plus a ContextIdStrategy) keep one sub-tree per tenant instead of per request, which is the usual multi-tenant fix.

Interview questions

  • What injection scopes does Nest have?
  • What does "request scope bubbles up" mean?
  • Why is singleton scope safe in Node but risky in some other platforms?
  • How would you build multi-tenancy with a separate DB connection per tenant?

Module types & dynamic modules (forRoot / forRootAsync)

A dynamic module is a static method that returns module metadata at runtime, so callers can configure the module when they import it.

  • Static modules have fixed metadata. Dynamic modules return a DynamicModule: { module, imports?, providers?, exports?, global? }, which extends the static metadata.
  • Naming convention: forRoot configures once for the whole app (DB, config). register configures per importing module (an HTTP client with a base URL). forFeature adds feature-specific parts on top of a forRoot (repositories, schemas).
  • Async variants (forRootAsync, registerAsync) take useFactory + inject + imports, or useClass / useExisting pointing to an options factory. Use them when options depend on other providers like ConfigService.
  • Options are usually exposed as a provider (an OPTIONS token) that the module's services inject.
  • ConfigurableModuleBuilder generates register / registerAsync (or forRoot with setClassMethodName('forRoot')) plus a MODULE_OPTIONS_TOKEN, so you do not write the boilerplate by hand.

Interview questions

  • What is a dynamic module and why does it exist?
  • Difference between forRoot, register and forFeature?
  • When do you need forRootAsync?

Circular dependencies & forwardRef

When A needs B and B needs A, Nest cannot order construction. Redesign first; use forwardRef or ModuleRef only when the cycle is real.

  • Two kinds: provider cycles (AService ↔ BService) and module cycles (UsersModule imports AuthModule and the reverse).
  • Symptom: "Nest can't resolve dependencies ... (?)" or "A circular dependency between modules", often with undefined at an index because of a file import cycle or a barrel index.ts.
  • forwardRef on both sides: @Inject(forwardRef(() => BService)) in the constructor, and imports: [forwardRef(() => BModule)] for modules.
  • ModuleRef: inject ModuleRef and call this.moduleRef.get(BService, { strict: false }) in onModuleInit, so construction no longer depends on B.
  • Better fixes: extract the shared logic into a third service, depend on an abstraction, or decouple with events (EventEmitter2, CQRS events).

Interview questions

  • How do you resolve a circular dependency in Nest?
  • What does forwardRef actually do?
  • What else can show up as a circular dependency even when the code looks fine?

Request pipeline

Request lifecycle & middleware

Middleware → guards → interceptors (before) → pipes → handler → interceptors (after). Any uncaught error jumps to exception filters.

  • Middleware runs first (global app.use(), then module-bound by consumer.apply().forRoutes()). It sees raw req, res, next, but does not know which handler will run.
  • Guards run next: global → controller → route. Return false (or throw) and the request stops with 403.
  • Interceptors run before the handler (global → controller → route) and after it in reverse order, because they wrap the handler like an onion.
  • Pipes run last before the handler: global → controller → route → parameter pipes. They transform or validate each argument.
  • Exception filters run only if something throws. Unlike the others, the closest filter wins: route → controller → global. Only one filter handles an exception.
  • Errors thrown in middleware only reach global filters, because no route is selected yet.

Interview questions

  • Explain the NestJS request lifecycle.
  • Difference between middleware and guards?
  • Difference between interceptors and middleware?
  • Where would you put request logging, and why?

Pipes, ValidationPipe & DTOs

Pipes transform or validate handler arguments. ValidationPipe + class-validator decorators on DTO classes is the standard way to validate input.

  • Built-in pipes: ValidationPipe, ParseIntPipe, ParseFloatPipe, ParseBoolPipe, ParseArrayPipe, ParseUUIDPipe, ParseEnumPipe, DefaultValuePipe, ParseFilePipe, and ParseDatePipe (Nest 11+).
  • A custom pipe implements PipeTransform.transform(value, metadata) and returns the new value or throws (usually BadRequestException).
  • A DTO (data transfer object) is a class with class-validator decorators: @IsEmail(), @IsString(), @Length(8, 64), @IsOptional(), @IsInt(), @Min(0), @ValidateNested() + @Type(() => Address).
  • Key ValidationPipe options: whitelist (strip unknown properties), forbidNonWhitelisted (reject them with 400), transform (turn the plain body into a DTO instance and convert primitives), transformOptions.enableImplicitConversion, stopAtFirstError, exceptionFactory.
  • Mapped types: PartialType, PickType, OmitType, IntersectionType (from @nestjs/mapped-types, or @nestjs/swagger to keep docs) build UpdateUserDto from CreateUserDto without repetition.
  • Nest 12 adds a schema-first option: @Body({ schema }) with a Zod or Valibot schema and StandardSchemaValidationPipe. The class-validator flow is still supported.

Interview questions

  • What is a pipe and what are its two uses?
  • Why must DTOs be classes and not interfaces?
  • What do whitelist, forbidNonWhitelisted and transform do?
  • How do you validate an array of objects in the body?

Guards & authentication (Passport, JWT, roles)

A guard's canActivate decides whether the request reaches the handler. Use it for auth and role checks, with metadata read via Reflector.

  • Implement CanActivate.canActivate(context); return a boolean, a promise or an Observable. false gives 403 ForbiddenException; throw UnauthorizedException yourself for 401.
  • ExecutionContext extends ArgumentsHost with getHandler() and getClass(), so a guard can read metadata set by decorators such as @Roles('admin') or @Public().
  • Bind with @UseGuards(JwtAuthGuard, RolesGuard) on a controller or route, or globally with { provide: APP_GUARD, useClass: JwtAuthGuard } and a @Public() opt-out.
  • JWT flow: login checks the password (bcrypt or argon2), JwtService.signAsync({ sub, roles }) returns an access token; the guard verifies the Authorization: Bearer header and puts the payload on request.user.
  • Passport: @nestjs/passport wraps strategies. Extend PassportStrategy(Strategy) and implement validate(); its return value becomes req.user. Use AuthGuard('jwt') or AuthGuard('local').
  • Order matters: authentication guard first (who are you), then authorization guard (what may you do).

Interview questions

  • How do you implement role-based access control in Nest?
  • What is the role of Passport in Nest, and do you need it?
  • What status does a guard return when it denies access, and how do you return 401 instead?
  • How would you protect every route by default?

Interceptors: logging, transform, caching, timeout

An interceptor wraps the handler call. It runs code before, then works on the result stream (RxJS) after.

  • Implement NestInterceptor.intercept(context, next). Call next.handle() to run the handler; it returns an Observable of the result.
  • Before-logic goes before next.handle(). After-logic goes into RxJS operators: map (reshape the response), tap (log), catchError (map errors), timeout (abort slow handlers).
  • Returning something without calling next.handle() skips the handler. This is how caching works: return of(cachedValue).
  • Built-ins: ClassSerializerInterceptor (applies class-transformer @Exclude / @Expose to responses) and CacheInterceptor from @nestjs/cache-manager (caches GET responses).
  • Order: global → controller → route on the way in, and the reverse on the way out.
  • Interceptors work the same for HTTP, GraphQL, WebSockets and microservices, because they use ExecutionContext.

Interview questions

  • What can an interceptor do that a guard or pipe cannot?
  • Why do interceptors use RxJS Observables?
  • How would you add a standard { data, meta } response envelope across the API?

Exceptions & exception filters

Throw HttpExceptions from anywhere. The built-in filter turns them into JSON; custom @Catch() filters let you control the response shape.

  • Built-in exceptions extend HttpException: BadRequestException (400), UnauthorizedException (401), ForbiddenException (403), NotFoundException (404), ConflictException (409), UnprocessableEntityException (422), InternalServerErrorException (500), and more.
  • Default response: { statusCode, message, error }. Any non-HTTP error becomes { statusCode: 500, message: 'Internal server error' }, so internal details are not leaked.
  • A custom filter: @Catch(HttpException) or @Catch() (everything) on a class implementing ExceptionFilter.catch(exception, host). Use host.switchToHttp() to get the request and response.
  • Bind with @UseFilters() on a route or controller, or globally with APP_FILTER or app.useGlobalFilters().
  • Extend BaseExceptionFilter to add logging but keep the default response behaviour.
  • Map domain errors (like EmailTakenError) to HTTP in one filter, so services stay free of HTTP classes.

Interview questions

  • How does Nest handle an error thrown in a service?
  • If filters are bound globally, at controller level and at route level, which one runs?
  • How would you translate database errors, like a unique-constraint violation, into HTTP responses?

Custom decorators & metadata

Use createParamDecorator for handler arguments, SetMetadata / Reflector.createDecorator for metadata, and applyDecorators to bundle several.

  • Param decorators: createParamDecorator((data, ctx) => ...) returns a value that is injected into the handler, such as @CurrentUser() reading request.user.
  • Metadata decorators: SetMetadata('roles', ['admin']) or the typed Reflector.createDecorator<string[]>(). Guards and interceptors read them through Reflector.
  • Composition: applyDecorators(UseGuards(JwtAuthGuard, RolesGuard), Roles(['admin']), ApiBearerAuth()) gives one @Auth('admin') decorator.
  • Pipes work on custom param decorators too: @CurrentUser(new ValidationPipe({ validateCustomDecorators: true })).
  • Decorators run once when the class is defined, not per request. They only store metadata; enhancers act on it at request time.

Interview questions

  • How do you create a @CurrentUser() decorator?
  • What is applyDecorators for?
  • What is Reflector and how do decorators and guards communicate?

Config, data & testing

Configuration & databases (TypeORM, Prisma, Mongoose)

Load and validate env vars with @nestjs/config, then wire the ORM with a forRootAsync that reads from ConfigService.

  • ConfigModule.forRoot({ isGlobal: true, cache: true, envFilePath, load: [dbConfig], validationSchema }) loads .env, merges custom config factories and validates at startup.
  • Read values with config.get<string>('DB_HOST') or getOrThrow(). For typed groups use registerAs('db', () => ({...})) and inject @Inject(dbConfig.KEY) cfg: ConfigType<typeof dbConfig>.
  • Validation: Joi or a validate() function with class-validator. Since Nest 12, validationSchema takes any Standard Schema library, such as Zod.
  • TypeORM: TypeOrmModule.forRootAsync({ inject: [ConfigService], useFactory }), forFeature([User]) per module, then @InjectRepository(User) repo: Repository<User>. Turn synchronize off in production and use migrations.
  • Prisma: a PrismaService extends PrismaClient implements OnModuleInit that calls $connect(), exported from a global PrismaModule. Schema-first, generated typed client, migrations with prisma migrate.
  • Mongoose: MongooseModule.forRoot(uri), forFeature([{ name: Cat.name, schema: CatSchema }]), @InjectModel(Cat.name) model: Model<Cat>; schemas via @Schema() / @Prop() classes.

Interview questions

  • How do you manage configuration per environment in Nest?
  • Why use TypeOrmModule.forRootAsync instead of forRoot?
  • TypeORM vs Prisma in a Nest project?
  • How do you run several writes in one transaction with TypeORM?

Testing: unit and e2e

Test.createTestingModule builds a mini DI container where you swap real providers for mocks; e2e tests boot the app and hit it with supertest.

  • Unit test: Test.createTestingModule({ providers: [UsersService, { provide: getRepositoryToken(User), useValue: repoMock }] }).compile(), then moduleRef.get(UsersService).
  • Overrides: .overrideProvider(X).useValue(mock), .overrideGuard(JwtAuthGuard).useValue({ canActivate: () => true }), also overrideInterceptor, overridePipe, overrideFilter and overrideModule.
  • useMocker(token => ...) auto-mocks every missing dependency, which keeps unit tests short.
  • e2e test: import AppModule, createNestApplication(), apply the same global pipes as main.ts, await app.init(), then request(app.getHttpServer()).get('/users').expect(200). Close with app.close().
  • Use moduleRef.resolve() (not get()) for request-scoped or transient providers.
  • Generated projects use Jest; Nest 12 ESM projects default to Vitest. @nestjs/testing works with either.

Interview questions

  • How do you unit test a service that depends on a repository?
  • How do you write e2e tests in Nest?
  • How do you test a guard or an interceptor on its own?

Architecture & scale

Microservices & transports

@nestjs/microservices lets the same controllers and DI talk over TCP, Redis, NATS, MQTT, RabbitMQ, Kafka or gRPC instead of HTTP.

  • Start one with NestFactory.createMicroservice(AppModule, { transport: Transport.RMQ, options }), or add transports to an HTTP app (hybrid app) with app.connectMicroservice() + app.startAllMicroservices().
  • Request-response: @MessagePattern('get_user') on the server, client.send(pattern, data) on the client. send returns a cold Observable: nothing is sent until you subscribe (or await firstValueFrom(...)).
  • Event-based: @EventPattern('user_created') on the server, client.emit() on the client. No reply is expected; many services can listen.
  • Clients come from ClientsModule.register([{ name: 'USERS', transport, options }]) and are injected with @Inject('USERS') client: ClientProxy.
  • Use @Payload() and @Ctx() to read data and transport context (Kafka partition, RMQ channel for manual ack). Throw RpcException for errors.
  • Guards, pipes, interceptors and filters all work, using switchToRpc() instead of switchToHttp().

Interview questions

  • Difference between @MessagePattern and @EventPattern?
  • What is a hybrid application?
  • How do you keep data consistent across microservices without distributed transactions?
  • How would you handle a slow or failing downstream service?

GraphQL & WebSocket gateways

@nestjs/graphql maps resolvers to classes like controllers; @WebSocketGateway does the same for real-time events.

  • GraphQL drivers: Apollo or Mercurius (Fastify). Code-first builds the schema from TypeScript classes (@ObjectType, @Field, autoSchemaFile). Schema-first starts from .graphql files (typePaths) and generates TS types.
  • Resolvers: @Resolver(() => Cat) with @Query(), @Mutation(), @Subscription(), @ResolveField() for nested fields, and @Args() for inputs (@InputType classes validated by ValidationPipe).
  • N+1 problem: a @ResolveField that queries per parent row. Fix with DataLoader (batch and cache per request), usually created per request in the GraphQL context.
  • Guards and interceptors work but need GqlExecutionContext.create(ctx) to get req and args.
  • Gateways: @WebSocketGateway({ namespace: 'chat', cors: true }), @SubscribeMessage('message') handlers with @MessageBody() and @ConnectedSocket(), and @WebSocketServer() server for broadcasts. Platforms: socket.io (default) or ws.
  • Hooks: OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect. Throw WsException for errors. Scale socket.io across instances with the Redis adapter.

Interview questions

  • Code-first vs schema-first GraphQL in Nest?
  • What is the N+1 problem in GraphQL and how do you fix it in Nest?
  • How do you scale WebSocket gateways across several instances?

CQRS with @nestjs/cqrs

Separate writes (commands) from reads (queries), and react to changes with events. Nest provides CommandBus, QueryBus, EventBus and sagas.

  • Command: intent to change state (PlaceOrderCommand). Exactly one @CommandHandler executes it via commandBus.execute().
  • Query: read request (GetOrderQuery). One @QueryHandler; it can read from a separate, denormalised read model.
  • Event: something that happened (OrderPlacedEvent). Zero or many @EventsHandlers react via eventBus.publish().
  • Sagas: @Saga() methods take the event stream (Observable) and return new commands, which is good for multi-step workflows.
  • AggregateRoot collects events with apply(); after publisher.mergeObjectContext(aggregate), calling commit() publishes them.
  • Use it when reads and writes have very different shapes or loads, or with event sourcing. For simple CRUD it adds ceremony without benefit.

Interview questions

  • What is CQRS and when would you use it in Nest?
  • Difference between a command and an event?
  • What is a saga in @nestjs/cqrs?

Express vs Fastify, lifecycle hooks & production

Swap the HTTP adapter for speed, use lifecycle hooks for startup and graceful shutdown, and know the production checklist.

  • Fastify: NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter()). Higher throughput and built-in schema-based serialization; Express has the larger middleware ecosystem.
  • On Fastify, Express-only middleware (for example some passport or multer setups) needs Fastify equivalents (@fastify/helmet, @fastify/multipart). Listen on '0.0.0.0' inside containers.
  • Startup hooks, in order: onModuleInit (per module, after its dependencies are resolved) → onApplicationBootstrap (all modules ready).
  • Shutdown hooks: onModuleDestroy → beforeApplicationShutdown → onApplicationShutdown. They only run on SIGTERM if you call app.enableShutdownHooks().
  • Production basics: helmet, CORS, rate limiting with @nestjs/throttler, health checks with @nestjs/terminus, structured logs, OpenAPI with @nestjs/swagger, and run behind a process manager or orchestrator.
  • CPU-heavy work blocks the single event loop. Offload it to queues (@nestjs/bullmq) or worker threads.

Interview questions

  • Express vs Fastify adapter: how do you choose?
  • What lifecycle hooks does Nest provide, and in what order?
  • How do you make a Nest service shut down gracefully in Kubernetes?