> For the complete documentation index, see [llms.txt](https://docs.groundcover.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.groundcover.com/collect-data/data-sources/postgresql-database-monitoring.md).

# PostgreSQL Database Monitoring

Collect PostgreSQL health metrics, statement measurements, and query traces without running a separate exporter

groundcover connects directly to PostgreSQL to collect health metrics, interval-based statement measurements, and query-statistics traces without a separate exporter. Health metrics describe engine health; measurements describe statement activity during collection intervals; query traces expose collected statement statistics. Activity Traces describe the integration itself.

**Amazon Aurora PostgreSQL is supported**, including writer and read-replica instances. Some PostgreSQL health functions are restricted or unsupported by Aurora; see [Aurora PostgreSQL limitations](#aurora-postgresql-limitations) below for their metric impact and how groundcover reports them.

## Prerequisites

### groundcover versions and execution location

The features described here require a groundcover backend running **1.13.269 or later**. If the integration runs from a monitored cluster (sensor-side execution), that cluster's groundcover sensor must also run **1.13.269 or later**. Upgrading only the backend does not upgrade the collector running in the selected cluster.

The integration must run from a groundcover backend or monitored cluster that can reach the PostgreSQL host and port.

### Monitoring user and database access

Create a dedicated monitoring user and grant access to statistics. Run these commands as a database administrator, replacing the password:

```sql
CREATE USER groundcover WITH PASSWORD '<password>';
GRANT pg_monitor TO groundcover;
```

groundcover automatically discovers eligible databases; you do not need to list each database in the integration configuration. To collect table/index metrics, the monitoring user must be able to connect to each discovered database. PostgreSQL grants `CONNECT` to all users through `PUBLIC` by default, so an additional grant is usually unnecessary unless your database access policy restricts it. See [PostgreSQL privileges](https://www.postgresql.org/docs/current/ddl-priv.html).

If the user lacks `CONNECT` on the configured connection database or a database you want to monitor, grant it explicitly as an administrator:

```sql
GRANT CONNECT ON DATABASE "<database-name>" TO groundcover;
```

A discovered database without `CONNECT` is skipped for table/index collection and reported in Activity Traces. Newly created eligible databases are discovered automatically, but must allow the monitoring user to connect.

The monitoring user must inherit its statistics privileges when it connects. groundcover does not switch roles with `SET ROLE`. See [permission checks](#check-permissions-and-settings).

Health-only collection does not require `pg_stat_statements`. Keep PostgreSQL statistics collection (`track_counts`) enabled for table/index statistics; see [PostgreSQL statistics configuration](https://www.postgresql.org/docs/current/monitoring-stats.html#MONITORING-STATS-SETUP). Instance control-data and WAL-directory metrics also depend on permission to execute the corresponding monitoring functions.

### Statement collection

For statement measurements and query-statistics traces, connect as an administrator to the **connection database configured in the integration**, then install the extension there:

```sql
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
```

The extension exposes instance-wide statement statistics from that connection database; the integration does not open every database to collect statements. If using a non-default extension schema, make sure the monitoring user's search path also resolves `pg_stat_statements` for query-statistics traces; see [Check the extension search path](#check-the-extension-search-path). On servers exposing `compute_query_id`, keep it `auto` or `on` unless another module supplies query identifiers. See PostgreSQL's [pg\_stat\_statements prerequisites](https://www.postgresql.org/docs/current/pgstatstatements.html).

As a database administrator, check the active preload value and whether the server has detected a change that requires a restart:

```sql
SELECT name, setting AS active_value, pending_restart, source, sourcefile, sourceline
FROM pg_settings
WHERE name = 'shared_preload_libraries';
```

`active_value` is the running server's value. `pending_restart = true` means the server has reread a changed setting that needs a restart; it does not show the replacement value. Changes in files that the server has not reread may not be reflected in this flag.

To inspect the current configuration-file values, including entries that override earlier ones, run:

```sql
SELECT sourcefile, sourceline, seqno, setting AS configured_value, applied, error
FROM pg_file_settings
WHERE name = 'shared_preload_libraries'
ORDER BY seqno;
```

Review the entries in order and check `error`; `applied = false` can indicate an overridden entry or a setting that cannot take effect yet. This view reads the current files, not the active server state, and requires superuser access by default. If your managed service restricts access, inspect its parameter group or database flags instead. See PostgreSQL's [pg\_settings](https://www.postgresql.org/docs/current/view-pg-settings.html) and [pg\_file\_settings](https://www.postgresql.org/docs/current/view-pg-file-settings.html) references.

Preserve every existing entry and append `pg_stat_statements` to the comma-separated list if it is not already present. For example, a configured value of `pgaudit` becomes `pgaudit,pg_stat_statements`. Do not replace an existing list with only `pg_stat_statements`. After applying the configuration and restarting, rerun the first query to confirm that the active value includes `pg_stat_statements` and `pending_restart` is false.

Configure these settings in `postgresql.conf`:

```ini
# Use this assignment only if the existing preload list is empty.
# Otherwise, append pg_stat_statements to the existing list.
# Changes take effect after a restart.
shared_preload_libraries = 'pg_stat_statements'

# Track top-level statements to avoid counting nested work twice.
pg_stat_statements.track = top

# How many distinct statements the extension retains.
pg_stat_statements.max = 10000

# Enables I/O timing metrics. Off by default.
track_io_timing = on

# Enables WAL timing where the server exposes the corresponding counters.
track_wal_io_timing = on
```

If you need nested statements for other tools, check whether the installed extension supports `pg_stat_statements.track = all` with groundcover measurements. Run this in the integration's configured connection database as the monitoring user:

```sql
SELECT e.extversion AS extension_version,
       current_setting('pg_stat_statements.track', true) AS current_tracking,
       EXISTS (
         SELECT 1
         FROM pg_catalog.pg_class c
         JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid
         WHERE c.relnamespace = e.extnamespace
           AND c.relname = 'pg_stat_statements'
           AND a.attname = 'toplevel'
           AND a.attnum > 0
           AND NOT a.attisdropped
       ) AS supports_track_all
FROM pg_catalog.pg_extension e
WHERE e.extname = 'pg_stat_statements';
```

* **`supports_track_all = true`:** You can use `top` or `all`. With `all`, groundcover selects only top-level statements for measurements to avoid double counting.
* **`supports_track_all = false`:** Set `pg_stat_statements.track = top`. With `all`, measurement collection is skipped to avoid double counting.
* **No rows:** The extension is not installed in this database. Confirm you connected to the configured connection database and install the extension there as described above.

This checks the installed extension's columns directly, so it also works with custom extension schemas and does not depend on the server version alone.

If you use a managed PostgreSQL service, apply server-level settings through the provider's parameter-group or database-flags interface. Preserve the existing `shared_preload_libraries` entries there and append `pg_stat_statements` if it is missing. Apply the change and restart the database as required by your provider. Managed services also expose administrative databases that the monitoring user cannot read; exclude those databases from collection.

{% hint style="info" %}
The integration probes server capabilities and primary/standby role on every scrape. A missing setting, grant, server capability, or primary/standby role can make only the affected health group unavailable while other groups continue collecting.
{% endhint %}

## What it collects

| Signal                  | What it contains                                                                                   | Where to use it                                                                                                                                                                                  |
| ----------------------- | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Built-in health metrics | PostgreSQL engine health and capacity under the `groundcover_db_pg_*` prefix                       | [Data Explorer](https://app.groundcover.com/explore/data-explorer), monitors, and the PostgreSQL dashboard from the [Dashboard Catalog](/investigate/dashboards-and-alerts/dashboard-catalog.md) |
| Statement measurements  | Per-interval calls, execution time, rows, block activity, and available I/O/WAL statistics         | [Database measurements API](/reference/remote-access-and-apis/api-examples/query-database-measurements.md)                                                                                       |
| Query statistics        | Rows from `pg_stat_statements`, represented as traces with database semantic-convention attributes | [Traces](https://app.groundcover.com/traces)                                                                                                                                                     |

`tables.pgStatStatements.enabled` enables both statement measurements and query-statistics traces, independently of health metrics. Query-statistics traces contain cumulative snapshot values and are not joined to the application trace that issued the query. Measurements contain interval deltas; do not sum the cumulative values from repeated query traces to calculate workload volume.

For per-group metric names, types, labels, sources, and examples, see the [PostgreSQL Health Metrics Reference](/collect-data/data-sources/postgresql-database-monitoring/postgresql-health-metrics.md).

See [Verify collection](#verify-collection) for copyable metric queries and trace filters.

### Health metric groups

All health groups are enabled by default when built-in health metrics are enabled. You can disable groups in configuration. The app exposes the existing health-group controls; configure Tables, Indexes, Autovacuum, and relation limits through API/IaC if those controls are not shown.

| Group                  | Description                                                                                                                         | Availability and empty results                                                                                                 |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| Connections            | Client connections by state (active, idle, idle in transaction, waiting) and the server's max\_connections limit.                   | Available from standard statistics views.                                                                                      |
| Replication            | Replication lag in seconds and bytes per replica, and how much WAL each replication slot is holding back.                           | Replica and slot series are empty when neither is configured. Some queries apply only to a primary.                            |
| Standby                | On a replica: how far behind the primary it is, and whether the WAL receiver is still connected.                                    | Collected only when the monitored instance is in recovery.                                                                     |
| Database stats         | Per-database transactions, cache hit/read counters, rows read and written, deadlocks, temp file spills and session totals.          | Excluded databases do not produce series.                                                                                      |
| Transaction wraparound | How much transaction ID headroom each database has left before wraparound forces the server to stop accepting writes.               | Excluded databases do not produce series.                                                                                      |
| Database size          | On-disk size of each database.                                                                                                      | Excluded databases do not produce series.                                                                                      |
| Conflicts              | Queries cancelled on a standby because WAL replay conflicted with them, broken down by reason.                                      | Zero-valued counters are normal when no conflicts have occurred.                                                               |
| WAL archiver           | WAL segments successfully archived, and archive failures.                                                                           | Counters can remain zero when archiving is inactive.                                                                           |
| Instance               | Server uptime, current timeline, and the count, size and age of files in the WAL directory.                                         | Some filesystem-level values require statistics-monitoring privileges.                                                         |
| Locks                  | Locks held and waiting by lock mode, and how long the oldest idle-in-transaction session has been holding one.                      | Requires statistics-monitoring privileges; lock combinations are zero-filled; the idle-in-transaction age series can be empty. |
| Checkpoints            | How often checkpoints run and how long they take, and how many buffers the checkpointer, background writer and backends each wrote. | The exact server counters used are selected automatically from available capabilities.                                         |
| WAL                    | WAL records and bytes generated, full-page images written, and time spent writing and syncing WAL.                                  | Collected when the server exposes the required WAL statistics.                                                                 |
| I/O                    | Reads, writes, extends and fsyncs by backend type and context, with timing when track\_io\_timing is enabled.                       | Collected when the server exposes the required I/O statistics. Timing values require `track_io_timing`.                        |
| Tables                 | Estimated live/dead tuples, scans, tuple changes, relation sizes, and maintenance counts/ages.                                      | Top-N per eligible database; unknown maintenance ages are omitted.                                                             |
| Indexes                | Scans, size, and unique/valid/primary metadata for selected indexes.                                                                | Independent top-N per eligible database; requires CONNECT.                                                                     |
| Autovacuum             | Instance enablement, configured worker maximum, and running autovacuum workers.                                                     | Running workers require usable pg\_monitor; manual VACUUM is excluded.                                                         |

## Set it up

{% tabs %}
{% tab title="In the app (recommended)" %}
Open [Data Sources](https://app.groundcover.com/data-sources), select **PostgreSQL**, and complete the wizard:

<figure><img src="https://2771001740-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUHgqKYgCiRKdOpWQdi52%2Fuploads%2Fgit-blob-de8afa3bf5c264dbdf08b8cab9223f966168edcd%2Fpostgresql-database-monitoring-wizard.png?alt=media" alt="PostgreSQL setup wizard showing connection and cluster-scoping settings"><figcaption><p>Configure the PostgreSQL connection in the Data Sources wizard.</p></figcaption></figure>

1. **Prepare PostgreSQL** — create the monitoring user and apply its grants. For statement collection, also configure the extension and server settings.
2. **Connection** — enter a name, host, optional port and database, and TLS settings. The database is the connection database. Per-database health metrics honor exclusions; table/index collection also checks CONNECT and collection limits.
3. **Cluster scoping** — run the integration from the backend or from a monitored cluster that can reach the database.
4. **Authentication** — provide the monitoring user's basic-auth credentials and enable TLS under **Connection**. Select no authentication only when the database is deliberately configured for passwordless access and network controls restrict access to trusted clients, including the integration's execution location. Never expose an unauthenticated database endpoint to the public internet.
5. **Collection** — choose query-statistics collection (which also enables statement measurements), INSERT filtering, the maximum statements per scrape, the shared scrape interval, and health-metric groups.
6. **Database filtering** — list administrative or application databases to exclude. Table/index discovery includes non-template databases that allow connections, subject to permissions and collection limits.
7. **Ingestion settings** — add labels such as `environment` or `team` to every collected metric.

Save the integration, then use [Verify collection](#verify-collection) to confirm each enabled output is arriving.
{% endtab %}

{% tab title="Terraform" %}
Use the [canonical Terraform examples](https://github.com/groundcover-com/terraform-provider-groundcover/blob/main/examples/resources/groundcover_dataintegration/resource.tf), selecting the `postgresql_dbm` resource with `type = "postgresqldbm"`. Follow the [provider configuration guide](https://registry.terraform.io/providers/groundcover-com/groundcover/latest/docs) and [`groundcover_dataintegration` reference](https://registry.terraform.io/providers/groundcover-com/groundcover/latest/docs/resources/dataintegration).

Replace the example endpoint, database, username, and integration name with your values. Configure the execution cluster and password reference as described in [Credentials and execution location](#credentials-and-execution-location), then review `terraform plan` before applying.
{% endtab %}

{% tab title="Crossplane" %}
Use the [canonical PostgreSQL `DataIntegration` manifest](https://github.com/groundcover-com/crossplane-provider-groundcover/blob/main/examples/dataintegration-postgresql.yaml). Follow the [provider setup instructions](https://github.com/groundcover-com/crossplane-provider-groundcover#readme) to install the provider and configure its credentials.

Replace the example endpoint, database, username, integration name, and `providerConfigRef` with your values. Configure the execution cluster and password reference as described in [Credentials and execution location](#credentials-and-execution-location), then apply the manifest to the Kubernetes cluster running Crossplane.
{% endtab %}
{% endtabs %}

## Configuration notes

### Credentials and execution location

Choose an execution location with network access to the PostgreSQL endpoint:

* A cluster-run integration uses the integrations agent in the selected monitored cluster. Use `secretRef::k8s::<namespace>::<secret-name>::<key>` to read an existing Kubernetes Secret from that cluster.
* A backend-run integration uses the integrations agent on the groundcover backend. Store the password through the app or use `secretRef::store::<id>` in API-managed configuration.

#### Create a Kubernetes Secret

For a cluster-run integration, store the monitoring user's database password in a local file using your secret-management workflow. Restrict access to the file and ensure it contains only the password, with no trailing newline. Create the Secret in the cluster selected in **Cluster scoping**:

```bash
kubectl --context "<execution-cluster-context>" --namespace groundcover \
  create secret generic groundcover-postgresql \
  --from-file=admin-password=/path/to/password-file
```

The namespace must already exist. This creates a Secret named `groundcover-postgresql` with a data key named `admin-password`. Reference it in the integration's `authentication.basicAuth.password` field:

```
secretRef::k8s::groundcover::groundcover-postgresql::admin-password
```

Replace the context, namespace, Secret name, and key to match your environment. Use the dedicated monitoring username created in [Prerequisites](#prerequisites).

#### Backend-run credentials

For a backend-run integration, select **Run the integration from the backend** and enter the monitoring username and password under **Authentication** in the app wizard. Saving the integration stores the password as a secret. A `secretRef::store::<id>` reference identifies a secret in that store; use an existing secret's ID for IaC configuration. Omit `cluster` for backend execution.

Never put a plaintext production password in Terraform or Crossplane configuration.

### TLS

Enable TLS for encrypted database connections. Keep certificate verification enabled whenever the PostgreSQL endpoint presents a certificate trusted by the integration's runtime. Use the skip-verification option only when you understand and accept the risk of an internal or self-signed certificate chain.

### Collection settings and coverage

Use the shared scrape interval to set the collection frequency. The default is `1m`.

The integration automatically discovers databases for table and index health metrics. The monitoring user needs permission to connect to each database you want to monitor. Use `ignoreDatabases` to exclude administrative or other unwanted databases from database-scoped health metrics. This setting does not exclude their statement measurements or query-statistics traces.

Table and index metrics cover a selection of the largest tables and indexes in each database. A missing table or index does not necessarily mean it is inactive.

Merge these fields into the existing integration `config`, preserving its connection and authentication fields:

```json
{
  "ignoreDatabases": ["<administrative-database>"],
  "healthMetrics": {
    "enabled": true
  },
  "tables": {
    "pgStatStatements": {
      "enabled": true
    }
  }
}
```

For API/IaC configurations, set `healthMetrics.enabled` to `true` to enable health metrics. All health groups are enabled by default; see the [health metrics reference](/collect-data/data-sources/postgresql-database-monitoring/postgresql-health-metrics.md) for available groups. Enable `tables.pgStatStatements` to collect statement measurements and query-statistics traces.

To customize statement collection, add these optional settings under `tables.pgStatStatements`:

* Set `filterInserts` to `true` to exclude INSERT statements from both measurements and query-statistics traces.
* Set `ignoreUsers` to a list of PostgreSQL usernames to exclude from measurements. By default, the monitoring user is excluded; use `[]` to include all users. This setting does not filter query-statistics traces.

### How statement measurements work

Statement measurements show query activity during each collection interval, including execution counts, execution time, processed rows, and available I/O and WAL statistics. Allow at least two successful scrapes with query activity before expecting measurements. New statements, database restarts, and statistics resets can delay measurements until the next collection interval.

Measurements prioritize queries that consumed the most execution time during the interval. Query-statistics traces reflect cumulative statistics, so the queries shown in the two outputs can differ.

Use `sum(calls)` to count query executions and `sum(exec_seconds)` to measure their total execution time. Execution time can exceed elapsed wall time when queries run concurrently. Missing values indicate unavailable statistics, not zero activity. See [Query Database Measurements](/reference/remote-access-and-apis/api-examples/query-database-measurements.md) for queries and API examples.

## Verify collection

1. Open the integration from [Data Sources](https://app.groundcover.com/data-sources).
2. Use **Stats** to confirm that PostgreSQL metrics are arriving and **Activity Traces** to inspect collection attempts and errors.
3. In [Data Explorer](https://app.groundcover.com/explore/data-explorer), query the built-in metrics for this integration:

   ```promql
   {__name__=~"groundcover_db_pg_.*", gc_integration_name="<integration-name>"}
   ```
4. Install the PostgreSQL dashboard from the [Dashboard Catalog](/investigate/dashboards-and-alerts/dashboard-catalog.md) and select the integration or server endpoint.
5. In [Traces](https://app.groundcover.com/traces), choose a time range covering recent database activity. Filter by `gc_integration_name` using the **Name** you entered in the wizard (or `config.name` in IaC), and by `source.table` to find the collected database statements:

   ```
   gc_integration_name:"<integration-name>" source.table:"pg_stat_statements"
   ```

   Open a matching trace to inspect its SQL statement and database statistics. These are the collected query-statistics traces; **Activity Traces** in the data-source drawer show the integration's collection attempts.

To verify measurements, run the [database-measurements API example](/reference/remote-access-and-apis/api-examples/query-database-measurements.md) over a recent range, using a query such as:

```
db_system:postgresql server_address:"<database-host>" | stats by (db_namespace, query_id) sum(calls) as calls, sum(exec_seconds) as execution_seconds
```

Allow at least two successful scrapes with intervening statement activity. In Activity Traces, inspect the `statements` child span and `statements.exported_count`; a health-metric prefix query or a `source.table` trace filter does not verify measurement ingestion.

## Troubleshooting

### The integration cannot connect

Confirm that the selected execution location can resolve and reach the host and port. Then verify the username, secret reference, TLS mode, and certificate trust. Use the most recent **Activity Traces** entry to inspect reported network, authentication, and query failures.

### Health metrics are missing

* Confirm the backend and, for sensor-side execution, the selected cluster meet the [minimum versions](#groundcover-versions-and-execution-location).
* Edit the integration and confirm that **Collect health metrics** and the expected groups are enabled.
* Confirm that the user still has `pg_monitor` and can read PostgreSQL statistics views.
* Check whether the group applies to the server's current capabilities and primary/standby role. Replica/slot details and idle-in-transaction ages can be absent; lock, conflict, and archiver metrics can legitimately be zero.
* For missing I/O or WAL timing values, see [Enable I/O timing](#enable-io-timing).
* For Aurora warnings about unsupported functions or checkpoint prerequisites, see [Aurora PostgreSQL limitations](#aurora-postgresql-limitations).
* Check **Stats**, **Activity Traces**, and the MetricsQL selector above. The product does not currently expose a persisted per-group status view.

### Aurora PostgreSQL limitations

groundcover attempts enabled, applicable health queries on every scrape, including on Aurora writers and read replicas. When a query returns one of the known errors below, groundcover records a warning and continues collecting supported metrics without failing the scrape because of that error. It does not proactively disable these queries or omit metrics based on the server being Aurora. A query rejected by Aurora cannot supply its metrics for that scrape; those values are unavailable, not zero. The query is attempted again on the next scrape, so collection can recover after permissions or settings change.

| Query name in Activity Traces                              | Health group          | Errors handled as warnings                                                                                                                                                                                                       | Metric impact when the query is unavailable                                                                                                                        |
| ---------------------------------------------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `standby_replay_lag`                                       | Standby (`standby`)   | Unsupported function (`0A000`), such as `pg_last_xact_replay_timestamp()` on an Aurora reader.                                                                                                                                   | Replay lag in seconds is unavailable.                                                                                                                              |
| `standby_receiver_connection`, `standby_receiver_messages` | Standby (`standby`)   | Unsupported function (`0A000`), such as `pg_stat_get_wal_receiver()` on an Aurora reader.                                                                                                                                        | WAL receiver connection state, message ages, and timeline are unavailable.                                                                                         |
| `checkpoint_state`                                         | Instance (`instance`) | Unsupported function (`0A000`), insufficient privileges (`42501`), or unmet server-state prerequisite (`55000`). Aurora readers can reject the receive-location function; writers can report that `wal_level` must be `logical`. | Checkpoint delay in seconds/bytes, redo delay in bytes, and checkpoint timeline are unavailable. Other Instance queries, including uptime, continue independently. |
| `wal_directory`                                            | Instance (`instance`) | Unsupported function (`0A000`) or insufficient privileges (`42501`) for the WAL-directory query.                                                                                                                                 | WAL file count, directory size, and oldest-file age are unavailable.                                                                                               |
| `wal`                                                      | WAL (`wal`)           | Unsupported function (`0A000`) or insufficient privileges (`42501`) for the WAL statistics query.                                                                                                                                | Metrics supplied by this query are unavailable.                                                                                                                    |

`checkpoint_state` belongs to **Instance**, not **Checkpoints**. Disabling the Checkpoints group does not affect this query. Keep the groups enabled to collect everything the server supports; no Aurora-specific group configuration is required to handle these known errors. Enabling logical WAL solely to prevent a scrape failure is unnecessary. I/O timing settings are separate; see [Enable I/O timing](#enable-io-timing).

In **Activity Traces**, inspect the affected query span and its parent scrape span for a `<query-name> (unavailable)` event. The warning includes `severity_text = WARN`, the query/group context, and `integration.query.reason` containing the availability reason and original database error. `integration.query.execution = executed` confirms that the query was attempted. The affected query span remains `Unset` rather than `Error`; the parent scrape can succeed while exposing these warnings.

### Enable I/O timing

If I/O timing values are missing or remain zero despite database activity, connect to the monitored database and check:

```sql
SELECT current_setting('track_io_timing') AS track_io_timing,
       current_setting('track_wal_io_timing', true) AS track_wal_io_timing;
```

Set `track_io_timing` to `on` to collect database I/O timings. For WAL I/O timings, also enable `track_wal_io_timing` if the server supports it; a NULL result means that setting is unavailable. Both are [on/off settings](https://www.postgresql.org/docs/current/runtime-config-statistics.html), and neither accepts `logical`.

On **Aurora PostgreSQL or RDS for PostgreSQL**, update the custom parameter group attached to the monitored cluster or instance. Check both cluster and instance settings on Aurora, since instance settings can override cluster defaults; see [Aurora parameter groups](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraPostgreSQL.Reference.ParameterGroups.html). On other managed services, use the provider's server-parameter or database-flags interface. Apply the settings to the database workload, not only the monitoring user's session, and follow the provider's apply or restart requirements. Then reconnect, repeat the check, and allow new I/O activity and collection intervals before checking the metrics again. Available timing metrics depend on the statistics exposed by the database service.

`wal_level = logical` controls logical replication, separately from I/O timing. On Aurora, it is enabled through `rds.logical_replication`; see [AWS's logical replication guide](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraPostgreSQL.Replication.Logical.Configure.html). Enabling logical replication is not a prerequisite for enabling I/O timing.

### Query traces are missing

Confirm that query-statistics collection is enabled, `pg_stat_statements` is loaded, and the extension exists in the connection database. Check that statements have executed since statistics were last reset and that INSERT filtering is not excluding the workload you expect.

### Check the extension search path

If query-statistics collection reports `relation "pg_stat_statements" does not exist`, connect **as the monitoring user to the configured connection database** and run:

```sql
SHOW search_path;
SELECT n.nspname AS extension_schema,
       has_schema_privilege(current_user, n.oid, 'USAGE') AS can_use_schema
FROM pg_extension e
JOIN pg_namespace n ON n.oid = e.extnamespace
WHERE e.extname = 'pg_stat_statements';
SELECT to_regclass('pg_stat_statements') AS resolved_relation;
```

No extension row means it is not installed in this database. If the extension exists but `resolved_relation` is NULL, check schema access and add its schema to the monitoring user's search path. As an administrator connected to the same database:

```sql
-- Run the grant only if can_use_schema is false.
GRANT USAGE ON SCHEMA "<extension-schema>" TO groundcover;

-- Example for an existing search_path of "$user", public.
ALTER ROLE groundcover IN DATABASE "<connection-database>"
  SET search_path = "$user", public, "<extension-schema>";
```

Replace the placeholders and username. Preserve any custom entries from the monitoring user's existing path when adding the extension schema. The [role setting](https://www.postgresql.org/docs/current/sql-alterrole.html) applies to new connections: reconnect as the monitoring user and repeat the checks, then disable and re-enable the integration so its connections use the updated path.

### A database produces permission errors

Add managed-service administrative databases and any intentionally inaccessible databases to **Ignored databases**. New eligible databases are discovered automatically. A database skipped for missing CONNECT can have a successful database span with a skip event; it is not proof that its relation metrics were collected.

### Check permissions and settings

Run these read-only checks **as the integration user**, using its configured connection database:

```sql
SELECT current_user, current_database(),
       pg_has_role(current_user, 'pg_monitor', 'USAGE') AS can_monitor,
       pg_has_role(current_user, 'pg_read_all_stats', 'USAGE') AS can_read_all_stats;

SELECT datname, has_database_privilege(oid, 'CONNECT') AS can_connect
FROM pg_database
WHERE datallowconn AND NOT datistemplate
ORDER BY datname;

SELECT name, setting
FROM pg_settings
WHERE name IN ('track_counts', 'track_io_timing', 'track_wal_io_timing', 'compute_query_id',
               'shared_preload_libraries', 'pg_stat_statements.track');

SELECT e.extname, n.nspname AS extension_schema
FROM pg_extension e
JOIN pg_namespace n ON n.oid = e.extnamespace
WHERE e.extname = 'pg_stat_statements';
```

As an administrator, grant the missing role or database access from [Prerequisites](#prerequisites), then repeat the checks as the integration user. If membership exists but `USAGE` is false, correct role inheritance; the collector does not issue `SET ROLE`. Do not grant access to administrative databases you intentionally exclude.

### Interpret collection events

| Reason or symptom in Activity Traces                          | Meaning and action                                                                                                                                                                                                                                            |
| ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `CONNECT privilege is unavailable`                            | Tables/Indexes were skipped for this database. Grant CONNECT if intended, or exclude it.                                                                                                                                                                      |
| `database collection limit exceeded`                          | Discovery exceeded 1,000 databases. Inspect discovered/limit/skipped attributes and narrow collection scope with exclusions.                                                                                                                                  |
| `topN adjusted from ... to ...`                               | A configured relation limit was clamped to 1–500. Correct the configuration; this is not a query failure.                                                                                                                                                     |
| Initial snapshot / restart / reset; seeding baseline          | Expected measurement warm-up. Wait for another successful interval with activity; investigate repeated server/statistics resets.                                                                                                                              |
| Statement counters reset; reseeding affected row              | That row cannot produce a trustworthy delta this interval. It resumes after a new baseline.                                                                                                                                                                   |
| Extension missing, tracking disabled, or module not preloaded | Check the connection database, preload list, and tracking settings. Apply required server configuration and restart, then verify the active value.                                                                                                            |
| Extension lacks toplevel                                      | Use `pg_stat_statements.track = top` to avoid nested-statement double counting.                                                                                                                                                                               |
| pg\_monitor / pg\_read\_all\_stats not immediately usable     | Run the role checks above as the actual monitoring user and correct its privileges/inheritance.                                                                                                                                                               |
| I/O timings unfilled or WAL counters unavailable              | Other measurements can continue. Enable the relevant timing setting, or accept missing fields when the source does not expose them.                                                                                                                           |
| pg\_stat\_statements\_info could not be read                  | Other measurements may export, but reset metadata and the eviction counter are unavailable. Check access to the extension's info view and the span exception.                                                                                                 |
| Statement text unavailable or fingerprinting failed           | A statement row was skipped. Verify statistics visibility for text access; for repeated fingerprint failures, provide the integration identity and diagnostic trace to support.                                                                               |
| Primary/standby or capability skip                            | No action if the group does not apply. Check the target's role and the named source view/columns before changing configuration.                                                                                                                               |
| `<query-name> (unavailable)` with `severity_text = WARN`      | The query ran and returned a known availability error. The warning preserves the database error without failing the scrape; supported queries continue. See [Aurora PostgreSQL limitations](#aurora-postgresql-limitations) for affected queries and metrics. |

Unknown maintenance ages are omitted. Table row counts are estimates, and index coverage is top-N; do not interpret absent relation series as zero activity. For errors, export retries, and the meaning of a successful span with diagnostic events, see [Database monitoring diagnostics](/collect-data/monitor-data-sources-integrations.md#database-monitoring-diagnostics).

For general integration diagnostics, see [Monitor Data Sources Integrations](/collect-data/monitor-data-sources-integrations.md).

## Related documentation

* [ClickHouse Database Monitoring](/collect-data/data-sources/clickhouse-database-monitoring.md)
* [Monitor Data Sources Integrations](/collect-data/monitor-data-sources-integrations.md)
* [Dashboard Catalog](/investigate/dashboards-and-alerts/dashboard-catalog.md)
* [groundcover Terraform Provider](/reference/groundcover-terraform-provider.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.groundcover.com/collect-data/data-sources/postgresql-database-monitoring.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
