NestJS Features, Scaling, and Performance
Choose the NestJS primitive whose lifecycle matches the concern. Diagnose the limiting resource before optimizing or distributing the system.
Pre-execution conflict guard
Run this guard after identifying every applicable skill and before editing files, installing packages, generating code, changing infrastructure, or executing any other state-changing command. Read-only repository and runtime inspection is allowed while resolving the guard.
Prerequisites
- Read repository instructions, installed versions, bootstrap and transport setup, deployment configuration, relevant tests, and the coordination contract of every other active skill.
- Identify the requested runtime outcome, public and operational contracts, baseline evidence, and the files, environments, and commands likely to be affected.
- Do not choose a framework feature, dependency, optimization, or deployment action before its lifecycle and evidence requirements are known.
Primary ownership
This skill leads decisions about NestJS lifecycle features, API and transport contracts, error mapping, security controls, test-layer selection, queues and schedulers, runtime reliability, observability, performance evidence, CI/CD, containers, Kubernetes, rollout, and recovery.
It shares provider/module placement with nestjs-architecture-principles and shares collaborator design with nestjs-oop-design-patterns. It yields capability, data/write, transaction, dependency, and service boundaries to the architecture skill. It yields local object responsibilities, invariant placement, and design-pattern selection to the OOP skill.
For a whole-repository review, nestjs-code-audit owns read-only evidence collection, deduplication, and report assembly while this skill remains the primary owner of runtime, security, testing, performance, and delivery findings.
For a roadmap-scoped review, nestjs-feature-audit owns target-branch preparation, roadmap traceability, status classification, and report assembly while this skill remains the primary owner of runtime, security, testing, performance, and delivery judgments.
For implementation, nestjs-professional-software-engineering coordinates project inspection, syntax selection, coding, and verification while this skill remains the primary owner of NestJS runtime, security, reliability, performance, and delivery decisions.
nestjs-git-commit-pr-message owns Git publication and CI/Pages follow-up after verification; this skill retains runtime deployment and production-readiness ownership.
Conflict test
A conflict exists when active skills would:
- change the same file or contract toward incompatible outcomes;
- require commands whose order, target environment, or side effects cannot both be satisfied;
- claim primary ownership of the same decision without a clear handoff; or
- proceed without another skill's prerequisite, repository constraint, runtime evidence, or required authorization.
Resolve conflicts in this order: explicit user intent, repository contracts and verified runtime constraints, then the narrowest primary owner above. Assign one lead skill per disputed decision; other skills may advise only within that boundary. For example, the architecture skill owns transaction and partial-effect boundaries, while this skill owns HTTP, message, and worker failure mapping plus retry behavior around them.
If the conflict remains material, stop before mutation and ask for clarification. Report the conflicting instructions, affected files, commands, or environments, why both cannot be satisfied, and the smallest safe choices. Never deploy, migrate, install, or optimize merely because one skill requests it when another applicable constraint makes that action unsafe.
Establish the runtime baseline
Before recommending or changing behavior:
- Read the installed NestJS/Node versions, bootstrap code, adapter, modules, transports, persistence clients, cache/queue setup, and deployment manifests.
- Trace one representative request, message, or job through guards, pipes, interceptors, handlers, providers, persistence, and external calls.
- Identify the current symptom and evidence: latency percentiles, throughput, error rate, event-loop delay, CPU, heap/GC, database time, pool saturation, external latency, or queue lag.
- Define a target and workload. "Make it faster" is not a measurable acceptance criterion.
- Check framework and library APIs against official documentation and the repository version.
Never claim a performance improvement from code appearance. Measure before and after under a representative workload.
Put behavior in the correct NestJS feature
Use references/feature-selection.md.
General HTTP lifecycle:
request
-> middleware
-> guards
-> interceptors (before)
-> pipes
-> controller/resolver + providers
-> interceptors (after, reverse order)
-> exception filters for uncaught errors
-> responseDefaults:
- Middleware: raw protocol preprocessing and correlation context.
- Guard: authentication/authorization decision for an execution context.
- Pipe: input validation and transformation.
- Interceptor: behavior around handler execution, response mapping, timing, tracing, or compatible caching.
- Exception filter: final protocol-specific error mapping.
- Decorator: declarative metadata or extraction of established context, not hidden I/O.
- Provider/application operation: business behavior and orchestration.
- Queue/worker: durable, deferred, bursty, or resource-heavy work.
- Event: a completed fact with independent reactions; choose in-process versus durable delivery explicitly.
For API and transport guidance, load references/api-runtime.md. Use the focused rulebooks for error handling, security, testing, API design, and deployment when those risks are in scope.
Diagnose performance by resource
Use references/performance-diagnosis.md.
Classify the primary constraint before selecting a remedy:
| Constraint | Evidence | Typical first moves |
|---|---|---|
| Event-loop blocking | High event-loop delay/utilization, CPU callback hotspots | Remove synchronous work; bound input; offload CPU work |
| Database | Slow queries, N+1, pool waits, locks, high rows scanned | Fix query shape/indexes; bound results; shorten transactions |
| External I/O | Dependency spans dominate latency | Deadlines, connection reuse, bounded retry, concurrency control |
| Memory/GC | Heap growth, GC pauses, OOM/restarts | Remove retention; stream/bound data; profile allocations |
| Serialization/logging | CPU or payload size grows with response | Select fields; paginate/stream; reduce hot-path logging |
| Capacity | Stable per-instance performance but saturated replicas | Horizontal scale with stateless processes and safe dependencies |
Do not switch to Fastify, add Redis, introduce worker threads, or split services before evidence identifies the bottleneck and compatibility cost is understood.
Scaling rules
Use references/scaling-reliability.md.
- Keep web replicas stateless; move shared sessions, locks, job state, and coordination to appropriate external systems.
- Prefer default singleton providers. Request scope propagates through the injection chain and adds per-request allocation; use only for a real lifetime requirement.
- Bound every collection, page, batch, queue concurrency, retry count, payload, upload, and timeout.
- Make jobs and message consumers idempotent. Assume duplicate delivery and partial failure.
- Use exponential backoff with jitter for transient failures; never blindly retry validation, authorization, or invariant errors.
- Add backpressure. Reject, shed, pause, or queue load instead of allowing unbounded memory and latency growth.
- Separate user-facing processes from CPU-heavy or slow background work when their capacity profiles differ.
- Treat caches as derived state. Define key namespace, TTL, invalidation, stampede behavior, and safe fallback.
- Drain before shutdown: stop accepting work, mark unready, finish or safely requeue in-flight work, then close resources.
- Scale from service-level objectives and saturation signals, not average CPU alone.
Implementation workflow
Add or change a feature
- Locate the correct lifecycle stage and existing repository convention.
- Define the contract, scope, and failure behavior.
- Implement the smallest provider/component and bind it at the narrowest useful level.
- Test its behavior in isolation and its ordering/wiring at a boundary.
- Update OpenAPI/schema, configuration validation, telemetry, and docs when the public or operational contract changes.
Design or repair error handling
- Inventory every entry point, current public error contract, filter binding, adapter/vendor error, client dependency, and partial side effect.
- Classify expected business, validation, identity/access, conflict, transient, permanent, cancellation/timeout, and unknown failures without parsing messages.
- Define the application-owned type/result and translate vendor failures at infrastructure adapters while preserving a safe cause.
- Map each HTTP, GraphQL, RPC/gRPC, WebSocket, or worker boundary independently; keep one non-sensitive unknown fallback.
- Define deadlines, cancellation, retry/idempotency, acknowledgement, transaction, and unknown-outcome behavior before adding recovery logic.
- Bind the narrowest correct NestJS filter/handler and verify hybrid, gateway, adapter, stream, and process-fatal paths as applicable.
- Test the stable contract, side effects, observability ownership, sensitive-data absence, and restart/recovery behavior.
Optimize a slow path
- Reproduce with a controlled benchmark or trace.
- Record baseline percentiles, throughput, errors, and resource saturation.
- Profile the dominant path.
- Change one limiting factor.
- Repeat the same workload and compare.
- Run correctness and failure tests; faster incorrect behavior is a regression.
- Document the capacity limit and rollback signal.
Plan scale
- Define workload shape, SLO, consistency, durability, and cost constraints.
- Estimate per-instance capacity and identify shared dependency limits.
- Choose vertical tuning, replicas, workers, queues, partitions, or service extraction based on the actual resource boundary.
- Design overload and partial-failure behavior before adding capacity.
- Prove the plan with load, soak, spike, and failure tests appropriate to the risk.
Build, deploy, or diagnose production
- Identify the source revision, immutable artifact/image digest, target environment, and owner.
- Compare repository intent, built artifact, desired deployment, and running state; do not infer live state from configuration files alone.
- Define migration/configuration compatibility, rollout strategy, success signals, abort threshold, and rollback or forward-repair path.
- Apply the smallest authorized change through the repository's delivery mechanism.
- Verify live revision, readiness, representative traffic/work, errors, latency, saturation, queues/dependencies, and drain behavior.
- Record the release or incident evidence and reconcile any emergency drift back into declared state.
Production gate
Use references/production-readiness.md before calling a feature production-ready. At minimum verify configuration, security, contracts, resource bounds, observability, health/readiness, shutdown, and recovery.
Reference routing
| Task | Load |
|---|---|
| Pick middleware, guard, pipe, interceptor, filter, decorator, event, queue, or scheduler | feature-selection.md |
| Build HTTP/GraphQL/WebSocket/SSE/microservice contracts and tests | api-runtime.md |
| Classify failures, map stable errors, or design filters and retries | error-handling.md |
| Define typed errors/results, public codes, validation shape, Problem Details, or HTTP semantics | error-taxonomy-contracts.md |
| Implement filters across HTTP, GraphQL, RPC/gRPC, WebSocket, workers, or hybrid apps | exception-filters-transports.md |
| Design deadlines, cancellation, safe retries, fatal-process handling, telemetry, or failure tests | failure-resilience-testing.md |
| Review authentication, authorization, validation, secrets, output, or abuse controls | security.md |
| Choose unit, module, integration, contract, E2E, or reliability tests | testing.md |
| Design DTOs, responses, errors, pagination, idempotency, or versioning | api-design.md |
| Diagnose latency, CPU, event loop, database, memory, cache, or Fastify choices | performance-diagnosis.md |
| Add replicas, workers, queues, retries, idempotency, backpressure, or distributed coordination | scaling-reliability.md |
| Design build, configuration, migration, health, observability, rollout, or shutdown controls | devops-deployment.md |
| Build CI/CD, container images, provenance, promotion, or artifact rollback | ci-cd-containers.md |
| Configure or diagnose Kubernetes workloads, probes, resources, HPA, rollout, or termination | kubernetes-operations.md |
| Define SLOs, logs/metrics/traces, alerts, dashboards, incidents, backups, or recovery | observability-sre.md |
| Review operational readiness and rollout safety | production-readiness.md |
Expected response
For performance/scaling work, report:
- Symptom and target
- Baseline evidence
- Primary constraint
- Recommended change and trade-off
- Correctness/failure risks
- Before/after verification plan
If evidence is missing, propose the smallest measurement needed before an architectural change.
For Error Handling work, report:
- Failure model: categories, stable codes/types, and expected versus unknown behavior.
- Boundary mapping: application-to-transport mapping for every affected entry point.
- Effects and resilience: committed/possible side effects, deadline, cancellation, retry/idempotency, and recovery ownership.
- Disclosure: public fields, redaction, logging ownership, and sensitive-data controls.
- Framework wiring: filter/handler scope, execution context, adapter/hybrid coverage, and fatal-process behavior.
- Verification: contract, adapter, timeout, duplicate, partial-effect, privacy, and restart tests.
For DevOps work, report:
- Release identity: source revision, artifact/digest, environment, and owner.
- State comparison: repository intent, desired deployment, and observed runtime.
- Safety: migrations/configuration compatibility, security gates, and failure risks.
- Rollout: strategy, success/abort signals, observation window, and capacity impact.
- Verification: live revision, health, representative work, telemetry, and drain.
- Recovery: rollback or forward-repair procedure and trigger.
Canonical source: skills/nestjs-features-performance/SKILL.md. This page is generated during the documentation build.