typescript
36 lines · 7 steps
Graceful shutdown hooks in NestJS
A service that cleanly drains Redis, TypeORM, and Kafka connections when the app receives a shutdown signal.
Explained by
highlit
1import { Injectable, Logger, OnApplicationShutdown } from '@nestjs/common';
2import { InjectRedis } from '@nestjs-modules/ioredis';
3import Redis from 'ioredis';
4import { DataSource } from 'typeorm';
5import { KafkaProducer } from './kafka.producer';
6
7@Injectable()
8export class ConnectionLifecycleService implements OnApplicationShutdown {
9 private readonly logger = new Logger(ConnectionLifecycleService.name);
10
11 constructor(
12 @InjectRedis() private readonly redis: Redis,
13 private readonly dataSource: DataSource,
14 private readonly producer: KafkaProducer,
15 ) {}
16
17 async onApplicationShutdown(signal?: string): Promise<void> {
18 this.logger.log(`Received ${signal ?? 'shutdown'} signal, draining connections`);
19
20 const results = await Promise.allSettled([
21 this.producer.flush(5_000).then(() => this.producer.disconnect()),
22 this.redis.quit(),
23 this.dataSource.isInitialized
24 ? this.dataSource.destroy()
25 : Promise.resolve(),
26 ]);
27
28 for (const result of results) {
29 if (result.status === 'rejected') {
30 this.logger.error('Failed to close a resource cleanly', result.reason);
31 }
32 }
33
34 this.logger.log('All external resources released');
35 }
36}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Implementing OnApplicationShutdown lets NestJS notify your service when the process is terminating, giving you a hook to release resources.
- 2Promise.allSettled runs all cleanup in parallel and never short-circuits, so one failing resource doesn't abandon the others.
- 3Flushing buffered work before disconnecting prevents in-flight messages from being silently dropped on exit.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/graceful-shutdown-hooks-in-nestjs-explained-typescript-abc4/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.