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
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 needcontrollers— HTTP/RPC/WS handlers registered in this moduleproviders— injectable services/repositories/factoriesexports— 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.
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.
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.
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.
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.
Answer:
Yes. Re-exporting forwards another module’s public API—useful for facade modules that package TypeOrmModule.forFeature so consumers import one module.
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.
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.
Answer:
Create DatabaseModule with TypeOrmModule.forRootAsync, mark @Global() or export the connection module, and use forFeature([Entity]) inside each feature module for repositories.
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*).
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.
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.
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.
Answer: They set status, response headers, and redirects respectively. Prefer consistent exception filters/interceptors for cross-cutting HTTP shaping.
Answer:
POST /bookings, GET /bookings/:id, POST /bookings/:id/cancel, GET /bookings/:id/tracking. Use DTOs + ValidationPipe, problem+json filters, and ownership/role guards.
Answer:
Yes via @HttpCode, @Res({ passthrough: true }), or interceptors. Prefer throwing typed exceptions for error paths (404/409/410).
Answer:
Use @Controller('shipments/:shipmentId/events') and validate parent existence in a pipe/service; authorize access to that shipment.
Answer:
The controller path prefixes all handler paths. Global prefix app.setGlobalPrefix('api') applies app-wide. Combine with versioning: /api/v1/quotes.
Answer:
@HttpCode(204) and return nothing/undefined, or @Res() with res.status(204).send(). Useful for delete/cancel acknowledgements.
Answer:
@All matches any HTTP verb; prefer explicit verbs for clarity and OpenAPI accuracy.
Answer:
Anything injectable via the IoC container—services, repos, factories, values—registered in providers or by dynamic modules, resolved by token (class/string/symbol).
Answer:
Constructor injection is preferred: explicit, required, easy to mock. Property @Inject helps with optional deps or base-class constraints.
Answer: Singleton (default), per-request instance, and per-injection-site instance. Request scope bubbles to dependents and costs performance.
Answer:
Hold tenantId/claims per HTTP request and inject TenantContext into quote/booking queries. Alternatives: AsyncLocalStorage with singletons for fewer scope cascades.
Answer:
When the token differs from the TypeScript type—custom tokens, interfaces, or forwardRef.
Answer:
Allows unresolved dependencies to be undefined—optional Redis/cache/feature plugins.
Answer:
TypeORM Nest tokens for repositories (forFeature) and DataSource/query runners for transactions.
Answer:
Reading handler/class metadata set by custom decorators (SetMetadata)—roles, permissions, cache TTL, public routes.
Answer:
It generally cannot for constructor cycles—you need forwardRef, property injection, or redesign (events/mediator).
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.
Answer:
Alternate class, constant/mock, factory (sync/async with inject), and token alias—core tools for ports/adapters and testing.
Answer:
Use a string/symbol token with @Inject(RATE_ENGINE) because interfaces are erased at runtime.
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.
Answer: Aliasing tokens without a second instance—legacy token + new port token.
Answer:
overrideProvider(CarrierApiClient).useValue({ getRates: jest.fn() }) in Test.createTestingModule.
Answer: Yes—Nest awaits async factories during bootstrap. Ideal for DB/Kafka/Redis connections.
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.
Answer:
useFactory reads config and returns StubRateEngine in test, CachedRateEngine in prod wrapping carrier HTTP clients.
Answer:
@Inject(forwardRef(() => OtherService)) on both sides if needed; prefer extracting a third service or events.
Answer:
imports: [forwardRef(() => OtherModule)] on one or both modules. Still reconsider boundaries.
Answer:
QuoteService ↔ BookingService cycles mean tangled responsibilities. Prefer QuoteAccepted events handled by booking application services.
Answer: They can obscure resolution order and complicate testing. Eliminate cycles first; use request scope only where necessary.
Answer:
Runtime-configured DynamicModule. forRoot once for connections/config; forFeature per feature (entities, queues).
Answer:
Defers options until ConfigService (etc.) exists—standard for TypeORM, Bull, JWT.
Answer:
Dynamic providers per carrier kind plus a CarrierRegistry exported for quote orchestration.
Answer:
Helper generating typed forRoot/forRootAsync boilerplate and options tokens.
Answer:
global: true on DynamicModule mirrors @Global()—convenient for infra, hides deps if overused.
Answer:
forRoot configures Redis connection; registerQueue({ name: 'tracking' }) is forFeature-style per queue.
Answer:
NestMiddleware.use(req,res,next) wraps platform middleware, configured via MiddlewareConsumer. Runs early—good for correlation IDs; prefer guards for DI-heavy auth.
Answer:
consumer.apply(Mw).forRoutes(Controller) / .exclude('health').
Answer: Middleware → Guards → Interceptors (before) → Pipes → Handler → Interceptors (after); Filters on errors.
Answer:
Read/generate x-correlation-id, attach to request, set response header, propagate to Kafka headers.
Answer:
Yes—consumer.apply((req,res,next)=>{...})—but class middleware supports DI.
Answer: Simple static API key can be middleware; tenant-aware keys with DB lookup fit better as a guard with DI.
Answer: Access control returning boolean/Promise/Observable—authn/authz, feature flags.
Answer:
SetMetadata('roles', roles) + Reflector.getAllAndOverride comparing request.user.roles.
Answer: Authn identifies the user (JWT); authz checks permissions (owner/admin/carrier).
Answer:
Use ExecutionContext / GqlExecutionContext / WS handshake auth payload.
Answer:
JwtAuthGuard + ownership guard loading booking and comparing shipperId to user.sub.
Answer:
Passport strategy bridge that validates JWT and attaches user to the request.
Answer:
@Public() sets metadata; guard checks Reflector and skips auth when present.
Answer:
Custom HmacSignatureGuard reading raw body + secret; exclude from JWT global guard via @Public() + HMAC guard.
Answer:
Wraps next.handle() Observable—logging, mapping, caching, timeouts via operators.
Answer:
map(data => ({ data, meta }))—keep one envelope convention.
Answer:
timeout(ms) → RequestTimeoutException; cache check before handler, tap to store. Quote cache keys include lane/weight/date.
Answer: Middleware early platform; guard access; interceptor AOP; pipe input validate/transform; filter exceptions.
Answer: Logging interceptor on quotes controller with timing + result length + correlation id.
Answer:
catchError in the pipe chain—rethrow Nest HTTP exceptions or map to domain errors.
Answer:
Applies class-transformer @Exclude/@Expose on response entities—hide password hashes.
Answer:
Transform/validate arguments before the handler—ValidationPipe, ParseUUIDPipe, custom PipeTransform.
Answer: Transform coerces types; validate asserts constraints and throws 400.
Answer:
Regex/format check throwing BadRequestException on mismatch.
Answer: Param, method, controller, or globally.
Answer:
@Query('status', new ParseEnumPipe(BookingStatus)) ensures only known statuses.
Answer:
@Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number.
Answer:
Maps exceptions to responses via @Catch and ArgumentsHost.
Answer:
@Catch(QuoteExpiredError) → HTTP 410 with code: QUOTE_EXPIRED.
Answer: No args = catch-all base filter; prefer specific filters plus one global unexpected-error filter.
Answer:
host.switchToRpc() / switchToWs()—return RpcException-compatible payloads.
Answer: Global filter maps P2002 → 409 Conflict with field info for duplicate booking references.
Answer: Transforms to class instances and validates decorators; failures → 400. Use whitelist/forbidNonWhitelisted/transform globally.
Answer: Strip unknown, reject unknown, convert types/DTO instances—security-critical.
Answer:
@ValidateNested + @Type(() => QuoteItemDto) with transform: true.
Answer:
Custom validator or @MinDate; service enforces timezone cutoffs per carrier.
Answer: Also validate values coming from custom param decorators, not only body/query/param.
Answer:
@IsOptional({ groups:['draft'] }) etc., pass groups in ValidationPipe per route.
Answer:
forRoot with env files + Joi/Zod validation; inject ConfigService.
Answer: Fail fast before serving traffic—missing DB/Kafka config should crash startup.
Answer:
registerAs('carriers', () => (...)) + ConfigType<typeof carriersConfig> injection.
Answer:
Separate namespaces; never log secrets; .env.example without real values.
Answer: Global avoids repetitive imports; still fine for config. Don’t make all feature modules global.
Answer:
load: [() => yaml.load(fs.readFileSync(...))] in ConfigModule or custom factory.
Answer:
onModuleInit → onApplicationBootstrap → … → onModuleDestroy / beforeApplicationShutdown / onApplicationShutdown. Enable shutdown hooks for SIGTERM.
Answer:
Connect in factory/onModuleInit; disconnect in shutdown hooks.
Answer: Stop intake, flush batches/queues, then close connections; align with K8s grace period.
Answer: Module init: that module’s deps ready. Application bootstrap: entire app graph ready—safe for cross-module warmups.
Answer: Without it, Nest may not run destroy/shutdown hooks on SIGTERM—leaking connections during deploys.
Answer:
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter(),
);Install @nestjs/platform-fastify. Some Express middleware needs Fastify plugins instead.
Answer: Fastify generally higher throughput/lower overhead; Express has broader middleware ecosystem. Nest abstracts both, but raw middleware and some passport strategies may differ.
Answer:
May need preParsing hooks or content-type parsers to retain raw Buffer for HMAC—Express often uses verify in bodyParser. Document per adapter.
Answer:
Types differ (Express.Request vs FastifyRequest). Prefer Nest abstractions; if needed, use generics from the platform package.
Answer:
Express uses middleware functions; Fastify uses plugins (@fastify/cors, etc.). Nest app.enableCors() works on both.
Answer: Prefer Fastify for CPU-efficient JSON serialization under heavy quote traffic; still measure with realistic carrier latency mocks.
Answer:
const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
transport: Transport.KAFKA,
options: { client: { brokers: ['localhost:9092'] }, consumer: { groupId: 'tracking' } },
});
await app.listen();Answer:
@MessagePattern request/response (RPC-style). @EventPattern fire-and-forget events. Choose based on whether the caller needs a reply.
Answer: Kafka client/consumer options; patterns map to topics. Mind consumer groups, partitions, and idempotent handlers for at-least-once delivery.
Answer: Lightweight pub/sub or Redis-based microservice messaging for internal low-latency commands—not a full Kafka replacement for durable logistics event streams.
Answer:
Transport.GRPC with proto files, @GrpcMethod handlers. Strong contracts and streaming; good for internal carrier-adapter services.
Answer:
NestFactory.create then app.connectMicroservice(...) + app.startAllMicroservices() + app.listen()—common for modular monolith transitioning to events.
Answer: Bookings service emits event after commit; Tracking/Notifications consumers update projections and email. Use outbox pattern for reliability.
Answer: Store eventId uniquely; ignore duplicates. Kafka at-least-once requires this for ETA updates.
Answer:
Inject microservice clients via ClientsModule.register to emit/send messages from HTTP APIs.
Answer: gRPC for synchronous multi-carrier rate calls needing aggregated response; Kafka for async lifecycle events after booking.
Answer: Microservice exception type serialized to the caller; map domain errors in RPC filters.
Answer: Provide custom serializer options to control JSON/Avro encoding and headers (correlation ids).
Answer: True EOS is hard; use transactional outbox + idempotent consumers + ledger unique constraints to achieve effective exactly-once side effects.
Answer:
Code-first: decorators generate schema (@ObjectType, @Resolver). Schema-first: write SDL + implement resolvers. Code-first fits TS-heavy teams.
Answer:
GraphQLModule.forRoot({ autoSchemaFile: true, driver: ApolloDriver }) with resolvers as providers.
Answer: Resolvers map queries/mutations/field resolvers. Keep business logic in services—resolvers orchestrate.
Answer:
GqlExecutionContext.create(context).getContext().req for user; same AOP concepts apply.
Answer: Batch load events by bookingIds per request; provide request-scoped DataLoader factory.
Answer: GraphQL subscriptions over WebSocket; publish on tracking event ingest. Auth handshake carefully.
Answer: Split by domain modules with multiple resolver classes; larger orgs may use Apollo Federation across services.
Answer: GraphQL helps flexible quote UIs; REST/webhooks fit carrier booking integrations. Hybrid is fine.
Answer:
@WebSocketGateway({ namespace: '/tracking', cors: true })
export class TrackingGateway {
@SubscribeMessage('subscribeShipment')
handleSubscribe() { /* ... */ }
}Answer: Nest supports both; Socket.IO adds rooms/namespaces; native ws is lighter. Choose based on client needs.
Answer:
Validate JWT in handleConnection or middleware from handshake auth/query; disconnect on failure.
Answer:
On Kafka tracking consume, server.to(shipmentRoom).emit('eta', payload). Clients join room on subscribe.
Answer:
Namespace per product; rooms per shipmentId or tenantId to isolate broadcasts.
Answer: Use Redis adapter for Socket.IO so emits cross processes; sticky sessions may still help.
Answer:
Commands/queries/events with CommandBus, QueryBus, EventBus. Handlers implement ICommandHandler etc.
Answer: Command: change state. Query: read. Event: fact that happened (side effects/projections).
Answer: When write model (booking aggregate) differs from read needs (search, tracking timeline). Avoid for simple CRUD.
Answer:
@Saga listens to events and dispatches commands—e.g., on BookingConfirmed dispatch SchedulePickupCommand.
Answer: Collect domain events in aggregate; publish after successful commit (or outbox) to avoid phantom events.
Answer: In-process EventBus is same JVM/process; Kafka is cross-service. Often map domain events to integration events.
Answer:
BullModule.forRoot({ redis: { host: 'localhost' } }),
BullModule.registerQueue({ name: 'notifications' }),Inject @InjectQueue('notifications') queue: Queue.
Answer:
Producers add jobs; @Processor('notifications') classes with @Process() consume them.
Answer: Configure retries/backoff for flaky carrier emails; delay for reminder jobs; priority for urgent customs alerts.
Answer: Idempotent processor keyed by bookingId; limited attempts; move to DLQ/failed set; alert ops.
Answer: Bull: background jobs/retries tied to Redis. Kafka: durable event streaming/fan-out. Often both.
Answer:
BullMQ is newer; @nestjs/bullmq module. Prefer BullMQ for new projects.
Answer:
@Process({ name: 'send-pod', concurrency: 5 }) controls parallelism per job type.
Answer: Enqueue rate requests; processor uses bottleneck/limiter so aggregate RPS stays under carrier caps.
Answer: Unit-test processor methods with mocked jobs; e2e with Redis testcontainer or override queue provider.
Answer:
Extend PassportStrategy(Strategy) implementing validate(); register as provider; guard with AuthGuard('strategy-name').
Answer:
Validate credentials, JwtService.sign({ sub, roles }), return token; protect routes with JwtAuthGuard.
Answer: Store refresh token hashes; rotate on use; revoke on logout; short-lived access tokens.
Answer: Local: username/password login. JWT: bearer token validation on subsequent requests.
Answer:
Custom @CurrentUser() decorator reading request.user set by Passport.
Answer:
Custom passport strategy or guard validating X-API-Key against hashed keys per partner.
Answer: Use passport OAuth strategies or integrate IdP (Auth0/Azure AD) validating JWKS-signed tokens.
Answer:
Don’t put PII in tokens; validate aud/iss; short expiry; HTTPS only; careful CORS.
Answer:
Support role + audited impersonation token with act claim; still enforce tenant boundaries.
Answer:
forRoot connection; forFeature([Entity]) registers repositories in a feature module.
Answer:
Inject @InjectRepository(Booking) private repo: Repository<Booking> or custom repository classes.
Answer: Wrap booking create + outbox insert in one transaction for consistency.
Answer:
Provide PrismaService extends PrismaClient with onModuleInit $connect and shutdown $disconnect.
Answer: TypeORM: Active Record/Data Mapper, mature Nest module. Prisma: strong typing, migrations DX; transactions/middleware differ.
Answer: Version column; catch update count 0 → conflict if two agents cancel/confirm concurrently.
Answer: Run migrations in CI/CD job before deploy; never auto-sync schema in production.
Answer:
deletedAt column; default scopes/filters exclude deleted; admin restore endpoints.
Answer: Multiple named DataSources; route read-heavy quote history to replica; writes to primary.
Answer:
Mock PrismaService methods; or use test DB with truncated tables for integration tests.
Answer:
const module = await Test.createTestingModule({
providers: [QuotesService, { provide: RATE_ENGINE, useValue: mockEngine }],
}).compile();Answer:
Create full app, app.getHttpServer(), supertest requests; override external carriers.
Answer:
.overrideGuard(JwtAuthGuard).useValue({ canActivate: () => true }).
Answer:
Use module.resolve(Token) instead of get for transient/request-scoped.
Answer: e2e post invalid payloads; expect 400 structure stable for mobile clients.
Answer: Jest is default in Nest schematics; Vitest possible with config work—team consistency matters.
Answer: Unit-test handler methods with payload fixtures; integration with embedded/testcontainers Kafka.
Answer:
DocumentBuilder + SwaggerModule.setup('docs', app, document) with DTO @ApiProperty.
Answer:
addBearerAuth() + @ApiBearerAuth() on controllers.
Answer:
@ApiResponse({ status: 410, description: 'Quote expired' }) and shared error schema.
Answer: Use same DTO classes; plugins can enrich OpenAPI from class-validator in some setups.
Answer:
Gate setup behind NODE_ENV or internal network; never expose public admin schemas carelessly.
Answer:
nest generate app / library in a monorepo; shared libs for contracts/DTOs between apps.
Answer:
Different scale/SLA, independent deploy cadence, or team ownership—share libs/contracts for events.
Answer:
Use tsconfig paths and Nest webpack/tsc builders; CI builds affected apps only when possible.
Answer: Breaking DTO changes affect all apps—use careful semver or consumer-driven contracts.
Answer: Health checks module for readiness/liveness—DB, Redis, Kafka, custom indicators.
Answer: Liveness: process up. Readiness: can accept traffic (DB pool ok). Don’t kill on dependency blips via wrong probe.
Answer: If API can still serve reads without publishing, maybe not block readiness; if bookings require outbox publish, fail readiness.
Answer: Ping carrier sandbox lightly or check circuit breaker state—avoid hammering third parties every second.
Answer:
Store expiresAt; Validation on accept; scheduled Bull job marks expired; return 410 via filter.
Answer:
DB unique constraint on quoteId booking; transactional status flip quote→accepted; second attempt conflicts.
Answer:
Promise.allSettled with per-carrier AbortSignal/timeouts in RateEngine; interceptor overall timeout 3s; partial quotes ok.
Answer: HMAC guard, rate limit IP, enqueue raw payloads to Bull for async processing, fast 202 response.
Answer: Shipment aggregate with legs; TrackingModule emits per-leg events; Bookings owns commercial contract.
Answer:
Command cancels locally, enqueues VoidLabelJob, emits BookingCancelled; saga handles carrier void failures with retry/manual queue.
Answer:
Re-rate on book if policy requires; or lock rate with carrier API; surface PriceChangedError to client.
Answer: Hard-delete/anonymize across Quotes/Bookings/Tracking; queue cascade jobs; retain non-PII audit where legally required.
Answer: Middleware/interceptor stores key→response; replay same response on retries from mobile clients.
Answer: Extract Tracking consumer first (already event-driven), put Anti-Corruption Layer, share auth JWKS, move DB tables last.
Answer: Interceptor metrics + Prometheus; alert when carrier adapter p95 exceeds budget; circuit-break slow carriers.
Answer: BFF accepts batched scans, validates, enqueues; conflict resolution on duplicate scan events.
Answer: ValidationPipe + domain service rules; exclude carriers lacking DG certification in registry filter.
Answer: Fallback geocoder chain; return 422 with actionable error; cache successful geocodes in Redis.
Answer: TenantModule request scope loads brand config; Swagger per-tenant optional; rate limits per API key.
Answer: Importing grants access only to exports. Non-exported providers remain private encapsulation—use that to hide repositories.
Answer: No—controllers aren’t exported via module exports; only providers/modules. Controllers register routes when their module is imported into the app graph.
Answer: Introduce events or a shared ApplicationModule facade; avoid A→B→C→A imports.
Answer:
Nest supports lazy modules via LazyModuleLoader for rarely used admin features to reduce startup.
Answer:
Use consistent { statusCode, message, errorCode, correlationId } via filters—not ad-hoc strings.
Answer:
@UseInterceptors(FileInterceptor('file')) + @UploadedFile(); validate MIME/size for POD uploads.
Answer:
Return Observable streams with @Sse() for one-way tracking feeds when WS is overkill.
Answer: Pairs with view engines—less common for pure APIs; logistics UIs usually SPA + JSON API.
Answer:
Patterns using ModuleRef.createDecorator / lazy getters—rarely needed; prefer explicit async factories.
Answer:
Prefer Symbol('BOOKINGS_REPO') or const tokens in shared libs to avoid silent collisions.
Answer: Middleware is instantiated differently; prefer guards/interceptors for request-scoped DI-heavy logic.
Answer:
Don’t—use REQUEST scope, or AsyncLocalStorage/REQUEST token carefully without leaking across requests.
Answer: Thrown errors fail app start—desired for missing critical config. Catch only for optional integrations.
Answer:
{ provide: PaymentPort, useClass: StripePaymentAdapter } where PaymentPort is abstract class (emitted to JS).
Answer: Factory reads LaunchDarkly/config flag and returns mock or live implementation without changing consumers.
Answer: Same as static—consumers only see exported tokens. ForRoot often exports the configured service.
Answer:
useExisting: ConfigService when an existing provider already implements the options factory interface.
Answer:
Bull registerQueueAsync injects config for queue name/prefix per environment.
Answer:
consumer.apply(A, B, C).forRoutes('*')—order is left-to-right.
Answer:
.exclude({ path: 'health', method: RequestMethod.GET }, 'metrics').
Answer: Cache permissions; avoid heavy queries per request; prefer claims in JWT for hot paths.
Answer: Nest runs guards in order; first failure denies. Put cheap authn before expensive authz.
Answer: Guard checks flag for tenant; returns 404/403 if disabled to hide incomplete features.
Answer: Rarely—for chaining dependent async work. Prefer services; keep interceptors thin.
Answer: Usually controller returns StreamableFile; interceptor shouldn’t buffer large POD PDFs.
Answer: Redact email/phone in logged bodies for quote requests before writing to stdout.
Answer:
@Query('ids', new ParseArrayPipe({ items: String })).
Answer:
Mark @Injectable() and register as provider; use class ref in @UsePipes / param pipes carefully with DI.
Answer: Extend to reuse default HTTP mapping while adding logging/Sentry.
Answer:
catch can be async for logging sinks; still ensure response is sent once.
Answer:
Interpolates ${VAR} in env values—useful for composing URLs; beware surprise expansions.
Answer:
Config maps CARRIER_ENV; factory builds baseURL; prevent prod keys in staging via validation.
Answer:
beforeApplicationShutdown receives signal reason; good for coordinated drain. onModuleDestroy for module-local cleanup.
Answer: Repeated init without full shutdown can leak connections in dev—use graceful restarts.
Answer: Rebalances pause consumption—keep handlers fast; avoid long DB work inline; use queues for heavy work.
Answer: After N failures, publish to DLTwith headers; ops replay tooling; don’t block partition forever.
Answer: Client streaming or bidi possible; complexity high—often REST/gRPC unary batch is enough.
Answer: Put correlation id in message headers; interceptor/middleware restores ALS on consume.
Answer: Monitor lag; scale consumers; shed load; pause webhook ACK until queue depth healthy.
Answer: Protect against expensive nested queries on booking→events→signatures.
Answer:
Use @Extensions/guards on field resolvers to hide carrier rates from unauthorized roles.
Answer: Possible but REST upload + GraphQL metadata often simpler operationally.
Answer: On disconnect remove user from rooms; avoid leaking membership maps in memory.
Answer:
Client sends lastEventId; gateway fetches from store and replays then live-tails.
Answer:
Controller awaits commandBus.execute; map domain errors via filters.
Answer: Same as messaging—store processed event ids when handlers have side effects.
Answer: Long label PDF generation needs higher lockDuration; otherwise Bull reclaims and duplicates work.
Answer:
queue.add with repeat cron; ensure only one Nest instance adds repeatable config at bootstrap.
Answer:
Expose Bull metrics gauges; alert on growing waiting for tracking processors.
Answer:
ExtractJwt.fromExtractors([cookieExtractor, bearerExtractor]) for BFF cookie sessions.
Answer:
mTLS at mesh; JWT for user identity propagation (Authorization + original user claims).
Answer: Use argon2/bcrypt in AuthService; never log passwords; constant-time compare.
Answer: Subscribers couple to ORM lifecycle; prefer domain events for business side effects.
Answer:
Inject tenantId into queries via middleware—careful with raw queries bypassing it.
Answer: Expand/contract migrations; avoid destructive downs in prod without backup.
Answer: Provider/consumer contracts on Kafka payload schemas—catch breaking field renames.
Answer: For critical pricing logic yes; for thin controllers usually not.
Answer: Build two documents with different include/exclude controllers.
Answer: Publish OpenAPI artifact in CI; generate TypeScript SDK for shipper integrations.
Answer: Root configs with project references; enforce module boundaries (no deep relative imports across apps).
Answer: Affected-based pipelines; independent deploy for tracking-service vs quotes-api.
Answer: Custom indicator returns info (not fail) when secondary cache is down but primary DB ok.
Answer: Terminus MemoryHealthIndicator for liveness heuristics—tune thresholds carefully.
Answer: Abstraction over HTTP/RPC/WS/GraphQL handler context—used by guards/interceptors/filters.
Answer: ArgumentsHost is the base for filters; ExecutionContext extends it with handler/class metadata.
Answer:
Compose multiple decorators into one exported decorator (e.g., @Auth() = Jwt + Roles).
Answer: DI-only context without HTTP—useful for CLI scripts, cron workers, seeders.
Answer: CreateApplicationContext or dedicated microservice app importing processors—scale workers independently.
Answer:
app.setGlobalPrefix('api', { exclude: ['health'] }).
Answer:
app.use(helmet()) on Express; Fastify plugin equivalent—standard for public APIs.
Answer:
@nestjs/throttler guards, API gateway limits, or Redis token buckets for partner keys.
Answer: ThrottlerGuard keyed by API key/tenant; higher limits for premium partners.
Answer:
CacheModule.register + CACHE_MANAGER interceptors; Redis store for multi-instance quote caches.
Answer:
@Cron marks expired quotes; ensure single-leader or DB-safe updates under multi-pod.
Answer:
@nestjs/event-emitter simple in-process emitter; CQRS richer command/query separation.
Answer: Inject HttpService; set timeouts; map errors; wrap carrier clients; don’t leak axios types domain-wide.
Answer: Use opossum/cockatiel in CarrierClient provider; fallback to cached rates or omit carrier.
Answer:
Use Nest Logger or custom logger (Pino) with context; structured JSON in prod.
Answer: Custom logger provider implementing Nest logger interface; better perf/structured fields.
Answer: ParseUUIDPipe on params or middleware—prefer pipes for clear 400s.
Answer: Configure body size limits per adapter; virus scan async via queue.
Answer: Possible for BFF; many logistics APIs remain bearer-token stateless.
Answer: Configure trust proxy for accurate client IPs used in rate limits/audit.
Answer: Domain events → AuditInterceptor or event handler writing immutable audit rows.
Answer: 401 unauthenticated; 403 authenticated but forbidden—keep guards consistent.
Answer:
Filter returns application/problem+json with type/title/detail/status for partner APIs.
Answer: Gateway coarse limits/WAF; Nest fine-grained tenant quotas and business rules.
Answer: DTO lists accessorial codes; rate engine maps to carrier surcharges; validate carrier support.
Answer: Guard/validator ensures invoice docs present when origin/dest countries differ; else 422.
Answer: Tracking projector sorts by carrier event time + sequence; ignore stale older timestamps.
Answer: State machine: only allow cancel from certain statuses; notify carrier via async job; fee rules.
Answer: Idempotency by event id; if same id different hash, quarantine for manual review.
Answer: Cache hot lanes, Fastify adapter, horizontal pods, degrade to fewer carriers, queue noncritical work.
Answer: Retry with jitter in client; Bull job for async confirmation mode; user sees pending state.
Answer: Pipe/service ensures sum(parcel weights)=total; dimensional weight rules per carrier.
Answer: gRPC PredictEta; Tracking calls it; fallback heuristic if ML service unhealthy (Terminus).
Answer:
Kafka ShipmentException → Bull notification queue → provider adapters; user prefs in DB.
Answer: Embargo list in config/DB; filter carriers/lanes before calling out; audit decisions.
Answer:
New command with version check; may require re-quote; emit BookingAmended.
Answer: Upload to quarantine bucket; async scanner job; only then attach to tracking timeline.
Answer: Always filter by tenantId from auth context; add e2e IDOR tests; no trust client-sent tenant.
Answer:
Return 202 + bookingId when carrier confirm slow; client polls/subscribes to status.
Answer: Admin CLI using ApplicationContext republishes from DLT with new consumer code.
Answer: Lock FX rate at quote time store on quote; booking uses locked rate for billing consistency.
Answer: Move PDF generation to isolated worker queue with memory limits; stream to object storage.
Answer: Feature flag percentage traffic to v2 engine; compare prices; interceptor tags metrics by version.
Answer: Erasure service checks legal hold flag; anonymize non-essential fields only.
Answer: Controllers handle transport; services encapsulate business rules—easier testing and reuse across HTTP/RPC.
Answer: Ports as tokens/abstract classes; adapters as useClass providers; modules wire them.
Answer: No—map to response DTOs to avoid leaking persistence and over-fetching relations.
Answer: Domain entities/value objects or domain services—not only ValidationPipe (syntax vs business rules).
Answer: Avoid dumping everything into shared; only truly common types/events; prevent hidden coupling.
Answer:
Provide FeatureFlags service; guards/factories depend on it; cache flags with short TTL.
Answer:
Stable errorCode strings documented in Swagger; don’t break codes casually.
Answer:
correlationId, tenantId, bookingId, shipmentId, carrier—enable support debugging.
Answer: Same transaction writes business row + outbox row; relay polls/publishes to Kafka; marks sent.
Answer: Store inbound message id before side effects; skip duplicates—pairs with outbox producers.
Answer: CarrierAdapter translates weird carrier payloads into clean domain models inside Nest module.
Answer: Nest BFF aggregates quotes+tracking+user prefs; not a dump of internal microservices.
Answer:
Schema registry / explicit eventVersion field; consumers tolerate unknown fields.
Answer: Add optional fields; don’t rename/remove without version bump; contract tests.
Answer: Propagate tenant/user through async chains without request-scoping entire tree.
Answer: Factory functions returning decorated classes for reusable parameterized guards.
Answer: Stop readiness, stop consuming, drain HTTP, flush producers, close DB.
Answer: Readiness gates traffic; ensure migrations compatible with both versions during rolling.
Answer: Support multiple verify keys (JWKS); rotate sign key; short token TTL.
Answer: Auto-instrument HTTP/Prisma; propagate traceparent over Kafka headers.
Answer: Pass trace context in job/event headers; visualize in Jaeger/Tempo.
Answer: UUIDv5 from Idempotency-Key + tenant; unique constraint enforces once.
Answer: Cursor by (eventTime, id) for stable infinite scroll; offset ok for small admin lists.
Answer: Whitelist allowed sort columns to avoid SQL injection via raw order strings.
Answer: Return cached/partial results under shed load; hard 429 when abusive.
Answer: Aggregate specs or BFF-only public docs; internal services stay private.
Answer:
nest g resource scaffolds module/controller/service/DTO—customize to your architecture.
Answer: Don’t put all logic in services operating on bare data bags—use rich domain entities where complexity warrants.
Answer: Background job rewrites tenantIds with FK care; dual-read period; audit; invalidate tokens.
Answer: Adapter feature flag to v2; contract tests; monitor error rates; keep v1 fallback briefly.