Skip to content

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 

Repository files navigation

NestJS-Interview-Questions-And-Answers

Comprehensive interview questions and detailed answers covering NestJS modules, DI, request pipeline, microservices, GraphQL, WebSockets, CQRS, queues, auth, ORM, testing, and logistics domain scenarios (quotes, bookings, tracking).

Total questions: 336 | Scenario-based: 108


Modules

Q1. What is a NestJS module and why does every app need at least one?

Answer: A NestJS module is a class annotated with @Module() that groups related providers, controllers, and imported modules into a cohesive domain boundary.

Every NestJS application has a root module (typically AppModule) because the Nest factory bootstraps from a single module graph. Modules declare:

  • imports — other modules whose exported providers you need
  • controllers — HTTP/RPC/WS handlers registered in this module
  • providers — injectable services/repositories/factories
  • exports — subset of providers (or re-exported modules) visible to importers

Without modules, DI boundaries blur and feature ownership becomes unclear. Prefer feature modules (QuotesModule, BookingsModule) over dumping everything into AppModule.


Q2. Explain the difference between importing a module and exporting a provider.

Answer: Importing a module makes that module’s exported providers available in the importing module’s DI context. Exporting a provider from Module A does not automatically inject it into Module B unless B imports A (or a module that re-exports A).

@Module({
  providers: [QuotesService],
  exports: [QuotesService],
})
export class QuotesModule {}

@Module({
  imports: [QuotesModule],
  controllers: [BookingsController],
})
export class BookingsModule {}

Common mistake: listing a provider in both modules creates duplicate instances.


Q3. What is a global module in NestJS and when should you use one?

Answer: @Global() makes a module’s exports available everywhere without repeated imports. Use sparingly for cross-cutting infrastructure: ConfigModule, logging, database wrappers, or shared auth helpers.

Overusing global modules hides dependencies and makes testing harder—feature modules should still declare explicit imports for domain services.


Q4. How do you structure feature modules for a logistics quotes/bookings domain? (Scenario)

Answer: Split by bounded context: QuotesModule, BookingsModule, TrackingModule, thin SharedKernelModule, and InfrastructureModule (ORM, Redis, Kafka). Each feature owns controllers and application services; persistence stays behind interfaces. Avoid circular imports by extracting contracts or publishing domain events.


Q5. What happens if you register the same provider in two different modules?

Answer: Nest creates separate instances per registration. To share one instance: provide once, export it, and import that module elsewhere—or use a global module. Duplicate registration often causes “cache/state disappeared” bugs.


Q6. Can a module export a module it imported? What is re-exporting?

Answer: Yes. Re-exporting forwards another module’s public API—useful for facade modules that package TypeOrmModule.forFeature so consumers import one module.


Q7. How does Nest resolve the module dependency graph at bootstrap?

Answer: Nest builds a graph from imports, instantiates modules (including dynamic metadata), registers providers, then creates controllers and binds routes. Circular module imports and provider cycles need forwardRef. Lifecycle hooks run after the graph is ready.


Q8. What is the difference between AppModule and a feature module?

Answer: AppModule is the composition root: imports features, config, health. Feature modules encapsulate vertical slices. Keep AppModule thin with no domain logic so features stay testable and extractable.


Q9. How do you share a DatabaseModule across Quotes and Bookings without duplication?

Answer: Create DatabaseModule with TypeOrmModule.forRootAsync, mark @Global() or export the connection module, and use forFeature([Entity]) inside each feature module for repositories.


Q10. What metadata does the @Module decorator accept?

Answer: imports, controllers, providers, exports. Dynamic modules also return module (the host class) plus those fields. Providers can be classes or custom provider objects (provide/use*).


Controllers

Q11. What is a NestJS controller and how does routing work?

Answer: Controllers handle inbound transport (HTTP, RPC, WS). Method decorators (@Get, @Post, @MessagePattern) register routes on the Express/Fastify adapter via reflection. Keep controllers thin: parse input, call services, return DTOs.


Q12. Explain @Param, @Query, @Body, @Headers, @Req, and @Res.

Answer: Path, query, body, and headers bind inputs. @Req/@Res expose the platform objects—prefer Nest decorators for portability. If you use @Res() without { passthrough: true }, you must send the response yourself.


Q13. How do you version APIs in NestJS controllers?

Answer: Enable app.enableVersioning({ type: VersioningType.URI }) and set @Controller({ path: 'bookings', version: '1' }) or @Version('2') per handler. Version quote schemas carefully when carrier contracts change.


Q14. What do @HttpCode, @Header, and @Redirect do?

Answer: They set status, response headers, and redirects respectively. Prefer consistent exception filters/interceptors for cross-cutting HTTP shaping.


Q15. How should a BookingsController expose create, cancel, and tracking link? (Scenario)

Answer: POST /bookings, GET /bookings/:id, POST /bookings/:id/cancel, GET /bookings/:id/tracking. Use DTOs + ValidationPipe, problem+json filters, and ownership/role guards.


Q16. Can one handler return different success status codes?

Answer: Yes via @HttpCode, @Res({ passthrough: true }), or interceptors. Prefer throwing typed exceptions for error paths (404/409/410).


Q17. How do you organize nested routes like /shipments/:id/events?

Answer: Use @Controller('shipments/:shipmentId/events') and validate parent existence in a pipe/service; authorize access to that shipment.


Q18. What is @Controller() path prefix inheritance?

Answer: The controller path prefixes all handler paths. Global prefix app.setGlobalPrefix('api') applies app-wide. Combine with versioning: /api/v1/quotes.


Q19. How do you return empty 204 No Content from Nest?

Answer: @HttpCode(204) and return nothing/undefined, or @Res() with res.status(204).send(). Useful for delete/cancel acknowledgements.


Q20. Difference between @All, @Get, and method-specific decorators?

Answer: @All matches any HTTP verb; prefer explicit verbs for clarity and OpenAPI accuracy.


Providers & Dependency Injection

Q21. What is a provider in NestJS?

Answer: Anything injectable via the IoC container—services, repos, factories, values—registered in providers or by dynamic modules, resolved by token (class/string/symbol).


Q22. Constructor injection vs property injection?

Answer: Constructor injection is preferred: explicit, required, easy to mock. Property @Inject helps with optional deps or base-class constraints.


Q23. What are DEFAULT, REQUEST, and TRANSIENT scopes?

Answer: Singleton (default), per-request instance, and per-injection-site instance. Request scope bubbles to dependents and costs performance.


Q24. When would you use REQUEST scope in a multi-tenant logistics API? (Scenario)

Answer: Hold tenantId/claims per HTTP request and inject TenantContext into quote/booking queries. Alternatives: AsyncLocalStorage with singletons for fewer scope cascades.


Q25. What is @Inject() and when is it required?

Answer: When the token differs from the TypeScript type—custom tokens, interfaces, or forwardRef.


Q26. How does @Optional() work?

Answer: Allows unresolved dependencies to be undefined—optional Redis/cache/feature plugins.


Q27. Explain @InjectRepository and @InjectDataSource.

Answer: TypeORM Nest tokens for repositories (forFeature) and DataSource/query runners for transactions.


