How to Check Blocking Sessions in PostgreSQL
How to Check Blocking Sessions in PostgreSQL
When working with PostgreSQL databases, you might encounter situations where one session is blocking another, causing performance issues or query delays.
Understanding which session is blocking and why is crucial for quick troubleshooting.
In this guide, we’ll explore different ways to identify blocking sessions, view lock details, and terminate blocking processes safely.
1. Simple Query to Check Blocking Sessions
You can identify blocking and blocked sessions by using PostgreSQL’s system views pg_locks
and pg_stat_activity
.
SQL Query
Explanation
-
pg_locks
→ Displays locks held by all active sessions. -
pg_stat_activity
→ Provides details about current queries and session states. -
WHERE NOT blocked_locks.GRANTED
→ Filters only those locks waiting for release (i.e., blocked sessions).
This query gives you detailed insights into who is blocking whom, what query they’re executing, and since when the block has been active.
2. Quick Summary View (Simplified)
If you just need a quick summary to identify blocking and blocked users, use the following lightweight query:
This provides a minimal view — useful for quick checks during database performance monitoring.
3. Kill Blocking Session
Once you identify the blocking session PID, you can terminate it to release the lock using the following command:
Example:
4. View All Current Locks and Queries
To see all active locks in your PostgreSQL database:
To view currently running queries along with their start time:
This helps in understanding which queries are long-running and might be contributing to blocking behavior.
Summary
Task | Query / Command |
---|---|
Check detailed blocking sessions | Full join query with pg_locks and pg_stat_activity |
Quick summary view | Simple blocking vs blocked session query |
Terminate blocking session | SELECT pg_terminate_backend(<pid>); |
View all locks | SELECT * FROM pg_locks; |
View running queries | SELECT pid, usename, query, query_start FROM pg_stat_activity; |
Conclusion
Blocking sessions are common in multi-user databases but can cause performance bottlenecks if not managed properly.
By using the above queries, DBAs can quickly identify blocking sessions, analyze their impact, and take corrective actions.
Regularly monitoring pg_stat_activity
and pg_locks
helps maintain a smooth and high-performing PostgreSQL environment.