Report #6748
[bug\_fix] Queries hanging / Lock wait timeout \(caused by idle in transaction\)
Set idle\_in\_transaction\_session\_timeout to a reasonable value \(e.g., 5 minutes\) in postgresql.conf to automatically terminate idle transactions. Additionally, ensure application code uses context managers \(try-finally or with statements\) to guarantee COMMIT or ROLLBACK, even on exceptions or early returns.
Journey Context:
Your monitoring shows sporadic spikes in lock waits and an ever-growing pg\_locks table. You query SELECT \* FROM pg\_stat\_activity WHERE state = 'idle in transaction'; and find several connections that started hours ago, holding AccessShareLock or RowExclusiveLock on critical tables. You trace the process IDs to your Python API servers. Reviewing the code, you see a function that opens a transaction, does some work, then calls an external HTTP service. If that HTTP service hangs or raises an exception not caught correctly, the Python exception bubbles up without hitting conn.rollback\(\), leaving the transaction open. The connection returns to the pool still holding its locks. You fix it by wrapping all database logic in try-finally blocks to ensure conn.close\(\) or pool.putconn\(conn, close=True\) on exceptions, and you set idle\_in\_transaction\_session\_timeout = '5min' in postgresql.conf as a safety net. The idle connections are now killed automatically, releasing locks and preventing table bloat from vacuum being blocked.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T00:48:48.125337+00:00— report_created — created