NestJS Senior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. How does Nest know what to inject into
constructor(private users: UsersService)?Correct answer: It reads
design:paramtypesmetadataThat's why type-only imports (
import type) or interfaces break injection: there is no runtime value to use as a token.2. Why can a bundler or compiler without decorator metadata support break a Nest app?
Correct answer: Without
design:paramtypes, types can't be resolvedesbuild, for example, doesn't emit decorator metadata. SWC supports it with the right config, which is why Nest documents an SWC setup.
3. How is the DI container organized across modules?
Correct answer: Each module has its own scope, shared via exports
This encapsulation is why the same class listed in two modules' providers results in two instances.
4. A REQUEST-scoped provider is injected into a singleton service. What happens?
Correct answer: The whole chain becomes request-scoped
Scope bubbles up. In a busy app this can multiply allocations per request; durable providers or ALS are alternatives for multi-tenancy.
5. What are durable providers for?
Correct answer: Caching request-scoped subtrees per tenant
You map each request to a tenant context ID, so tenant-specific providers (like a tenant DB connection) are reused across that tenant's requests.
6. How do you inject the current request into a provider, and what does it cost?
Correct answer: Inject
REQUEST; dependents become request-scopedIn GraphQL the request lives in the context (
CONTEXT). For most needs, ALS gives per-request data without scope changes.7. How can you discover all providers with a custom decorator at startup, e.g. to register event handlers automatically?
Correct answer: With
DiscoveryServiceandcreateDecoratorLibraries like
@nestjs/cqrsand@nestjs/scheduleuse the same scanning mechanism.8. How does
ConfigurableModuleBuilderhelp when writing a reusable dynamic module?Correct answer: It generates
registermethods and an options tokenWriting
forRootAsyncwithuseFactory,useClassanduseExistingby hand is repetitive; the builder handles it consistently.9. Why can
forwardRefhide a design problem even when it fixes the error?Correct answer: A cycle means two parts depend on each other's internals
Typical fixes: extract shared logic into a third module, invert the dependency with events, or depend on an abstraction.
10. Why might an injected value be
undefinedinside a constructor but defined later, with circular dependencies?Correct answer: With
forwardRef, one side may not be ready yetAvoid doing work in constructors that depends on other providers' state.
11. Where does Nest's overhead usually matter, and where doesn't it?
Correct answer: It's small next to I/O, but scoped chains add up
Profile before optimizing. Switching to Fastify, avoiding request scope and using schema-based serialization are common wins.
12. Why can
class-transformerserialization become a bottleneck for large responses?Correct answer: It walks every object using reflection
Measure with realistic payloads. Pagination also limits the cost.
13. How do you reduce cold-start time of a Nest app on serverless platforms?
Correct answer: Bundle the app and cache the bootstrapped instance
Initialization (module scanning, DI graph, DB connections) dominates cold starts. Reuse the app across warm invocations.
14. Why is SWC often used in Nest development?
Correct answer: It compiles TypeScript much faster than
tscUse
nest start -b swc --type-checkto keep type errors visible while getting fast rebuilds.15. In Nest microservices over Kafka, what must handlers be prepared for?
Correct answer: At-least-once delivery, so they must be idempotent
Choose message keys so related events go to the same partition, and commit offsets only after successful processing.
16. Why can request-response (
client.send) between microservices be risky at scale?Correct answer: It couples services in time, so failures cascade
Prefer events for notifications and keep synchronous calls for queries that truly need an immediate answer. Always set
timeout()on the Observable.17. How do you get reliable event publishing from a Nest service that also writes to the database?
Correct answer: Use a transactional outbox
Emitting outside the transaction can lose or duplicate events if either step fails.
18. What does the gRPC transport in Nest rely on?
Correct answer:
.protofiles bound with@GrpcMethod()Protobuf contracts give typed, compact messages and streaming. Changes must stay backward compatible (don't reuse field numbers).
19. How do you propagate a trace or correlation ID across Nest microservices?
Correct answer: Put it in message metadata, then store it in ALS
Consistent propagation lets you follow one user action through HTTP calls, queues and workers.
20. How would you structure a large Nest codebase to keep boundaries clear?
Correct answer: Feature modules with explicit exports
Keeping domain code free of framework decorators makes it testable and portable. Lint rules can forbid imports across module boundaries.
21. What does hexagonal (ports and adapters) architecture look like in Nest?
Correct answer: The domain depends on ports; adapters implement them
Swapping adapters in tests or migrations becomes a module configuration change, not a rewrite.
22. When does
@nestjs/cqrspay off?Correct answer: In complex domains with distinct models
CQRS adds indirection. For simple resources it hides straightforward logic behind buses and handlers.
23. How do you keep transactions consistent across several services in one request without passing a transaction object everywhere?
Correct answer: Store the transaction in ALS for repositories
ALS keeps the transaction bound to the async flow of the request, so nested service calls join it.
24. How would you implement multi-tenancy with a database per tenant in Nest?
Correct answer: Resolve the tenant, then give it its own connection
Cache connections per tenant and limit pool sizes, or the total number of DB connections explodes.
25. What's a risk of putting authorization logic only in guards?
Correct answer: Guards often lack the loaded resource
Combine route-level guards (who may call this?) with checks in the domain layer (may this user touch this object?).
26. Why is it useful to have the same validation and authorization for HTTP, GraphQL and message handlers?
Correct answer: Each entry point is a door into the system
Guards and pipes can be written to work with any
ExecutionContexttype, or rules can live in services.27. How should a Nest app shut down in Kubernetes to avoid dropped requests?
Correct answer: Fail readiness, finish in-flight work, then close
Enable shutdown hooks; also set keep-alive timeouts correctly behind load balancers.
28. What should a readiness check in Nest verify, and what should liveness avoid?
Correct answer: Readiness checks dependencies; liveness avoids them
A database outage that restarts all pods makes recovery worse. Liveness answers only 'is this process stuck?'.
29. How do you make outbound HTTP calls from Nest resilient?
Correct answer: Timeouts, backoff retries and circuit breaking
RxJS operators (
timeout,retrywith delay) work well withHttpService; libraries likecockatieladd circuit breakers.30. What problem can a global
@Croncause in a scaled Nest deployment, and how do you solve it?Correct answer: Every replica runs the job; use a lock or a queue
Jobs should also be idempotent, because locks can expire and runs can overlap.
31. How should BullMQ workers in Nest be deployed under load?
Correct answer: As separate processes, scaled by queue depth
Separating workers keeps slow jobs from hurting API latency and lets each part scale on its own metric.
32. Why should errors in event handlers (
@OnEvent) be handled carefully?Correct answer: They run in-process, with no retry on failure
For important side effects, emit to a queue instead of relying on in-memory events.
33. How do you add distributed tracing to a Nest app?
Correct answer: Initialize OpenTelemetry before Nest loads
Instrumentation must patch modules before they're required, which is why it runs first.
34. How do you make Nest's logs structured and correlated?
Correct answer: Replace the logger, e.g. with
nestjs-pinoNestFactory.create(AppModule, { bufferLogs: true })thenapp.useLogger(...)captures logs from the bootstrap phase too.35. How can you test a module that uses a request-scoped provider?
Correct answer: With
moduleRef.resolve()and a context IDYou can also register a request object for that context ID with
moduleRef.registerRequestByContextId().36. What's a good strategy for testing a Nest app's database layer in CI?
Correct answer: Real PostgreSQL in Docker with migrations applied
This catches migration errors, constraints and query bugs that mocks would hide.
37. How do you test that guards, pipes and filters are wired correctly for a route?
Correct answer: With e2e tests through the HTTP layer
Unit tests of a controller method skip the enhancers, so wiring bugs only show up in HTTP-level tests.
38. How do you protect a Nest GraphQL API from very expensive queries?
Correct answer: Limit query depth and complexity
One GraphQL request can ask for huge nested data; per-request cost limits complement rate limiting.
39. Why must DataLoader instances be created per request in a Nest GraphQL app?
Correct answer: Its cache would leak data between users
Create loaders in the GraphQL context factory or a request-scoped provider.
40. What does Apollo Federation (supported by Nest's GraphQL module) allow?
Correct answer: Composing one schema from several subgraphs
A gateway or router composes subgraphs. It suits several teams owning separate domains behind one API.
41. Which settings make a Nest API safer by default?
Correct answer: Strict
ValidationPipe, Helmet and deny-by-default authDeny-by-default means every route requires auth unless explicitly marked public.
42. How do you prevent mass assignment when updating entities in Nest?
Correct answer: Accept a DTO of allowed fields; copy them explicitly
TypeScript types don't exist at runtime; only validation and explicit mapping stop extra fields.
43. Why should secrets not be logged by Nest's default exception or request logging?
Correct answer: Bodies and headers can contain passwords and tokens
Pino's
redactoption removes paths likereq.headers.authorizationbefore writing logs.44. How do you safely handle file uploads at scale in Nest?
Correct answer: Limit size and type, stream to object storage
Presigned uploads move heavy traffic away from the API; the API only records metadata and verifies the result.
45. What's a sensible approach to upgrading a large Nest app to a new major version?
Correct answer: Follow the migration guide, upgrade all packages together
Mismatched
@nestjs/*versions cause subtle DI and type errors. Keep them aligned.46. Why might a team choose Nest over a minimal framework like Fastify alone?
Correct answer: Conventions, DI and modules for large teams
For small services, a minimal framework may be simpler. For many developers and features, Nest's structure pays off.
47. How can you share DTOs and validation between a Nest backend and a TypeScript front end?
Correct answer: With a shared package or a generated OpenAPI client
Generated or shared contracts catch breaking API changes at compile time.
48. What's a concern with exposing Swagger UI in production?
Correct answer: It reveals the full surface of the API
Internal endpoints listed in the docs make attackers' reconnaissance easier.
49. How can one interceptor implement idempotency keys for POST endpoints?
Correct answer: Check the key, lock it, then store the result
Store keys in Redis or the database with the request hash; handle concurrent requests with the same key via a lock.
50. How would you implement response caching that varies by user in Nest?
Correct answer: Extend
CacheInterceptorand overridetrackBy()The default key is based on the URL. Caching personalized responses under a shared key leaks data.
51. How can you implement API versioning without duplicating whole controllers?
Correct answer: Version only the changed routes with
@VersionVERSION_NEUTRALroutes serve all versions; only routes whose contract changed need a new version.52. What's a pitfall of
@Res()withoutpassthroughin interceptors and filters?Correct answer: The handler bypasses Nest's response handling
Streaming downloads are a valid reason to use
@Res(); otherwise prefer returning values orStreamableFile.53. How do you stream a large file download in Nest without loading it into memory?
Correct answer: Return a
StreamableFilewrapping a readable streamStreamableFileworks with both Express and Fastify and keeps interceptors working.54. What's the difference between
onModuleInitandonApplicationBootstrap?Correct answer:
onApplicationBootstrapruns after all modules initUse
onApplicationBootstrapfor work that needs the whole app, like warming caches that use several modules.55. Why do lifecycle hooks not run for request-scoped or transient providers in the usual way?
Correct answer: They're created per request, not during bootstrap
Put initialization that must run once into singleton providers.
56. What happens to global enhancers in a hybrid app's microservice part by default?
Correct answer: Not applied without
inheritAppConfig: trueThis surprises teams that rely on a global
ValidationPipefor message payloads too.57. How do you write a guard that works for HTTP and GraphQL?
Correct answer: Check
context.getType()and useGqlExecutionContextAuthGuardfrom Passport also needsgetRequest()overridden for GraphQL.58. What's the effect of throwing inside an interceptor's
mapoperator?Correct answer: It reaches the exception filters
Use
catchErrorin interceptors to map errors, e.g. converting domain errors into HTTP exceptions.59. Why should long CPU-bound work not run in a Nest request handler?
Correct answer: CPU work blocks the one event loop for all requests
Watch event loop delay; a single slow handler raises latency for everyone.
60. How can you enforce module boundaries automatically in a Nest monorepo?
Correct answer: With lint rules on imports, e.g. dependency-cruiser
TypeScript lets any file import any other; tooling keeps the intended architecture from eroding.
61. Why is it a good idea to separate the Nest app bootstrap (
main.ts) from app configuration (e.g. aconfigureApp(app)function)?Correct answer: Tests can reuse the same configuration
Or register enhancers through
APP_*providers so they're part of the module graph.62. How can Nest's
ValidationPipeerrors be made more useful to API clients?Correct answer: Use
exceptionFactoryfor field-level errorsStable error shapes let front ends show messages next to the right fields.
63. What does
app.useGlobalInterceptors()NOT give you compared toAPP_INTERCEPTOR?Correct answer: Dependency injection into the interceptor
Instances passed to
useGlobal*are created outside the container.64. How would you implement soft-delete filtering globally with TypeORM in Nest?
Correct answer: With
@DeleteDateColumnandsoftDeleteUnique constraints still need care (partial indexes), and raw queries don't apply the filter automatically.
65. Why can
@nestjs/event-emitterhandlers run before the database transaction commits?Correct answer: Events inside a transaction fire immediately
Emit after commit, or write to an outbox in the same transaction and process it afterwards.
66. What does
onApplicationShutdown(signal)receive and why is it useful?Correct answer: The signal that triggered the shutdown
It runs after connections are closed by the HTTP server, as the last chance to flush logs or metrics.
67. How do you limit the impact of a slow downstream service on a Nest API's thread of execution?
Correct answer: Bound concurrent calls per dependency (bulkhead)
Without limits, waiting calls accumulate memory and sockets until the whole service degrades.
68. Why should controller tests not be the only tests for authorization rules?
Correct answer: Only HTTP-level tests show the real status codes
Write a few e2e tests per protected resource: no token, wrong user, right user.
69. What does
useMocker()on a testing module builder help with?Correct answer: Auto-creating mocks for unprovided dependencies
Combine it with a mocking library factory (e.g.
jest-mock-extendedor@golevelup/ts-jest) and override only what the test cares about.70. How can Nest consume messages from a broker it has no built-in transport for, like AWS SQS?
Correct answer: With a custom
CustomTransportStrategytransporterCommunity packages exist for SQS, Pub/Sub and others. A custom strategy keeps handler code transport-agnostic.
71. Why should domain services throw domain errors rather than
HttpExceptions?Correct answer: Domain code is reused beyond HTTP
A
UserNotFoundErrorbecomes 404 in HTTP,NOT_FOUNDin GraphQL, and a non-retryable failure in a queue.72. How do you rate limit per authenticated user instead of per IP with
@nestjs/throttler?Correct answer: Extend
ThrottlerGuardand overridegetTracker()Many users behind one corporate NAT share an IP; per-user limits are fairer for authenticated APIs.
73. How do you broadcast WebSocket messages across several Nest instances?
Correct answer: With a shared-channel adapter, e.g. Socket.IO Redis
A custom
IoAdaptersubclass can create the Redis adapter and be set withapp.useWebSocketAdapter().74. What is a Backend for Frontend (BFF) and how might Nest implement it?
Correct answer: A backend tailored to one client type
Each client gets the API shape it needs without forcing every internal service to serve every client's format.
75. Why may a global
ClassSerializerInterceptornot hide fields when you return results from Prisma?Correct answer: Prisma returns plain objects, not class instances
With Prisma,
selectoromitin the query is the most reliable way to never fetch sensitive fields.