Q28. What is the Reflector class used for?

Answer: Reading handler/class metadata set by custom decorators (SetMetadata)—roles, permissions, cache TTL, public routes.


Q29. How does Nest resolve circular constructor dependencies without forwardRef?

Answer: It generally cannot for constructor cycles—you need forwardRef, property injection, or redesign (events/mediator).


Q30. What is ModuleRef and when do you use it?

Answer: Runtime provider lookup (moduleRef.get(Token) / resolve for transient/request). Useful for plugin registries or delayed resolution; avoid as a Service Locator smell in core flows.


Custom Providers

Q31. Explain useClass, useValue, useFactory, and useExisting.

Answer: Alternate class, constant/mock, factory (sync/async with inject), and token alias—core tools for ports/adapters and testing.


Q32. How do you register an interface-based provider?

Answer: Use a string/symbol token with @Inject(RATE_ENGINE) because interfaces are erased at runtime.


Q33. Write a useFactory that creates a Kafka producer from ConfigService.

Answer:

{
  provide: KAFKA_PRODUCER,
  useFactory: async (config: ConfigService) => {
    const kafka = new Kafka({ brokers: config.getOrThrow('KAFKA_BROKERS').split(',') });
    const producer = kafka.producer();
    await producer.connect();
    return producer;
  },
  inject: [ConfigService],
}

Disconnect on shutdown.


Q34. What is useExisting useful for?

Answer: Aliasing tokens without a second instance—legacy token + new port token.


Q35. How do you provide a mock CarrierApiClient in e2e tests?

Answer: overrideProvider(CarrierApiClient).useValue({ getRates: jest.fn() }) in Test.createTestingModule.


Q36. Can useFactory be async?

Answer: Yes—Nest awaits async factories during bootstrap. Ideal for DB/Kafka/Redis connections.


Q37. How do multi-providers / array injection work?

Answer: Register multiple providers with the same token and { multi: true } patterns via custom techniques, or collect adapters in a registry factory that injects many tokens.


Q38. Inject different rate engines per NODE_ENV. (Scenario)

Answer: useFactory reads config and returns StubRateEngine in test, CachedRateEngine in prod wrapping carrier HTTP clients.


Circular Dependencies

Q39. How do you resolve circular dependency between two providers?

Answer: @Inject(forwardRef(() => OtherService)) on both sides if needed; prefer extracting a third service or events.


Q40. How do circular module imports get fixed?

Answer: imports: [forwardRef(() => OtherModule)] on one or both modules. Still reconsider boundaries.


Q41. Why are circular dependencies a smell in logistics domain services? (Scenario)

Answer: QuoteServiceBookingService cycles mean tangled responsibilities. Prefer QuoteAccepted events handled by booking application services.


Q42. Do forwardRef and REQUEST scope interact badly?

Answer: They can obscure resolution order and complicate testing. Eliminate cycles first; use request scope only where necessary.


Dynamic Modules

Q43. What is a dynamic module and why forRoot/forFeature?

Answer: Runtime-configured DynamicModule. forRoot once for connections/config; forFeature per feature (entities, queues).


Q44. Explain forRootAsync with useFactory.

Answer: Defers options until ConfigService (etc.) exists—standard for TypeORM, Bull, JWT.


Q45. How would you build CarriersModule.register(carriers)? (Scenario)

Answer: Dynamic providers per carrier kind plus a CarrierRegistry exported for quote orchestration.


Q46. What is ConfigurableModuleBuilder?

Answer: Helper generating typed forRoot/forRootAsync boilerplate and options tokens.


Q47. Difference between global dynamic module and importing it everywhere?

Answer: global: true on DynamicModule mirrors @Global()—convenient for infra, hides deps if overused.


Q48. How does BullModule.forRoot vs registerQueue relate to dynamic modules?

Answer: forRoot configures Redis connection; registerQueue({ name: 'tracking' }) is forFeature-style per queue.


Middleware

Q49. What is Nest middleware vs Express middleware?

Answer: NestMiddleware.use(req,res,next) wraps platform middleware, configured via MiddlewareConsumer. Runs early—good for correlation IDs; prefer guards for DI-heavy auth.


Q50. How do you apply middleware to specific routes?

Answer: consumer.apply(Mw).forRoutes(Controller) / .exclude('health').


Q51. Order: middleware, guards, interceptors, pipes, filters?

Answer: Middleware → Guards → Interceptors (before) → Pipes → Handler → Interceptors (after); Filters on errors.


Q52. Implement correlation ID middleware for tracking requests. (Scenario)

Answer: Read/generate x-correlation-id, attach to request, set response header, propagate to Kafka headers.


Q53. Can middleware be functional (not class-based)?

Answer: Yes—consumer.apply((req,res,next)=>{...})—but class middleware supports DI.


Q54. Block requests missing API key at edge middleware vs guard? (Scenario)

Answer: Simple static API key can be middleware; tenant-aware keys with DB lookup fit better as a guard with DI.


Guards

Q55. What is a guard and what does canActivate return?

Answer: Access control returning boolean/Promise/Observable—authn/authz, feature flags.


Q56. Implement RolesGuard with @Roles metadata.

Answer: SetMetadata('roles', roles) + Reflector.getAllAndOverride comparing request.user.roles.


Q57. Authentication vs authorization guards?

Answer: Authn identifies the user (JWT); authz checks permissions (owner/admin/carrier).


Q58. Guards with GraphQL and WebSockets?

Answer: Use ExecutionContext / GqlExecutionContext / WS handshake auth payload.


Q59. Only booking owner or admin can cancel—how? (Scenario)

Answer: JwtAuthGuard + ownership guard loading booking and comparing shipperId to user.sub.


Q60. What is AuthGuard('jwt') from @nestjs/passport?

Answer: Passport strategy bridge that validates JWT and attaches user to the request.


Q61. How do you mark a route as public while using a global JwtAuthGuard?

Answer: @Public() sets metadata; guard checks Reflector and skips auth when present.


Q62. Carrier webhook endpoints need HMAC verification, not JWT. (Scenario)

Answer: Custom HmacSignatureGuard reading raw body + secret; exclude from JWT global guard via @Public() + HMAC guard.


Interceptors

Q63. What is an interceptor and how does it use RxJS?

Answer: Wraps next.handle() Observable—logging, mapping, caching, timeouts via operators.


Q64. Response mapping interceptor pattern?

Answer: map(data => ({ data, meta }))—keep one envelope convention.


Q65. Timeout and cache interceptors?

Answer: timeout(ms)RequestTimeoutException; cache check before handler, tap to store. Quote cache keys include lane/weight/date.


Q66. Interceptor vs middleware vs guard vs pipe vs filter?

Answer: Middleware early platform; guard access; interceptor AOP; pipe input validate/transform; filter exceptions.


Q67. Log quote requests with duration and carrier count. (Scenario)

Answer: Logging interceptor on quotes controller with timing + result length + correlation id.


Q68. How do you handle errors inside interceptors?

Answer: catchError in the pipe chain—rethrow Nest HTTP exceptions or map to domain errors.


