# Graceful Shutdown

When the process receives `SIGTERM` (for example, when Kubernetes replaces a pod during a deploy), the app stops accepting new connections, waits for in-flight HTTP requests to finish and exits.

Work that the app runs outside HTTP requests, such as queues, background jobs, leases or streams, is not part of that wait. Use `onShutdown` to finish it before the process exits.

## Shutdown Hook

`onShutdown` is called once on `SIGTERM`. The process exits only after the hook and the in-flight requests have both finished.

```js title="index.js"
import crowdinModule from '@crowdin/app-project-module';

crowdinModule.createApp({
  // ...
  shutdownTimeout: 25_000,
  onShutdown: async () => {
    // hand the work over to another replica instead of waiting for its lease to expire
    await automationRuns.releaseAll();
  },
});
```

The same options work with `crowdinModule.express()`:

```js title="index.js"
import crowdinModule from '@crowdin/app-project-module';

const app = crowdinModule.express();

crowdinModule.addCrowdinEndpoints(app, {
  // ...
  shutdownTimeout: 25_000,
  onShutdown: async () => {
    await queue.close();
  },
});

app.listen(3000, () => console.log('Crowdin app started'));
```

The hook starts right away, while the in-flight requests are still finishing, so an open stream (for example, Server-Sent Events) does not delay it. An error thrown by the hook is logged and the process still exits with code `0`.

## Shutdown Timeout

By default the app waits for the hook and the in-flight requests with no time limit. Set `shutdownTimeout` (in milliseconds) to cap the whole shutdown: when it passes, the error is logged and the process exits with code `1`.

**Note:** Keep `shutdownTimeout` below the time your platform waits before killing the process. In Kubernetes this is `terminationGracePeriodSeconds`, 30 seconds by default. Otherwise the process is killed with `SIGKILL` and the rest of the hook does not run.

## Configuration

| Option            | Type                          | Default | Description                                                                 |
|-------------------|-------------------------------|---------|-----------------------------------------------------------------------------|
| `onShutdown`      | `() => Promise<void> \| void` | -       | Called once on `SIGTERM`. The process waits for it before exiting           |
| `shutdownTimeout` | `number`                      | -       | Deadline for the whole shutdown, in milliseconds. No deadline when not set |

**Caution:** The hook runs only when the app is started with `app.listen` on a long-running Node.js server. On AWS Lambda, Vercel and Cloudflare Workers the platform stops the instance itself and the hook is not called.