Source: https://frameworkrecipes.dev/express/transaction-cleanup/

# Return the PostgreSQL client after every Express transaction outcome

A transaction helper often looks correct in a successful request while leaking a connection on an exception. Under load the pool exhausts and later requests wait indefinitely. finally covers the paths that normal return statements and rollback handlers miss.

Save this requirement in Perch and check it after each agent edit. The rule gives your agent a named check to run, a finding to repair, and the same command to recheck.

## Implement the Express boundary

Save this illustrative integration module as `transaction.cjs`.

```
async function withTransaction(pool, operation) {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    const result = await operation(client);
    await client.query("COMMIT");
    return result;
  } catch (error) {
    try { await client.query("ROLLBACK"); }
    catch (rollbackError) { error.rollbackError = rollbackError; }
    throw error;
  } finally {
    client.release();
  }
}
module.exports = { withTransaction };
```

The order, inventory, or resource-lifetime scenario is adapted from Perch’s public [order-service source at commit 4af67af](https://github.com/lakeday-org/perch/blob/4af67af46d76ac99398d61c7ad0a45441760d4dc/test/fixtures/order-service/storage.py). This Express implementation is an illustrative adaptation.

## Integrate with your application

In an Express POST handler, await withTransaction(pool, client => yourMutation(client)) and forward its rejection to the route error handler. Use a node-postgres Pool. Pass a callback that uses only the provided client throughout the transaction; pool.query may run on another connection. This helper attempts rollback after any error and preserves the original Error object; require operation to throw Error instances. If rollback fails because the connection is unhealthy, extend the adapter to destroy that client with release(error) rather than reuse it.

## Exercise the boundary and failure paths

| Scenario | Expected outcome |
| --- | --- |
| Operation succeeds | COMMIT then release once |
| Operation throws | ROLLBACK, original error, release once |
| ROLLBACK throws | Original error preserved, release still attempted |
| Pool acquisition fails | No acquired client to release |

Add regression tests for these cases in your existing Express test project. Use separate connections or deliberately reordered completion where the case involves concurrency; a sequential happy-path test does not exercise that failure. Run the test command after creating the matching test file or suite:

```
node --test tests/transaction.test.cjs
```

A focused test to adapt to the paths and test dependencies in your project:

```
const test = require("node:test");
const assert = require("node:assert/strict");
const { withTransaction } = require("../transaction.cjs");
test("rollback failure still releases", async () => {
  let released = 0;
  const original = new Error("operation failed");
  const client = { query: async sql => { if (sql === "ROLLBACK") throw new Error("connection lost"); }, release: () => released++ };
  await assert.rejects(withTransaction({connect:async()=>client}, async()=>{throw original}), error=>error === original);
  assert.equal(released, 1);
});
```

## Introduce the specific agent regression

In a throwaway copy, replace this source span:

```
client.release();
```

with:

```
// Client is accidentally retained.
```

Run the relevant negative test and the Perch command on that broken copy. Restore the corrected source before committing the application. The supplied mutation reproduces the exact regression for the rule check.

## Preserve the requirement as a Perch rule

Save this in `.perch/rules/perch-guide-express-transaction-cleanup.yaml` at the repository root, keeping your existing `perch.yaml`:

```
- name: transaction-releases-client
  where: "transaction.cjs"
  ensure: >-
    The withTransaction helper returns every acquired PostgreSQL client to its pool by executing client.release() in finally, including when the operation or rollback throws. A finally block containing only a comment leaves the acquired client unreleased.
```

Install and authenticate the CLI once, then check the current working file:

```
npm install -g @lakeday/perch
perch login
perch check transaction.cjs --rules transaction-releases-client --json
```

Use Node 22 or newer. The framework can use another language; Perch’s CLI remains a Node command. A gated finding exits 3. Exits 1 or 2 mean the check did not complete and must be reported as a blocker.

## Inspect the captured rule check

On 2026-10-14, Perch using jev-latest checked the exact fixed and broken source provided here. The capture records SHA-256 hashes of both sources and the requirement.

| Source control | Exit | Outcome |
| --- | --- | --- |
| Broken | 3 | Rule finding |
| Corrected | 0 | No rule finding |

The rule distinguished these controls in this run. [Raw Perch capture](https://frameworkrecipes.dev/express/transaction-cleanup/capture.json) · [Exact sources and mutation](https://frameworkrecipes.dev/express/transaction-cleanup/source.json).

## Install the rule pack and configure your agent

[Download this rule pack ZIP](https://reporules.fyi/express/transaction-cleanup/rule-pack.zip) · [Download the YAML rules](https://reporules.fyi/express/transaction-cleanup/rules.yaml) · [Agent task](https://reporules.fyi/express/transaction-cleanup/agent-task.txt). The pack contains the rule, its example paths and the repair/recheck instructions. Review the `where` selector before using it in an existing project. Keep your root `perch.yaml`; install this rule as a separate file under `.perch/rules/`.

1. Install Perch using Node 22 or newer and sign in once:

```
npm install -g @lakeday/perch
perch login
```

1. Download the pack, inspect it, and extract it from your repository root. The extraction preserves any existing files:

```
curl -fL 'https://frameworkrecipes.dev/express/transaction-cleanup/rule-pack.zip' -o 'perch-guide-express-transaction-cleanup.zip'
unzip -n 'perch-guide-express-transaction-cleanup.zip'
```

The installed rule is `.perch/rules/perch-guide-express-transaction-cleanup.yaml`. Its selector matches `transaction.cjs` in this example; adapt the selector to your application file before checking an existing project.

1. Configure the coding agent you use. Run one of these commands:

Claude Code:

```
perch setup claude-code
```

Codex:

```
perch setup codex
```

Cursor:

```
perch setup cursor
```

Pi:

```
perch setup pi
```

1. Ask the agent to edit the implementation and check the saved requirement:

> Use the installed Perch skill while editing transaction.cjs. Preserve transaction-releases-client. Run perch check transaction.cjs --rules transaction-releases-client --json after the edit. Read each finding and the affected code, fix the implementation, and run the identical check again after the fix. Keep the rule and regression tests intact. Run the application's relevant regression tests and report the commands and actual results. Exit 3 means a rule finding; exit 1 or 2 means the check did not complete. Report an unavailable or incomplete check as blocked. Do not claim the application tests ran if only the Perch check ran.

1. After repairing a finding, run the same check again and inspect the result:

```
perch check transaction.cjs --rules transaction-releases-client --json
```

Commit the downloaded rule and the installed agent configuration with your application. The rule file adds no guarantee of correctness; keep the regression tests from this guide.

With the base reference fetched, use `perch scan --since origin/main --filter type=lint` in CI.

## Framework references and verification scope

- [node-postgres.com reference](https://node-postgres.com/features/transactions)

The dated capture records the source check shown above. Implement the adapters, schema and regression tests described in this guide in your application. Unchanged requests reuse cached answers; fresh model judgments can vary. Model analysis sends relevant source to the configured service.

**Framework Recipes**

Implementation, failure path, check.

Published by Perch · © 2026 Verglas LLC. Framework Recipes is a Perch publication.

Perch’s MIT license covers the CLI; hosted model analysis is a paid service. Relevant source is sent to the configured model service.

[Perch CLI MIT license](https://github.com/lakeday-org/perch/blob/main/LICENSE) · [Article text](https://frameworkrecipes.dev/express/transaction-cleanup/index.md) · [Resource index](https://frameworkrecipes.dev/llms.txt)
