nestjs-performance

$npx mdskill add HoangNguyen0403/agent-skills-standard/nestjs-performance

1. **Switch to Fastify** — Replace Express with `FastifyAdapter` for ~2x throughput. 2. **Enable compression** — Add Gzip/Brotli middleware. 3. **Audit provider scopes** — Ensure no unintended `REQUEST` scope chains. 4. **Add query projections** — Use `select: []` on all repository queries. 5. **Profile overhead** — Benchmark Total Duration, DB Execution, and API Overhead.

SKILL.md

.github/skills/nestjs-performanceView on GitHub ↗
---
name: nestjs-performance
description: Optimize NestJS throughput with Fastify adapter, singleton scope enforcement, compression, and query projections. Use when switching to Fastify, diagnosing request-scoped bottlenecks, or profiling API overhead.
metadata:
  triggers:
    files:
    - 'main.ts'
    keywords:
    - FastifyAdapter
    - compression
    - SINGLETON
    - REQUEST scope
---
# Performance Tuning

## **Priority: P1 (OPERATIONAL)**


## Workflow: Performance Audit

1. **Switch to Fastify** — Replace Express with `FastifyAdapter` for ~2x throughput.
2. **Enable compression** — Add Gzip/Brotli middleware.
3. **Audit provider scopes** — Ensure no unintended `REQUEST` scope chains.
4. **Add query projections** — Use `select: []` on all repository queries.
5. **Profile overhead** — Benchmark Total Duration, DB Execution, and API Overhead.

## Fastify + Compression Setup

See [implementation examples](references/example.md)

- **Keep-Alive**: Configure `http.Agent` keep-alive settings to reuse TCP connections for upstream services.

## Scope & Dependency Injection

- **Default Scope**: Adhere to `SINGLETON` scope (default).
- **Request Scope**: AVOID `REQUEST` scope unless absolutely necessary.
 - **Pro Tip**: single request-scoped service makes its entire injection chain request-scoped.
 - **Solution**: Use **Durable Providers** (`durable: true`) for multi-tenancy.
- **Lazy Loading**: Use `LazyModuleLoader` for heavyweight modules (e.g., Admin panels).

## Caching Strategy

- **Application Cache**: Use `@nestjs/cache-manager` for computation results.
 - **Deep Dive**: See **[Caching & Redis](../nestjs-caching/SKILL.md)** for L1/L2 strategies and Invalidation patterns.
- **HTTP Cache**: Set `Cache-Control` headers for client-side caching (CDN/Browser).
- **Distributed**: In microservices, use Redis store, not memory store.

## Queues & Async Processing

- **Offloading**: Never block HTTP request for long-running tasks (Emails, Reports, webhooks).
- **Tool**: Use `@nestjs/bull` (BullMQ) or RabbitMQ (`@nestjs/microservices`).
 - **Pattern**: Producer (Controller) -> Queue -> Consumer (Processor).

## Serialization

- **Warning**: `class-transformer` CPU expensive.
- **Optimization**: For high-throughput READ endpoints, consider manual mapping or using `fast-json-stringify` (built-in fastify serialization) instead of interceptors.

## Database Tuning

- **Projections**: Always use `select: []` to fetch only needed columns.
- **N+1**: Prevent N+1 queries by using `relations` carefully or `DataLoader` for Graph/Field resolvers.
- **Connection Pooling**: Configure pool size (e.g., `pool: { min: 2, max: 10 }`) in config to match DB limits.

## Profiling & Scaling

- **API Overhead vs DB Execution**: Use "Execution Bucket" strategy to continuously benchmark `Total Duration`, `DB Execution Time`, and `API Overhead`.
 - **Total Baseline**: Excellent (< 50ms), Acceptable (< 200ms), Poor (> 500ms). _Exception: Authentication routes (e.g. bcrypt/argon2) should take 300-500ms intentionally._
 - **DB Execution Baseline**: Excellent (< 5ms), Acceptable (< 30ms), Poor (> 100ms - implies missing index or N+1 problem).
 - **API Overhead Baseline**: Excellent (< 20ms), Poor (> 100ms - implies heavy synchronous processing or serialization blocking Node's event loop).
- **Offloading**: Move CPU-heavy tasks (Image processing, Crypto) to `worker_threads`.
- **Clustering**: For non-containerized environments, use `ClusterModule` to utilize all CPU cores. In K8s, prefer ReplicaSets.


## Anti-Patterns

- **No REQUEST scope without evaluation**: One REQUEST-scoped provider makes entire chain request-scoped.
- **No CPU tasks in HTTP handler**: Offload image/crypto work to `worker_threads` or BullMQ.
- **No unprojected queries**: Always `select: []` needed columns to avoid serializing unused data.

More from HoangNguyen0403/agent-skills-standard

SkillDescription
android-agp-upgradeUpgrade an Android project to Android Gradle Plugin (AGP) 9. Use when migrating to AGP 9, updating Gradle build files, migrating to built-in Kotlin, or adopting the new AGP DSL.
android-architectureApply Clean Architecture layering, modularization, and Unidirectional Data Flow in Android projects. Use when setting up project structure, placing code in layers, configuring feature/core modules, or implementing UDF patterns.
android-background-workImplement WorkManager and background processing correctly on Android. Use when creating Worker classes, scheduling tasks, choosing between WorkManager and Foreground Services, or setting up Hilt in workers.
android-composeBuild high-performance declarative UI with Jetpack Compose. Use when writing Composable functions, optimizing recomposition, hoisting state, or working with LazyColumn and side effects.
android-compose-migrationMigrate an Android XML View to Jetpack Compose following a structured 10-step workflow. Use when converting XML layouts to Compose, setting up Compose in an existing View-based project, or incrementally adopting Compose.
android-concurrencyWrite correct coroutine scopes, Flow collection, and dispatcher injection in Android. Use when writing suspend functions, choosing between StateFlow and SharedFlow, or injecting Dispatchers for testability.
android-deploymentConfigure release signing, R8 obfuscation, and App Bundle publishing for Android. Use when setting up signing configs, enabling minification, adding ProGuard keep rules, or preparing for Play Store submission.
android-design-systemEnforce Material Design 3 theming and design token usage in Jetpack Compose. Use when implementing M3 components, color schemes, typography, or design tokens.
android-diConfigure Hilt dependency injection with proper scoping, modules, and constructor injection in Android. Use when setting up Hilt DI, defining modules, or configuring component scoping.
android-edge-to-edgeMigrate a Jetpack Compose app to edge-to-edge display and fix system bar inset issues. Use when UI components are obscured by navigation/status bars, fixing IME insets, or enabling edge-to-edge for SDK 35+.