Shutting down cleanly

Ensure your app shuts down cleanly when terminated

Often you'll want to run your app in a way that it can terminate cleanly and give it time to finish doing its work before exiting. This is common if you manually terminate it (CTRL + C), send it a kill signal like kill -INT 1234 or if the underlying pod/container/host is stopping.

In these situations your app should finish processing the any messages its read from the queue and not read any more, allowing it to exit gracefully.

To do this, hooking into the process signals and calling dispose on the bus is the cleanest way.

Example handling SIGINT

import { Bus, BusInstance } from '@node-ts/bus-core'

let bus: BusInstance

const start = async () => {
  bus = Bus.configure().initialize()
  await bus.start()
}

/**
* Listens for a signal interrupt and gracefully disposes the bus
* before exiting.
*/
const listenForSigInt = () => {
  process.once('SIGINT', async () => {
    console.log('Received SIGINT, shutting down...')
    if (bus) {
      await bus.dispose()
    }
  })
}

listenForSigInt()
start().catch(console.err)

Last updated