# Shutting down

> Stop the ApiTraffic SDK cleanly in scripts, workers, tests and servers with shutdown(), and deliver captured data before a serverless freeze with flush().

Source: https://www.apitraffic.io/docs/reference/shutdown

The SDK keeps a realtime connection open so configuration changes reach your servers in seconds. That is
right for a long-running server and wrong for anything that is meant to finish - a script, a queue worker,
a test run: the connection's reconnect timers keep Node's event loop alive. Stop the SDK when you are done.

```js
const apitraffic = require('@apitraffic/node'); // or @apitraffic/express, /fastify, /koa, /hapi

process.once('SIGTERM', async () => {
  await apitraffic.shutdown({ flushTimeoutMs: 2000 });
  server.close();
});
```

## `shutdown({ flushTimeoutMs })`

1. Stops capturing new requests and outbound calls.
2. Delivers what is already captured - in flight and in the retry queue - waiting at most
   `flushTimeoutMs` (default `2000`). Whatever is left is dropped and counted in the delivery stats:
   uploads still in flight at the deadline are cancelled, and nothing is retried or sent afterwards.
   Requests still waiting for your redaction rules are dropped, never sent unredacted.
3. Closes the realtime connection, stops background timers and the host sampler, and removes the
   `http`, `https` and `fetch` hooks, so those modules are exactly what they were before the SDK loaded.

It resolves with `{ flushed, remaining }`, never throws, and installs no signal handlers - your
application decides when to stop. Calling it twice is safe: a second call while the first is running returns the same result. Setting the SDK
up again starts it again, even while a shutdown is still flushing; the new setup then keeps running.

With `@apitraffic/node`, `shutdown()` also stops the APM tracing that `register()` started, within the same
`flushTimeoutMs` budget. The Strapi plugin calls `shutdown()` for you when Strapi stops.

## `flush({ timeoutMs })`

Delivers what has been captured so far without stopping anything - use it before a serverless invocation
is frozen. Anything not delivered within `timeoutMs` (default `2000`) stays queued for the next attempt.

```js
export const handler = async (event) => {
  const result = await work(event);
  await apitraffic.flush({ timeoutMs: 1000 });
  return result;
};
```

## Startup never waits for realtime

Setup does not wait for the realtime connection to attach. Where your network blocks it, live
configuration updates are off and nothing else is affected; see [If ApiTraffic is unreachable](https://www.apitraffic.io/docs/reference/unreachable).

## Related

- [If ApiTraffic is unreachable](https://www.apitraffic.io/docs/reference/unreachable):
    Delivery limits and what happens during an outage.

- [SDK configuration](https://www.apitraffic.io/docs/integrations/configuration):
    Every option, and the process-level functions.
