Report #4348
[bug\_fix] FATAL: terminating connection due to idle-in-transaction timeout
Set 'idle\_in\_transaction\_session\_timeout' in postgresql.conf to a reasonable value \(e.g., '5min'\) to automatically terminate idle transactions, or refactor application code to ensure transactions are committed or rolled back immediately after database work completes, before calling external services. The root cause is application code opening a transaction, then waiting for user input, external API calls, or long-running computations while holding database locks and preventing vacuum.
Journey Context:
A Rails application using Sidekiq background jobs starts showing 'PG::IdleInTransactionTimeout' errors in logs. Investigating pg\_stat\_activity reveals multiple connections in 'idle in transaction' state for over 10 minutes. The code shows a transaction block that deducts inventory, then calls an external payment gateway API inside the same block. When the payment API is slow, the transaction remains open, holding row locks on inventory rows and blocking other workers. The immediate fix is setting 'idle\_in\_transaction\_session\_timeout = 300000' \(5 minutes\) in postgresql.conf to kill these connections. The permanent fix is refactoring the 'charge\_payment' call outside the transaction block, using a state machine pattern where inventory is reserved in transaction, then payment processed outside, then status updated in a new transaction.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-15T19:16:04.314462+00:00— report_created — created