# Postgres "idle in transaction": how one forgotten COMMIT blocks VACUUM and migrations, and the timeouts that fix it

What idle in transaction means in pg_stat_activity, which of those sessions actually stop VACUUM (and which don't), how they block row updates and ALTER TABLE, how to find and kill them, and how idle_in_transaction_session_timeout and PostgreSQL 17's new transaction_timeout end them for you. Every example replayed on Postgres 17.11.

**A session in the `idle in transaction` state isn't doing anything. It ran `BEGIN`, maybe a query or two, and then the application went off to call an API, wait for a user, or crash on an exception path that never rolled back. It uses no CPU. But until it ends, it can keep `VACUUM` from cleaning up dead rows in every table of the database, hold row locks your other requests wait on, and make the next `ALTER TABLE` stall every query behind it. On a serverless Postgres like Relyt One it also counts as activity, so the compute can't suspend while the transaction stays open. Below we reproduce each effect on PostgreSQL 17.11, show the query that finds the culprit, and set the two timeouts that clean these sessions up automatically. PostgreSQL 17 added one of them, `transaction_timeout`.**

## The short version

- **`idle in transaction`** means the session is inside an open transaction and waiting for its client to send the next statement.
- **Not every one hurts VACUUM.** A read-only transaction at the default `READ COMMITTED` level held nothing back in our test. A `REPEATABLE READ` reader, or any transaction that has written a row, kept 20,000 dead rows in an unrelated table from being removed until it ended.
- **Every one holds its locks.** Even a plain `SELECT` keeps an `ACCESS SHARE` lock, which is enough to make `ALTER TABLE` wait, and every query on that table then queues behind the `ALTER`.
- **Find them** with `pg_stat_activity` (`state`, `xact_start`, `backend_xid`, `backend_xmin`) and `pg_blocking_pids()`. The `query` column shows the *last* statement, not the one that took the lock.
- **Fix them** with `idle_in_transaction_session_timeout` and, on Postgres 17, `transaction_timeout`. Both are off by default. Set them on the role your application connects as.

## How a session ends up idle in transaction

Every one of these has the same shape: a transaction is opened, and then the code that should end it doesn't run for a while.

- **Work inside the transaction that isn't database work.** The handler opens a transaction, reads a row, calls a payment API or sends an email, and only then writes and commits. If the API takes 30 seconds, the transaction is idle for 30 seconds.
- **An error path that never rolls back.** An exception is thrown between `BEGIN` and `COMMIT`, the code that catches it doesn't roll back, and the connection goes back to the pool with the transaction still open. If a statement failed, the state is `idle in transaction (aborted)`, and every later statement on that connection fails until someone rolls back.
- **A person at a SQL prompt.** Someone opens a SQL client with autocommit off, or types `BEGIN` in `psql`, runs a query, and goes to lunch.
- **A transaction around a batch job.** A script wraps a long loop in one transaction and spends most of each iteration in application code.

## What it looks like

Here is the reproduction setup: a 100,000-row `accounts` table and a two-row `settings` table, on a fresh `postgres:17.11-alpine` container with default settings.

```sql
CREATE TABLE accounts (id int PRIMARY KEY, balance int NOT NULL);
INSERT INTO accounts SELECT g, 1000 FROM generate_series(1, 100000) g;
CREATE TABLE settings (key text PRIMARY KEY, value text);
INSERT INTO settings VALUES ('theme', 'dark'), ('lang', 'en');
```

A second session runs a transaction and then stops talking:

```sql
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 42;
SELECT balance FROM accounts WHERE id = 42;
-- ...and nothing else for a while
```

From any other session, this query lists every open transaction that is waiting on its client, oldest first:

```sql
SELECT pid, application_name, state,
       backend_xid, backend_xmin,
       date_trunc('second', now() - xact_start)   AS in_tx_for,
       date_trunc('second', now() - state_change) AS idle_for,
       left(query, 60) AS last_query
FROM pg_stat_activity
WHERE state IN ('idle in transaction', 'idle in transaction (aborted)')
ORDER BY xact_start;
```

```text
 pid | application_name |        state        | backend_xid | backend_xmin | in_tx_for | idle_for |                 last_query
-----+------------------+---------------------+-------------+--------------+-----------+----------+---------------------------------------------
 160 | idle_app         | idle in transaction |         787 |              | 00:00:02  | 00:00:02 | SELECT balance FROM accounts WHERE id = 42;
```

Three columns do most of the work:

- `in_tx_for` is how long the transaction has been open. `idle_for` is how long since the client last sent anything. A transaction that has been open for an hour and idle for 59 minutes is the one you're looking for.
- `backend_xid` is set once the transaction has written something. `backend_xmin` is set while it holds a snapshot. Either one means it can hold back VACUUM (next section).
- `last_query` is the **last** statement the session ran, not the one that matters. Here it shows the `SELECT`, while the `UPDATE` before it is what holds the row lock. Don't read `query` as "what this session is doing".

To see what it holds, join `pg_locks` on the pid:

```sql
SELECT l.locktype, l.relation::regclass AS relation, l.mode, l.granted
FROM pg_locks l
WHERE l.pid = 160 AND l.locktype IN ('relation', 'transactionid')
ORDER BY 1, 2, 3;
```

```text
   locktype    |   relation    |       mode       | granted
---------------+---------------+------------------+---------
 relation      | accounts      | AccessShareLock  | t
 relation      | accounts      | RowExclusiveLock | t
 relation      | accounts_pkey | AccessShareLock  | t
 relation      | accounts_pkey | RowExclusiveLock | t
 transactionid |               | ExclusiveLock    | t
```

Every one of these is held until the transaction ends. The row lock on id 42 doesn't show up here; Postgres records it on the row itself, and the `transactionid` lock is what other sessions wait on to get it.

## Which ones stop VACUUM

When you update or delete a row, Postgres keeps the old version until no transaction could still need to see it. VACUUM removes old versions older than the oldest snapshot or transaction ID still in use. That point is called the **xmin horizon**, and one old transaction holds it back for every table in its database. The [PostgreSQL documentation](https://www.postgresql.org/docs/17/runtime-config-client.html#GUC-IDLE-IN-TRANSACTION-SESSION-TIMEOUT) puts it this way: "an open transaction prevents vacuuming away recently-dead tuples that may be visible only to this transaction."

But "open transaction" covers three different situations, and they don't behave the same. We left each kind of session idle on the tiny `settings` table, updated 20,000 rows of `accounts` from another session, and ran `VACUUM (VERBOSE) accounts`:

1. **Read-only, `READ COMMITTED`** (`BEGIN; SELECT count(*) FROM settings;`). Neither `backend_xid` nor `backend_xmin` was set. VACUUM reported `20000 removed`. At `READ COMMITTED`, each statement takes its own snapshot and drops it when it finishes, so between statements this session holds nothing back.
2. **Read-only, `REPEATABLE READ`** (`BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT count(*) FROM settings;`). `backend_xmin` was set. VACUUM reported `0 removed` and `20000 are dead but not yet removable`. The transaction keeps its first snapshot until it ends, so the old row versions in `accounts` must stay, even though it never touched that table.
3. **Wrote something, `READ COMMITTED`** (`BEGIN; UPDATE settings SET value = value WHERE key = 'theme';`). `backend_xid` was set. VACUUM reported `20000 are dead but not yet removable` again. A transaction with an ID holds back the horizon for as long as it's open.

The VACUUM output in case 3:

```text
tuples: 0 removed, 91954 remain, 20000 are dead but not yet removable
removable cutoff: 785, which was 2 XIDs old when operation ended
```

As soon as the `REPEATABLE READ` session and the writing session committed, the next VACUUM reported `20000 removed`. So the danger isn't "a transaction is open". It's **an open transaction that has written something, runs at `REPEATABLE READ` or `SERIALIZABLE`, or still has a cursor open**. The reliable test is the one from the previous section: if `backend_xid` or `backend_xmin` is set, the session is holding the horizon back. Left for hours on a busy database, it means tables and indexes that keep growing, autovacuum that runs and removes nothing, and queries that wade through dead rows.

The `removable cutoff ... which was N XIDs old` line is the quickest way to spot it from the VACUUM side: on a busy database, a cutoff that is millions of XIDs old points at something old holding the horizon. Besides idle transactions, that can be a long-running query, a replication slot, or a prepared transaction.

## Which ones block other sessions

Locks are a separate problem, and here every idle transaction that has touched a table counts, including the read-only `READ COMMITTED` one that VACUUM didn't care about.

**Row locks.** A session that updated row 8 and went idle keeps that row locked. Another `UPDATE` on row 8 waits for it, indefinitely by default. With `lock_timeout` set, it gives up instead:

```sql
SET lock_timeout = '2s';
UPDATE accounts SET balance = 1 WHERE id = 8;
```

```text
ERROR:  canceling statement due to lock timeout
CONTEXT:  while updating tuple (442,110) in relation "accounts"
```

**Table locks and the lock queue.** A session that only ran `SELECT balance FROM accounts WHERE id = 7` and went idle still holds `ACCESS SHARE` on `accounts`. That doesn't conflict with other reads or writes, but it does conflict with the `ACCESS EXCLUSIVE` lock most `ALTER TABLE` forms need. So the migration waits. And while it waits, every new query on `accounts`, even a plain `SELECT`, queues behind it. `pg_blocking_pids()` shows who is waiting on whom:

```sql
SELECT a.application_name AS waiting, a.wait_event_type, a.wait_event,
       b.application_name AS blocked_by, b.state AS blocker_state
FROM pg_stat_activity a
CROSS JOIN LATERAL unnest(pg_blocking_pids(a.pid)) AS bp(pid)
JOIN pg_stat_activity b ON b.pid = bp.pid
ORDER BY 1, 4;
```

```text
  waiting  | wait_event_type | wait_event | blocked_by  |    blocker_state
-----------+-----------------+------------+-------------+---------------------
 migration | Lock            | relation   | idle_reader | idle in transaction
 migration | Lock            | relation   | idle_writer | idle in transaction
```

A `SELECT` on `accounts` sent from another session at that point, with `statement_timeout = '2s'`, failed with `canceling statement due to statement timeout`. That's the part that turns a forgotten transaction into an outage: the idle session isn't blocking your reads directly, the migration waiting behind it is. We go through the lock queue in detail, and how to run DDL so it fails fast instead, in [which locks a migration takes](/blog/postgres-migration-locks).

## Ending one by hand

Once you've found the pid, `pg_terminate_backend()` closes that connection and rolls back its transaction. Unless you're a superuser, you can only signal sessions of a role whose privileges you have (or with `pg_signal_backend`), so the simplest way is to connect as the same role as the stuck session:

```sql
SELECT pg_terminate_backend(160);
```

In our run the session disappeared from `pg_stat_activity`, and the balance of account 42 was unchanged: the `- 10` was rolled back. `pg_cancel_backend()` won't help here. It cancels the *running* statement, and an idle session isn't running one: in our replay it returned `t`, the session stayed `idle in transaction`, and when its client came back it committed normally.

Termination means the application's next statement on that connection fails, and a well-behaved connection pool replaces the connection. That's acceptable for a stuck session, but it's not a fix. The fix is to make the server do it for you, quickly and consistently.

## The timeouts that end them automatically

Five settings matter here. All are off (`0`) by default, and all can be set per session, per role or per database:

- **`statement_timeout`** cancels a statement that runs too long. The error is an `ERROR`, the session survives, and the transaction is aborted.
- **`lock_timeout`** cancels a statement that waits too long for one lock. Also an `ERROR`.
- **`idle_in_transaction_session_timeout`** closes a session that has been idle inside a transaction too long. The error is `FATAL`, and the connection is gone.
- **`transaction_timeout`** (new in PostgreSQL 17) closes a session whose transaction has been open too long, idle or not. Also `FATAL`.
- **`idle_session_timeout`** closes a session that has been idle *outside* a transaction too long. Also `FATAL`.

Here is what each one looked like in our replay.

**`idle_in_transaction_session_timeout`** fires while the client is silent, but the client only finds out when it next sends something:

```sql
SET idle_in_transaction_session_timeout = '2s';
BEGIN;
UPDATE accounts SET balance = balance + 100 WHERE id = 1;
-- client waits 3 seconds
SELECT 'still here';
```

```text
FATAL:  terminating connection due to idle-in-transaction timeout
server closed the connection unexpectedly
```

The `UPDATE` was rolled back. Your driver will report this as a lost connection on the next query, so make sure the error path doesn't retry the second half of the transaction on a new connection as if the first half had happened.

**`transaction_timeout`** counts from the start of the transaction, whether the session is busy or idle. With a 3-second limit, a transaction that ran `pg_sleep(1)`, waited one second on the client, and then started `pg_sleep(2)` was ended partway through the second sleep:

```text
FATAL:  terminating connection due to transaction timeout
```

It also applies to a single statement outside `BEGIN`, which runs in its own implicit transaction. With `transaction_timeout = '1s'`, a bare `SELECT pg_sleep(2)` was ended the same way. So unlike `statement_timeout`, hitting it costs you the connection, not just the statement.

**`statement_timeout`**, for comparison, only cancels:

```text
ERROR:  canceling statement due to statement timeout
ERROR:  current transaction is aborted, commands ignored until end of transaction block
```

After `ROLLBACK` the same session kept working.

**When two of them apply**, the documentation says that if `transaction_timeout` is shorter than or equal to `idle_in_transaction_session_timeout` or `statement_timeout`, the longer one is ignored. We set the idle timeout to 10 seconds and the transaction timeout to 2; a transaction left idle was ended after 2 seconds by the transaction timeout.

### What to set

The documentation recommends against setting `statement_timeout`, `lock_timeout` or `transaction_timeout` in `postgresql.conf`, because they would apply to every session, including your migrations and maintenance jobs. Set them on the role your application connects as:

```sql
ALTER ROLE app_user SET idle_in_transaction_session_timeout = '30s';
ALTER ROLE app_user SET transaction_timeout = '5min';
```

Role settings apply at login: new connections as `app_user` pick these up, existing ones keep what they had, and a session that switches with `SET ROLE app_user` doesn't get them either. A job that legitimately needs longer can raise its own limit before it starts the transaction (`SET transaction_timeout = '30min'`, then `BEGIN`), since all of these are ordinary user-level settings. Raising it inside a transaction that is already running doesn't extend that transaction. Do this on a direct connection: behind a transaction-mode pooler, a session-level `SET` stays on the server connection and the next client inherits it. Simpler still, give long jobs their own role with a higher limit. We checked that a non-superuser role with `CREATEROLE` can create `app_user` and set both values on it, and that a new `app_user` session sees `30s` and `5min`.

Some starting points, to adjust for your workload:

- **`idle_in_transaction_session_timeout`**: seconds to a minute for a web app. A request handler has no reason to sit inside a transaction for longer than a request takes.
- **`transaction_timeout`**: longer than your slowest legitimate transaction. It's the backstop for transactions that are busy but endless, which the idle timeout never sees.
- **`statement_timeout`**: per role or per request, for runaway queries. It doesn't help with idle transactions at all.
- **`idle_session_timeout`**: usually leave it off for application roles. Plain idle sessions cost little, and the documentation warns that connection pools and other middleware may not react well when connections close under them. It's more useful for people who connect interactively.

A timeout is a safety net, not the fix. If it fires often, find the code that opens a transaction around non-database work and move that work outside it: read, call the API without a transaction open, then open a short transaction to write the result.

## On a serverless compute

On Relyt One, a compute that has had nothing to do for about ten minutes suspends, and the next connection resumes it. The compute's activity monitor decides what "nothing to do" means by looking at client sessions in `pg_stat_activity`: a session in the `idle` state counts as activity as of its last state change, and **any session in any other state, including `idle in transaction`, counts as activity right now**.

So a single forgotten transaction does more than block VACUUM. It keeps the compute awake for as long as the transaction stays open: overnight, over the weekend, until someone notices. Plain idle connections in your pool don't do that, as long as the pool isn't sending health-check queries: their last state change just keeps getting older. `idle_in_transaction_session_timeout` and `transaction_timeout` set on your application role therefore also put a ceiling on how long a stuck transaction can keep the compute running.

Relyt One runs PostgreSQL 17, so `transaction_timeout` is available, and the queries, the timeouts and the `ALTER ROLE` settings above are standard Postgres. The project's owner role can create the role your application connects as and set these values on it. For a role it didn't create, connect as that role and run `ALTER ROLE CURRENT_USER SET idle_in_transaction_session_timeout = '30s';` instead.

## Try it on a branch

To find out what your application does when a timeout fires, create a branch, set the timeouts on the role your staging app uses there (as shown above), and run your test suite against it. A branch has its own compute, so a transaction left open there doesn't affect the parent's VACUUM, locks or suspend. Then check `pg_stat_activity` with the query above while the tests run.

For more on what happens behind transaction-mode pooling, see [what breaks behind PgBouncer transaction pooling](/blog/pgbouncer-transaction-pooling). For the locking side, see [deadlock detected](/blog/postgres-deadlock-detected) and [transaction isolation levels](/blog/postgres-transaction-isolation-levels).

[Start for free](/auth/signin?ref=blog-postgres-idle-in-transaction)
