# Can AI subagents exhaust your connection pool?

> **Quick answer:** Yes, and it is easy. A subagent that opens its own connection
> holds it across reasoning steps that last seconds, so a handful of parallel
> agents can occupy a large share of a small pool while doing little work.
> Cap it at the server with `ALTER ROLE ... CONNECTION LIMIT` on a `NOSUPERUSER`
> role before you encounter the problem.

## What is the problem?

A database connection is not free. In PostgreSQL, each one is a separate
operating-system process with its own memory, and `max_connections` defaults to
100. Read your own value rather than assuming a managed instance is close to it:
the number varies by provider and instance size, and the budget an ordinary role
can actually use is smaller than the setting.

Agent workloads can use connections in an unusual way. The runtime does not
force this pattern, but it is what a straightforward implementation does:

- They fan out. One task becomes five or ten subagents, and the simple way to
  write that gives each its own client.
- They hold connections while thinking. The gap between two queries is a
  model call that lasts seconds, not microseconds.
- They retry. A retry that opens a new connection instead of returning one to a
  bounded pool turns a failure into a connection storm.

When agents behave this way, many connections remain idle and open for a long
time. That exhausts a pool while the database looks unloaded. A subagent behind
a shared client-side pool or a pooler avoids this problem, which addresses most
of the cause.

The failure also lands in the wrong place. When connections run out, the error
goes to whatever tries to connect next, which is usually your application
rather than the agent.

## How do I confirm it?

Count what is connected, by role and by state:

```sql
SELECT usename,
       application_name,
       state,
       count(*) AS connections
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY usename, application_name, state
ORDER BY connections DESC;
```

`idle in transaction` in that output is the row to worry about. Idle is a
connection doing nothing; idle in transaction is a connection doing nothing
inside an open transaction, still holding whatever locks it already took.
Whether it is also holding back vacuum is a separate question with its own
column, below.

Work out the budget an ordinary role actually has:

```sql
SELECT count(*) FILTER (WHERE backend_type = 'client backend') AS client_backends,
       count(*) AS all_backends,
       current_setting('max_connections')::int AS max_connections,
       current_setting('superuser_reserved_connections')::int AS superuser_reserved,
       coalesce(nullif(current_setting('reserved_connections', true), '')::int, 0)
         AS reserved
FROM pg_stat_activity;
```

Only client backends count against `max_connections`. Measured on 17.11 with
`max_connections = 12` and `superuser_reserved_connections = 3`, an ordinary role
got exactly nine connections and the tenth was refused with `remaining connection
slots are reserved for roles with the SUPERUSER attribute`. The checkpointer, the
background writer, the WAL writer, the autovacuum launcher, the logical
replication launcher and an open `walsender` were all present in
`pg_stat_activity` at the time and none of them changed that nine, which is why
the filter is there.

So the ordinary-role budget is `max_connections` minus both reservations.
`reserved_connections` is the second tier, added in PostgreSQL 16 for roles
granted `pg_use_reserved_connections`; it defaults to 0, so on most servers the
subtraction is just the superuser three. Those slots are for diagnosis, not
headroom.

Find the ones held open without work:

```sql
SELECT pid,
       usename,
       application_name,
       state,
       backend_xmin,
       now() - state_change AS in_state_for,
       now() - xact_start   AS xact_age
FROM pg_stat_activity
WHERE backend_type = 'client backend'
  AND state IN ('idle', 'idle in transaction', 'idle in transaction (aborted)')
ORDER BY state_change
LIMIT 20;
```

`idle in transaction (aborted)` belongs in that list and is easy to leave out. A
statement failed, the transaction is still open, and the client has to send
`ROLLBACK` before it can do anything else. An agent that swallows the error and
sits there produces exactly this state.

`backend_xmin` is the column that says whether the session is holding back
cleanup. A value means yes, null means no.

## What to do about it

### Cap the agent at the server

Do this first, because it is the only limit the agent cannot bypass from the
client side. The agent needs a role of its own:

```sql
CREATE ROLE ai_agent LOGIN PASSWORD 'use-a-generated-secret'
    NOSUPERUSER NOCREATEDB NOCREATEROLE;

ALTER ROLE ai_agent CONNECTION LIMIT 5;
```

Measured on PostgreSQL 17.11 in a stock `postgres:17.11` container on
2026-09-20, with that same role and `CONNECTION LIMIT 2` instead of 5, the third
concurrent connection was refused with
`FATAL:  too many connections for role "ai_agent"`. The error names the role, so
it goes to the tool that caused it instead of to your checkout page.

Two limits on that are stated in the manual for `CREATE ROLE`:

> The `CONNECTION LIMIT` option is only enforced approximately; if two new
> sessions start at about the same time when just one connection "slot" remains
> for the role, it is possible that both will fail. Also, the limit is never
> enforced for superusers.

The approximation errs towards refusing, so it costs you a connection rather than
the protection. The superuser exemption is absolute: with the same `CONNECTION
LIMIT 2` role altered to `SUPERUSER`, all four concurrent connections succeeded.
The cap depends on the `NOSUPERUSER` in the `CREATE ROLE` above.

