NestJS — Enterprise Node.js

Performance, Keep-Alive & Graceful Shutdown

18 min Lesson 78 of 80

Performance, Keep-Alive & Graceful Shutdown

Performance is not only framework speed. It includes connection reuse, payload size, adapter choice, shutdown behavior, resource cleanup, and how the application reacts when Kubernetes or systemd asks it to stop.

Core idea

This feature is about controlling how the application is organized and how it behaves at runtime. These are the points a developer should understand before using it in a real project:

  • Keep-alive connections reduce TCP/TLS handshake overhead for repeated client calls.
  • Graceful shutdown lets Nest run lifecycle hooks and close database, Redis, and broker clients.
  • enableShutdownHooks() wires process signals into Nest lifecycle events.
  • Fastify may improve throughput, but payload design, caching, and downstream latency often dominate real performance.
  • Compression and caching should usually be handled close to the edge for public traffic.

Practical example

The following example shows the idea in a practical NestJS project. The goal is not to memorize the snippet, but to understand where it belongs in the architecture:

async function bootstrap() { const app = await NestFactory.create(AppModule); app.enableShutdownHooks(); await app.listen(3000); } @Injectable() export class PrismaService extends PrismaClient implements OnModuleDestroy { async onModuleDestroy() { await this.$disconnect(); } }
Design note: A fast app that drops in-flight requests during deployment is not production-ready. Performance work must include startup, steady state, and shutdown.

Production checklist

  • Enable shutdown hooks in deployed services.
  • Close database, Redis, HTTP, and broker clients in destroy hooks.
  • Use keep-alive agents for high-volume outbound HTTP.
  • Measure p95/p99 latency before optimizing the framework adapter.
Rule of thumb: If the feature makes boundaries clearer and tests easier, it is probably the right choice. If it hides dependencies or makes tracing harder, redesign.

Summary

This lesson covers an advanced NestJS area that matters when building enterprise applications. Focus on clear boundaries, testable behavior, and choosing the right tool for the context instead of using every feature everywhere.