> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sqd.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Reach for SQD when you need onchain data without running a node or an indexer: decoded EVM logs and transactions, Solana instructions, Bitcoin transactions, Substrate events and calls, or Hyperliquid fills, over any block range on 110+ networks.
> To query directly, POST to https://portal.sqd.dev/datasets/{dataset}/stream. The full API is described at https://docs.sqd.dev/openapi.json, and responses to the stream endpoints are JSON Lines.
> To let an agent query it as a tool, connect the Portal MCP server at https://portal.sqd.dev/mcp.
> For Portal availability errors, stalled streams, or rate limiting, read https://status.sqd.dev/status.md. The status index at https://status.sqd.dev/llms.txt explains network and plan filters.
> Every page on this site is available as Markdown by appending .md to its URL.

# Graceful shutdown

> Handle SIGTERM and SIGINT cleanly in EVM Pipes SDK pipelines.

`pipeTo` handles `SIGTERM` and `SIGINT` by default for every target. On a signal, the pipe stops reading, finishes the batch it is writing, saves its cursor, closes the resources it created, and rejects with [`PipelineStoppedError`](https://docs.sqd.dev/en/sdk/pipes-sdk/reference/errors/E3001).

```ts theme={"system"}
await stream.pipeTo(target)
```

## Options

Configure shutdown behavior through the second argument to `pipeTo`:

```ts theme={"system"}
// A cleanup callback, with the default 30s timeout
await stream.pipeTo(target, {
  shutdown: async () => {
    await server.close()
  },
})

// A custom timeout and an optional callback
await stream.pipeTo(target, {
  shutdown: {
    timeout: '60s',
    onShutdown: async () => {
      await server.close()
    },
  },
})

// Let your application handle signals itself
await stream.pipeTo(target, { shutdown: false })
```

| Option | Default | Description |
| - | - | - |
| `timeout` | `'30s'` | Total time from the first signal for draining, cleanup, and `onShutdown`. |
| `onShutdown` | | Runs once after draining and cleanup settle, sync or async. Runs on a signal only, not when a range completes. |

`timeout` takes a positive duration string with a unit, such as `'500ms'`, `'30s'`, `'1m'`, `'2m 30s'`, or `'1h'`. Passing an invalid, zero, or negative duration—or a bare number—rejects with [`E0005`](https://docs.sqd.dev/en/sdk/pipes-sdk/reference/errors/E0005) before the pipe starts.

Set `timeout` below your orchestrator's termination grace period (for example Kubernetes `terminationGracePeriodSeconds`) so the pipe finishes draining before `SIGKILL`.

## What happens on a signal

1. The pipe stops reading. Any in-flight read waiting for the next block, any retry, and any read-ahead batch are cancelled, including during startup.
2. The batch the target is writing finishes and saves its cursor. A commit or fork rollback already in progress is never cancelled, and commit retries continue.
3. Transformers stop, and the target flushes and closes what it opened. Parquet closes its open files at the last written batch.
4. `onShutdown` runs after draining and cleanup settle, even if they failed.
5. `pipeTo` rejects (see [How `pipeTo` settles](#how-pipeto-settles)).

`timeout` bounds how long `pipeTo` waits. If it expires during draining, `pipeTo` rejects immediately with [`E3002`](https://docs.sqd.dev/en/sdk/pipes-sdk/reference/errors/E3002), while `onShutdown` waits for draining and cleanup to settle (and never runs if draining never settles). Additional signals do not restart the timeout.

### Portal reads in hooks and caches

Transformer [`start` hooks](../../reference/basic-components/transformer#start-context) receive the run's effective `finalized` mode and an optional `signal`. Pass `signal` as `abort` to cancel extra Portal reads and retries on shutdown:

```ts theme={"system"}
start: async ({ portal, finalized, signal }) => {
  const head = await portal.getHead({ finalized, abort: signal })
}
```

Custom `PortalCache` implementations receive the same `finalized` and `signal` fields. Forward them on a cache miss with `portal.getStream(query, { finalized, request: { abort: signal } })` and stop iterating when `signal` aborts. The built-in [`portalSqliteCache`](../../reference/utility-components/sqlite-cache) handles this automatically.

## How `pipeTo` settles

`pipeTo` resolves only when the configured range completes, so code after `await stream.pipeTo(target)` does not run on a signal stop.

| Outcome | `pipeTo` result |
| - | - |
| Range completed | Resolves; `onShutdown` does not run |
| Failure with no signal | Rejects with the failure; `onShutdown` does not run |
| Signal, shutdown succeeded | Rejects with `PipelineStoppedError` ([`E3001`](https://docs.sqd.dev/en/sdk/pipes-sdk/reference/errors/E3001)) |
| Signal, drain failed | Rejects with the drain error |
| Signal, `onShutdown` failed | Rejects with the callback error |
| Signal, both failed | Rejects with an `AggregateError` holding both |
| Signal, `timeout` expired | Rejects with `PipelineShutdownTimeoutError` ([`E3002`](https://docs.sqd.dev/en/sdk/pipes-sdk/reference/errors/E3002)) |

A signal that arrives while a completed range is closing also counts as a stop.

## Exit codes

The SDK never calls `process.exit()`. An unhandled `await stream.pipeTo(target)` exits with code 1 on a signal stop. Catch `PipelineStoppedError` to exit cleanly with code 0 once nothing else keeps the event loop alive:

```ts theme={"system"}
import { PipelineStoppedError } from '@subsquid/pipes'

try {
  await stream.pipeTo(target)
} catch (error) {
  if (!(error instanceof PipelineStoppedError)) throw error
}
```

After a timeout (`PipelineShutdownTimeoutError`), uncancelled work may keep the process alive; decide explicitly when to exit if you catch it.

The SDK removes its signal listeners as soon as no managed `pipeTo` runs remain.

## Resource ownership

The SDK closes only resources it created itself. Clients you pass in stay open—for every stop reason, including range completion—so other pipes or application code can share them:

| Target | Closed by the SDK | Stays open for you to close |
| - | - | - |
| [BigQuery](https://docs.sqd.dev/en/sdk/pipes-sdk/evm/reference/basic-components/target/bigquery.md) | Write streams, and a `WriterClient` the target created | `client.bigquery`, any `client.writer` you passed |
| [Pub/Sub](https://docs.sqd.dev/en/sdk/pipes-sdk/evm/reference/basic-components/target/pubsub.md) | The state file, and a client built from a `ClientConfig` | A `PubSub` instance you passed |
| [ClickHouse](https://docs.sqd.dev/en/sdk/pipes-sdk/evm/reference/basic-components/target/clickhouse.md) | Nothing | `client` |
| [Postgres (Drizzle)](https://docs.sqd.dev/en/sdk/pipes-sdk/evm/reference/basic-components/target/postgres-drizzle.md) | Nothing | `db` |
| [Parquet](https://docs.sqd.dev/en/sdk/pipes-sdk/evm/reference/basic-components/target/parquet.md) | Open files | |

When running several pipes against one shared client, close the client after all pipes settle:

```ts theme={"system"}
const results = await Promise.allSettled([
  streamA.pipeTo(targetA),
  streamB.pipeTo(targetB),
])

await client.close()
```

## Multiple pipes and custom signal handlers

One signal stops every managed pipe in the process, and each runs its own `onShutdown` callback with its own `timeout`. Any pipe configured with `shutdown: false` keeps running until your code stops it.

Your own `process.on('SIGTERM', ...)` handlers still run alongside the SDK's. A custom handler that calls `process.exit()` terminates the process before draining finishes—move that cleanup into `onShutdown`, or pass `shutdown: false` and coordinate shutdown yourself.

## `SIGKILL` and crash recovery

`SIGKILL`, crashes, and lost machines skip draining. On restart, each target recovers to its saved cursor and resumes from the next block:

| Target | After a `SIGKILL` or crash |
| - | - |
| Postgres (Drizzle) | Batch and cursor commit in one transaction, so a batch lands completely or not at all. |
| BigQuery | Recovery deletes rows from an unfinished batch, then reads the batch again. |
| ClickHouse | `onRollback` with `reason: 'recovery'` removes rows above the saved cursor. Without it, those rows duplicate. |
| Parquet | Unpublished temporary files are discarded, and blocks since the last checkpoint are read again. |
| Pub/Sub | Unpublished outbox messages go out first and may repeat; consumers apply messages by sequence/version. |
| Custom (`createTarget`) | Depends on your target. Persist the cursor only after data is confirmed. |

The same recovery applies if a shutdown exceeds `timeout` and the process is killed.


## Related topics

- [Graceful shutdown](https://docs.sqd.dev/en/sdk/pipes-sdk/solana/guides/architecture-deep-dives/graceful-shutdown.md)
- [Error reference](https://docs.sqd.dev/en/sdk/pipes-sdk/reference/errors.md)
- [E3002](https://docs.sqd.dev/en/sdk/pipes-sdk/reference/errors/E3002.md)
- [E3001](https://docs.sqd.dev/en/sdk/pipes-sdk/reference/errors/E3001.md)
- [Portal stream](https://docs.sqd.dev/en/sdk/pipes-sdk/evm/reference/basic-components/source.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.