Q69. ClassSerializerInterceptor purpose?

Answer: Applies class-transformer @Exclude/@Expose on response entities—hide password hashes.


Pipes

Q70. What are pipes in NestJS?

Answer: Transform/validate arguments before the handler—ValidationPipe, ParseUUIDPipe, custom PipeTransform.


Q71. Transform vs validate pipes?

Answer: Transform coerces types; validate asserts constraints and throws 400.


Q72. Create ParseShipmentIdPipe.

Answer: Regex/format check throwing BadRequestException on mismatch.


Q73. Where can pipes be applied?

Answer: Param, method, controller, or globally.


Q74. ParseEnumPipe use case in booking status filters? (Scenario)

Answer: @Query('status', new ParseEnumPipe(BookingStatus)) ensures only known statuses.


Q75. DefaultValuePipe example?

Answer: @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number.


Exception Filters

Q76. What is an exception filter?

Answer: Maps exceptions to responses via @Catch and ArgumentsHost.


Q77. Handle QuoteExpiredError with a filter. (Scenario)

Answer: @Catch(QuoteExpiredError) → HTTP 410 with code: QUOTE_EXPIRED.


Q78. @Catch() with no args vs specific types?

Answer: No args = catch-all base filter; prefer specific filters plus one global unexpected-error filter.


Q79. How do filters work for RPC/microservice contexts?

Answer: host.switchToRpc() / switchToWs()—return RpcException-compatible payloads.


Q80. Prisma ClientKnownRequestError P2002 unique violation mapping. (Scenario)

Answer: Global filter maps P2002 → 409 Conflict with field info for duplicate booking references.


ValidationPipe

Q81. How does ValidationPipe work with class-validator DTOs?

Answer: Transforms to class instances and validates decorators; failures → 400. Use whitelist/forbidNonWhitelisted/transform globally.


Q82. Explain whitelist, forbidNonWhitelisted, transform.

Answer: Strip unknown, reject unknown, convert types/DTO instances—security-critical.


Q83. Validate nested quote line items.

Answer: @ValidateNested + @Type(() => QuoteItemDto) with transform: true.


Q84. Reject quote requests with pickupDate in the past. (Scenario)

Answer: Custom validator or @MinDate; service enforces timezone cutoffs per carrier.


Q85. What is validateCustomDecorators in ValidationPipe?

Answer: Also validate values coming from custom param decorators, not only body/query/param.


Q86. Different DTO validation groups for draft vs submit quote. (Scenario)

Answer: @IsOptional({ groups:['draft'] }) etc., pass groups in ValidationPipe per route.


Configuration

Q87. How do you use @nestjs/config ConfigModule?

Answer: forRoot with env files + Joi/Zod validation; inject ConfigService.


Q88. Why validate env at bootstrap?

Answer: Fail fast before serving traffic—missing DB/Kafka config should crash startup.


Q89. Namespaced registerAs config for carriers?

Answer: registerAs('carriers', () => (...)) + ConfigType<typeof carriersConfig> injection.


Q90. Structure secrets for Kafka, Redis, DB? (Scenario)

Answer: Separate namespaces; never log secrets; .env.example without real values.


Q91. ConfigModule isGlobal true vs importing everywhere?

Answer: Global avoids repetitive imports; still fine for config. Don’t make all feature modules global.


Q92. How to load YAML/JSON config files?

Answer: load: [() => yaml.load(fs.readFileSync(...))] in ConfigModule or custom factory.


Lifecycle Hooks

Q93. List Nest lifecycle hooks and typical order.

Answer: onModuleInitonApplicationBootstrap → … → onModuleDestroy / beforeApplicationShutdown / onApplicationShutdown. Enable shutdown hooks for SIGTERM.


Q94. Where to connect/disconnect Redis?

Answer: Connect in factory/onModuleInit; disconnect in shutdown hooks.


Q95. Flush tracking buffers on shutdown. (Scenario)

Answer: Stop intake, flush batches/queues, then close connections; align with K8s grace period.


Q96. Difference between onModuleInit and onApplicationBootstrap?

Answer: Module init: that module’s deps ready. Application bootstrap: entire app graph ready—safe for cross-module warmups.


Q97. Why call app.enableShutdownHooks()?

Answer: Without it, Nest may not run destroy/shutdown hooks on SIGTERM—leaking connections during deploys.


HTTP Adapter: Fastify vs Express

Q98. How do you switch NestJS from Express to Fastify?

Answer:

const app = await NestFactory.create<NestFastifyApplication>(
  AppModule,
  new FastifyAdapter(),
);

Install @nestjs/platform-fastify. Some Express middleware needs Fastify plugins instead.


Q99. Performance and ecosystem trade-offs: Fastify vs Express?

Answer: Fastify generally higher throughput/lower overhead; Express has broader middleware ecosystem. Nest abstracts both, but raw middleware and some passport strategies may differ.


Q100. How do raw body / webhook signature verification differ on Fastify? (Scenario)

Answer: May need preParsing hooks or content-type parsers to retain raw Buffer for HMAC—Express often uses verify in bodyParser. Document per adapter.


Q101. Are @Req()/@Res() types portable across adapters?

Answer: Types differ (Express.Request vs FastifyRequest). Prefer Nest abstractions; if needed, use generics from the platform package.


Q102. CORS, compression, helmet setup differences?

Answer: Express uses middleware functions; Fastify uses plugins (@fastify/cors, etc.). Nest app.enableCors() works on both.


Q103. High QPS public rate-quote API—which adapter and why? (Scenario)

Answer: Prefer Fastify for CPU-efficient JSON serialization under heavy quote traffic; still measure with realistic carrier latency mocks.


Microservices (Kafka, Redis, gRPC)

Q104. How do you create a Nest microservice?

Answer:

const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
  transport: Transport.KAFKA,
  options: { client: { brokers: ['localhost:9092'] }, consumer: { groupId: 'tracking' } },
});
await app.listen();

Q105. What are @MessagePattern and @EventPattern?

Answer: @MessagePattern request/response (RPC-style). @EventPattern fire-and-forget events. Choose based on whether the caller needs a reply.


Q106. How does Kafka transport work in Nest?

Answer: Kafka client/consumer options; patterns map to topics. Mind consumer groups, partitions, and idempotent handlers for at-least-once delivery.


Q107. Redis transport use cases?

Answer: Lightweight pub/sub or Redis-based microservice messaging for internal low-latency commands—not a full Kafka replacement for durable logistics event streams.


Q108. gRPC in NestJS basics?

Answer: Transport.GRPC with proto files, @GrpcMethod handlers. Strong contracts and streaming; good for internal carrier-adapter services.


Q109. Hybrid application: HTTP + Kafka consumer in one process?

Answer: NestFactory.create then app.connectMicroservice(...) + app.startAllMicroservices() + app.listen()—common for modular monolith transitioning to events.


Q110. Publish BookingConfirmed to Kafka and update read models. (Scenario)

Answer: Bookings service emits event after commit; Tracking/Notifications consumers update projections and email. Use outbox pattern for reliability.


Q111. How do you handle idempotency for TrackingEvent consumers? (Scenario)

