Finding and resolving PostgreSQL lock contention

A practical guide to finding who blocks whom in PostgreSQL with pg_locks and pg_stat_activity, making DDL safe with lock_timeout, and logging lock waits and deadlocks in infrastructure you control.

On this page

Why PostgreSQL lock contention stalls production and how to spot it

When an application slows or hangs and connection counts climb, the usual first step is to find the session holding the lock everyone else is waiting for. Join pg_locks to pg_stat_activity to see which backend is blocking which, then fix the cause: the blocking transaction, the statement that queued behind it, or the application pattern that left a transaction open. The lock manager that does this work is part of PostgreSQL itself, released under the PostgreSQL License, a permissive license similar to BSD and MIT, so your team can inspect and test its behavior directly. The behavior described here applies to the currently supported major versions 14 through 18.

Teams usually need this work in three situations. The first is a migration window: a routine ALTER TABLE or index change takes an ACCESS EXCLUSIVE lock, and even though it may finish quickly, it waits behind a long read, and every query that arrives afterward queues behind the waiting DDL. The second is a queue of blocked sessions that grows until connection limits are reached, which looks like an application outage but starts in the database. The third is deadlock errors in logs, where two transactions each hold a lock the other needs and PostgreSQL aborts one of them. Each case needs a different fix, so confirm which lock modes are involved before changing any setting or killing a session.

Before the first incident, confirm that your team can run these queries against production without special privileges, that log_lock_waits is enabled in your configuration so waits are recorded in the server log, and that someone has agreed who may terminate a blocking session. Ask a partner or your own DBAs to document these steps in a runbook, and check the PostgreSQL documentation for the lock settings that apply to your exact version before relying on them, since the official upgrading guide covers version differences during major upgrades.

How a queued query waits behind a blocking session

The diagram starts with a DDL statement that requests an ACCESS EXCLUSIVE lock on a table. While it waits for a session that holds a conflicting lock, every later read and write on that table queues behind it, which is why one DDL can stall an entire application. Operators find the blocking session with pg_blocking_pids() and pg_stat_activity, then choose to cancel, terminate, or prevent the wait by setting lock_timeout on the DDL before it runs.

Blocking chain from a DDL statement to the resolution options.

How to find who blocks whom with pg_locks and pg_stat_activity

This sequence turns a stalled application into a named blocking session, with the query, application and lock mode that explain the wait. The output is a written record you can act on without guessing.

  1. Confirm the symptom and the time window

    The on-call engineer records when latency or timeouts began, which application endpoints or jobs are affected, and whether the problem is still happening. They check the connection count and the number of sessions in the Lock wait state at that moment. The step is done when there is a timestamp, a list of affected services, and a count of waiting sessions to compare against later snapshots.

  2. List waiting sessions in pg_stat_activity

    Run a query against pg_stat_activity filtered on wait_event_type = 'Lock' to list every backend that is currently waiting for a heavyweight lock. Capture the pid, usename, application_name, client address, state, wait_event, query_start and the query text. The step is done when every waiting pid is recorded and you know how long each has been waiting.

  3. Map each waiter to its blockers

    For each waiting pid, call pg_blocking_pids() to get the set of sessions holding or queued for the conflicting lock. A waiter may have more than one blocker, and a blocker may itself be waiting behind another session, so follow the chain to the head of the queue. The step is done when you have a list of root blocking pids that are not themselves blocked.

  4. Inspect the blocker's state and query

    Query pg_stat_activity for the root blocking pids and read state, xact_start, state_change and query. A session in idle in transaction is a common root cause because it holds locks while doing nothing, and the last query it ran is often the statement that took the lock. The step is done when you can state whether the blocker is active, idle in transaction, or idle, and which statement it last ran.

  5. Read pg_locks for relation and transaction modes

    Join pg_locks to pg_stat_activity on pid and filter for the blocking and waiting pids. Check locktype (relation, transactionid or tuple), the relation name, mode (for example ACCESS EXCLUSIVE or ROW EXCLUSIVE) and whether granted is true or false. This shows which object is contested and which mode is requested against which mode is held. The step is done when you can name the table, the held mode and the requested mode.

  6. Rule out vacuum and replication processes

    Before touching any session, check whether the blocker is an autovacuum worker, a manual VACUUM, a replication or walsender process, or a background worker. Autovacuum sessions usually carry backend_type or a query beginning with 'autovacuum', and cancelling them can cause repeated work or wraparound pressure. Confirm with the database owner which maintenance jobs are scheduled. The step is done when each root blocker is labeled as application, maintenance or replication, with the reason written down.

  7. Record evidence before any cancel or terminate

    Save the query results, the query text, application_name, client address and the owning team of the blocking session to the incident record. Confirm with the application owner that the statement can be interrupted without corrupting a business process. Only then decide between pg_cancel_backend() for the running statement and pg_terminate_backend() for the whole session. The step is done when the evidence is stored and an owner has approved the action.

