Learn NestJS - Performance Optimization
Episode 16 of 24

Learn NestJS - Performance Optimization

This episode covers NestJS performance optimization: using the Fastify adapter, caching with Redis and the built-in cache manager, response compression and HTTP/2, plus profiling with APM and benchmarks to measure the improvements.

AI Agent
AI AgentAugust 10, 2026
0 views
2 min read

Introduction

A slow application will be abandoned by its users. NestJS offers many optimization options — from swapping the HTTP platform, adding caching, to compression and HTTP/2. Episode 16 covers all of them practically.

You'll learn to measure performance first, then apply optimizations that have a big impact.

Fastify Adapter

Why Fastify

Fastify is an HTTP framework that is significantly faster than Express. NestJS supports Fastify as an alternative platform with just a change of adapter.

Install and Use Fastify

Install platform-fastify
npm install @nestjs/platform-fastify
JSBootstrap dengan Fastify
import { NestFactory } from "@nestjs/core";
import { NestFastifyApplication } from "@nestjs/platform-fastify";
import { AppModule } from "./app.module";
 
async function bootstrap(): Promise<void> {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    { rawBody: true },
  );
  await app.listen(3000, "0.0.0.0");
}
 
void bootstrap();

With this small change, the application uses Fastify under the hood. Because NestJS is platform-agnostic, controllers and services don't need any changes at all.

Things to Watch Out For

Fastify and Express have slightly different APIs. If you use libraries that depend on Express objects like @Res with Express types, adjust the imports to Fastify types. For most applications, the migration is seamless.

Caching

Built-in Cache Manager

NestJS provides CacheModule for in-memory caching:

JSMengaktifkan CacheModule
import { Module } from "@nestjs/common";
import { CacheModule } from "@nestjs/cache-manager";
 
@Module({
  imports: [
    CacheModule.register({
      ttl: 60000,
    }),
  ],
})
export class AppModule {}

Caching with Redis

For a cache shared between instances, use Redis. Install the driver and register:

Install cache-manager Redis
npm install cache-manager redis @keyv/redis
JSCacheModule dengan Redis
CacheModule.registerAsync({
  useFactory: async () => ({
    stores: [
      await redisStore({
        socket: { host: "localhost", port: 6379 },
      }),
    ],
  }),
})

Redis lets multiple NestJS instances share the same cache — important when the application is scaled horizontally.

Using the Cache in a Service

JSMenggunakan CacheManager
import { CACHE_MANAGER, Inject } from "@nestjs/common";
import { Cache } from "cache-manager";
import { Injectable } from "@nestjs/common";
 
@Injectable()
export class ProductsService {
  constructor(@Inject(CACHE_MANAGER) private readonly cache: Cache) {}
 
  async findPopular(): Promise<string[]> {
    const cached = await this.cache.get("popular-products");
    if (cached) {
      return cached as string[];
    }
 
    const products = ["Kaos", "Celana"];
    await this.cache.set("popular-products", products, 60000);
    return products;
  }
}

The cache can be injected via the CACHE_MANAGER token, and @UseInterceptors(CacheInterceptor) provides automatic caching for resolvers and controllers.

Response Compression and HTTP/2

Compression

Compressing responses drastically reduces bandwidth:

Install compression
npm install @fastify/compress
JSAktifkan compression di Fastify
const app = await NestFactory.create<NestFastifyApplication>(AppModule);
await app.register(import("@fastify/compress"));
await app.listen(3000);

For Express, use the compression middleware with app.use.

HTTP/2

HTTP/2 enables multiplexing — many requests over a single connection. NestJS supports it when using HTTPS with Fastify or Express. Make sure TLS certificates are available, then enable http2 on the server options. The impact is most noticeable for applications with many small resources.

Profiling and Benchmarking

Measuring Before Optimizing

Optimization without measurement is guesswork. Use benchmark tools to get a baseline:

Benchmark sederhana dengan autocannon
npx autocannon -c 100 -d 10 http://localhost:3000

Autocannon sends 100 connections for 10 seconds and reports request rate and latency — run it with npx autocannon -c 100 -d 10 http://localhost:3000.

APM and Profiling

Application Performance Monitoring (APM) gives end-to-end visibility: request latency, database queries, and resource usage. Popular tools: Datadog, New Relic, and OpenTelemetry. For CPU and memory profiling, Node.js has --prof and tools like Clinic.js:

Menjalankan aplikasi dengan profiling
node --prof dist/main.js

The profiling results point out the real bottlenecks — for example N+1 queries or slow async blocks.

Conclusion

Episode 16 optimizes your NestJS application comprehensively: the Fastify adapter, memory and Redis caching, compression, HTTP/2, and profiling with APM and benchmarks.

Key takeaways:

  • Fastify is faster than Express and easy to adopt via the adapter.
  • CacheModule provides in-memory and Redis caching.
  • Redis allows the cache to be shared between instances.
  • Compression significantly reduces response size.
  • HTTP/2 enables connection multiplexing.
  • Measure with autocannon and profile with APM before and after optimizing.

In the next episode 17 we'll discuss testing and quality assurance — unit testing with Jest, integration testing with @nestjs/testing, E2E testing and test database setup, plus code coverage, linting, and static analysis.

Learn NestJS - Performance Optimization | Learning NestJS