Answer: Store eventId uniquely; ignore duplicates. Kafka at-least-once requires this for ETA updates.


Q112. ClientProxy and ClientKafka usage?

Answer: Inject microservice clients via ClientsModule.register to emit/send messages from HTTP APIs.


Q113. When choose gRPC over Kafka for quote fan-out to carrier adapters? (Scenario)

Answer: gRPC for synchronous multi-carrier rate calls needing aggregated response; Kafka for async lifecycle events after booking.


Q114. What is RpcException?

Answer: Microservice exception type serialized to the caller; map domain errors in RPC filters.


Q115. Serializer/deserializer customization for Kafka payloads?

Answer: Provide custom serializer options to control JSON/Avro encoding and headers (correlation ids).


Q116. Exactly-once booking debit illusion with Kafka? (Scenario)

Answer: True EOS is hard; use transactional outbox + idempotent consumers + ledger unique constraints to achieve effective exactly-once side effects.


GraphQL

Q117. Code-first vs schema-first GraphQL in Nest?

Answer: Code-first: decorators generate schema (@ObjectType, @Resolver). Schema-first: write SDL + implement resolvers. Code-first fits TS-heavy teams.


Q118. How do you set up Apollo GraphQL driver?

Answer: GraphQLModule.forRoot({ autoSchemaFile: true, driver: ApolloDriver }) with resolvers as providers.


Q119. What are resolvers, mutations, and fields?

Answer: Resolvers map queries/mutations/field resolvers. Keep business logic in services—resolvers orchestrate.


Q120. Guards and interceptors in GraphQL context?

Answer: GqlExecutionContext.create(context).getContext().req for user; same AOP concepts apply.


Q121. DataLoader to avoid N+1 on booking → tracking events? (Scenario)

Answer: Batch load events by bookingIds per request; provide request-scoped DataLoader factory.


Q122. Subscriptions for live tracking updates? (Scenario)

Answer: GraphQL subscriptions over WebSocket; publish on tracking event ingest. Auth handshake carefully.


Q123. Federation / modular GraphQL schemas?

Answer: Split by domain modules with multiple resolver classes; larger orgs may use Apollo Federation across services.


Q124. Expose quote search via GraphQL but bookings via REST—why? (Scenario)

Answer: GraphQL helps flexible quote UIs; REST/webhooks fit carrier booking integrations. Hybrid is fine.


WebSockets

Q125. Gateway basics with @WebSocketGateway?

Answer:

@WebSocketGateway({ namespace: '/tracking', cors: true })
export class TrackingGateway {
  @SubscribeMessage('subscribeShipment')
  handleSubscribe() { /* ... */ }
}

Q126. Socket.IO vs ws adapter?

Answer: Nest supports both; Socket.IO adds rooms/namespaces; native ws is lighter. Choose based on client needs.


Q127. How to authenticate WebSocket connections?

Answer: Validate JWT in handleConnection or middleware from handshake auth/query; disconnect on failure.


Q128. Push ETA updates to shipper dashboards. (Scenario)

Answer: On Kafka tracking consume, server.to(shipmentRoom).emit('eta', payload). Clients join room on subscribe.


Q129. Rooms and namespaces for multi-tenant tracking?

Answer: Namespace per product; rooms per shipmentId or tenantId to isolate broadcasts.


Q130. Scaling WebSockets across multiple Nest pods? (Scenario)

Answer: Use Redis adapter for Socket.IO so emits cross processes; sticky sessions may still help.


CQRS

Q131. How does @nestjs/cqrs work?

Answer: Commands/queries/events with CommandBus, QueryBus, EventBus. Handlers implement ICommandHandler etc.


Q132. Command vs Event vs Query in Nest CQRS?

Answer: Command: change state. Query: read. Event: fact that happened (side effects/projections).


Q133. When to introduce CQRS in bookings? (Scenario)

Answer: When write model (booking aggregate) differs from read needs (search, tracking timeline). Avoid for simple CRUD.


Q134. Saga / ProcessManager for quote→book→dispatch? (Scenario)

Answer: @Saga listens to events and dispatches commands—e.g., on BookingConfirmed dispatch SchedulePickupCommand.


Q135. How are events published after TypeORM transaction?

Answer: Collect domain events in aggregate; publish after successful commit (or outbox) to avoid phantom events.


Q136. Difference between EventBus and external Kafka events?

Answer: In-process EventBus is same JVM/process; Kafka is cross-service. Often map domain events to integration events.


Bull Queues

Q137. How do you register a Bull queue in Nest?

Answer:

BullModule.forRoot({ redis: { host: 'localhost' } }),
BullModule.registerQueue({ name: 'notifications' }),

Inject @InjectQueue('notifications') queue: Queue.


Q138. Producer vs processor (@Process)?

Answer: Producers add jobs; @Processor('notifications') classes with @Process() consume them.


Q139. Job options: delay, attempts, backoff, priority?

Answer: Configure retries/backoff for flaky carrier emails; delay for reminder jobs; priority for urgent customs alerts.


Q140. Retry failed label purchase jobs safely. (Scenario)

Answer: Idempotent processor keyed by bookingId; limited attempts; move to DLQ/failed set; alert ops.


Q141. Bull vs Kafka for workload?

Answer: Bull: background jobs/retries tied to Redis. Kafka: durable event streaming/fan-out. Often both.


Q142. BullMQ vs Bull in Nest?

Answer: BullMQ is newer; @nestjs/bullmq module. Prefer BullMQ for new projects.


Q143. Named job processors and concurrency?

Answer: @Process({ name: 'send-pod', concurrency: 5 }) controls parallelism per job type.


Q144. Rate-limit carrier API calls via a queue. (Scenario)

Answer: Enqueue rate requests; processor uses bottleneck/limiter so aggregate RPS stays under carrier caps.


Q145. How do you test queue processors?

Answer: Unit-test processor methods with mocked jobs; e2e with Redis testcontainer or override queue provider.


Authentication (JWT & Passport)

Q146. Passport strategy pattern in Nest?

Answer: Extend PassportStrategy(Strategy) implementing validate(); register as provider; guard with AuthGuard('strategy-name').


Q147. Implement JWT login + access token issuance.

Answer: Validate credentials, JwtService.sign({ sub, roles }), return token; protect routes with JwtAuthGuard.


Q148. Refresh token rotation pattern? (Scenario)

Answer: Store refresh token hashes; rotate on use; revoke on logout; short-lived access tokens.


Q149. LocalStrategy vs JwtStrategy?

Answer: Local: username/password login. JWT: bearer token validation on subsequent requests.


Q150. How to extract user in controllers?

Answer: Custom @CurrentUser() decorator reading request.user set by Passport.


Q151. API key auth for partner carrier portals? (Scenario)

Answer: Custom passport strategy or guard validating X-API-Key against hashed keys per partner.


Q152. OAuth2/OIDC with Nest?

Answer: Use passport OAuth strategies or integrate IdP (Auth0/Azure AD) validating JWKS-signed tokens.


Q153. Security pitfalls with JWT in logistics APIs?

Answer: Don’t put PII in tokens; validate aud/iss; short expiry; HTTPS only; careful CORS.