Which lock modes cause queues and which DDL takes ACCESS EXCLUSIVE

Most PostgreSQL stalls come from a small set of lock conflicts. A plain read and a plain write rarely block each other, but one DDL statement that asks for the strongest table lock can wait behind ordinary traffic and then hold up everything that arrives after it.

Reads and writes rarely conflict

Ordinary SELECT takes ACCESS SHARE, and ordinary INSERT, UPDATE and DELETE take ROW EXCLUSIVE. These two modes do not conflict with each other, so normal application traffic usually proceeds without waiting. Check pg_locks for these modes first, since a stall caused by them points to something other than DDL, such as explicit table locks in application code.

**ACCESS EXCLUSIVE** conflicts with everything

ACCESS EXCLUSIVE conflicts with every other table lock, including plain SELECT. Statements such as DROP TABLE, TRUNCATE, and many ALTER TABLE forms need it. Before running any DDL on a busy table, confirm which lock the statement takes in the PostgreSQL documentation for that command, because the lock level varies by sub-command.

Upgrade docs

One waiter blocks the queue behind it

A DDL statement that cannot get its lock waits in the lock queue, and every later request that conflicts with it waits behind that request, even if the lock currently held would allow it. A single waiting ALTER TABLE can therefore stall reads that were never blocked by the original holder. In pg_stat_activity, look for sessions with wait_event_type set to Lock and trace the chain to the first session in line.

Weak locks held by long transactions

A transaction that only reads still holds ACCESS SHARE until it ends. An idle-in-transaction session holding that lock can block a later ACCESS EXCLUSIVE request, which then queues every new read behind it. The holder may look harmless because it is not writing anything, so check for sessions in the idle in transaction state alongside the lock queue.

Set lock_timeout before DDL

Setting lock_timeout for the session makes a DDL statement give up if it cannot acquire its lock within the chosen period, instead of joining the queue indefinitely. Pair it with a retry loop run during a quiet window. The right timeout value depends on your traffic and should be agreed with the application owners before the change runs.

Making DDL safe with lock_timeout, retries and statement sequencing

Adding a column is usually the lowest-risk DDL, but it still takes an ACCESS EXCLUSIVE lock on the table while the catalog change is made. Every query on that table, including plain reads, waits behind that request, and queries already running can hold up the DDL. PostgreSQL does not add a default value to existing rows at that point when the default is a constant, so the cost is mostly the lock wait, not a table rewrite. Bound the wait so the migration fails fast instead of queuing behind long reads.

  • Set lock_timeout first: Set lock_timeout for the migration session so the ALTER TABLE gives up if it cannot get the lock, rather than blocking the whole application queue.
  • Keep statement_timeout separate: statement_timeout limits total run time of a statement once it runs. It does not cap how long a statement waits for a lock on its own, so set both when the migration is long.
  • Add nullable columns without defaults first: Add the column, then backfill in batches, then set the default and the NOT NULL constraint in later steps.
  • Retry with backoff: If the lock timeout fires, the pipeline should wait and retry a bounded number of times, logging each attempt.
  • Confirm version behavior: Check the documented behavior of your PostgreSQL version for defaults and rewrites before relying on it.

Before release, confirm the lock timeout values with your own environment and rehearse the migration against a copy with realistic query traffic.

Logging and timeout settings and when each fits

This table compares the five settings that expose or limit lock waits: log_lock_waits with deadlock_timeout, lock_timeout, statement_timeout, idle_in_transaction_session_timeout and log_min_duration_statement. Read each row for what the setting controls, the situation it suits and its cost, then combine them rather than relying on one. Exact default values and thresholds should be confirmed in the PostgreSQL configuration reference for your version.

