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 { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config';
How a JWT strategy authenticates in NestJS
authentication
jwt
passport
Intermediate
7 steps
typescript
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http'; import { BehaviorSubject, Observable, throwError } from 'rxjs'; import { catchError, filter, take, switchMap } from 'rxjs/operators';
Refreshing auth tokens in an Angular interceptor
http-interceptor
token-refresh
rxjs
Advanced
8 steps
typescript
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'; import { GqlExecutionContext } from '@nestjs/graphql'; import { Reflector } from '@nestjs/core'; import { JwtService } from '@nestjs/jwt';
How a GraphQL auth guard works in NestJS
authentication
authorization
jwt
Intermediate
7 steps
python
import os from datetime import timedelta
Class-based config in a Flask app factory
configuration
app-factory
inheritance
Intermediate
7 steps
typescript
type ResizeCallback = (size: { width: number; height: number }) => void; export function observeResize(callback: ResizeCallback, delay = 150) { let timeoutId: ReturnType<typeof setTimeout> | undefined;
Debouncing window resize in TypeScript
debounce
closures
event-listeners
Intermediate
6 steps
typescript
import { Injectable, OnModuleInit, Logger } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { Cron, CronExpression } from '@nestjs/schedule';
A self-refreshing feature flags provider in NestJS
caching
scheduled-tasks
dependency-injection
Intermediate
8 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.