Q154. Impersonation for customer support on bookings? (Scenario)

Answer: Support role + audited impersonation token with act claim; still enforce tenant boundaries.


TypeORM & Prisma

Q155. TypeOrmModule.forRoot vs forFeature?

Answer: forRoot connection; forFeature([Entity]) registers repositories in a feature module.


Q156. Repository pattern with Nest TypeORM?

Answer: Inject @InjectRepository(Booking) private repo: Repository<Booking> or custom repository classes.


Q157. Transactions with DataSource.transaction / QueryRunner?

Answer: Wrap booking create + outbox insert in one transaction for consistency.


Q158. Prisma integration in Nest?

Answer: Provide PrismaService extends PrismaClient with onModuleInit $connect and shutdown $disconnect.


Q159. TypeORM vs Prisma trade-offs?

Answer: TypeORM: Active Record/Data Mapper, mature Nest module. Prisma: strong typing, migrations DX; transactions/middleware differ.


Q160. Optimistic locking on booking status updates. (Scenario)

Answer: Version column; catch update count 0 → conflict if two agents cancel/confirm concurrently.


Q161. Migrations strategy in Nest monorepo?

Answer: Run migrations in CI/CD job before deploy; never auto-sync schema in production.


Q162. Soft deletes for shipments?

Answer: deletedAt column; default scopes/filters exclude deleted; admin restore endpoints.


Q163. Multi-DB — quotes read replica vs bookings primary. (Scenario)

Answer: Multiple named DataSources; route read-heavy quote history to replica; writes to primary.


Q164. How to unit test services using Prisma?

Answer: Mock PrismaService methods; or use test DB with truncated tables for integration tests.


Testing

Q165. unit testing a Nest provider with TestingModule?

Answer:

const module = await Test.createTestingModule({
  providers: [QuotesService, { provide: RATE_ENGINE, useValue: mockEngine }],
}).compile();

Q166. e2e testing with supertest?

Answer: Create full app, app.getHttpServer(), supertest requests; override external carriers.


Q167. How to override guards in tests?

Answer: .overrideGuard(JwtAuthGuard).useValue({ canActivate: () => true }).


Q168. Testing request-scoped providers?

Answer: Use module.resolve(Token) instead of get for transient/request-scoped.


Q169. Contract test for CreateBooking DTO validation. (Scenario)

Answer: e2e post invalid payloads; expect 400 structure stable for mobile clients.


Q170. Jest vs Vitest with Nest?

Answer: Jest is default in Nest schematics; Vitest possible with config work—team consistency matters.


Q171. How do you test Kafka consumers?

Answer: Unit-test handler methods with payload fixtures; integration with embedded/testcontainers Kafka.


Swagger / OpenAPI

Q172. How to set up Swagger in Nest?

Answer: DocumentBuilder + SwaggerModule.setup('docs', app, document) with DTO @ApiProperty.


Q173. Bearer auth in Swagger UI?

Answer: addBearerAuth() + @ApiBearerAuth() on controllers.


Q174. Document quote error codes for partners. (Scenario)

Answer: @ApiResponse({ status: 410, description: 'Quote expired' }) and shared error schema.


Q175. Keep Swagger in sync with ValidationPipe DTOs?

Answer: Use same DTO classes; plugins can enrich OpenAPI from class-validator in some setups.


Q176. Disable Swagger in production?

Answer: Gate setup behind NODE_ENV or internal network; never expose public admin schemas carelessly.


Monorepo

Q177. Nest CLI monorepo mode basics?

Answer: nest generate app / library in a monorepo; shared libs for contracts/DTOs between apps.


Q178. When extract quotes and tracking into separate apps? (Scenario)

Answer: Different scale/SLA, independent deploy cadence, or team ownership—share libs/contracts for events.


Q179. Path aliases and build for Nest monorepos?

Answer: Use tsconfig paths and Nest webpack/tsc builders; CI builds affected apps only when possible.


Q180. Shared library versioning pitfalls?

Answer: Breaking DTO changes affect all apps—use careful semver or consumer-driven contracts.


Terminus / Health

Q181. What is @nestjs/terminus?

Answer: Health checks module for readiness/liveness—DB, Redis, Kafka, custom indicators.


Q182. Liveness vs readiness for K8s with Nest?

Answer: Liveness: process up. Readiness: can accept traffic (DB pool ok). Don’t kill on dependency blips via wrong probe.


Q183. Readiness fails if Kafka producer down—good idea? (Scenario)

Answer: If API can still serve reads without publishing, maybe not block readiness; if bookings require outbox publish, fail readiness.


Q184. Custom HealthIndicator for carrier API?

Answer: Ping carrier sandbox lightly or check circuit breaker state—avoid hammering third parties every second.


Logistics Scenarios

Q185. Design quote TTL expiry with Nest. (Scenario)

Answer: Store expiresAt; Validation on accept; scheduled Bull job marks expired; return 410 via filter.


Q186. Concurrent booking on same quote—how to prevent double book? (Scenario)

Answer: DB unique constraint on quoteId booking; transactional status flip quote→accepted; second attempt conflicts.


Q187. Fan-out rate requests to 5 carriers with timeout budget. (Scenario)

Answer: Promise.allSettled with per-carrier AbortSignal/timeouts in RateEngine; interceptor overall timeout 3s; partial quotes ok.


Q188. Tracking webhook storm—how to protect Nest API? (Scenario)

Answer: HMAC guard, rate limit IP, enqueue raw payloads to Bull for async processing, fast 202 response.


Q189. Multi-leg shipment modeling across modules? (Scenario)

Answer: Shipment aggregate with legs; TrackingModule emits per-leg events; Bookings owns commercial contract.


Q190. Cancel booking after label purchased—compensating transaction? (Scenario)

Answer: Command cancels locally, enqueues VoidLabelJob, emits BookingCancelled; saga handles carrier void failures with retry/manual queue.


Q191. Quote price changed at carrier between quote and book? (Scenario)

Answer: Re-rate on book if policy requires; or lock rate with carrier API; surface PriceChangedError to client.


Q192. GDPR erasure request for shipper PII in Nest services? (Scenario)

Answer: Hard-delete/anonymize across Quotes/Bookings/Tracking; queue cascade jobs; retain non-PII audit where legally required.


Q193. Idempotency-Key header for CreateBooking. (Scenario)

Answer: Middleware/interceptor stores key→response; replay same response on retries from mobile clients.


Q194. Split Nest modular monolith into microservices—strangler steps? (Scenario)

Answer: Extract Tracking consumer first (already event-driven), put Anti-Corruption Layer, share auth JWKS, move DB tables last.


Q195. SLA monitoring for quote latency p95. (Scenario)

Answer: Interceptor metrics + Prometheus; alert when carrier adapter p95 exceeds budget; circuit-break slow carriers.


Q196. Offline depot scanning via Nest mobile BFF? (Scenario)

Answer: BFF accepts batched scans, validates, enqueues; conflict resolution on duplicate scan events.


Q197. Dangerous goods flags affecting quote eligibility. (Scenario)

