Index of every page on this site: llms.txt
All skills
amirtaherkhani avatar

/nestjs-features-performance

@8272374
Run it yourself

Selects and implements NestJS runtime features, error and API contracts, security, testing, DevOps, performance, and safe scale. Use for middleware, guards, pipes, interceptors, exception filters, typed failures/results, Problem Details, validation errors, HTTP/GraphQL/RPC/gRPC/WebSocket error mapping, deadlines, cancellation, retry classification, fatal process errors, authentication, authorization, caching, queues, schedulers, CI/CD, containers, Kubernetes, configuration and secrets, migrations, supply-chain controls, health probes, logs/metrics/traces, SLOs and alerts, incident recovery, rollout and rollback, event-loop or database bottlenecks, load tests, horizontal scaling, idempotency, backpressure, and graceful shutdown. Do not use for frontend-only performance or non-NestJS services. When other skills also apply, reconcile ownership before mutation.

Use this Skill: https://skilld.dev/gh/amirtaherkhani/nestjs-skills/nestjs-features-performance

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesperformance-diagnosis.md

≈1.6k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Performance Diagnosis

Optimize the dominant constraint under a representative workload.

Define the experiment

Record:

  • route/message/job and payload distribution;
  • concurrency and arrival pattern;
  • warm-up and test duration;
  • data volume and cache state;
  • p50/p95/p99 latency, throughput, and errors;
  • CPU, event-loop delay/utilization, heap, GC, and RSS;
  • database query/pool/lock metrics;
  • external dependency spans;
  • queue depth, age, and processing duration.

Change one major variable at a time. Compare the same workload and environment.

Event loop and CPU

Node.js serves many clients with a small number of threads. A long synchronous callback delays unrelated requests and can become a denial-of-service vector when input controls its cost.

Inspect for:

  • synchronous filesystem/crypto/compression calls in request paths;
  • large JSON parse/stringify or validation;
  • unbounded loops, regex backtracking, sorting, and transformations;
  • image/PDF/media processing;
  • expensive logging or stack creation;
  • synchronous password hashing or encryption misuse.

Remedies:

  • bound input and algorithmic work;
  • use asynchronous APIs for I/O;
  • stream or partition large work where appropriate;
  • move CPU-heavy work to a pooled worker thread or separate worker process;
  • queue work when the result may be asynchronous and durable.

Worker threads help CPU-intensive JavaScript; they usually do not improve ordinary asynchronous I/O. Use a pool instead of spawning one worker per request.

Provider scope

Singleton is the default and preferred scope. Request-scoped providers are recreated for every request, and scope bubbles to their consumers.

Measure before using request scope broadly. Prefer explicit principals/context or an existing request-context mechanism when it keeps the graph singleton-safe. Never store per-request data in singleton fields.

Framework loading and lifecycle

Do not present lazy-loaded modules or lifecycle hooks as generic performance optimizations.

  • Lifecycle hooks coordinate initialization and shutdown correctness. Keep startup work bounded and observable, but optimize it only when startup measurements and deployment requirements identify a problem.
  • Nest lazy-loading support is useful for niche, optional dependency graphs. It adds wiring and first-use complexity and does not automatically reduce steady-state request latency or memory.
  • Dynamic imports, deferred initialization, and lazy modules can shift cost to the first request. Measure cold start, first-use latency, readiness, memory, and failure behavior before and after.
  • Avoid discovering dependencies at runtime merely to defer construction; preserve explicit provider contracts and verify the installed NestJS API.

Database

Database latency often dominates framework overhead.

Check:

  • N+1 query patterns;
  • missing or unused indexes for real predicates/order;
  • unbounded results and offset pagination at large depth;
  • overfetching wide rows/relations;
  • pool waits, leaked connections, and mismatched pool size;
  • long transactions and lock contention;
  • read-then-write races and missing constraints;
  • repeated counts/aggregations on hot paths.

Use query plans and production-like data. An index accelerates some reads while adding write/storage cost; do not add one from column names alone.

Keep external network calls outside database transactions whenever correctness permits.

External calls

  • Set a deadline/timeout for every dependency call.
  • Reuse connections/agents according to the client library.
  • Propagate cancellation where supported.
  • Retry only transient, safe operations within a total time budget.
  • Bound concurrency to protect both systems.
  • Use circuit breaking or load shedding only with explicit recovery behavior.

Parallelize independent calls only when it reduces latency without overwhelming downstream capacity.

Memory and payloads

Look for retained request data, unbounded maps/listeners, large buffers, ORM relation graphs, and full in-memory exports.

Use heap snapshots/allocation profiling to identify retainers. Stream or page large data; remove listeners/timers; bound caches. Increasing the heap may delay failure but does not repair a leak.

Caching

Cache only after identifying repeated expensive work and acceptable staleness. Measure hit ratio, load time, eviction, memory, and origin impact.

Protect against stampedes with single-flight/locking, early refresh, or jittered TTL where appropriate. Include tenant, locale, permissions, and representation in keys when they change the result.

Express versus Fastify

Fastify can improve HTTP-layer throughput, but application latency may be dominated by database or network work. Before migration:

  1. profile and isolate HTTP adapter overhead;
  2. inventory Express-specific middleware and response APIs;
  3. benchmark representative routes, validation, serialization, and logging;
  4. run all transport/e2e tests;
  5. verify deployment binding and proxy behavior.

Do not quote generic framework benchmarks as proof for this application.

Logging and observability overhead

Use structured logs with appropriate levels and redaction. Avoid serializing complete bodies, ORM entities, buffers, or stack traces on every successful request. Sample high-volume traces deliberately while retaining errors and critical transactions.

Result format

Baseline: workload + p95/p99 + throughput + errors
Bottleneck: evidence and dominant span/resource
Change: one intervention
Result: same metrics after change
Correctness: tests and failure behavior
Capacity: new saturation point and next limiting dependency

See Node.js guidance on event-loop safety and worker threads, plus NestJS guidance on injection scope and Fastify.

Runnable runtime contracts

The runtime suite in examples/runtime-contracts/ (run npm run test:runtime from the source repository) checks a bounded single-value cache, query projection/limit requests, awaited lifecycle work and real lazy-module reuse. It records failure and scope limitations without timing thresholds. A fake query adapter does not prove an SQL plan; lazy provider construction does not prove deferred JavaScript loading or a startup speedup. Keep actual database and production load evidence separate from these deterministic contracts.

Source: SKILL.md on GitHub

No rule matched.

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

1 warning3d3 checks · Risk SAFE
  • Gen Agent Trust Hub4d

    This skill provides extensive architectural, operational, and security guidance for developing and scaling NestJS applications. It contains best practices for error handling, performance diagnosis, CI/CD, and deployment. No malicious behavior or security risks were identified.

  • Socket3d

    No alerts

  • Snyk4d

    Risk: MEDIUM · 1 issue

Signed by skilld at 8272374. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 4 days ago.

Activeupdated 5 days ago
metadata
{
  "author": "amirtaherkhani",
  "version": "1.5.0"
}

README badge

README badge for amirtaherkhani/nestjs-skills/nestjs-features-performance