postgresql 12, how to monitor what queries are performing now
Assistant
User
sometime postgres is stuck, and too many connection happens, how to find out why this happens? in that times disc read iops is very high
Assistant
User
how to view number of active connections in psql cli
Assistant
To view the number of active connections in PostgreSQL using the command-line interface (CLI), you can query the system view. Here are a few SQL queries that you can run in to get the desired information.
To monitor currently running queries in PostgreSQL 12, you can make use of the pg_stat_activity system view. This view provides information about the currently active sessions, including the queries that are being executed.
Below is an example query to retrieve information about currently running queries:
sql
SELECT
pid,
usename,
datname,
state,
query_start,
wait_event_type,
wait_event,
query
FROM
pg_stat_activity
WHERE
state = 'active';
Explanation of the Columns:
pid: The process ID of the PostgreSQL backend.
usename: The name of the user connected to the database.
datname: The name of the database the user is connected to.
state: The current state of the backend (active, idle, idle in transaction, etc.).
query_start: The timestamp when the query began execution.
wait_event_type and wait_event: Information about what the backend is waiting for (useful for identifying why a query is slow).
query: The actual SQL query currently being executed.
Additional Notes:
Ensure you have necessary permissions to run this query. PostgreSQL usually requires superuser privileges or pg_monitor role for accessing some columns in pg_stat_activity.
Filtering by state = 'active' helps in focusing on only the currently running queries and ignoring idle connections.
Optionally, you can add more filters or sorting to this query to narrow down the long-running queries specifically, for example by adding a condition like query_start < now() - interval '1 minute'.
Example:
To get the long-running queries that have been running for more than 5 minutes, you can do:
sql
SELECT
pid,
usename,
datname,
state,
query_start,
wait_event_type,
wait_event,
query
FROM
pg_stat_activity
WHERE
state = 'active'
AND query_start < now() - interval '5 minutes';
Monitoring Tools:
For more advanced monitoring, you may also consider using third-party monitoring tools or extensions like:
pgAdmin: Provides a graphical interface for monitoring queries and database performance.
pgBadger: Generates detailed reports of PostgreSQL logs including slow queries.
pg_stat_statements: An extension that collects statistics on SQL statements that are executed.
Make sure the above extensions or tools are appropriately configured and installed based on your requirements.
By regularly monitoring this information, you can gain insights into the performance of your database and take actionable steps to optimize and improve query performance.
When PostgreSQL appears to be stuck with too many connections and high disk read IOPS, it indicates possible performance bottlenecks or resource contention. You can investigate this issue by examining a combination of database system views, logs, and external system tools. Here’s a step-by-step approach to troubleshoot the issue:
1. Check Active Queries
Use the pg_stat_activity view to identify active and long-running queries that might be causing high I/O and resource contention:
sql
SELECT
pid,
usename,
datname,
state,
query_start,
wait_event_type,
wait_event,
query
FROM
pg_stat_activity
WHERE
state = 'active'
ORDER BY
query_start;
Look for:
Long-running queries.
Queries with wait events indicating locking issues.
2. Identify Lock Contention
Check for lock conflicts that can cause blockage and high IOPs using the pg_locks view:
sql
SELECT
pg_stat_activity.pid,
pg_stat_activity.query,
pg_locks.mode,
pg_locks.locktype,
pg_locks.relation::regclass,
pg_locks.granted
FROM
pg_stat_activity
JOIN
pg_locks ON pg_stat_activity.pid = pg_locks.pid
WHERE
pg_locks.granted IS FALSE;
3. Analyze Disk Usage and Indexing
Ensure that queries are using appropriate indexes and not causing excessive I/O due to full table scans. Use EXPLAIN (ANALYZE, BUFFERS) to analyze query plans and buffer usage:
sql
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM your_table WHERE some_column = 'some_value';
4. Check System Resource Utilization
Use OS-level tools to monitor system resources such as CPU, memory, and disk I/O:
iostat -x 1: Provides detailed I/O statistics.
htop or top: For real-time CPU and memory usage.
vmstat 1: For system performance metrics.
5. Review PostgreSQL Logs
Inspect the PostgreSQL logs for any error messages, warnings, or slow query logs. Make sure log_min_duration_statement is set (e.g., in postgresql.conf):
conf
log_min_duration_statement = 1000 # Log all queries that take longer than 1000 ms (1 second)
6. Connection Management
Evaluate the settings regarding connections. PostgreSQL can handle only a certain number of connections efficiently. Ensure proper configuration of settings like max_connections, shared_buffers, and work_mem.
7. Adjust Configuration Parameters
Several configuration parameters can help optimize performance:
shared_buffers: Typically set to 25-40% of available RAM.
effective_cache_size: Provides an estimate of how much memory PostgreSQL can use for disk caching.
work_mem: Memory for sort operations and hash tables before writing to disk.
maintenance_work_mem: Used for maintenance operations like VACUUM, CREATE INDEX, etc.
Ensure your tables are regularly vacuumed and analyzed. Autovacuum should be running to prevent table bloat and maintain statistics:
sql
VACUUM (VERBOSE, ANALYZE);
9. Extensions and Monitoring Tools:
Consider using extensions and monitoring tools for more in-depth analysis:
pg_stat_statements: Tracks execution statistics of all SQL queries.
pgBadger: For detailed log analysis.
pgbouncer: A lightweight connection pooler that can help manage connection spikes.
Example: Using pg_stat_statements
Enable the extension and view the top resource-consuming queries:
sql
CREATE EXTENSION pg_stat_statements;
SELECT * FROM pg_stat_statements ORDER BY total_time DESC LIMIT 10;
Conclusion
By combining these methods, you can gain a comprehensive understanding of the issues causing PostgreSQL to become unresponsive due to too many connections and high disk read IOPS, and subsequently take appropriate steps to address them. Regular monitoring and tuning based on your workload and performance patterns are essential for optimal PostgreSQL performance.
psql
pg_stat_activity
psql
Option 1: Basic Count of Active Connections
You can simply count the number of active connections by using the following query:
sql
SELECT COUNT(*)
FROM pg_stat_activity
WHERE state = 'active';
Option 2: Group by State to Get All Connection States
Sometimes it's helpful to see all connection states, not just active ones:
sql
SELECT state, COUNT(*)
FROM pg_stat_activity
GROUP BY state;
Option 3: Detailed Information About Active Connections
If you need more details about the active connections, you can use:
sql
SELECT
pid,
usename,
datname,
client_addr,
application_name,
backend_start,
state,
query
FROM
pg_stat_activity
WHERE
state = 'active';
Option 4: Using psql Features
You can run these queries directly in your psql CLI. Open your psql and connect to your database, then execute any of the queries. Here’s an example session:
sh
$ psql -U your_username -d your_database
-- Once in the psql shell, run any of the above queries. For example:
your_database=# SELECT COUNT(*) FROM pg_stat_activity WHERE state = 'active';
To see the count of all connections excluding idle ones:
sql
SELECT COUNT(*)
FROM pg_stat_activity
WHERE state != 'idle';
Additional Tips
Ensure you are logged in with a user that has appropriate permissions to view the pg_stat_activity view.
You can make use of \x in psql to enable extended display, which formats the output for better readability if the rows have many columns.
Example Session
Here’s a full example of how to execute these steps in psql:
sh
$ psql -U postgres -d mydatabase
Password for user postgres:
psql (12.9)
Type "help" for help.
mydatabase=# SELECT COUNT(*) FROM pg_stat_activity WHERE state = 'active';
count
-------
5
(1 row)
mydatabase=# SELECT state, COUNT(*) FROM pg_stat_activity GROUP BY state;
state | count
---------+-------
active | 5
idle | 10
(2 rows)
By using these queries, you can effectively monitor the number of active connections in your PostgreSQL database from the psql CLI. This will help you manage and troubleshoot connection-related performance issues.