Answer: ValidationPipe + domain service rules; exclude carriers lacking DG certification in registry filter.


Q198. Postal vs coordinate geocoding failures in quote request. (Scenario)

Answer: Fallback geocoder chain; return 422 with actionable error; cache successful geocodes in Redis.


Q199. Partner white-label booking API with per-tenant branding config? (Scenario)

Answer: TenantModule request scope loads brand config; Swagger per-tenant optional; rate limits per API key.


Modules Advanced

Q200. What is a transient module import vs exported provider?

Answer: Importing grants access only to exports. Non-exported providers remain private encapsulation—use that to hide repositories.


Q201. Can controllers be exported?

Answer: No—controllers aren’t exported via module exports; only providers/modules. Controllers register routes when their module is imported into the app graph.


Q202. Circular dependency between three modules—mitigation?

Answer: Introduce events or a shared ApplicationModule facade; avoid A→B→C→A imports.


Q203. How do you lazy-load a Nest module path?

Answer: Nest supports lazy modules via LazyModuleLoader for rarely used admin features to reduce startup.


Controllers Advanced

Q204. What is @HttpException body shape best practice?

Answer: Use consistent { statusCode, message, errorCode, correlationId } via filters—not ad-hoc strings.


Q205. File upload with FileInterceptor? (Scenario)

Answer: @UseInterceptors(FileInterceptor('file')) + @UploadedFile(); validate MIME/size for POD uploads.


Q206. SSE (Server-Sent Events) in Nest controllers?

Answer: Return Observable streams with @Sse() for one-way tracking feeds when WS is overkill.


Q207. How does @Render work with MVC views?

Answer: Pairs with view engines—less common for pure APIs; logistics UIs usually SPA + JSON API.


DI Advanced

Q208. What is Durable providers / lazy provider injection?

Answer: Patterns using ModuleRef.createDecorator / lazy getters—rarely needed; prefer explicit async factories.


Q209. Injection token collision risks with strings?

Answer: Prefer Symbol('BOOKINGS_REPO') or const tokens in shared libs to avoid silent collisions.


Q210. Scoped provider + middleware DI limitation?

Answer: Middleware is instantiated differently; prefer guards/interceptors for request-scoped DI-heavy logic.


Q211. How to inject the current request into a singleton?

Answer: Don’t—use REQUEST scope, or AsyncLocalStorage/REQUEST token carefully without leaking across requests.


Custom Providers Advanced

Q212. Factory provider error handling during bootstrap?

Answer: Thrown errors fail app start—desired for missing critical config. Catch only for optional integrations.


Q213. Provide an abstract class token with useClass?

Answer: { provide: PaymentPort, useClass: StripePaymentAdapter } where PaymentPort is abstract class (emitted to JS).


Q214. Feature-flagged provider switch between mock and live carriers. (Scenario)

Answer: Factory reads LaunchDarkly/config flag and returns mock or live implementation without changing consumers.


Dynamic Modules Advanced

Q215. Why return exports from dynamic modules?

Answer: Same as static—consumers only see exported tokens. ForRoot often exports the configured service.


Q216. Async configuration with useExisting?

Answer: useExisting: ConfigService when an existing provider already implements the options factory interface.


Q217. RegisterQueueAsync pattern?

Answer: Bull registerQueueAsync injects config for queue name/prefix per environment.


Middleware Advanced

Q218. Apply multiple middlewares in order?

Answer: consumer.apply(A, B, C).forRoutes('*')—order is left-to-right.


Q219. Exclude health and metrics from auth middleware?

Answer: .exclude({ path: 'health', method: RequestMethod.GET }, 'metrics').


Guards Advanced

Q220. CanActivate async DB lookup performance?

Answer: Cache permissions; avoid heavy queries per request; prefer claims in JWT for hot paths.


Q221. Composition of multiple guards—short circuit?

Answer: Nest runs guards in order; first failure denies. Put cheap authn before expensive authz.


Q222. Feature flag guard for new booking v2 flow. (Scenario)

Answer: Guard checks flag for tenant; returns 404/403 if disabled to hide incomplete features.


Interceptors Advanced

Q223. RxJS switchMap in interceptors—when?

Answer: Rarely—for chaining dependent async work. Prefer services; keep interceptors thin.


Q224. Stream file download via interceptor?

Answer: Usually controller returns StreamableFile; interceptor shouldn’t buffer large POD PDFs.


Q225. Mask PII in logs interceptor. (Scenario)

Answer: Redact email/phone in logged bodies for quote requests before writing to stdout.


Pipes Advanced

Q226. ParseArrayPipe for batch tracking event ids?

Answer: @Query('ids', new ParseArrayPipe({ items: String })).


Q227. Custom pipe injecting services?

Answer: Mark @Injectable() and register as provider; use class ref in @UsePipes / param pipes carefully with DI.


Filters Advanced

Q228. BaseExceptionFilter extension?

Answer: Extend to reuse default HTTP mapping while adding logging/Sentry.


Q229. Async filters?

Answer: catch can be async for logging sinks; still ensure response is sent once.


Config Advanced

Q230. expandVariables in ConfigModule?

Answer: Interpolates ${VAR} in env values—useful for composing URLs; beware surprise expansions.


Q231. Per-environment carrier sandbox vs production endpoints. (Scenario)

Answer: Config maps CARRIER_ENV; factory builds baseURL; prevent prod keys in staging via validation.


Lifecycle Advanced

Q232. onModuleDestroy vs beforeApplicationShutdown?

Answer: beforeApplicationShutdown receives signal reason; good for coordinated drain. onModuleDestroy for module-local cleanup.


Q233. Hot reload / watch mode lifecycle caveats?

Answer: Repeated init without full shutdown can leak connections in dev—use graceful restarts.


Microservices Advanced

Q234. Kafka consumer group rebalance impact on Nest handlers? (Scenario)

Answer: Rebalances pause consumption—keep handlers fast; avoid long DB work inline; use queues for heavy work.


Q235. Dead-letter topic strategy for failed tracking events? (Scenario)

Answer: After N failures, publish to DLTwith headers; ops replay tooling; don’t block partition forever.


Q236. gRPC streaming for live rate negotiation?

Answer: Client streaming or bidi possible; complexity high—often REST/gRPC unary batch is enough.


Q237. Context propagation: correlation id across Kafka?

Answer: Put correlation id in message headers; interceptor/middleware restores ALS on consume.


Q238. Backpressure when tracking consumers lag. (Scenario)

Answer: Monitor lag; scale consumers; shed load; pause webhook ACK until queue depth healthy.


GraphQL Advanced

Q239. Complexity / depth limiting?

Answer: Protect against expensive nested queries on booking→events→signatures.


Q240. Field-level authorization?

Answer: Use @Extensions/guards on field resolvers to hide carrier rates from unauthorized roles.


Q241. Upload proof-of-delivery via GraphQL multipart?

Answer: Possible but REST upload + GraphQL metadata often simpler operationally.


WebSockets Advanced

Q242. Heartbeat / disconnect cleanup for shipment rooms?

Answer: On disconnect remove user from rooms; avoid leaking membership maps in memory.


