Healthchecks (Terminus)

Terminus integration provides you with readiness/liveness health checks. Healthchecks are crucial when it comes to complex backend setups. In a nutshell, a health check in the realm of web development usually consists of a special address, for example, https://my-website.com/health/readiness. A service or a component of your infrastructure (e.g., Kubernetes) checks this address continuously. Depending on the HTTP status code returned from a GET request to this address the service will take action when it receives an “unhealthy” response. Since the definition of “healthy” or “unhealthy” varies with the type of service you provide, the Terminus integration supports you with a set of health indicators.

As an example, if your web server uses MongoDB to store its data, it would be vital information whether MongoDB is still up and running. In that case, you can make use of the MongooseHealthIndicator. If configured correctly - more on that later - your health check address will return a healthy or unhealthy HTTP status code, depending on whether MongoDB is running.

Getting started

To get started with @nestjs/terminus we need to install the required dependency.

  1. $ npm install --save @nestjs/terminus

Setting up a Healthcheck

A health check represents a summary of health indicators. A health indicator executes a check of a service, whether it is in a healthy or unhealthy state. A health check is positive if all the assigned health indicators are up and running. Because a lot of applications will need similar health indicators, @nestjs/terminus provides a set of predefined indicators, such as:

  • HttpHealthIndicator
  • TypeOrmHealthIndicator
  • MongooseHealthIndicator
  • SequelizeHealthIndicator
  • MicroserviceHealthIndicator
  • GRPCHealthIndicator
  • MemoryHealthIndicator
  • DiskHealthIndicator

To get started with our first health check, we need to import the TerminusModule into our AppModule.

  1. @@filename(app.module)
  2. import { Module } from '@nestjs/common';
  3. import { TerminusModule } from '@nestjs/terminus';
  4. @Module({
  5. imports: [TerminusModule]
  6. })
  7. export class AppModule {}

Our healthcheck(s) can be executed using a controller, which can be easily set up using the Nest CLI.

  1. $ nest g controller health

info Info It is highly recommended to enable shutdown hooks in your application. Terminus integration makes use of this lifecycle event if enabled. Read more about shutdown hooks here.

HTTP Healthcheck

Once we have installed @nestjs/terminus, imported our TerminusModule and created a new controller, we are ready to create a health check.

  1. @@filename(health.controller)
  2. import { Controller, Get } from '@nestjs/common';
  3. import { HealthCheckService, HttpHealthIndicator, HealthCheck } from '@nestjs/terminus';
  4. @Controller('health')
  5. export class HealthController {
  6. constructor(
  7. private health: HealthCheckService,
  8. private http: HttpHealthIndicator,
  9. ) {}
  10. @Get()
  11. @HealthCheck()
  12. check() {
  13. return this.health.check([
  14. () => this.http.pingCheck('nestjs-docs', 'https://docs.nestjs.com'),
  15. ]);
  16. }
  17. }
  18. @@switch
  19. import { Controller, Get } from '@nestjs/common';
  20. import { HealthCheckService, HttpHealthIndicator, HealthCheck } from '@nestjs/terminus';
  21. @Controller('health')
  22. @Dependencies(HealthCheckService, HttpHealthIndicator)
  23. export class HealthController {
  24. constructor(
  25. private health,
  26. private http,
  27. ) { }
  28. @Get()
  29. @HealthCheck()
  30. healthCheck() {
  31. return this.health.check([
  32. async () => this.http.pingCheck('nestjs-docs', 'https://docs.nestjs.com'),
  33. ])
  34. }
  35. }

Our health check will now send a GET-request to the https://docs.nestjs.com address. If we get a healthy response from that address, our route at http://localhost:3000/health will return the following object with a 200 status code.

  1. {
  2. "status": "ok",
  3. "info": {
  4. "nestjs-docs": {
  5. "status": "up"
  6. }
  7. },
  8. "error": {},
  9. "details": {
  10. "nestjs-docs": {
  11. "status": "up"
  12. }
  13. }
  14. }

The interface of this response object can be accessed from the @nestjs/terminus package with the HealthCheckResult interface.

statusIf any health indicator failed the status will be ‘error’. If the NestJS app is shutting down but still accepting HTTP requests, the health check will have the ‘shutting_down’ status.‘error’ | ‘ok’ | ‘shutting_down’
infoObject containing information of each health indicator which is of status ‘up’, or in other words “healthy”.object
errorObject containing information of each health indicator which is of status ‘down’, or in other words “unhealthy”.object
detailsObject containing all information of each health indicatorobject

TypeOrm health indicator

Terminus offers the capability to add database checks to your health check. In order to get started with this health indicator, you should check out the Database chapter and make sure your database connection within your application is established.

info Hint Behind the scenes the TypeOrmHealthIndicator simply executes a SELECT 1-SQL command which is often used to verify whether the database still alive. In case you are using an Oracle database it uses SELECT 1 FROM DUAL.

  1. @@filename(health.controller)
  2. @Controller('health')
  3. export class HealthController {
  4. constructor(
  5. private health: HealthCheckService,
  6. private db: TypeOrmHealthIndicator,
  7. ) {}
  8. @Get()
  9. @HealthCheck()
  10. check() {
  11. return this.health.check([
  12. () => this.db.pingCheck('database'),
  13. ]);
  14. }
  15. }
  16. @@switch
  17. @Controller('health')
  18. @Dependencies(HealthCheckService, TypeOrmHealthIndicator)
  19. export class HealthController {
  20. constructor(
  21. private health,
  22. private db,
  23. ) { }
  24. @Get()
  25. @HealthCheck()
  26. healthCheck() {
  27. return this.health.check([
  28. async () => this.db.pingCheck('database'),
  29. ])
  30. }
  31. }