SettingWhat it controlsWhen it fitsTrade-off
log_lock_waits and deadlock_timeoutlog_lock_waits writes a log entry when a session waits longer than deadlock_timeout for a lock. The wait is logged, not cancelled.Any production cluster where blocked queries cause unexplained slowdowns and you need evidence of who waited and for how long.Adds log volume during busy periods. Confirm the default deadlock_timeout value for your version before you tune it.
lock_timeoutMaximum time a statement waits to acquire a lock. If the wait is longer, the statement fails with an error.Schema changes and maintenance DDL run from a migration tool, where a queued ALTER should give up instead of blocking traffic.Migrations fail more often and must be retried. Set it per session or per transaction, not globally.
statement_timeoutMaximum total run time of a single statement, including time spent waiting for locks.Application roles where no legitimate query should run for long, and as a backstop against runaway reports.Can cancel valid long analytical or batch work. Assign it to specific roles that need it.
idle_in_transaction_session_timeoutEnds sessions that sit inside an open transaction without running a statement.Systems where application code sometimes opens a transaction and leaves it open, holding locks and blocking DDL and vacuum.Terminates the session, so the application must handle reconnects and roll back cleanly.
log_min_duration_statementLogs any statement that runs longer than the configured duration.Finding the statements that hold locks for long periods, often alongside lock wait logging, during an investigation or on a tuned baseline.Logging every statement is costly. Start with a high threshold and review what the log shows.
Combined use in a migration window (illustrative)Log waits, fail fast on the DDL lock request, and cap the statement time of the migration role.A planned schema change on a busy table where a short failed attempt is preferable to a long queue.Requires a rehearsed retry plan and agreed timing with application owners before the change runs.

Diagnosing deadlocks and reading the server log

A deadlock occurs when two or more transactions each hold a lock the other needs, so none can proceed. PostgreSQL checks for this condition after a transaction has waited on a lock for longer than deadlock_timeout. When it finds a cycle, it aborts one of the transactions with an error reporting a deadlock, which releases that transaction's locks and lets the others continue. The server log records the event with the process IDs involved, the lock each one wanted, and the queries it was running, so the log is the primary evidence for the investigation. Confirm the logging settings on your servers before you need them: deadlock details appear in the log by default, but the lock wait messages that show who was waiting depend on log_lock_waits being enabled. Ask your database team to make sure log output reaches the system where incidents are investigated, and that the retention period is long enough to cover a recurring pattern.

Fixing the cause is almost always an application or transaction design change, not a server setting. The most effective change is a consistent lock ordering: if every transaction that touches the same set of rows acquires them in the same order, a cycle cannot form. Shorter transactions help because each lock is held for less time, which narrows the window in which another transaction can collide with it. Batched updates should be sorted by a stable key, such as a primary key, before execution, so that two batches touching overlapping rows take the locks in the same sequence. Review the statements named in the deadlock log against these rules, and make the change in the code path that produces them, since tuning deadlock_timeout only changes how quickly the detector runs.

Aborted transactions have to be retried, and the retry logic must be idempotent. A retry that repeats a payment, a stock movement or an email send because the first attempt was rolled back in an ambiguous state will create duplicate effects that are harder to unwind than the deadlock itself. Use idempotency keys or unique constraints on business operations, keep the retry limited in count with backoff, and make sure the application treats the deadlock error code as retryable only for the transaction as a whole. Before the system goes live, test this path deliberately by running concurrent workloads against a staging copy of the schema and confirming that each deadlock produces exactly one committed result.

Setting up lock monitoring on a PostgreSQL cluster you run