Q243. Agent app flaky network—replay missed tracking events? (Scenario)

Answer: Client sends lastEventId; gateway fetches from store and replays then live-tails.


CQRS Advanced

Q244. Unhandled command errors bubbling to HTTP?

Answer: Controller awaits commandBus.execute; map domain errors via filters.


Q245. EventHandler idempotency in @nestjs/cqrs?

Answer: Same as messaging—store processed event ids when handlers have side effects.


Bull Advanced

Q246. Stalled jobs and lock duration? (Scenario)

Answer: Long label PDF generation needs higher lockDuration; otherwise Bull reclaims and duplicates work.


Q247. Repeatable jobs for nightly invoice export?

Answer: queue.add with repeat cron; ensure only one Nest instance adds repeatable config at bootstrap.


Q248. Observability for queue depth?

Answer: Expose Bull metrics gauges; alert on growing waiting for tracking processors.


Auth Advanced

Q249. JWT passport extractors custom from cookies?

Answer: ExtractJwt.fromExtractors([cookieExtractor, bearerExtractor]) for BFF cookie sessions.


Q250. Service-to-service mTLS vs JWT between Nest services? (Scenario)

Answer: mTLS at mesh; JWT for user identity propagation (Authorization + original user claims).


Q251. Password hashing with Argon2 in Nest auth service?

Answer: Use argon2/bcrypt in AuthService; never log passwords; constant-time compare.


ORM Advanced

Q252. TypeORM subscribers vs Nest events?

Answer: Subscribers couple to ORM lifecycle; prefer domain events for business side effects.


Q253. Prisma middleware for tenant isolation? (Scenario)

Answer: Inject tenantId into queries via middleware—careful with raw queries bypassing it.


Q254. Migration rollback strategy during bad booking deploy?

Answer: Expand/contract migrations; avoid destructive downs in prod without backup.


Testing Advanced

Q255. Pact contract testing between Booking API and Tracking consumer? (Scenario)

Answer: Provider/consumer contracts on Kafka payload schemas—catch breaking field renames.


Q256. Mutation testing worth it for rate engine?

Answer: For critical pricing logic yes; for thin controllers usually not.


Swagger Advanced

Q257. Multiple OpenAPI documents for public vs internal APIs?

Answer: Build two documents with different include/exclude controllers.


Q258. Generate partner SDK from Nest Swagger. (Scenario)

Answer: Publish OpenAPI artifact in CI; generate TypeScript SDK for shipper integrations.


Monorepo Advanced

Q259. Shared ESLint/tsconfig across Nest apps?

Answer: Root configs with project references; enforce module boundaries (no deep relative imports across apps).


Q260. One CI pipeline vs many for Nest monorepo? (Scenario)

Answer: Affected-based pipelines; independent deploy for tracking-service vs quotes-api.


Terminus Advanced

Q261. Graceful degradation indicator?

Answer: Custom indicator returns info (not fail) when secondary cache is down but primary DB ok.


Q262. Memory heap health check?

Answer: Terminus MemoryHealthIndicator for liveness heuristics—tune thresholds carefully.


Nest Core Miscellaneous

Q263. What is ExecutionContext?

Answer: Abstraction over HTTP/RPC/WS/GraphQL handler context—used by guards/interceptors/filters.


Q264. ArgumentsHost vs ExecutionContext?

Answer: ArgumentsHost is the base for filters; ExecutionContext extends it with handler/class metadata.


Q265. applyDecorators utility?

Answer: Compose multiple decorators into one exported decorator (e.g., @Auth() = Jwt + Roles).


Q266. What does NestFactory.createApplicationContext do?

Answer: DI-only context without HTTP—useful for CLI scripts, cron workers, seeders.


Q267. Standalone application for a Bull worker process? (Scenario)

Answer: CreateApplicationContext or dedicated microservice app importing processors—scale workers independently.


Q268. Global prefix exclude for health?

Answer: app.setGlobalPrefix('api', { exclude: ['health'] }).


Q269. Helmet and security headers in Nest?

Answer: app.use(helmet()) on Express; Fastify plugin equivalent—standard for public APIs.


Q270. Rate limiting approaches in Nest?

Answer: @nestjs/throttler guards, API gateway limits, or Redis token buckets for partner keys.


Q271. Throttle quote spam from a single API key. (Scenario)

Answer: ThrottlerGuard keyed by API key/tenant; higher limits for premium partners.


Q272. Caching with CacheModule?

Answer: CacheModule.register + CACHE_MANAGER interceptors; Redis store for multi-instance quote caches.


Q273. ScheduleModule cron for expire quotes? (Scenario)

Answer: @Cron marks expired quotes; ensure single-leader or DB-safe updates under multi-pod.


Q274. EventEmitterModule vs CQRS EventBus?

Answer: @nestjs/event-emitter simple in-process emitter; CQRS richer command/query separation.


Q275. HTTP module (@nestjs/axios) best practices?

Answer: Inject HttpService; set timeouts; map errors; wrap carrier clients; don’t leak axios types domain-wide.


Q276. Circuit breaker around carrier HTTP calls. (Scenario)

Answer: Use opossum/cockatiel in CarrierClient provider; fallback to cached rates or omit carrier.


Q277. Logger service vs console.log?

Answer: Use Nest Logger or custom logger (Pino) with context; structured JSON in prod.


Q278. Replace Nest logger with Pino?

Answer: Custom logger provider implementing Nest logger interface; better perf/structured fields.


Q279. Validation of UUID path params globally?

Answer: ParseUUIDPipe on params or middleware—prefer pipes for clear 400s.


Q280. Multipart booking document upload limits? (Scenario)

Answer: Configure body size limits per adapter; virus scan async via queue.


Q281. Cookie-parser and sessions with Nest?

Answer: Possible for BFF; many logistics APIs remain bearer-token stateless.


Q282. Proxy / trust middleware behind load balancer?

Answer: Configure trust proxy for accurate client IPs used in rate limits/audit.


Q283. Audit log every booking state transition. (Scenario)

Answer: Domain events → AuditInterceptor or event handler writing immutable audit rows.


Q284. Differentiate 401 vs 403 in Nest auth?

Answer: 401 unauthenticated; 403 authenticated but forbidden—keep guards consistent.


Q285. Problem+JSON error responses?

Answer: Filter returns application/problem+json with type/title/detail/status for partner APIs.


Q286. API gateway vs Nest throttling responsibilities?

Answer: Gateway coarse limits/WAF; Nest fine-grained tenant quotas and business rules.


Logistics Domain Deep Scenarios

Q287. Quote includes accessorials (liftgate, residential). (Scenario)

Answer: DTO lists accessorial codes; rate engine maps to carrier surcharges; validate carrier support.


Q288. Booking requires customs invoice for cross-border. (Scenario)

Answer: Guard/validator ensures invoice docs present when origin/dest countries differ; else 422.


Q289. Partial delivery events out of order. (Scenario)

Answer: Tracking projector sorts by carrier event time + sequence; ignore stale older timestamps.


Q290. Shipper cancels while pickup is en route. (Scenario)

Answer: State machine: only allow cancel from certain statuses; notify carrier via async job; fee rules.


