Compression and Fastify

Compression

Gzip/Brotli shrinks JSON responses by 70–90%. In production it is usually done by nginx or the load balancer; in the app it is one line:

import compression from 'compression';
app.use(compression({ threshold: 1024 }));   // only bodies larger than 1 KB

The Fastify Adapter

Fastify is a faster HTTP library than Express (often 2x more requests per second in benchmarks). NestJS code (controllers, services, pipes, guards) stays the same; only Express-specific middleware must be swapped for Fastify plugins.

Example

npm i @nestjs/platform-fastify @fastify/helmet @fastify/compress

Example output

added 38 packages in 6s

src/main.ts

import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import helmet from '@fastify/helmet';
import compress from '@fastify/compress';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter({ logger: false }));
  await app.register(helmet);
  await app.register(compress);
  await app.listen(3000, '0.0.0.0');      // Fastify listens on localhost only by default
}
bootstrap();

Example

A quick benchmark with autocannon on a laptop (numbers vary by machine):

npx autocannon -c 100 -d 10 http://localhost:3000/products/7

Example output

Express adapter:  Req/Sec avg 11,240   Latency avg 8.4 ms
Fastify adapter:  Req/Sec avg 24,870   Latency avg 3.6 ms