TL;DR: A session in the idle in transaction state has opened a transaction and is doing nothing, usually because application code is waiting on something else (an HTTP call, a user, a forgotten commit). It keeps its locks and pins the oldest visible transaction, so migrations queue behind it and vacuum cannot clean up dead rows. Find the sessions in pg_stat_activity, fix the code path that holds a transaction open across slow work, and set idle_in_transaction_session_timeout as a backstop.

Behavior described here is accurate for current Postgres releases as of late 2026; the parameters I mention exist in the versions noted below.

How do I know this is my problem?

The symptoms are indirect, which is why this one takes people days. A migration that should take milliseconds hangs on ALTER TABLE. Table bloat grows even though autovacuum is running. Or the connection count creeps toward max_connections with nothing obviously busy.

Start here:

SELECT pid, usename, application_name, now() - xact_start AS xact_age, now() - state_change AS idle_for, left(query, 80) AS last_query FROM pg_stat_activity WHERE state = 'idle in transaction' ORDER BY xact_start; 

query shows the last statement that session ran, not what it is waiting for. If you see a SELECT or UPDATE with an idle_for measured in minutes, that session began a transaction, ran something, and then went quiet. Check application_name to tell which service owns it; if yours is blank, set it in the connection string, it pays for itself the first time you need it.

Takeaway: idle in transaction with a large idle_for is never normal load; it is a client that stopped talking mid-transaction.

Why does it block migrations and vacuum?

Two separate mechanisms, both consequences of the transaction staying open.

Locks. Any lock the transaction took is held until it ends. A plain SELECT takes an ACCESS SHARE lock on the table, and that is enough to make ALTER TABLE (which needs ACCESS EXCLUSIVE) wait. Worse, once your migration is queued waiting, every new query on that table queues behind the migration. One forgotten session turns into an outage.

Vacuum horizon. Vacuum can only remove dead row versions that no open transaction could still need to see. A transaction that has been open for hours holds the cleanup horizon back, so dead rows accumulate across every table it could theoretically read. You can see the culprit's horizon like this:

SELECT pid, age(backend_xmin) AS xmin_age, state, now() - xact_start AS xact_age FROM pg_stat_activity WHERE backend_xmin IS NOT NULL ORDER BY age(backend_xmin) DESC LIMIT 5; 

Takeaway: one idle transaction can block DDL through locks and block vacuum through its snapshot, and neither shows up as a slow query.

What code actually causes it?

In my experience it is almost always one of four patterns:

  1. Network calls inside a transaction. Open a transaction, update a row, call a payment or email API, then commit. The API's latency is now your lock duration.
  2. Implicit transactions from the driver. Many Python drivers do not autocommit. In psycopg 3, for example, the first statement on a connection starts a transaction, so a read-only SELECT followed by lots of non-database work leaves the session idle in transaction until you commit or roll back.
  3. Exceptions that skip the cleanup. A commit at the end of a function with no finally or context manager.
  4. A human. Someone ran BEGIN; in a SQL console and went to lunch.

Here is the first two patterns in code, and the fix:

import psycopg import requests # Anti-pattern: the connection sits in a transaction during the HTTP call. def charge_bad(conn, order_id): row = conn.execute("SELECT amount FROM orders WHERE id = %s", (order_id,)).fetchone() requests.post("https://payments.example.com/charge", json={"amount": row[0]}, timeout=10) conn.execute("UPDATE orders SET status = 'paid' WHERE id = %s", (order_id,)) conn.commit() # Better: keep each transaction short and do slow work between them. def charge_good(conn, order_id): with conn.transaction(): row = conn.execute("SELECT amount FROM orders WHERE id = %s", (order_id,)).fetchone() requests.post("https://payments.example.com/charge", json={"amount": row[0]}, timeout=10) with conn.transaction(): conn.execute("UPDATE orders SET status = 'paid' WHERE id = %s", (order_id,)) 

The with conn.transaction() block commits on success and rolls back on exception, which removes pattern 3 as well. (If a payment can succeed while your second transaction fails, you need an idempotency key; that is a separate problem from this one.)

The same shape applies in ORMs: do not hold a session open across a request handler that also calls external services. Open it late, close it early.

Takeaway: a transaction should contain database work only; anything that can wait on the network belongs outside it.

Which timeout should I set?

Postgres gives you server-side backstops. Use them, but understand they kill connections, so your app must handle that.

Setting Scope What it does Availability
idle_in_transaction_session_timeout session/role/db Terminates a session idle inside a transaction too long Postgres 9.6+
idle_session_timeout session/role/db Terminates sessions idle outside a transaction Postgres 14+
transaction_timeout session/role/db Caps total transaction duration, active or idle Postgres 17+
statement_timeout session/role/db Caps a single statement Long-standing
lock_timeout session/role/db Gives up waiting for a lock Long-standing

Set the first one per role rather than globally, so an admin's console session is not treated the same as your web app:

ALTER ROLE app_user SET idle_in_transaction_session_timeout = '30s'; 

When it fires, the server log shows FATAL: terminating connection due to idle-in-transaction timeout, and the client's next query fails with a connection error. Pooled connections handle this unevenly: make sure your pool validates or discards dead connections. If you use PgBouncer, it has its own idle_transaction_timeout setting that acts at the pooler.

Also add lock_timeout to your migration runner so that a blocked ALTER TABLE fails fast instead of queueing the whole table's traffic behind it. To clear a stuck session right now:

SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'idle in transaction' AND now() - state_change > interval '10 minutes'; 

Run that with care in production: terminating rolls back whatever that session had uncommitted.

Takeaway: the timeout is a seatbelt, not the fix; if it ever fires in normal operation, the bug is still in your code.

FAQ

Why is my Postgres connection stuck in "idle in transaction"?
The client opened a transaction (explicitly, or implicitly via its driver) and has not committed or rolled back. The usual cause is application code doing slow non-database work, or throwing an exception, between statements.

Does "idle in transaction" block other queries?
Yes, if it holds a lock another query needs; a queued ALTER TABLE will then block later queries behind it. Even when nothing is blocked, it holds back vacuum from removing dead rows.

What is a safe value for idle_in_transaction_session_timeout?
Something longer than your slowest legitimate gap between statements, commonly tens of seconds for a web app. Apply it to the application role and leave it off for roles used by people at consoles.

Bottom line

If you run a web app on Postgres, query pg_stat_activity for idle in transaction today; finding one is cheap and tells you whether your code holds transactions across network calls. Fix the code first by keeping transactions short and scoped with a context manager. Then set idle_in_transaction_session_timeout on the app role and lock_timeout on migrations so the next mistake costs seconds instead of an outage.

Related reading