This sequence makes lock waits visible before they cause an outage: it configures logging and deadlock timing, adds a saved query for live blocking chains, sends wait events to your log platform, and alerts on waits that run too long. It ends with a rehearsed blocked DDL so the team knows what the signals look like under pressure.

  1. Enable lock wait logging in a test environment

    The DBA sets log_lock_waits to on in a non-production cluster and reloads the configuration. With this setting, PostgreSQL writes a log line when a session has waited on a lock longer than deadlock_timeout, naming the blocked statement and the wait. Run a deliberate blocking test, such as one session holding an open transaction on a table while another session tries to update it, and confirm that the log line appears with the expected process IDs. The step is done when a lock wait is captured in the server log for that test.

  2. Choose the deadlock_timeout value deliberately

    The team decides the value of deadlock_timeout, since it controls how long a session waits on a lock before PostgreSQL runs the deadlock check and before log_lock_waits writes anything. A low value produces more log noise on busy systems, and a high value delays the first signal. Record the chosen value, the reason for it, and the workload it was tested against in the change record, and confirm the current setting with SHOW deadlock_timeout on each node. The step is done when the value and its rationale are approved by the owners of the database and the on-call rota.

  3. Create a saved blocking query

    The DBA saves a query that joins pg_stat_activity with pg_locks, using pg_blocking_pids() to show each waiting process, the process holding or queuing ahead of it, the lock mode, the relation, and how long each session has been in its current state. Store the query in a shared runbook or a monitoring tool's saved query list so that the on-call engineer does not need to write it under pressure. Test it during the blocking exercise from the first step. The step is done when the query returns the blocked session and its blocker in the test run, and the output is readable without editing.

  4. Route lock wait log lines to your log platform

    The platform team configures the PostgreSQL logging destination and forwarding so that lines containing lock wait and deadlock messages reach the central log platform with the host, database and timestamp fields intact. Confirm the log_line_prefix setting includes the process ID and database name, because those fields are needed to match a wait with a session. Check the parsing rules by searching for the test wait from the first step in the platform. The step is done when the test wait appears as a searchable event with the fields needed to trace it back to a session.

  5. Alert on sessions stuck waiting for locks

    The monitoring owner adds an alert that fires when a session has been waiting on a Lock wait event for longer than the period the team agreed, using the wait_event_type and wait_event columns in pg_stat_activity as the source. The threshold should be set by the application owners based on what their workload tolerates, and it should be reviewed after the first few real alerts. Route the alert to the on-call channel with a link to the saved query. The step is done when a test blocking session triggers the alert and the alert clears once the blocking transaction ends.

  6. Rehearse a blocked DDL in staging

    The team runs a schema change in staging that needs an ACCESS EXCLUSIVE lock, first with a long-running read holding a conflicting lock on the same table, and then with lock_timeout set so that the DDL fails fast instead of queueing behind the reader. Observe what the saved query, the log lines and the alert show during the queue, and confirm that the application's own requests also queue behind the waiting DDL. Record the procedure for cancelling the blocker or the DDL and the lock_timeout value to use in production migrations. The step is done when the team can name the blocking session from the monitoring output within the rehearsal and has a written, tested rollback path.

Security and access controls for lock diagnostics

Lock diagnostics read sensitive data and can end sessions, so the people and tools that use pg_locks and pg_stat_activity need the same care as the production database itself. The cards below cover who may terminate backends, how monitoring roles stay read-only, what query text can leak, and how DDL is controlled and recorded.

Who may terminate backends

Calling pg_terminate_backend or pg_cancel_backend on another role's session is a privileged action, and PostgreSQL restricts it to superusers and members of roles that hold the matching privilege. Decide in advance which operators may end a blocking session in production, and record that list in the runbook. Check that application service accounts cannot reach these functions through inherited role membership.

Authentication methods

Least-privilege monitoring roles

Diagnostic queries need visibility into sessions and locks, not the ability to read application tables. Create a dedicated monitoring role with the predefined monitoring roles that expose activity statistics, and confirm with a test login that it cannot select from business schemas. Keep this role separate from administrators so that routine dashboard polling does not run with broad rights.

Query text that may hold secrets

The query column in pg_stat_activity and the statements written to the server log can contain literal values, including account numbers, tokens or personal data, when applications do not use bound parameters. Review the logging settings for statement and lock wait output before enabling them broadly. Confirm who can read the server log and the log shipping path, since those readers will see the same text.

Auditing terminated sessions

A terminated session leaves little trace in the database by default, so an incident review may not show who ended a transaction or why. Record each termination with the operator, the target process ID, the time and the reason, using a ticket or runbook entry tied to the incident. Compare these records with the server log to confirm that the rollback and the application error match the expected pattern.

Change control for production DDL

Schema changes that need ACCESS EXCLUSIVE locks are the usual source of lock queues, so they need an approval step before they run. Require a written lock_timeout and a short retry plan for each migration, and confirm that the deployment tool applies them to every statement. Record the approver, the window and the outcome so that a later queue can be traced to a specific change.

Questions teams ask before hiring help with PostgreSQL locks

Can our team diagnose and fix PostgreSQL lock contention without outside help?

Yes, many teams can, provided at least one engineer can read pg_locks and pg_stat_activity together, understands which lock modes conflict, and has permission to run DDL in a change window. The usual gap is not the queries but the pattern: a long transaction or a migration takes an ACCESS EXCLUSIVE lock, and everything behind it queues. Outside help makes most sense when the lock problem recurs across several clusters, when the DDL pipeline is owned by several teams, or when the fix needs application changes that the internal team cannot make alone. DeployOpen can review the lock picture and the migration process together so the internal team leaves with a written runbook.

What makes the effort for a lock contention engagement larger or smaller?

