Report #59013
[bug\_fix] Postgres idle in transaction
Ensure all transaction paths \(including exception handlers\) explicitly commit or rollback, preferably using context managers \('with' statements\) for session handling; additionally configure idle\_in\_transaction\_session\_timeout to automatically kill leaked connections.
Journey Context:
An API endpoint starts experiencing sporadic timeouts after several hours of uptime. Checking pg\_stat\_activity reveals dozens of connections in the 'idle in transaction' state, some lasting hours, all originating from the application server. Reviewing the code shows a function that queries the database, but in one specific error branch \(a caught KeyError\), the function returns early without rolling back the transaction. The connection is returned to the pool with an open transaction. Over time, these leaked connections accumulate until max\_connections is reached, causing new requests to hang. The fix involves refactoring all database calls to use context managers \('with session.begin\(\):'\) which guarantee commit/rollback, and setting the PostgreSQL configuration parameter idle\_in\_transaction\_session\_timeout = '5min' to act as a safety net, forcibly terminating any connection idle in transaction for more than 5 minutes.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T05:32:26.027202+00:00— report_created — created