If your database is reachable, you should now see the following JSON-result when requesting http://localhost:3000 with a GET request:

  1. {
  2. "status": "ok",
  3. "info": {
  4. "database": {
  5. "status": "up"
  6. }
  7. },
  8. "error": {},
  9. "details": {
  10. "database": {
  11. "status": "up"
  12. }
  13. }
  14. }

In case your app uses multiple databases, you need to inject each connection into your HealthController. Then, you can simply pass the connection reference to the TypeOrmHealthIndicator.

  1. @@filename(health.controller)
  2. @Controller('health')
  3. export class HealthController {
  4. constructor(
  5. private health: HealthCheckService,
  6. private db: TypeOrmHealthIndicator,
  7. @InjectConnection('albumsConnection')
  8. private albumsConnection: Connection,
  9. @InjectConnection()
  10. private defaultConnection: Connection,
  11. ) {}
  12. @Get()
  13. @HealthCheck()
  14. check() {
  15. return this.health.check([
  16. () => this.db.pingCheck('albums-database', { connection: this.albumsConnection }),
  17. () => this.db.pingCheck('database', { connection: this.defaultConnection }),
  18. ]);
  19. }
  20. }

Custom health indicator

In some cases, the predefined health indicators provided by @nestjs/terminus do not cover all of your health check requirements. In that case, you can set up a custom health indicator according to your needs.

Let’s get started by creating a service that will represent our custom indicator. To get a basic understanding of how an indicator is structured, we will create an example DogHealthIndicator. This service should have the state 'up' if every Dog object has the type 'goodboy'. If that condition is not satisfied then it should throw an error.

  1. @@filename(dog.health)
  2. import { Injectable } from '@nestjs/common';
  3. import { HealthIndicator, HealthIndicatorResult, HealthCheckError } from '@nestjs/terminus';
  4. export interface Dog {
  5. name: string;
  6. type: string;
  7. }
  8. @Injectable()
  9. export class DogHealthIndicator extends HealthIndicator {
  10. private dogs: Dog[] = [
  11. { name: 'Fido', type: 'goodboy' },
  12. { name: 'Rex', type: 'badboy' },
  13. ];
  14. async isHealthy(key: string): Promise<HealthIndicatorResult> {
  15. const badboys = this.dogs.filter(dog => dog.type === 'badboy');
  16. const isHealthy = badboys.length === 0;
  17. const result = this.getStatus(key, isHealthy, { badboys: badboys.length });
  18. if (isHealthy) {
  19. return result;
  20. }
  21. throw new HealthCheckError('Dogcheck failed', result);
  22. }
  23. }
  24. @@switch
  25. import { Injectable } from '@nestjs/common';
  26. import { HealthCheckError } from '@godaddy/terminus';
  27. @Injectable()
  28. export class DogHealthIndicator extends HealthIndicator {
  29. dogs = [
  30. { name: 'Fido', type: 'goodboy' },
  31. { name: 'Rex', type: 'badboy' },
  32. ];
  33. async isHealthy(key) {
  34. const badboys = this.dogs.filter(dog => dog.type === 'badboy');
  35. const isHealthy = badboys.length === 0;
  36. const result = this.getStatus(key, isHealthy, { badboys: badboys.length });
  37. if (isHealthy) {
  38. return result;
  39. }
  40. throw new HealthCheckError('Dogcheck failed', result);
  41. }
  42. }

The next thing we need to do is register the health indicator as a provider.

  1. @@filename(app.module)
  2. import { Module } from '@nestjs/common';
  3. import { TerminusModule } from '@nestjs/terminus';
  4. import { DogHealthIndicator } from './dog.health';
  5. @Module({
  6. controllers: [HealthController],
  7. imports: [TerminusModule],
  8. providers: [DogHealthIndicator]
  9. })
  10. export class AppModule { }

info Hint In a real-world application the DogHealthIndicator should be provided in a separate module, for example, DogModule, which then will be imported by the AppModule.

The last required step is to add the now available health indicator in the required health check endpoint. For that, we go back to our HealthController and add it to our check function.

  1. @@filename(health.controller)
  2. import { HealthCheckService } from '@nestjs/terminus';
  3. import { Injectable } from '@nestjs/common';
  4. import { DogHealthIndicator } from './dog.health';
  5. @Injectable()
  6. export class HealthController {
  7. constructor(
  8. private health: HealthCheckService,
  9. private dogHealthIndicator: DogHealthIndicator
  10. ) {}
  11. @Get()
  12. @HealthCheck()
  13. healthCheck() {
  14. return this.health.check([
  15. async () => this.dogHealthIndicator.isHealthy('dog'),
  16. ])
  17. }
  18. }
  19. @@switch
  20. import { HealthCheckService } from '@nestjs/terminus';
  21. import { Injectable } from '@nestjs/common';
  22. import { DogHealthIndicator } from './dog.health';
  23. @Injectable()
  24. @Dependencies(HealthCheckService, DogHealthIndicator)
  25. export class HealthController {
  26. constructor(
  27. private health,
  28. private dogHealthIndicator
  29. ) {}
  30. @Get()
  31. @HealthCheck()
  32. healthCheck() {
  33. return this.health.check([
  34. async () => this.dogHealthIndicator.isHealthy('dog'),
  35. ])
  36. }
  37. }

Examples

Some working examples are available here.