NestJS Graceful Shutdown 🐈
Elevate your NestJS application with seamless and reliable server shutdowns, guaranteeing uninterrupted user experiences and effortless handling of critical shutdown scenarios.
Table of Contents
Description
Don't let your server hang indefinitely!
When you explicitly call app.close()
or if the process receive a special system signal (such as SIGTERM) after correctly invoking enableShutdownHooks
during application bootstrap (check out the NestJS docs), the server stops accepting new connections while maintaining existing ones. This leads to your server hanging indefinitely due to lingering keep-alive connections or unresponsive requests.
Powered by the robust http-terminator
library and backed by NestJS's built-in shutdown hooks, nestjs-graceful-shutdown
ensures graceful communication with clients currently receiving responses from your server during the shutdown process. Experience a reliable and hassle-free server shutdown with ease.
Installation
You can install the library using npm:
npm install nestjs-graceful-shutdown http-terminator
Example
To integrate nestjs-graceful-shutdown
into your NestJS application, follow these steps:
- First, import the module with
GracefulShutdownModule.forRoot(...)
or GracefulShutdownModule.forRootAsync(...)
into your root AppModule
. (refer to the module configuration documentation below).
import { GracefulShutdownModule } from 'nestjs-graceful-shutdown';
@Module({
imports: [GracefulShutdownModule.forRoot()],
...
})
class AppModule {}
- Next, set up graceful shutdown for your NestJS application by calling the
setupGracefulShutdown(...)
function.
⚠️ Warning: nestjs-graceful-shutdown
will automatically enable the shutdown hooks. Avoid calling enableShutdownHooks
separately in your application, as it may lead to unexpected behavior. For more information on NestJS application lifecycle, refer to the NestJS documentation.
import { setupGracefulShutdown } from 'nestjs-graceful-shutdown';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
setupGracefulShutdown({ app });
await app.listen(3000);
setTimeout(() => {
process.kill(process.pid, 'SIGTERM');
}, 5000);
}
bootstrap();
Please note that the above code snippets demonstrate the basic setup of nestjs-graceful-shutdown
in your NestJS application. Make sure to adjust the code based on your specific application requirements and configuration.
Configuration
Configuration interface
The following interface is used for GracefulShutdownModule
configuration:
interface IGracefulShutdownConfigOptions {
cleanup?: (app: INestApplication, signal?: string) => any;
gracefulShutdownTimeout?: number;
keepNodeProcessAlive?: boolean;
}
The following interface is used for setupGracefulShutdown
function parameters:
interface ISetupFunctionParams {
app: INestApplication;
signals?: ShutdownSignal[] | string[];
}
Zero configuration
Just import GracefulShutdownModule
to AppModule
:
import { GracefulShutdownModule } from 'nestjs-graceful-shutdown';
@Module({
imports: [GracefulShutdownModule.forRoot()],
...
})
class AppModule {}
Synchronous configuration
Use GracefulShutdownModule.forRoot
method with argument of Configuration interface:
import { GracefulShutdownModule } from 'nestjs-graceful-shutdown';
@Module({
imports: [
GracefulShutdownModule.forRoot({
cleanup: async (app, signal) => {
},
gracefulShutdownTimeout:
Number(process.env.GRACEFUL_SHUTDOWN_TIMEOUT ?? 10000),
keepNodeProcessAlive: true,
})
],
...
})
class AppModule {}
Asynchronous configuration
With GracefulShutdownModule.forRootAsync
you can, for example, import your ConfigModule
and inject ConfigService
to use it in useFactory
method.
useFactory
should return object with Configuration interface
Here's an example:
import { GracefulShutdownModule } from 'nestjs-graceful-shutdown';
@Injectable()
class ConfigService {
public readonly timeout = 10000;
}
@Module({
providers: [ConfigService],
exports: [ConfigService]
})
class ConfigModule {}
@Module({
imports: [
GracefulShutdownModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (config: ConfigService) => {
await somePromise();
return {
gracefulShutdownTimeout: config.timeout,
};
}
})
],
...
})
class AppModule {}
Testing Instructions
When testing, you may need to override the graceful shutdown module with a mock module. Thanks to NestJS, this can easily be achieved using overrideModule
. See the following example:
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
})
.overrideModule(GracefulShutdownModule)
.useModule(MockModule)
.compile();
If you don't want to use a MockModule
, you can use app.listen()
instead of app.init()
in your test file.
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
setupGracefulShutdown({ app });
await app.listen();
});
Contact and Feedback
Feel free to reach out if you have any ideas, comments, or questions.
Best regards,
Hien Nguyen Minh
License
This library is licensed under the MIT License. See the LICENSE file for more details.