Q291. Duplicate tracking webhooks with different payloads. (Scenario)

Answer: Idempotency by event id; if same id different hash, quarantine for manual review.


Q292. Peak Black Friday quote traffic 10x. (Scenario)

Answer: Cache hot lanes, Fastify adapter, horizontal pods, degrade to fewer carriers, queue noncritical work.


Q293. Carrier API returns intermittent 503 during book. (Scenario)

Answer: Retry with jitter in client; Bull job for async confirmation mode; user sees pending state.


Q294. Multi-parcel booking weight distribution validation. (Scenario)

Answer: Pipe/service ensures sum(parcel weights)=total; dimensional weight rules per carrier.


Q295. ETA prediction service as Nest microservice. (Scenario)

Answer: gRPC PredictEta; Tracking calls it; fallback heuristic if ML service unhealthy (Terminus).


Q296. Notify shipper via SMS/email on exception event. (Scenario)

Answer: Kafka ShipmentException → Bull notification queue → provider adapters; user prefs in DB.


Q297. Rate shopping must exclude embargoed destinations. (Scenario)

Answer: Embargo list in config/DB; filter carriers/lanes before calling out; audit decisions.


Q298. Booking amendment changes delivery address. (Scenario)

Answer: New command with version check; may require re-quote; emit BookingAmended.


Q299. Proof of delivery image virus scanning. (Scenario)

Answer: Upload to quarantine bucket; async scanner job; only then attach to tracking timeline.


Q300. Tenant A must never see Tenant B quotes (IDOR). (Scenario)

Answer: Always filter by tenantId from auth context; add e2e IDOR tests; no trust client-sent tenant.


Q301. Synchronous book API vs async confirmation UX. (Scenario)

Answer: Return 202 + bookingId when carrier confirm slow; client polls/subscribes to status.


Q302. Reprocess DLQ tracking events after bugfix. (Scenario)

Answer: Admin CLI using ApplicationContext republishes from DLT with new consumer code.


Q303. Quote currency conversion mid-day FX change. (Scenario)

Answer: Lock FX rate at quote time store on quote; booking uses locked rate for billing consistency.


Q304. Nest worker OOMs generating bulk labels. (Scenario)

Answer: Move PDF generation to isolated worker queue with memory limits; stream to object storage.


Q305. Canary deploy of new rate engine. (Scenario)

Answer: Feature flag percentage traffic to v2 engine; compare prices; interceptor tags metrics by version.


Q306. Legal hold freezes deletion of booking records. (Scenario)

Answer: Erasure service checks legal hold flag; anonymize non-essential fields only.


Nest Patterns & Best Practices

Q307. Thin controllers, fat services—why?

Answer: Controllers handle transport; services encapsulate business rules—easier testing and reuse across HTTP/RPC.


Q308. Hexagonal architecture with Nest providers?

Answer: Ports as tokens/abstract classes; adapters as useClass providers; modules wire them.


Q309. DTO vs entity—should you return TypeORM entities?

Answer: No—map to response DTOs to avoid leaking persistence and over-fetching relations.


Q310. Where to put domain invariants?

Answer: Domain entities/value objects or domain services—not only ValidationPipe (syntax vs business rules).


Q311. Shared kernel pitfalls in monorepo?

Answer: Avoid dumping everything into shared; only truly common types/events; prevent hidden coupling.


Q312. Feature toggle module design?

Answer: Provide FeatureFlags service; guards/factories depend on it; cache flags with short TTL.


Q313. Error codes catalog for partner integrations?

Answer: Stable errorCode strings documented in Swagger; don’t break codes casually.


Q314. Semantic logging fields for logistics?

Answer: correlationId, tenantId, bookingId, shipmentId, carrier—enable support debugging.


Q315. Outbox pattern implementation sketch in Nest? (Scenario)

Answer: Same transaction writes business row + outbox row; relay polls/publishes to Kafka; marks sent.


Q316. Inbox pattern for consumers? (Scenario)

Answer: Store inbound message id before side effects; skip duplicates—pairs with outbox producers.


Q317. Anti-corruption layer for carrier APIs?

Answer: CarrierAdapter translates weird carrier payloads into clean domain models inside Nest module.


Q318. API composition BFF for mobile shipper app? (Scenario)

Answer: Nest BFF aggregates quotes+tracking+user prefs; not a dump of internal microservices.


Q319. Versioning Kafka event schemas?

Answer: Schema registry / explicit eventVersion field; consumers tolerate unknown fields.


Q320. Backward compatible additive DTO changes?

Answer: Add optional fields; don’t rename/remove without version bump; contract tests.


Q321. Using nestjs-cls / ALS for request context?

Answer: Propagate tenant/user through async chains without request-scoping entire tree.


Q322. When to use Mixin modules/guards?

Answer: Factory functions returning decorated classes for reusable parameterized guards.


Q323. Shutdown order for HTTP server vs consumers? (Scenario)

Answer: Stop readiness, stop consuming, drain HTTP, flush producers, close DB.


Q324. Blue/green vs rolling with Nest health checks?

Answer: Readiness gates traffic; ensure migrations compatible with both versions during rolling.


Q325. Secret rotation for JWT signing keys? (Scenario)

Answer: Support multiple verify keys (JWKS); rotate sign key; short token TTL.


Q326. Nest + OpenTelemetry instrumentation?

Answer: Auto-instrument HTTP/Prisma; propagate traceparent over Kafka headers.


Q327. Trace a booking across API, Bull, Kafka, consumer. (Scenario)

Answer: Pass trace context in job/event headers; visualize in Jaeger/Tempo.


Q328. Deterministic UUID for idempotent booking creates? (Scenario)

Answer: UUIDv5 from Idempotency-Key + tenant; unique constraint enforces once.


Q329. Pagination patterns: offset vs cursor for tracking events?

Answer: Cursor by (eventTime, id) for stable infinite scroll; offset ok for small admin lists.


Q330. Filtering/sorting DTOs with ValidationPipe?

Answer: Whitelist allowed sort columns to avoid SQL injection via raw order strings.


Q331. Soft rate limit vs hard reject for quotes? (Scenario)

Answer: Return cached/partial results under shed load; hard 429 when abusive.


Q332. Maintaining OpenAPI for microservices gateway?

Answer: Aggregate specs or BFF-only public docs; internal services stay private.


Q333. Nest CLI schematics for generating resources?

Answer: nest g resource scaffolds module/controller/service/DTO—customize to your architecture.


Q334. Avoid anemic domain model in Nest services?

Answer: Don’t put all logic in services operating on bare data bags—use rich domain entities where complexity warrants.


Q335. Merge two shipper tenant accounts. (Scenario)

Answer: Background job rewrites tenantIds with FK care; dual-read period; audit; invalidate tokens.


Q336. Carrier deprecates API v1 mid-quarter. (Scenario)

Answer: Adapter feature flag to v2; contract tests; monitor error rates; keep v1 fallback briefly.


About

NestJS interview Q&A (300+): modules, DI, guards/pipes/interceptors, microservices, auth, ORM, testing, and logistics-style scenarios.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors