Long-running and idle-in-transaction sessions in PostgreSQL

How to find the sessions that hold back vacuum and replication, which timeout settings stop them and what application changes remove the cause, planned for PostgreSQL you run.

On this page

Why long-running transactions in PostgreSQL stall vacuum and replication

This section explains why a single open transaction can stop PostgreSQL from reclaiming dead rows and can push a replica or the WAL directory far behind, and it sets up the checks and settings that follow on this page. An open transaction holds back the cleanup horizon: while it lives, VACUUM cannot remove row versions that the transaction might still need to see, so dead tuples accumulate and tables and indexes bloat. The same snapshot logic affects standbys with hot standby feedback enabled, and a long-lived transaction can keep old WAL and replication slot positions from advancing. The symptom usually appears far from the cause: a table grows steadily, pg_wal fills, or a replica lags, and the team spends days on VACUUM tuning before anyone looks at the sessions.

Idle-in-transaction sessions are the most common culprit. An application opens a transaction, runs a query, then waits on an external call, a user, a message queue or a connection pool that never releases the session. The backend state shows idle in transaction in pg_stat_activity, and the transaction keeps its snapshot and locks until it ends. Long batch jobs, cursors left open, and ORMs that wrap reads in transactions by default produce the same pattern. A session that is actively running a slow query is a different problem, and it needs query tuning rather than session timeouts, so the first task is to tell the two apart.

A team needs this work when vacuum falls behind on a busy table, when the age of the oldest transaction keeps climbing, when replication lag grows without a network or disk fault, or when a planned cleanup does not free space. Before changing any setting, confirm which application or service owns each session, whether the transaction is intentional, and whether your monitoring already captures transaction age. Changing timeouts without knowing the owner tends to break jobs that were correct, so the diagnosis should come first and the fixes should follow the findings.

Which timeout or view fits which situation

This table compares the inspection view and the four timeout and guard settings that bound long or idle transactions, showing what each limits, where it is set and what it costs the workload. Read it by matching the symptom you see to the row, then check the trade-off column before changing any setting in production.

ToolWhat it limits or showsWhere it is setTrade-off to weigh
pg_stat_activity inspectionShows current sessions, state, xact_start and query_start so you can find old transactions and sessions stuck idle in transactionA read-only view; no setting to changeShows the problem but does not stop it; you must act on what you find
statement_timeoutCancels any single statement that runs longer than the limit, leaving the session openServer, role, database or sessionCan kill legitimate batch or reporting queries and surprise application code that does not handle the cancellation error
transaction_timeoutEnds a whole transaction, including idle time inside it, once it exceeds the limitServer, role, database or sessionLong multi-step jobs that span many statements may fail; confirm the release that introduced it in the PostgreSQL docs before relying on it
idle_in_transaction_session_timeoutTerminates a session that has sat idle inside an open transaction for longer than the limitServer, role, database or sessionApplication pools or ORMs that hold transactions open while waiting on external calls will see dropped connections
lock_timeoutGives up waiting for a lock after the limit, so a DDL or query does not queue behind others indefinitelyServer, role, database or sessionFailed statements must be retried; it does not end sessions that already hold locks

How to find and contain offending sessions safely

This sequence moves from observing the offending sessions to fixing their cause, so the team can identify who holds a transaction open, what it is holding back, and which timeout to set before anyone terminates a session.

  1. Snapshot current session state in pg_stat_activity

    The DBA or platform engineer runs a query against pg_stat_activity that lists sessions with state, xact_start, query_start, state_change and backend_xmin, filtered to rows where state is idle in transaction or where the transaction has been open for a long time. Save the output with a timestamp so the picture can be compared later. Done when the team has a saved list of candidate sessions, each with its transaction start time and its state.

  2. Identify the application and client behind each session

    For each candidate session, the engineer reads application_name, client_addr, usename, datname and backend_type from the same view. They match these values to a service, job or connection pool the application owner recognizes. Where application_name is empty or generic, the team confirms the source through connection pool configuration or the deployment inventory. Done when every long-lived session maps to a named workload or is marked as unknown for follow-up.

  3. Check whether the session holds back xmin

    The engineer compares backend_xmin values in pg_stat_activity against the oldest xmin the cluster is holding, and checks the xmin column in pg_replication_slots for slots that may pin old row versions. A session with an old backend_xmin prevents VACUUM from removing dead rows that are newer than that transaction. Done when the team knows whether a session, a replication slot, or both are the oldest holdback, and records which one is the limiting factor.

  4. Review replication slots for holdbacks

    The DBA reviews pg_replication_slots for inactive or lagging slots, looking at active, xmin, catalog_xmin and restart_lsn. A slot whose consumer has stopped can hold back cleanup and WAL retention even when no application session is idle. Done when each slot is labeled as active and healthy, active but lagging, or inactive, with the owning consumer identified. Slots are not dropped in this step.

  5. Decide when to contact the application owner

    Before any session is terminated, the team contacts the application owner if the session belongs to a business workload, if it may hold an uncommitted write, if it is part of a batch or migration, or if the owner cannot be identified. The owner confirms whether the transaction can be rolled back safely and whether a retry is possible. Terminating a session rolls back its open work, so this decision must be recorded. Done when the owner has replied or the team has documented why the session is safe to end.

  6. Set timeouts at the narrowest effective scope

    The team sets idle_in_transaction_session_timeout, transaction_timeout and statement_timeout at the scope that matches the offending workload, such as a specific role, database or application user, using ALTER ROLE or ALTER DATABASE, before changing cluster-wide defaults in postgresql.conf. Settings that apply to a whole cluster affect every client, so the team confirms the values with each owner first. Done when the new values are in place for the chosen scope and recorded in change control.

  7. Verify the timeouts with a controlled test

    In a non-production environment or during a planned window, the engineer opens a session, starts a transaction, runs a short statement, and leaves the transaction idle to confirm the timeout terminates it with the expected error. The test also confirms that a normal short transaction and a legitimate long job are not affected. Done when the test shows the expected termination and the application team confirms its retry behavior against the logged error.

  8. Fix the application pattern and monitor recurrence

    The application owner changes the code that opened the transaction early, such as an external API call or user prompt made while a transaction is open, and adds commit or rollback handling. The platform team then watches pg_stat_activity and xmin holdbacks on a schedule and alerts when idle-in-transaction time or oldest transaction age rises again. Done when the sessions no longer appear in the snapshot over a period the team agrees, and the alert has been tested.

Application patterns that leave transactions open

Connection poolers hand a physical connection from one client to another. If a client begins a transaction and disconnects, or the application fails to commit or roll back on an error path, the server session can come back to the pool still inside a transaction. The next borrower then inherits an open snapshot that it did not create, and the session can sit in the idle-in-transaction state for as long as the pool keeps it. The fix lives in both the application and the pool configuration.

  • Always close the transaction on every path: Wrap work in a construct that commits on success and rolls back on any exception, so error branches cannot skip the rollback.
  • Set pool reset behavior deliberately: Confirm how your pooler resets sessions between clients, and whether it runs a rollback or discards the connection when a client leaves mid-transaction. Check the PgBouncer documentation for the pool modes that match your application.
  • Pick the pool mode with transactions in mind: Transaction-level pooling returns the server connection at each commit, which limits how long a leaked transaction can pin it. Session-level pooling does not offer that boundary.
  • Stop leaked sessions from being reused: Use a server-side idle-in-transaction timeout as a backstop so a leaked session is terminated rather than inherited.
  • Test error paths: Force failures in integration tests and confirm that no session is left in the idle-in-transaction state afterward.

Check that every pooled connection returns to the idle state after each request, and that error paths in your code tested in staging leave no open transaction.

How a stuck session holds back vacuum and WAL recycling

The flow starts when an application checks out a pooled connection and opens a transaction that never commits or rolls back. The backend keeps its snapshot, so the oldest transaction xmin stays pinned and vacuum cannot remove dead rows newer than that point. Check pg_stat_activity for idle in transaction sessions and the backend_xmin column first, then pg_replication_slots and standby replay positions, where the same pin shows up as lag. The timeout settings mark where the chain can be broken.

Where an open transaction pins vacuum, WAL and replicas, with detection and timeout points marked.

Security and operational risks of killing sessions and changing timeouts

Timeouts and session kills are effective because they act fast, but they also end work that someone expected to finish. The cards below cover who may end sessions, how those actions are recorded, how applications recover without losing writes, how admin and migration accounts are exempted, and who can see other users' queries.

Limit who can terminate backends

Calling pg_terminate_backend() or pg_cancel_backend() on another role's session requires membership in the pg_signal_backend role or superuser rights. Decide in advance which operators and monitoring accounts hold that privilege, because a terminated backend rolls back its open transaction and can interrupt a batch job or a migration. Check which roles in your cluster hold it today and remove it from shared or application accounts.

Replication docs

Log killed and cancelled sessions

A timeout that rolls back work produces an error in the application but may leave no clear trace on the database side. Set log_min_error_statement and review the server log for FATAL or ERROR entries that show timeout messages, and record which role issued any manual termination in your own runbook or audit trail. Confirm that log retention covers the period when a slowdown happened, so the incident can be reconstructed later.

Make application retries safe

When a session is ended mid-transaction, the database discards every uncommitted change, but the application may not know whether a non-idempotent write (a payment, a stock movement or an email send) completed. Use idempotency keys for writes that a retry could repeat, and retry only whole transactions, never single statements inside one. Test each retry path by forcing a timeout in a staging copy and confirming that no record is duplicated or lost.

Scope timeouts to admin and migration roles

Setting statement_timeout or idle_in_transaction_session_timeout cluster-wide can break pg_dump runs, index builds and schema migrations that legitimately run for hours. Apply stricter values to application roles with ALTER ROLE ... SET and give maintenance accounts a documented exemption, or set the value to 0 for that role only. Review role-level settings during each change window, since a timeout set on the wrong role is a common source of failed jobs.

Restrict who can see other sessions

pg_stat_activity shows the query text of other roles' sessions to users with the pg_read_all_stats role, and to superusers. Query text can contain personal data or values typed into filters, so grant that role only to monitoring and on-call accounts. Confirm that application roles see only their own sessions, and treat the monitoring account's credentials as sensitive since they expose client addresses and application names.

Separate emergency access from daily use

Operators who need to end a session during an incident should use a named account with its own credentials, not a shared superuser login. Record who held that access and when, and rehearse the procedure so that a termination is deliberate and scoped to a specific pid after checking its state and transaction start time. Ask your identity team how that access is granted and removed, and whether it expires automatically.

Questions teams ask before fixing long transactions

How much does it cost to fix long-running transactions in PostgreSQL?

The cost depends on how many applications connect to the database, how much of their code and configuration must change, and whether the team needs monitoring and alerting added at the same time. Most of the spend is labor: someone must find the sessions that stay open, trace each one to application code, and test the change. Ask for a written scope that lists the applications in scope, the timeouts to configure, the monitoring to add and the retest to run, then compare the quote line by line against that list. DeployOpen does not publish a price list, so a quote follows from the written scope.

How long does a fix for idle-in-transaction sessions usually take?

Duration depends on how many services hold transactions open, how quickly the owners can review their code, and how long the change windows are. The configuration change itself is quick to make, but confirming that no legitimate batch job breaks takes longer. Plan for a short discovery period to measure session behavior in pg_stat_activity, then a staged rollout of timeouts per application. Ask the provider to state the phases, the dependencies on application teams and the point at which the work is considered complete.

What does our team need to provide for this work?

The work needs read access to the PostgreSQL server statistics and logs, a list of applications and their owners, and access to the code or configuration that opens database connections. It also needs a test or staging environment that resembles production traffic, and a change window for timeout settings. Application owners must be available to review their session patterns, because most idle transactions come from code that opens a transaction and then waits on an external call. Confirm these inputs in the scope before work starts.

Can our own DBA or platform team fix long transactions without a partner?

Yes, many teams can. The database settings are standard, and the investigation uses built-in views and logs. A partner adds value when many applications are involved, when the ORM or pooler design makes the root cause hard to see, or when the team needs an independent review before a change to production timeouts. Your team should be able to read pg_stat_activity, understand transaction boundaries in its own code, and test timeouts in staging. If one of these is missing, a fixed-scope engagement can cover the gap.

Which factors raise the effort for this work the most?

Three factors raise effort most often. The first is the number of applications and services that share the database, since each one needs its own investigation and owner sign-off. The second is pooler design: transaction-mode pooling such as PgBouncer changes which session settings and prepared statements are safe, so the pooler configuration must be reviewed alongside the timeouts. The third is ORM use, because some frameworks open transactions implicitly or hold them across request boundaries. Each of these adds review time that a simple timeout change does not remove.

Will setting timeouts break our batch jobs or background workers?

It can, if the timeouts are set globally without checking what runs. Long migrations, reports and data loads may legitimately hold a transaction for a long time. The safer approach is to set idle_in_transaction_session_timeout and transaction_timeout at the role or application level, starting with the sessions that are clearly leaking, and to exempt known batch roles. Test each change against the batch schedule before enabling it everywhere. Confirm the expected maximum duration of each job with its owner.

What should we ask for in a written scope for this work?

Ask for a list of the applications and roles in scope, the PostgreSQL version and the connection path, including any pooler. Request the monitoring queries and thresholds to be used, the timeout values proposed for each role and the reasoning behind them, and the application changes expected from each owner. The scope should name the test environment, the rollout order, the rollback steps and the retest after changes. Also ask who signs off each change and what evidence is delivered at the end. Confirm which items are one-time work and which need an ongoing retainer.

Does fixing long transactions need ongoing support after the first rollout?

Usually some ongoing attention is needed, because new services and new releases can reintroduce the same patterns. Monitoring for old transactions should stay in place with alerts, and the timeouts should be reviewed when applications change. This recurring work can be handled by your own team or covered by a support retainer. Ask the provider which part is one-time configuration and which part is continuous monitoring and review, and how each is priced in the quote.

How DeployOpen scopes and delivers this work

The sequence runs from a written scope to a tuned set of session timeouts and application fixes that your team can operate after handover. Each step ends with a check you can review. DeployOpen does not publish prices, and a quote follows from the written scope.

  1. Agree the written scope and environments

    DeployOpen and your team define which PostgreSQL clusters, applications and environments are in scope, who owns each application, and which environments may receive configuration changes first. Ask for the scope to name the server versions, the replication topology, the connection pooler if one is in use, and the change windows your operations team allows. The step closes when the scope document is signed off and lists the deliverables, the exclusions and the decision owner for each application team. Quotes follow directly from this document, so unclear scope is the main driver of cost change later.

  2. Baseline sessions and transaction age

    DeployOpen captures a baseline from pg_stat_activity over a representative period, recording session state, the age of open transactions, the backend application and client address, and the wait events each session reports. The same review checks whether long transactions are holding back vacuum through the xmin horizon and whether replication slots or standbys report old transactions. The output is a snapshot showing which applications hold idle-in-transaction sessions, how often they occur and what time of day they peak, so later changes can be compared against a known starting point.

  3. Diagnose application patterns behind the sessions

    DeployOpen works with the owners of the flagged services to trace each pattern to code or configuration. Common causes include a transaction opened before an external call, a connection held while a user waits on a form, an ORM setting that starts a transaction on read, and background jobs that never commit. The review also checks whether application pools return connections correctly after errors. The step closes with a written list of findings per application, each with the code path, the observed symptom and the proposed change, which your developers can assign and review.

  4. Set timeouts in a staged rollout

    DeployOpen proposes values for statement_timeout, transaction_timeout and idle_in_transaction_session_timeout, along with where each should be set: at the role, database, or application connection level. Settings are applied first in a non-production environment, then in the agreed production stages. Ask the team to confirm which batch jobs and migrations legitimately run long, so those roles are excluded or given their own limits. The step closes when each setting is applied at the agreed level, the change is recorded, and the affected applications have confirmed their behavior on timeout errors.

  5. Fix application code and pool settings

    Your developers, with DeployOpen where agreed, implement the code changes from the findings list. Typical changes move external calls outside open transactions, commit or roll back explicitly on every path, and set pool limits and checkout timeouts so connections are returned. Each change is tested against a copy of the workload where possible. The step closes when the changes are merged, deployed and the pattern no longer appears in the monitored sessions over the agreed comparison period. Changes that alter transaction boundaries need functional testing, since behavior can differ under concurrency.

  6. Verify vacuum progress and replication impact

    DeployOpen compares post-change session data against the baseline and checks that autovacuum is removing dead tuples more effectively, that the oldest transaction age has fallen, and that standbys and replication slots no longer hold back cleanup. The review confirms that timeout errors are logged, that they reach the right owners and that no critical batch job is being cancelled. The step closes with a verification report listing the metrics before and after the change, the remaining exceptions and any open risks.

  7. Hand over runbooks and alerts

    DeployOpen delivers the timeout configuration as versioned files, a runbook explaining how to find and terminate a blocking session safely, and alert thresholds for oldest transaction age and idle-in-transaction counts. Your operations team runs a handover session where they perform one diagnostic query, one controlled timeout change and one alert test themselves. The step closes when your team confirms they can repeat these actions without DeployOpen present and the runbook has an owner.

  8. Optional retainer monitoring after handover

    If your organization wants continued review, DeployOpen can provide ongoing monitoring under a retainer. Scope usually covers periodic session reviews, checks after application releases, and support for timeout adjustments as workloads change. Ask for the retainer terms, response expectations and the reporting format in writing before you commit. The step closes when the retainer scope is signed and the review cadence is recorded in the runbook. Without a retainer, your team continues the monitoring described in the handover.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.