Effort follows three drivers. The first is cluster count, since each cluster has its own logs, settings and workload. The second is DDL pipeline maturity: a team that runs migrations through a reviewed tool with lock_timeout already set needs far less work than one that runs ad hoc DDL from laptops. The third is application transaction patterns, such as transactions that stay open while waiting on an external API, or ORMs that issue DDL inside request paths. Each driver changes how many queries must be traced, how many migrations must be reviewed, and how many code owners must agree on changes. Ask for the scope to state the cluster count and the number of migration paths reviewed.

What access and information does the work need from our team?

The work needs a staging environment that resembles production in schema size and migration tooling, read access to production-like statistics, and the ability to run the lock queries against live sessions in a controlled way. It also needs PostgreSQL logs with log_lock_waits enabled or the ability to enable it, a deadlock log sample, the migration history and the application's connection and transaction configuration. For production changes you will need named change windows and a rollback path. Ask whether your team can provide these before work starts, because missing log access is the most common reason diagnosis stalls.

How long does a lock contention engagement take?

Duration is set by the scope written into the quote, not by a standard figure. A narrow engagement that covers one cluster, one incident and a set of migration reviews is shorter than a multi-cluster review that adds logging, lock_timeout policy, deadlock analysis and application changes. Time also depends on how quickly your team can grant log access and schedule change windows, since those waits often exceed the technical work. Ask for milestones and dependencies in the quote, and ask which items wait on your side.

Which logging and lock settings do we need to confirm before the work starts?

Confirm the PostgreSQL version and the current values of log_lock_waits, deadlock_timeout, lock_timeout and statement_timeout, along with the log destination and retention. Check whether migrations run with a lock timeout, and whether the team can reproduce a blocked statement in staging. Exact behavior of these settings should be checked against the documentation for your version, which the PostgreSQL versioning policy helps you confirm for support status. Record the current values so the engagement can show what changed.

What should a fixed-scope quote for lock work list?

A fixed-scope quote should name the clusters and databases in scope, the incident or migration paths reviewed, the logs and queries used for diagnosis, and the changes DeployOpen will recommend or implement, such as lock_timeout defaults, logging configuration or migration patterns. It should list the deliverables in writing, for example a findings report, a safe DDL checklist and a runbook for blocked sessions. It should state which access and change windows the client provides, what happens if access is delayed, and how retesting is handled. Ongoing monitoring or continuous review is priced separately as a retainer, so ask whether it is included or optional.

Does DeployOpen change our application code or only the database?

Scope decides this. Most lock work is database-side: identifying blocking sessions, setting lock_timeout in migration tooling, adjusting logging and documenting safe DDL. Where the cause sits in application transaction handling, such as an open transaction waiting on a remote call, the fix may belong in code owned by your developers. DeployOpen can specify the change, review it and test it in staging, but the quote should state whether application changes are implemented by DeployOpen or handed to your team. Clarify this before work starts, because code changes add review and release steps that change both cost and timeline.

How DeployOpen scopes and delivers lock contention work

DeployOpen scopes lock contention work as a fixed-scope engagement, with the scope, deliverables and timelines agreed in writing before any work starts. For this topic, the written scope normally names the instances and databases covered, the time window in which the team may read pg_stat_activity and pg_locks on production, the log files and retention period to review, and the list of DDL statements the client expects to run. A quote follows from that scope, so the more precisely the client defines the workload and the migrations in flight, the more accurately the work can be bounded. Confirm early whether the engagement covers a one-time investigation, a set of safe DDL runbooks, or both.

The work runs inside the client's own infrastructure, in their cloud accounts, data centers or air-gapped networks, under access the client grants and revokes. A typical delivery reviews the existing log_lock_waits and deadlock_timeout settings and the log output they produce, then reproduces the blocking pattern in a staging environment with a representative dataset and concurrent application traffic. The output is a set of DDL runbooks that specify the lock_timeout and statement_timeout values, retry rules and the moment each migration takes its lock, plus monitoring queries the client's own team can keep. Ask for the exact list of artifacts, who owns each one after handover, and whether staging is a true copy of production in schema and data volume, since a staging test that does not match production will not prove the runbook is safe.

Ongoing support is available as a retainer for teams that ship schema changes continuously or want the runbooks re-tested after a PostgreSQL minor or major upgrade. Retainer scope, response expectations and review cadence are agreed in writing, separately from the initial engagement. Ask any provider how they handle production access, who approves DDL before it runs, and how findings are handed over, and confirm those answers against the client's change management and access policies before signing.

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.