Monitor PostgreSQL Active Sessions with pg_stat_activity
Monitoring PostgreSQL Active Sessions with pg_stat_activity Explained
As databases scale, monitoring active connections and queries in PostgreSQL becomes essential for performance tuning, troubleshooting, and ensuring stability. PostgreSQL provides a powerful system view called pg_stat_activity that contains detailed information about all current backend processes.
The following query allows database administrators to inspect active sessions:
1SELECT
2 pid,
3 usename,
4 client_addr,
5 client_hostname,
6 client_port,
7 backend_start,
8 query_start,
9 state,
10 -- not available on PostgreSQL < 10
11 backend_type
12FROM
13 pg_stat_activity
14ORDER BY
15 -- not available on PostgreSQL < 10
16 backend_type;
Purpose of the Query
This query helps you:
- Monitor active PostgreSQL connections and their originating clients.
- Track when sessions started and how long queries have been running.
- Diagnose issues like long-running queries or idle connections consuming resources.
- Identify the backend type (such as
client backendorautovacuum worker), useful for categorizing processes.
Breakdown of Each Column
- pid: Process ID of the backend process. Useful for terminating problematic queries with
pg_terminate_backend(pid). - usename: The PostgreSQL user running the query.
- client_addr: The IP address of the client application connected to the database.
- client_hostname: Hostname of the client, if available. Helpful for tracking connections from multiple servers.
- client_port: Port number from which the client connected.
- backend_start: Timestamp when the session started. Long-lived sessions could indicate connection pool misconfigurations.
- query_start: Timestamp when the query execution began. Helps in identifying long-running queries that may need attention.
- state: Current activity state. Common examples include
active,idle,idle in transaction, orwaiting. - backend_type: (PostgreSQL 10+) Identifies the type of process, such as
client backend,autovacuum worker, orlogical replication worker.
Key Insights & Practical Uses
- Performance tuning: Quickly locate long-running queries hogging system resources.
- Connection analysis: Spot unusual connections from unexpected IPs.
- Security insight: Detect unauthorized or idle sessions that may indicate misuse.
- Maintenance aid: Identify background workers and monitor autovacuum activity.
- Operational clarity: Sort results by
backend_typeto distinguish between client traffic and system tasks.
Best Practices
- Regular monitoring: Integrate this query into your monitoring dashboards (e.g., Grafana, pgAdmin, or custom scripts).
- Kill only if necessary: Use
pg_terminate_backend(pid)instead of abruptly killing processes at the OS level. - Combine with logging: Cross-reference query start times with PostgreSQL logs to correlate performance spikes.
- Connection pooling: If you see many idle connections, review your connection pooling strategy (e.g., use PgBouncer).
Conclusion
The pg_stat_activity view is one of the most powerful tools at a PostgreSQL administrator’s disposal. By running this query, you gain deep visibility into client connections, query activity, and background processes. With correct interpretation, this insight helps you optimize performance, improve reliability, and troubleshoot effectively.
References
- PostgreSQL Documentation: pg_stat_activity – Official PostgreSQL documentation explaining all columns in this view.
- Managing Connections & Performance – PostgreSQL runtime configuration for managing connections.
Posts in this series
- How Many Connections Can Your PostgreSQL Database Handle?
- PostgreSQL Backend Connections via pg_stat_database
- Identifying Blocking PostgreSQL Queries using pg_stat_activity
- List PostgreSQL Databases by Size with Access Check
- Assess PostgreSQL Database Sizes Quickly and Easily
- Unveiling Your PostgreSQL Server - A Diagnostic Powerhouse
- Keep Your PostgreSQL Database Clean, Identify Idle Connections
- Query the PostgreSQL Configuration
- PostgreSQL Recovery Monitoring: Essential SQL Insights
- Restart All PostgreSQL Sequences with ALTER SEQUENCE
- Monitor Running Queries in PostgreSQL using pg_stat_activity
- Monitor PostgreSQL Active Sessions with pg_stat_activity
- PostgreSQL Error Handling Settings via pg_settings
- PostgreSQL File Location Settings Query via pg_settings
- PostgreSQL Lock Management Settings via pg_settings
- PostgreSQL Logging Configuration Query via pg_settings
- Monitor PostgreSQL Memory Settings with pg_settings
- PostgreSQL Table Row Count Estimates with SQL
- List PostgreSQL Tables by Size with SQL
- PostgreSQL WAL Settings Query Guide
- PostgreSQL SSL Settings Query Guide
- PostgreSQL Statistics Settings Query Guide
- PostgreSQL Resource Settings Query Guide
- PostgreSQL Replication Settings Query Guide
- PostgreSQL Query Planning Settings Query Guide
- PostgreSQL Preset Options Settings Query Guide
- PostgreSQL Miscellaneous Settings Query Guide
- Count PostgreSQL Sessions by State with SQL
- Kill Idle PostgreSQL Sessions with SQL
- Grant SELECT on All Tables in PostgreSQL
- Identify Insert-Only Tables in PostgreSQL
- Detect Soft Delete Patterns in PostgreSQL
- List PostgreSQL Object Comments with SQL
- List Foreign Key Constraints in PostgreSQL
- List PostgreSQL Enum Types and Their Values with SQL
- List All Views in a PostgreSQL Database with SQL
- Find PostgreSQL Tables Without a Primary Key
- List PostgreSQL Partitioned Tables with SQL
- List All Schemas in Your PostgreSQL Database
- PostgreSQL Database Statistics with pg_stat_database
- List PostgreSQL Roles and Their Privileges
- Scrubbing Email PII in PostgreSQL for GDPR Compliance
- List Installed Extensions in PostgreSQL
- List Collations in Your PostgreSQL Database
- PostgreSQL Replica Identity for Logical Replication