The cap applies to the role, not to the agent. If subagents reach the database
through PgBouncer under one shared login, PostgreSQL sees the pooler's server
connections, so the limit bounds those and not the number of subagents. That is
still the bound you want, but know which number you are setting.

Check what limits are set:

```sql
SELECT rolname, rolconnlimit
FROM pg_roles
WHERE rolcanlogin
ORDER BY rolname;
```

`-1` means unlimited, and it is the default, so any role that nobody has
deliberately capped is on it.

### Stop connections being held in a transaction

```sql
ALTER ROLE ai_agent SET idle_in_transaction_session_timeout = '30s';
ALTER ROLE ai_agent SET statement_timeout = '30s';
```

The first setting matters most for agents. Set both on the agent's own role
rather than globally: a `statement_timeout` of 30 seconds applies to every
statement, so on a shared role it cancels the migration and the batch job as
readily as the runaway.

How much an agent that opens a transaction and then thinks costs you depends on
what it did inside that transaction, and one column shows this. Measured on
17.11, three shapes of the same 30-second pause, against a table with 50,000
dead rows in it:

| what the transaction did first | `backend_xmin` | dead rows vacuum could remove |
|---|---|---|
| `SELECT`, at the default `READ COMMITTED` | null | all 50,000 |
| one `INSERT`, at `READ COMMITTED` | null, but `backend_xid` set | none |
| `SELECT`, at `REPEATABLE READ` | set | none |

READ COMMITTED releases the snapshot at the end of each statement, so a
read-only transaction sitting idle is not holding the horizon at all. A
transaction that has written holds its own transaction id open, and that has
the same effect. The practical rule for agents is narrower than "never leave a
transaction open": a transaction that has written, or one at `REPEATABLE READ`
or `SERIALIZABLE`, must not span a model call.

The effect is per database, not per cluster. In the same test, the dead rows in
a second database on the same server were all reclaimed while the first was
frozen.

### Put a pooler in front

PgBouncer in transaction pooling mode lets many clients share few server
connections, which cuts the number of backend processes and the memory they hold
idle. It does not remove the cost: PgBouncer is itself a process and the active
backends are still backends. It also does not help with an agent that holds a
transaction open, because the server connection is held for the length of the
transaction. It gives clients a queue: they wait at the pooler instead of
arriving at the server, and `max_client_conn` and the pool sizes are yours to
set. Fix the client behaviour first, then pool.

Transaction pooling is not transparent. Session-scoped state does not survive
it, including session advisory locks, `PREPARE` and `DEALLOCATE`, and `WITH
HOLD` cursors. Check the PgBouncer feature matrix against what the client does
before switching a running application into it.

### Give the agent a replica

Read-only agent traffic on its own replica means exhausting that pool costs you
an agent, not an application. Two conditions apply: the replica has to be the
agent's rather than shared with reporting, or you have moved the problem, and
the agent has to tolerate replica lag, which rules out reading back its own
writes.

## Why does AI-generated code cause this?

There are two patterns. The first comes from the orchestration rather than from
generated code. Fan-out is the point of subagents, and the connection is usually
opened per subagent because that is the simple way to write it.

The second is the common generated shape: open a connection, `BEGIN`, do some
work, call something external, commit. In an agent, the external call is the
model itself, so the transaction lasts a reasoning step. On a single developer
machine that is invisible. With ten subagents against a shared database, a pool
can be exhausted by processes that are not doing anything.

## How do I stop it coming back?

**Set `CONNECTION LIMIT` on every agent role at creation**, not after the first
incident. Derive the number rather than copying one: start from
`max_connections`, subtract the reservations, subtract what the application and
its workers need at peak, and give the agent a slice of what is left. You can
raise it once you know which number you are moving.

**Do not hold a writing transaction across a model call.** Write, commit, think,
then open a new one. A read-only transaction at `READ COMMITTED` is the one case
where the pause is free, and relying on that means relying on nobody adding a
write to the middle of it later.

**Monitor connections by role**, so the number that climbs tells you which client
is responsible.

**Set `max_connections` from what the instance can support**, and remember that
raising it multiplies memory use rather than creating capacity.

## How DBGorilla helps

DBGorilla connects read-only and gives your AI coding agent the connection
picture as a time series rather than a single reading: total, active, idle and
idle-in-transaction counts at the latest snapshot, and the sessions in each
snapshot with their user, state, wait event and query duration. Sessions sitting plainly idle
are counted rather than listed one by one; idle-in-transaction sessions are
listed, which is the state that holds a pool slot and an open transaction at
once. Verified in a live session, those snapshots are sampled continuously, so
the agent can see the climb that led to exhaustion instead of the aftermath.
[Get started free →](https://app.dbgorilla.com/signup)

## Related

- [PostgreSQL connection pooling and too many connections](https://www.dbgorilla.com/learn/postgres/postgresql-connection-pooling-too-many-connections/)
- [How to fix idle in transaction connections](https://www.dbgorilla.com/learn/postgres/how-to-fix-idle-in-transaction-connections/)
- [How to set up a read-only Postgres role for an AI agent](https://www.dbgorilla.com/learn/postgres/how-to-set-up-a-read-only-postgres-role-for-an-ai-agent/)