A powerful package for gracefully shutting down NestJS applications
npm install nestjs-graceful-shutdown
Elevate your NestJS application with seamless and reliable server shutdowns, guaranteeing uninterrupted user experiences and effortless handling of critical shutdown scenarios.
> 🚀 Looking for an enhanced version? Check out @tygra/nestjs-graceful-shutdown - a production-ready fork with significant improvements:
>
> - Comprehensive test coverage: Achieved >99% statement coverage and >87% branch coverage with 44+ test cases
> - Robust error handling: Improved fallback mechanisms and graceful degradation when termination fails
> - Edge case coverage: Extensive testing of error scenarios including cleanup failures, termination errors, and signal handling
>
> We strongly recommend all users to use @tygra/nestjs-graceful-shutdown for enhanced reliability and better production support.
- Description
- Installation
- Example
- Configuration
- Testing Instructions
- Contact and Feedback
- License
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-terminatorlibrary 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.
You can install the library using npm:
```
npm install nestjs-graceful-shutdown http-terminator
To integrate nestjs-graceful-shutdown into your NestJS application, follow these steps:
1. First, import the module with GracefulShutdownModule.forRoot(...) or GracefulShutdownModule.forRootAsync(...) into your root AppModule. (refer to the module configuration documentation below).
`ts
import { GracefulShutdownModule } from 'nestjs-graceful-shutdown';
@Module({
imports: [GracefulShutdownModule.forRoot()],
...
})
class AppModule {}
`
2. 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.
`typescript
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);
// Additional configuration for your NestJS app
setupGracefulShutdown({ app });
await app.listen(3000);
// Note: Timeout is used for illustration of
// delayed termination purposes only.
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.
The following interface is used for GracefulShutdownModule configuration:
`tstrue
interface IGracefulShutdownConfigOptions {
/**
* Cleanup function for releasing application resources
* during server shutdown.
*/
cleanup?: (app: INestApplication, signal?: string) => any;
/**
* The duration in milliseconds before forcefully
* terminating a connection.
* Defaults: 5000 (5 seconds).
*/
gracefulShutdownTimeout?: number;
/**
* If set to , the Node process will not be terminatedapp.close()
* by a shutdown signal after closing all connections.
* The shutdown behavior is identical to invoking .`
* Defaults: false.
*/
keepNodeProcessAlive?: boolean;
}
The following interface is used for setupGracefulShutdown function parameters:
`ts`
interface ISetupFunctionParams {
/**
* Your NestJS application.
*/
app: INestApplication;
/**
* Shutdown signals that the application should listen to.
* By default, it listens to all ShutdownSignals.
*/
signals?: ShutdownSignal[] | string[];
}
Just import GracefulShutdownModule to AppModule:
`ts
import { GracefulShutdownModule } from 'nestjs-graceful-shutdown';
@Module({
imports: [GracefulShutdownModule.forRoot()],
...
})
class AppModule {}
`
Use GracefulShutdownModule.forRoot method with argument of Configuration interface:
`ts
import { GracefulShutdownModule } from 'nestjs-graceful-shutdown';
@Module({
imports: [
GracefulShutdownModule.forRoot({
cleanup: async (app, signal) => {
// releasing resources
},
gracefulShutdownTimeout:
Number(process.env.GRACEFUL_SHUTDOWN_TIMEOUT ?? 10000),
keepNodeProcessAlive: true,
})
],
...
})
class AppModule {}
`
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:
`ts
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 {}
`
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:
`typescript`
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.
`typescript
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
setupGracefulShutdown({ app });
await app.listen();
});
``
Feel free to reach out if you have any ideas, comments, or questions.
Best regards,
Hien Nguyen Minh
This library is licensed under the MIT License. See the LICENSE file for more details.