# Going to production

Checklist, in order.

## 1. `doctor` passes in the production image

```sh
npx db2kit doctor
```

No `FAIL`. Without a Db2 Connect license in the image, the Connection check fails with SQL1598N: the license must be present in the image, not only on development workstations.

## 2. libuv threadpool

`ibm_db` runs every call on the libuv threadpool, shared with `fs`, `dns` and `crypto`, and limited to 4 threads by default. With `pool.max: 8` and 4 threads, 4 connections wait for nothing and block the rest of Node.

Rule: `UV_THREADPOOL_SIZE = pool.max + 2`, set **in the environment that starts the process** (Dockerfile, Kubernetes manifest), not in the code:

```dockerfile
ENV UV_THREADPOOL_SIZE=10
```

A `.env` file the application loads, or an assignment to `process.env` in `main.ts`, comes too late to be sure of its effect. For the scripts of `package.json` (`cross-env`), a PowerShell session and a Kubernetes manifest: [configuration.md](configuration.md#setting-up-the-pool).

`createDb2` and `doctor` print a warning when the value is too low, or when it is not a positive whole number (libuv reads only its leading digits, and starts a single thread for an empty or unreadable value).

## 3. Pool size

`pool.max` is a **load limit on the mainframe**, not only a performance setting: each application instance opens up to `max` connections, and each one counts against the limits of the Db2 subsystem. Size it from the load, then check it against the DBA's quota and the threadpool.

**Inputs**, per application instance, at the busiest time:

| Symbol | Meaning                                                                                                                                                                                          | Where to find it                                       |
| :----- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------- |
| `R`    | Requests per second that reach Db2                                                                                                                                                               | Access logs or metrics of the application              |
| `T`    | Seconds one request holds a connection: the sum of `executeMs + fetchMs` of its statements, or the whole duration of its `db.$transaction` (the connection stays pinned while the callback runs) | Audit trail (`statsSink`, `jsonlSink`), or a load test |
| `N`    | Application instances (pods, processes)                                                                                                                                                          | Deployment                                             |
| `Q`    | Connections the DBA grants to the application, all instances together                                                                                                                            | DBA                                                    |

**Method**:

1. Average busy connections: `B = R × T` (Little's law).
2. Margin for bursts: `max = ceil(2 × B)`, at least 2, so that one slow statement does not block every other request.
3. Quota: `N × max ≤ Q`. If not, lower `max` to `floor(Q / N)` and look for the slow statements first: a shorter `T` frees more than a larger pool.
4. Threadpool: `UV_THREADPOOL_SIZE = max + 2` (section 2). Above about 30, ask why: the time is probably held by a few slow statements.

Example: 30 requests per second at the peak, 3 statements per request at 40 ms each. `T = 0.12 s`, `B = 3.6`, `max = 8`. With 3 instances, 24 connections to agree with the DBA, and `UV_THREADPOOL_SIZE=10`.

| Setting | Development | CLI (`db2kit.config.mts`)                            | Production                                                                                                                                                                                                                                                                                                                                                                                                  |
| :------ | :---------- | :--------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `max`   | 2 to 4      | 1: the CLI reads the catalog one statement at a time | the method above                                                                                                                                                                                                                                                                                                                                                                                            |
| `min`   | 0           | 0                                                    | 1: the first request after a quiet period does not wait for a login (observed: up to a few seconds on z/OS). With 0, the pool closes every connection after `idleTimeoutMs`. A connection kept open across a network cut is discarded at its next use and a pure read is retried once on another connection (section 8 below); any other statement fails that one request before the connection is replaced |

**After deployment**, `acquireMs` in the audit trail tells whether the size holds: close to 0, the pool has room. Often above a few milliseconds at the peak, the pool is saturated: look first for the statement holding the connections (`statsSink`, sorted by total time), then raise `max` within the quota.

**To ask the DBA**, since the subsystem limits connections whatever the application does: the quota for the application, and the subsystem limits on remote connections and active threads (`CONDBAT`, `MAXDBAT`), whose values decide what happens beyond them (queued or refused).

## 4. Time zone

`TIMESTAMP` values arrive as strings (`YYYY-MM-DD HH:MM:SS.ffffff`) with no time zone conversion. The process time zone only matters where the application turns them into `Date` objects: set `TZ` explicitly (an IANA name such as `America/New_York`), identical to the time zone in which times are recorded.

## 5. Audit

- `audit.params: 'types'` (default): no personal data in the logs, neither the values of the parameters nor the text of Db2 errors, which can carry one. Never enable `'full'` in production. The logs of the application itself write the text of an error it logs: `messageWithoutDb2Text(error)` leaves it out ([audit.md](audit.md#the-text-of-a-db2-error)).
- `consoleSink({ only: ConsoleLevel.SlowAndErrors })` to avoid flooding the logs (`ConsoleLevel.All` for a while to follow a problem), and `statsSink()` or `jsonlSink()` for analysis.
- `slowQueryMs`: set it with the team according to the expected response times.
- Retention: `jsonlSink` requires `retentionDays`, and the platform that receives the console logs needs its own. 30 days for events without values, decided with the data protection officer ([audit.md](audit.md#retention)).

## 6. Graceful shutdown

Call `db.close()` on shutdown (`onApplicationShutdown` in NestJS): connections are closed cleanly instead of being cut when the process exits.

## 7. Regular review with the DBA

Once per sprint, for instance:

1. Export `statsSink().snapshot()` or analyze the JSONL file.
2. Take the top 10 queries by total time.
3. For each one, give the DBA the SQL text and ask for the access path.

## 8. Connection recovery

What db2kit does when the network or the server fails, and what is left to the application.

| Situation                                                                        | What happens                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| :------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Network cut (VPN, firewall dropping idle sessions, subsystem restart), then back | Every idle connection is dead but still looks usable. The first statement that fails with a lost connection (SQL30081N, SQLSTATE `08xxx`) destroys its connection and discards every connection opened before it at its next loan, without failing a request: one warning line in the logs. A pure read outside a transaction runs once more on a new connection (`query.retryLostReads`): the caller sees no error, the audit trail shows both attempts, the second with `RETRIED`                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| A write, a `CALL`, or a statement inside `db.$transaction` loses its connection  | Never retried: its effect is unknown, or its transaction is already rolled back. The caller gets `Db2QueryError` with code `CONNECTION_LOST`. Check the effect before replaying a write. A transaction whose `COMMIT` is lost gives `Db2TransactionCommitError`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| Server unreachable                                                               | After `pool.breakerThreshold` (3) connection attempts failing on the network in a row, Db2 counts as unreachable: requests that need a new connection fail at once with `Db2UnavailableError` (code `UNAVAILABLE`, map it to HTTP 503) instead of each waiting `connectTimeoutMs`. One attempt is let through after 1 s, then after a delay that doubles up to `pool.breakerMaxDelayMs` (60 s). Its success closes the breaker: one warning line when it opens, one when it closes. Free connections are still lent meanwhile                                                                                                                                                                                                                                                                                                                                                                                                                |
| Wrong credentials                                                                | No breaker: the account protection stops every login with the same settings ([configuration.md](configuration.md#protection-of-the-account))                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| Statement waiting on a half-open TCP connection                                  | Without a limit, the driver waits for the operating system to give up, which can take minutes, holding a connection of the pool and a thread. `pool.receiveTimeoutMs` (60 s by default) sends the IBM CLI keywords `ReceiveTimeout` and `QueryTimeout`: past it, the driver gives the connection up and the statement fails with `CONNECTION_LOST`, flagged `NO_REPLY`. It is never retried: from the client, a cut network and a statement slower than the limit look the same, and running a slow statement again could cost as much. Set it above the slowest expected statement. Checked against Db2 13 for z/OS with a relay cut during a read (the `network-cut` integration suite, in the repository of db2kit): `ReceiveTimeout` alone did not end the read, `QueryTimeout` did. Not checked yet: a cut during a `COMMIT`, which is not a statement, and a statement merely slower than the limit (`CANCELLED` or `CONNECTION_LOST`) |

`db.health()` gives the state for a health check, without sending anything to Db2: the pool (`used`, `free`, `pending`, `opening`) and the connection state (`state`: `closed`, `open` or `half-open`, `failures`, `since`, `retryAt`, `lostConnections`, and `lastError` with its code, SQLCODE and SQLSTATE, never its message, which can hold a host address). `db.ping()` sends a statement: use it for a readiness check, not on every probe.

No automatic replay of a transaction or of a write: a lost `COMMIT` or write has an unknown outcome, and only the application knows whether replaying it is safe.

A check by hand against your test subsystem, once: a loop of reads, the VPN cut for 30 s then restored. Count the failed requests (expected: none for reads), the logins (one per connection, plus one attempt per breaker delay while cut) and the time to recover, and keep the figures with the notes of the application, outside its repository if they name the subsystem.
