PostgreSQL
Plugin: go.d.plugin Module: postgres
Overview
This collector monitors the activity and performance of Postgres servers, collects replication statistics, metrics for each database, table and index, and more.
Database load charts show how many sessions are running a statement and what they are waiting for, across the server and in each non-template database. Sessions in template databases count toward the server total only.
It establishes a connection to the Postgres instance via a TCP or UNIX socket.
To collect metrics for database tables and indexes, it establishes an additional connection for each discovered database; when the server refuses one because of a connection limit, it tries that database again every 10 minutes.
The Top Queries and Running Queries Functions open one more connection to the DSN database for each request and close it when the request ends, so they do not wait for metric collection and metric collection does not wait for them. They use the metrics connection instead, and the two wait for each other, in two cases: for 10 minutes after the server refuses a metrics or Function connection because of a connection limit (for example, a monitoring role created with CONNECTION LIMIT 1), and for a request that arrives while the metrics connection is closed between its 10-minute reconnects. On a server or role that allows one connection, a collection can still fail at most once in 10 minutes, when metrics reconnect during a Function request.
Database load (PostgreSQL 10 and later) is one pg_stat_activity sample per update interval: the client sessions, and the parallel workers of their queries, that are running a statement at that moment, by wait_event_type:
cpucounts active sessions with no reported wait event. Use it as an estimate of sessions running or ready to run on CPU.buffer:BufferPin, orBufferon PostgreSQL 19, which also reports the buffer content-lock waits that earlier versions report aslwlock.other: wait event types the collector does not know.- Every other dimension is the wait event type of the same name.
The sample excludes the connection taking it, autovacuum workers and replication processes. PostgreSQL 10 reports parallel workers as background workers, so only their leader counts. A Function query counts if it is active on a separate connection when the sample is taken.
Averaging the samples estimates the average number of active sessions. Longer update intervals can miss short bursts. If a workload repeats in step with the sampling interval, the estimate can stay too high or too low.
This collector is supported on all platforms.
This collector supports collecting metrics from multiple instances of this integration.
PostgreSQL can be monitored further using the following other integrations:
Default Behavior
Auto-Detection
By default, it detects instances running on localhost by trying to connect as root and netdata using known PostgreSQL TCP and UNIX sockets:
- 127.0.0.1:5432
- /var/run/postgresql/
Limits
By default, each database, including the database in the DSN, is monitored for up to 50 tables and 250 indexes. Above either limit, the collector selects TOP objects: tables by recent rows read, fetched, inserted, updated and deleted (PostgreSQL statistics counters, not SQL query counts), indexes by size. Table and index selection is independent and refreshes approximately every five minutes. A selected object stays until another has more than twice its row activity or size; a selected table also stays against tables below one row per second. Detailed metrics for the selected objects are collected at each update interval. Databases above the table limit need two successful observations before the first table selection; the second is attempted at the next update interval. Objects outside TOP have no individual metrics, and there is no aggregate for them. Rotation can cause gaps in individual charts and their alerts. While the corresponding limit is set, a table or index created after the last selection, including one recreated under the same name, has no metrics until the next refresh, even in a database below that limit. Set either limit to 0 for unlimited collection.
Performance Impact
While the corresponding limit is set, selection scans lightweight statistics for all accessible candidate tables and the size of every accessible index, at startup and approximately every five minutes. A database above the table limit repeats the table scan at the next update interval to establish recent activity, and a failed scan is retried after one minute. In-memory selection state grows with the number of candidates. Detailed statistics and size queries cover the selected objects; bloat and column checks run every five minutes. Unlimited collection increases detailed query cost and the number of charts.
Setup
You can configure the postgres collector in two ways:
| Method | Best for | How to |
|---|---|---|
| UI | Fast setup without editing files | Go to Nodes → Configure this node → Collectors → Jobs, search for postgres, then click + to add a job. |
| File | If you prefer configuring via file, or need to automate deployments (e.g., with Ansible) | Edit go.d/postgres.conf and add a job. |
UI configuration requires paid Netdata Cloud plan.
Prerequisites
Create netdata user
Create a user with granted pg_monitor
or pg_read_all_stats built-in role.
To create the netdata user with these permissions, execute the following in the psql session, as a user with CREATEROLE privileges:
CREATE USER netdata;
GRANT pg_monitor TO netdata;
After creating the new user, restart the Netdata Agent with sudo systemctl restart netdata, or
the appropriate method for your
system.
Configuration
Options
The following options can be defined globally: update_every, autodetection_retry.
Config options
| Group | Option | Description | Default | Required |
|---|---|---|---|---|
| Collection | update_every | Data collection interval (seconds). | 1 | no |
| autodetection_retry | Autodetection retry interval (seconds). Set 0 to disable. | 0 | no | |
| Target | dsn | Postgres connection string (DSN). See DSN syntax. | postgres://postgres:postgres@127.0.0.1:5432/postgres | yes |
| Cloud Auth | cloud_auth.provider | Cloud auth provider (none or azure_ad). | none | no |
| Cloud Auth/Azure | cloud_auth.azure_ad.mode | Azure AD credential mode (service_principal, managed_identity, or default). Required when cloud_auth.provider is azure_ad. | yes | |
| cloud_auth.azure_ad.mode_service_principal.tenant_id | Azure tenant ID. Required for service_principal mode. | no | ||
| cloud_auth.azure_ad.mode_service_principal.client_id | Azure client ID. Required for service_principal mode. | no | ||
| cloud_auth.azure_ad.mode_service_principal.client_secret | Azure client secret for service_principal mode. | no | ||
| cloud_auth.azure_ad.mode_managed_identity.client_id | Optional client ID of a user-assigned managed identity (managed_identity mode). | no | ||
| Target | timeout | Query timeout (seconds). | 2 | no |
| Filters | collect_databases_matching | Select additional databases for table/index metrics. The DSN database is always included; an empty selector disables additional connections. Server and database-level metrics remain available. Uses simple patterns. | no | |
| Limits | max_db_tables | Maximum tables monitored per database, including the DSN database. Above the limit, select TOP tables by recent row activity (0 = no limit). | 50 | no |
| max_db_indexes | Maximum indexes monitored per database, including the DSN database. Above the limit, select indexes by size, independently of tables; a selected index stays until another is more than twice as large (0 = no limit). | 250 | no | |
| Histograms | transaction_time_histogram | Upper bounds in seconds for the running time of transactions. An empty list counts all observations in a single +Inf bucket. | [0.1, 0.5, 1, 2.5, 5, 10] | no |
| query_time_histogram | Upper bounds in seconds for the running time of active queries. An empty list counts all observations in a single +Inf bucket. | [0.1, 0.5, 1, 2.5, 5, 10] | no | |
| Functions | functions.top_queries.disabled | Disable the top-queries function. | no | no |
| functions.top_queries.timeout | Query timeout (seconds). Uses collector timeout if not set. | no | ||
| functions.top_queries.limit | Maximum number of queries to return. | 500 | no | |
| Virtual Node | vnode | Associates this data collection job with a Virtual Node. | no |
via UI
Configure the postgres collector from the Netdata web interface:
- Go to Nodes.
- Select the node where you want the postgres data-collection job to run and click the ⚙ (Configure this node). That node will run the data collection.
- The Collectors → Jobs view opens by default.
- In the Search box, type postgres (or scroll the list) to locate the postgres collector.
- Click the + next to the postgres collector to add a new job.
- Fill in the job fields, then click Test to verify the configuration and Submit to save.
- Test validates the provided settings and checks the collector's startup prerequisites. Successful validation does not guarantee that every metric will be available during collection.
- If it fails, an error message appears with details (for example, connection refused, timeout, or command execution errors), so you can adjust and retest.
via File
The configuration file name for this integration is go.d/postgres.conf.
The file format is YAML. Generally, the structure is:
update_every: 1
autodetection_retry: 0
jobs:
- name: some_name1
- name: some_name2
You can edit the configuration file using the edit-config script from the
Netdata config directory.
cd /etc/netdata 2>/dev/null || cd /opt/netdata/etc/netdata
sudo ./edit-config go.d/postgres.conf
Examples
TCP socket
An example configuration.
jobs:
- name: local
dsn: 'postgresql://netdata@127.0.0.1:5432/postgres'
Unix socket
An example configuration.
Config
jobs:
- name: local
dsn: 'host=/var/run/postgresql dbname=postgres user=netdata'
Unix socket (custom port)
Connect to PostgreSQL using a Unix socket with a non-default port (5433).
Config
jobs:
- name: local
dsn: 'host=/var/run/postgresql port=5433 dbname=postgres user=netdata'
Azure Database for PostgreSQL with service principal
Use Microsoft Entra service principal authentication.
Config
jobs:
- name: azure_postgres_sp
dsn: 'postgresql://netdata@myserver.postgres.database.azure.com:5432/postgres?sslmode=require'
cloud_auth:
provider: azure_ad
azure_ad:
mode: service_principal
mode_service_principal:
tenant_id: "00000000-0000-0000-0000-000000000000"
client_id: "11111111-1111-1111-1111-111111111111"
client_secret: "super-secret-value"
Azure Database for PostgreSQL with managed identity
Use managed identity authentication (system-assigned by default).
Config
jobs:
- name: azure_postgres_mi
dsn: 'postgresql://netdata@myserver.postgres.database.azure.com:5432/postgres?sslmode=require'
cloud_auth:
provider: azure_ad
azure_ad:
mode: managed_identity
Multi-instance
Note: When you define multiple jobs, their names must be unique.
Local and remote instances.
Config
jobs:
- name: local
dsn: 'postgresql://netdata@127.0.0.1:5432/postgres'
- name: remote
dsn: 'postgresql://netdata@203.0.113.0:5432/postgres'
Alerts
The following alerts are available:
| Alert name | On metric | Description |
|---|---|---|
| postgres_total_connection_utilization | postgres.connections_utilization | Average total connection utilization over the last minute |
| postgres_acquired_locks_utilization | postgres.locks_utilization | Average acquired locks utilization over the last minute |
| postgres_txid_exhaustion_perc | postgres.txid_exhaustion_perc | Percent towards TXID wraparound |
| postgres_db_cache_io_ratio | postgres.db_cache_io_ratio | Average cache hit ratio in db ${label:database} over the last minute |
| postgres_db_transactions_rollback_ratio | postgres.db_transactions_ratio | Average aborted transactions percentage in db ${label:database} over the last five minutes |
| postgres_db_deadlocks_rate | postgres.db_deadlocks_rate | Number of deadlocks detected in db ${label:database} in the last minute |
| postgres_table_cache_io_ratio | postgres.table_cache_io_ratio | Average cache hit ratio in db ${label:database} table ${label:table} over the last minute |
| postgres_table_index_cache_io_ratio | postgres.table_index_cache_io_ratio | Average index cache hit ratio in db ${label:database} table ${label:table} over the last minute |
| postgres_table_toast_cache_io_ratio | postgres.table_toast_cache_io_ratio | Average TOAST hit ratio in db ${label:database} table ${label:table} over the last minute |
| postgres_table_toast_index_cache_io_ratio | postgres.table_toast_index_cache_io_ratio | average index TOAST hit ratio in db ${label:database} table ${label:table} over the last minute |
| postgres_table_bloat_size_perc | postgres.table_bloat_size_perc | Bloat size percentage in db ${label:database} table ${label:table} |
| postgres_table_last_autovacuum_time | postgres.table_autovacuum_since_time | Time elapsed since db ${label:database} table ${label:table} was vacuumed by the autovacuum daemon |
| postgres_table_last_autoanalyze_time | postgres.table_autoanalyze_since_time | Time elapsed since db ${label:database} table ${label:table} was analyzed by the autovacuum daemon |
| postgres_index_bloat_size_perc | postgres.index_bloat_size_perc | Bloat size percentage in db ${label:database} table ${label:table} index ${label:index} |
Metrics
Metrics grouped by scope.
The scope defines the instance that the metric belongs to. An instance is uniquely identified by a set of labels.
Per PostgreSQL instance
These metrics refer to the entire monitored application.
This scope has no labels.
Metrics:
| Metric | Description | Dimensions | Unit |
|---|---|---|---|
| postgres.connections_utilization | Connections utilization | used | percentage |
| postgres.connections_usage | Connections usage | available, used | connections |
| postgres.connections_state_count | Connections in each state | active, idle, idle_in_transaction, idle_in_transaction_aborted, fastpath_function_call, disabled | connections |
| postgres.active_sessions | Active sessions by wait event type | cpu, io, lock, lwlock, buffer, ipc, client, timeout, extension, other | sessions |
| postgres.transactions_duration | Observed transactions time | a dimension per upper bound in seconds, plus +Inf | transactions/s |
| postgres.queries_duration | Observed active queries time | a dimension per upper bound in seconds, plus +Inf | queries/s |
| postgres.locks_utilization | Acquired locks utilization | used | percentage |
| postgres.checkpoints_rate | Checkpoints | scheduled, requested | checkpoints/s |
| postgres.checkpoints_time | Checkpoint time | write, sync | milliseconds |
| postgres.bgwriter_halts_rate | Background writer scan halts | maxwritten | halts/s |
| postgres.buffers_io_rate | Buffers written rate | checkpoint, backend, bgwriter | B/s |
| postgres.buffers_backend_fsync_rate | Backend fsync calls | fsync | calls/s |
| postgres.buffers_allocated_rate | Buffers allocated | allocated | B/s |
| postgres.wal_io_rate | Write-Ahead Log writes | written | B/s |
| postgres.wal_files_count | Write-Ahead Log files | written, recycled | files |
| postgres.wal_archiving_files_count | Write-Ahead Log archived files | ready, done | files/s |
| postgres.autovacuum_workers_count | Autovacuum workers | analyze, vacuum_analyze, vacuum, vacuum_freeze, brin_summarize | workers |
| postgres.txid_exhaustion_towards_autovacuum_perc | Percent towards emergency autovacuum | emergency_autovacuum | percentage |
| postgres.txid_exhaustion_perc | Percent towards transaction ID wraparound | txid_exhaustion | percentage |
| postgres.txid_exhaustion_oldest_txid_num | Oldest transaction XID | xid | xid |
| postgres.catalog_relations_count | Relation count | ordinary_table, index, sequence, toast_table, view, materialized_view, composite_type, foreign_table, partitioned_table, partitioned_index | relations |
| postgres.catalog_relations_size | Relation size | ordinary_table, index, sequence, toast_table, view, materialized_view, composite_type, foreign_table, partitioned_table, partitioned_index | B |
| postgres.uptime | Uptime | uptime | seconds |
| postgres.databases_count | Number of databases | databases | databases |
Per repl application
These metrics refer to the replication application.
Labels:
| Label | Description |
|---|---|
| application | application name |
Metrics:
| Metric | Description | Dimensions | Unit |
|---|---|---|---|
| postgres.replication_app_wal_lag_size | Standby application WAL lag size | sent_lag, write_lag, flush_lag, replay_lag | B |
| postgres.replication_app_wal_lag_time | Standby application WAL lag time | write_lag, flush_lag, replay_lag | seconds |
Per repl slot
These metrics refer to the replication slot.
Labels:
| Label | Description |
|---|---|
| slot | replication slot name |
Metrics:
| Metric | Description | Dimensions | Unit |
|---|---|---|---|
| postgres.replication_slot_files_count | Replication slot files | wal_keep, pg_replslot_files | files |
Per database
These metrics refer to the database.
Labels:
| Label | Description |
|---|---|
| database | database name |
Metrics:
| Metric | Description | Dimensions | Unit |
|---|---|---|---|
| postgres.db_transactions_ratio | Database transactions ratio | committed, rollback | percentage |
| postgres.db_transactions_rate | Database transactions | committed, rollback | transactions/s |
| postgres.db_connections_utilization | Database connections utilization | used | percentage |
| postgres.db_connections_count | Database connections | connections | connections |
| postgres.db_active_sessions | Database active sessions by wait event type | cpu, io, lock, lwlock, buffer, ipc, client, timeout, extension, other | sessions |
| postgres.db_cache_io_ratio | Database buffer cache miss ratio | miss | percentage |
| postgres.db_io_rate | Database reads | memory, disk | B/s |
| postgres.db_ops_fetched_rows_ratio | Database rows fetched ratio | fetched | percentage |
| postgres.db_ops_read_rows_rate | Database rows read | returned, fetched | rows/s |
| postgres.db_ops_write_rows_rate | Database rows written | inserted, deleted, updated | rows/s |
| postgres.db_conflicts_rate | Database canceled queries | conflicts | queries/s |
| postgres.db_conflicts_reason_rate | Database canceled queries by reason | tablespace, lock, snapshot, bufferpin, deadlock | queries/s |
| postgres.db_deadlocks_rate | Database deadlocks | deadlocks | deadlocks/s |
| postgres.db_locks_held_count | Database locks held | access_share, row_share, row_exclusive, share_update, share, share_row_exclusive, exclusive, access_exclusive | locks |
| postgres.db_locks_awaited_count | Database locks awaited | access_share, row_share, row_exclusive, share_update, share, share_row_exclusive, exclusive, access_exclusive | locks |
| postgres.db_temp_files_created_rate | Database created temporary files | created | files/s |
| postgres.db_temp_files_io_rate | Database temporary files data written to disk | written | B/s |
| postgres.db_size | Database size | size | B |
Per table
These metrics refer to the database table.
Labels:
| Label | Description |
|---|---|
| database | database name |
| schema | schema name |
| table | table name |
| parent_table | parent table name |
Metrics:
| Metric | Description | Dimensions | Unit |
|---|---|---|---|
| postgres.table_rows_dead_ratio | Table dead rows | dead | % |
| postgres.table_rows_count | Table total rows | live, dead | rows |
| postgres.table_ops_rows_rate | Table throughput | inserted, deleted, updated | rows/s |
| postgres.table_ops_rows_hot_ratio | Table HOT updates ratio | hot | percentage |
| postgres.table_ops_rows_hot_rate | Table HOT updates | hot | rows/s |
| postgres.table_cache_io_ratio | Table I/O cache miss ratio | miss | percentage |
| postgres.table_io_rate | Table I/O | memory, disk | B/s |
| postgres.table_index_cache_io_ratio | Table index I/O cache miss ratio | miss | percentage |
| postgres.table_index_io_rate | Table index I/O | memory, disk | B/s |
| postgres.table_toast_cache_io_ratio | Table TOAST I/O cache miss ratio | miss | percentage |
| postgres.table_toast_io_rate | Table TOAST I/O | memory, disk | B/s |
| postgres.table_toast_index_cache_io_ratio | Table TOAST index I/O cache miss ratio | miss | percentage |
| postgres.table_toast_index_io_rate | Table TOAST index I/O | memory, disk | B/s |
| postgres.table_scans_rate | Table scans | index, sequential | scans/s |
| postgres.table_scans_rows_rate | Table live rows fetched by scans | index, sequential | rows/s |
| postgres.table_autovacuum_since_time | Table time since last auto VACUUM | time | seconds |
| postgres.table_vacuum_since_time | Table time since last manual VACUUM | time | seconds |
| postgres.table_autoanalyze_since_time | Table time since last auto ANALYZE | time | seconds |
| postgres.table_analyze_since_time | Table time since last manual ANALYZE | time | seconds |
| postgres.table_null_columns_count | Table null columns | null | columns |
| postgres.table_total_size | Table total size | size | B |
| postgres.table_bloat_size_perc | Table bloat size percentage | bloat | percentage |
| postgres.table_bloat_size | Table bloat size | bloat | B |
Per index
These metrics refer to the table index.
Labels:
| Label | Description |
|---|---|
| database | database name |
| schema | schema name |
| table | table name |
| parent_table | parent table name |
| index | index name |
Metrics:
| Metric | Description | Dimensions | Unit |
|---|---|---|---|
| postgres.index_size | Index size | size | B |
| postgres.index_bloat_size_perc | Index bloat size percentage | bloat | percentage |
| postgres.index_bloat_size | Index bloat size | bloat | B |
| postgres.index_usage_status | Index usage status | used, unused | status |
Live Data
This collector exposes real-time functions for interactive troubleshooting in the Live tab.
Top Queries
Retrieves aggregated SQL query performance metrics from PostgreSQL using either pg_stat_monitor (preferred) or pg_stat_statements.
The collector automatically detects which extension is available:
- pg_stat_monitor (Percona): Enhanced statistics with additional columns like application name, client IP, CPU time, error info, and query classification
- pg_stat_statements (standard): Core execution statistics available in all PostgreSQL installations
Each row is one normalized statement in one database, run by one user. Without pg_read_all_stats, the monitoring role cannot tell other users' statements apart, so they share one row per database, user and top-level flag. Top-level and nested runs of a statement are separate rows where the extension tells them apart (pg_stat_statements 1.9+, PostgreSQL 14+, and pg_stat_monitor). With pg_stat_monitor, rows are also per application and client address, and a row totals all retained time buckets, so executions drop out as their buckets expire.
Statistics include execution counts, timing metrics, I/O operations, and resource consumption. Columns are detected from the extension's view, so they follow your PostgreSQL and extension versions.
Use cases:
- Identify slow queries consuming the most total execution time
- Find queries with high shared block reads for I/O optimization
- Analyze temp block usage to detect queries needing memory tuning
- With pg_stat_monitor: Track queries by application, identify error patterns
Query text is truncated at 4096 characters for display purposes.
| Aspect | Description |
|---|---|
| Name | Postgres:top-queries |
| Require Cloud | yes |
| Performance | Queries pg_stat_statements or pg_stat_monitor which maintain statistics in shared memory:• On busy servers with many unique queries, the extension may consume significant memory • The server groups the view's rows per statement before the default limit of 500 rows applies • pg_stat_monitor uses time-based buckets which may have different memory characteristics • Runs on the Functions' own connection (the metrics connection when the server refuses a second one), bounded by functions.top_queries.timeout (the collector timeout when not set) |
| Security | Query text may contain unmasked literal values including potentially sensitive data: • Personal information in WHERE clauses or INSERT values • Business data and internal identifiers • Access should be restricted to authorized personnel only |
| Availability | Available when: • Either pg_stat_statements or pg_stat_monitor extension is installed in the DSN database (in any schema)• The collector has successfully connected to PostgreSQL • Returns HTTP 503 if no query statistics extension is installed • Returns HTTP 500 if the query fails • Returns HTTP 504 if the query times out • Returns HTTP 499 if the request is canceled |
Prerequisites
Enable pg_stat_statements or pg_stat_monitor
Either pg_stat_statements (standard) or pg_stat_monitor (Percona) must be installed. The collector auto-detects which is available, preferring pg_stat_monitor when both are present.
Option 1: pg_stat_statements (standard PostgreSQL)
-
Add to
postgresql.conf:shared_preload_libraries = 'pg_stat_statements' -
Restart PostgreSQL, then create the extension:
CREATE EXTENSION pg_stat_statements;
Option 2: pg_stat_monitor (Percona - recommended)
Provides additional columns: application name, client IP, CPU time, error tracking, and query classification.
-
Install pg_stat_monitor (available in Percona distribution or as separate package)
-
Add to
postgresql.conf:shared_preload_libraries = 'pg_stat_monitor' -
Restart PostgreSQL, then create the extension:
CREATE EXTENSION pg_stat_monitor;
- Both extensions require a server restart to load the shared library
- Statistics can be reset with
SELECT pg_stat_statements_reset()orSELECT pg_stat_monitor_reset() - Enable
track_io_timingfor block read/write timing metrics
Parameters
| Parameter | Type | Description | Required | Default | Options |
|---|---|---|---|---|---|
| Filter By | select | Select the primary sort column. Options include total time, mean time, calls, rows, shared blocks hit/read, and temp blocks written. Defaults to total time to focus on most resource-intensive queries. | yes | totalTime |
Returns
Aggregated query statistics from pg_stat_statements or pg_stat_monitor. Each row is one statement per database and user (and per top-level flag where available; with pg_stat_monitor, also per application and client address), with cumulative metrics across its executions. Without pg_read_all_stats, other users' statements share a row.
| Column | Type | Unit | Visibility | Description |
|---|---|---|---|---|
| Row ID | string | hidden | Unique row identifier: a JSON array of the database, user and query ID, plus the top-level flag where available and, with pg_stat_monitor, the application name and client address. Database and user are OIDs (names with pg_stat_monitor 1.x). | |
| Query ID | string | hidden | Internal hash identifier for the normalized query. Can be used to track queries across statistics resets. Empty for other users' statements when the monitoring role lacks pg_read_all_stats; those statements share one row per database, user and top-level flag. | |
| Query | string | Normalized SQL query text with literals replaced by parameter placeholders. Truncated to 4096 characters. | ||
| Database | string | Database name where the query was executed. | ||
| User | string | PostgreSQL role that executed the query, including roles without the LOGIN attribute reached through SET ROLE. | ||
| Calls | integer | Total number of times this query pattern has been executed. High values indicate frequently run queries. | ||
| Total Time | duration | milliseconds | Cumulative execution time across all executions. High values indicate queries consuming significant database resources. | |
| Mean Time | duration | milliseconds | Average execution time per call (Total Time divided by Calls). Use this to compare typical performance across different query patterns. | |
| Min Time | duration | milliseconds | hidden | Minimum execution time observed for a single execution. |
| Max Time | duration | milliseconds | hidden | Maximum execution time observed for a single execution. Large gaps between min and max may indicate performance variability. |
| Stddev Time | duration | milliseconds | hidden | Population standard deviation of execution time across all executions. High values indicate inconsistent query performance. |
| Plans | integer | hidden | Number of times the query was planned. Available in PostgreSQL 13+. | |
| Total Plan Time | duration | milliseconds | hidden | Cumulative time spent planning the query. Available in PostgreSQL 13+. |
| Mean Plan Time | duration | milliseconds | hidden | Average time spent planning per execution. Available in PostgreSQL 13+. |
| Min Plan Time | duration | milliseconds | hidden | Minimum planning time observed. Available in PostgreSQL 13+. |
| Max Plan Time | duration | milliseconds | hidden | Maximum planning time observed. Available in PostgreSQL 13+. |
| Stddev Plan Time | duration | milliseconds | hidden | Standard deviation of planning time. Available in PostgreSQL 13+. |
| Rows | integer | Total number of rows retrieved or affected across all executions. | ||
| Shared Blocks Hit | integer | Total shared buffer cache hits. High values indicate good cache utilization. | ||
| Shared Blocks Read | integer | Total shared blocks read from disk. High values indicate queries that bypass the cache and may benefit from more shared_buffers. | ||
| Shared Blocks Dirtied | integer | hidden | Total shared blocks dirtied by the query. | |
| Shared Blocks Written | integer | hidden | Total shared blocks written by the query. | |
| Local Blocks Hit | integer | hidden | Total local buffer cache hits (temporary tables). | |
| Local Blocks Read | integer | hidden | Total local blocks read from disk. | |
| Local Blocks Dirtied | integer | hidden | Total local blocks dirtied. | |
| Local Blocks Written | integer | hidden | Total local blocks written. | |
| Temp Blocks Read | integer | Total temp blocks read. Non-zero values indicate queries spilling to disk due to insufficient work_mem. | ||
| Temp Blocks Written | integer | Total temp blocks written. High values suggest increasing work_mem may improve performance. | ||
| Block Read Time | duration | milliseconds | Time spent reading shared blocks from disk (shared_blk_read_time on PostgreSQL 17+). Requires track_io_timing to be enabled. | |
| Block Write Time | duration | milliseconds | Time spent writing shared blocks to disk (shared_blk_write_time on PostgreSQL 17+). Requires track_io_timing to be enabled. | |
| WAL Records | integer | hidden | Total number of WAL records generated. Available in PostgreSQL 13+. | |
| WAL Full Page Images | integer | hidden | Total number of WAL full page images generated. Available in PostgreSQL 13+. | |
| WAL Bytes | integer | hidden | Total bytes of WAL generated. Available in PostgreSQL 13+. | |
| JIT Functions | integer | hidden | Total number of functions JIT-compiled. Available in PostgreSQL 15+. | |
| JIT Generation Time | duration | milliseconds | hidden | Time spent generating JIT code. Available in PostgreSQL 15+. |
| JIT Inlining Count | integer | hidden | Number of times JIT inlining was performed. Available in PostgreSQL 15+. | |
| JIT Inlining Time | duration | milliseconds | hidden | Time spent on JIT inlining. Available in PostgreSQL 15+. |
| JIT Optimization Count | integer | hidden | Number of times JIT optimization was performed. Available in PostgreSQL 15+. | |
| JIT Optimization Time | duration | milliseconds | hidden | Time spent on JIT optimization. Available in PostgreSQL 15+. |
| JIT Emission Count | integer | hidden | Number of times JIT code was emitted. Available in PostgreSQL 15+. | |
| JIT Emission Time | duration | milliseconds | hidden | Time spent emitting JIT code. Available in PostgreSQL 15+. |
| Temp Block Read Time | duration | milliseconds | hidden | Time spent reading temp blocks. Available in PostgreSQL 15+. Requires track_io_timing. |
| Temp Block Write Time | duration | milliseconds | hidden | Time spent writing temp blocks. Available in PostgreSQL 15+. Requires track_io_timing. |
| Application Name | string | Name of the application that executed the query. Available with pg_stat_monitor only. | ||
| Client IP | string | hidden | IP address of the client that executed the query. Available with pg_stat_monitor only. | |
| Command Type | string | Type of SQL command (SELECT, INSERT, UPDATE, DELETE, etc.), from the most recent bucket. Available with pg_stat_monitor only. | ||
| Comments | string | hidden | SQL comments extracted from the query, from the most recent bucket that recorded any. Available with pg_stat_monitor only. | |
| Relations | string | hidden | Tables/relations involved in the query, from the most recent bucket. Available with pg_stat_monitor only. | |
| CPU User Time | duration | milliseconds | hidden | CPU time spent in user mode. Available with pg_stat_monitor only. |
| CPU System Time | duration | milliseconds | hidden | CPU time spent in system/kernel mode. Available with pg_stat_monitor only. |
| Error Level | integer | hidden | PostgreSQL error level from the most recent bucket that recorded an error, 0 when none did. Available with pg_stat_monitor only. | |
| SQL Code | string | hidden | PostgreSQL SQLSTATE error code from the most recent bucket that recorded an error. Available with pg_stat_monitor only. | |
| Error Message | string | hidden | Error message from the most recent bucket that recorded an error. Available with pg_stat_monitor only. | |
| Top Level | string | hidden | Whether this is a top-level statement (true) or nested inside a function (false). Available with pg_stat_statements 1.9+ (PostgreSQL 14+) and with pg_stat_monitor. | |
| Oldest Bucket Start Time | string | hidden | Start time of the oldest retained bucket included in the row's totals. Available with pg_stat_monitor only. |
Running Queries
Retrieves currently executing queries from PostgreSQL pg_stat_activity system view.
This function queries pg_stat_activity which shows real-time information about each server process including the SQL query being executed, wait events, and session state. Unlike Top Queries which shows aggregated historical statistics, Running Queries shows live snapshots of active queries.
Use cases:
- Identify long-running queries that may be blocking other operations
- Debug stuck transactions or hanging connections
- Monitor active workload during performance issues
- Investigate wait events and lock contention in real-time
Query text is truncated at 4096 characters for display purposes.
| Aspect | Description |
|---|---|
| Name | Postgres:running-queries |
| Require Cloud | yes |
| Performance | Queries pg_stat_activity which is a live system view:• Very lightweight query, no impact on database performance • Returns only active queries by default (state = 'active') • Limited to 500 rows • Runs on the Functions' own connection (the metrics connection when the server refuses a second one), bounded by the collector timeout |
| Security | Query text contains actual SQL being executed, which may include: • Personal information in WHERE clauses or INSERT values • Business data and internal identifiers • Access should be restricted to authorized personnel only |
| Availability | Available when: • The collector has successfully connected to PostgreSQL • Returns HTTP 503 if collector is still initializing • Returns HTTP 500 if the query fails • Returns HTTP 504 if the query times out • Returns HTTP 499 if the request is canceled |
Prerequisites
Database user permissions
The monitoring user needs pg_monitor role to view all sessions:
GRANT pg_monitor TO netdata;
Without this role, the user can only see their own sessions.
Parameters
| Parameter | Type | Description | Required | Default | Options |
|---|---|---|---|---|---|
| Sort By | select | Select the sort column. Defaults to query duration (longest running first). | yes | durationMs |
Returns
Live query data from pg_stat_activity. Each row represents a currently active backend process.
| Column | Type | Unit | Visibility | Description |
|---|---|---|---|---|
| Duration | duration | milliseconds | Query duration in milliseconds (since query_start). High values indicate long-running queries. | |
| Query | string | Query text of the currently executing or most recent query. May be truncated at track_activity_query_size. | ||
| Database | string | Name of the database this backend is connected to. | ||
| User | string | Name of the user logged into this backend. | ||
| Application Name | string | Name of the application connected to this backend. | ||
| Client Address | string | IP address of the client (NULL for Unix socket or internal process). | ||
| Wait Event | string | Specific wait event name if backend is currently waiting. | ||
| PID | integer | Process ID of this backend. Use with pg_terminate_backend() to kill a query. | ||
| Wait Event Type | string | hidden | Type of event the backend is waiting for (Activity, BufferPin, Client, Extension, IO, IPC, Lock, LWLock, Timeout). | |
| State | string | hidden | Current state: active, idle, idle in transaction, idle in transaction (aborted), fastpath function call, disabled. | |
| Backend Type | string | hidden | Type of backend: client backend, autovacuum worker, parallel worker, walsender, walreceiver, etc. Available in PostgreSQL 10+. | |
| Query Start | timestamp | hidden | Time when the currently active query was started. | |
| Transaction Start | timestamp | hidden | Time when current transaction started (NULL if no transaction). | |
| Backend Start | timestamp | hidden | Time when this process/connection started. | |
| State Change | timestamp | hidden | Time when state was last changed. | |
| Query ID | string | hidden | Query identifier (requires compute_query_id or extension). Available in PostgreSQL 14+. | |
| Leader PID | integer | hidden | Process ID of parallel group leader (NULL if this is leader or not parallel). Available in PostgreSQL 13+. | |
| Database ID | integer | hidden | OID of the database this backend is connected to. | |
| User ID | integer | hidden | OID of the user logged into this backend. | |
| Client Hostname | string | hidden | Hostname of the client via reverse DNS (only if log_hostname enabled). | |
| Client Port | integer | hidden | TCP port of client (-1 for Unix socket, NULL for internal process). | |
| Backend Xid | string | hidden | Top-level transaction identifier of this backend. | |
| Backend Xmin | string | hidden | Backend's xmin horizon. |
Troubleshooting
Diagnostics
Debug Mode
Important: Debug mode is not supported for data collection jobs created via the UI using the Dyncfg feature.
To troubleshoot issues with the postgres collector, run the go.d.plugin with the debug option enabled. The output
should give you clues as to why the collector isn't working.
-
Navigate to the
plugins.ddirectory, usually at/usr/libexec/netdata/plugins.d/. If that's not the case on your system, opennetdata.confand look for thepluginssetting under[directories].cd /usr/libexec/netdata/plugins.d/ -
Switch to the
netdatauser.sudo -u netdata -s -
Run the
go.d.pluginto debug the collector:./go.d.plugin -d -m postgresTo debug a specific job:
./go.d.plugin -d -m postgres -j jobName
Getting Logs
If you're encountering problems with the postgres collector, follow these steps to retrieve logs and identify potential issues:
- Run the command specific to your system (systemd, non-systemd, or Docker container).
- Examine the output for any warnings or error messages that might indicate issues. These messages should provide clues about the root cause of the problem.
System with systemd
Use the following command to view logs generated since the last Netdata service restart:
journalctl _SYSTEMD_INVOCATION_ID="$(systemctl show --value --property=InvocationID netdata)" --namespace=netdata --grep postgres
System without systemd
Locate the collector log file, typically at /var/log/netdata/collector.log, and use grep to filter for collector's name:
grep postgres /var/log/netdata/collector.log
Note: This method shows logs from all restarts. Focus on the latest entries for troubleshooting current issues.
Docker Container
If your Netdata runs in a Docker container named "netdata" (replace if different), use this command:
docker logs netdata 2>&1 | grep postgres
Do you have any feedback for this page? If so, you can open a new issue on our netdata/learn repository.