Skip to content

Monitor a Managed PostgreSQL Service

Read the metrics and logs that Exoscale collects for a Managed PostgreSQL service, forward them to an external monitoring or logging system, and query PostgreSQL’s own statistics views.

Read Service Metrics

Exoscale samples host-level metrics for every node of a service and returns them as raw JSON.

exo dbaas metrics my-postgresql -z ch-gva-2 --period PERIOD

Parameters:

  • PERIOD: the time window to retrieve. One of hour, day, week, month or year. Defaults to hour, which returns one sample every 30 seconds; longer periods return coarser samples.

On a service created less than a day ago, month and year can return null until the first sample of that resolution exists.

The response is a JSON object with one entry per series:

KeySeries
cpu_usageCPU usage %
disk_usageDisk space usage %
diskio_readDisk IOPS (reads)
diskio_writesDisk IOPS (writes)
load_averageLoad average (5 min)
mem_availableMemory available %
mem_usageMemory usage %
net_receiveNetwork receive (bytes/s)
net_sendNetwork transmit (bytes/s)

Every series has the same shape:

  • data.cols: column headers. The first column is time; each remaining column is one node of the service, labeled with its node name and its role, for example my-postgresql-1 (master).
  • data.rows: the samples, one array per timestamp, in the column order above.
  • hints.title: the human-readable name of the series.
  • max_timestamp: Unix timestamp of the most recent sample.

Extract a single series with jq:

exo dbaas metrics my-postgresql -z ch-gva-2 --period day | jq '.disk_usage.data.rows'

Note

These series describe the machine, not the database. They contain no PostgreSQL counters such as connection count, cache hit ratio, deadlocks or replication lag. For those, query the pg_stat_* views as shown below, send the metrics to a Managed Thanos service as described in Send metrics to Managed Thanos, or scrape the service with Prometheus.

Disk usage is the series worth alerting on first. See Prevent a full disk for what to reclaim, and Scale a DBaaS service for adding headroom.

Read Service Logs

exo dbaas logs returns the PostgreSQL server log of the service nodes.

exo dbaas logs my-postgresql -z ch-gva-2 --limit LIMIT --sort SORT

Parameters:

  • LIMIT: number of entries to return, from 1 to 500. Without --limit, the command returns 100 entries (its help text says 10).
  • SORT: desc (newest first, the default) or asc. Both return the newest LIMIT entries; asc lists them oldest first.

Each entry carries four fields:

FieldContent
timeUTC timestamp of the entry
nodeNode that emitted the entry, for example my-postgresql-1
unitsystemd unit: postgresql-18.service on PostgreSQL 18. PgBouncer lines are not included.
messageThe log line: a sequence number such as [29-1], then the log_line_prefix, then the message

The stream lags behind the server by up to about a minute, and it never contains pgaudit records.

Print the time, unit and message of each entry with a custom output template:

exo dbaas logs my-postgresql -z ch-gva-2 --limit 200 \
  --output-template '{{range $l := .Logs}}{{println $l.Time $l.Unit $l.Message}}{{end}}'

Page Through Older Entries

The JSON output of the command contains an offset field. Feed it back to fetch the next batch:

exo dbaas logs my-postgresql -z ch-gva-2 --limit 500 --offset OFFSET

Parameters:

  • OFFSET: the opaque offset value taken from the JSON output of the previous call. With the default desc order, each call returns the next older batch.

Note

The log endpoint is a short buffer meant for interactive troubleshooting. To keep logs for longer, or to search them, send them to a Managed OpenSearch service as described in Send logs to Managed OpenSearch.

Choose a Log Line Format

log_line_prefix accepts four fixed values. Pick one that carries the user, the database and the client address, so that each line says who did what. The values, a sample line for each and the way to set them are in Log formats and log retrieval.

Log Slow Queries and Temporary Files

Three settings turn the server log into a usable performance record:

exo dbaas update my-postgresql -z ch-gva-2 -f \
  --pg-settings '{"log_min_duration_statement":1000,"log_temp_files":10240,"log_error_verbosity":"DEFAULT"}'
  • log_min_duration_statement: log any statement running longer than this many milliseconds. -1 disables it. A new service already logs statements slower than 1000 ms.
  • log_temp_files: log every temporary file larger than this many kilobytes. A new service logs files larger than 100 kB. Frequent entries mean work_mem is too small for the workload.
  • log_error_verbosity: TERSE, DEFAULT or VERBOSE.

Each update is merged into the stored settings, so keys you leave out keep their value. Read the stored settings with exo api get-dbaas-service-pg my-postgresql -z ch-gva-2 -q '"pg-settings"'.

Note

exo dbaas update --pg-settings leaves out keys whose value is 0, for example "log_min_duration_statement":0. Set such a value with the API instead: echo '{"pg-settings":{"log_min_duration_statement":0}}' | exo api update-dbaas-service-pg my-postgresql -z ch-gva-2.

Forward Metrics to an External System

Exoscale DBaaS pushes telemetry to external endpoints: Datadog and Prometheus for metrics, rsyslog, OpenSearch and Elasticsearch for logs. An endpoint is created once per destination in your organization, then attached to as many services as you like. The procedure, including Datadog, is in Use External Integrations; list the flags of a type with exo dbaas external-endpoint create --help-TYPE, for example --help-rsyslog.

To send the telemetry to Exoscale services of your own organization instead, see Send logs to Managed OpenSearch, Send metrics to Managed Thanos and Visualize a service in Managed Grafana.

Scrape the Service with Prometheus

Create a prometheus endpoint with the credentials your Prometheus server will use, then attach it to the service:

exo dbaas external-endpoint create prometheus my-prometheus \
  --prometheus-basic-auth-username SCRAPE_USER \
  --prometheus-basic-auth-password SCRAPE_PASSWORD
exo dbaas external-integration attach prometheus \
  --source-service-name my-postgresql \
  --destination-endpoint-id ENDPOINT_ID

Parameters:

  • SCRAPE_USER, SCRAPE_PASSWORD: the basic-auth credentials Prometheus sends. The password cannot be read back later.
  • ENDPOINT_ID: the Endpoint ID printed by the first command, also listed by exo dbaas external-endpoint list.

The scrape target then appears in the service description:

exo api get-dbaas-service-pg my-postgresql -z ch-gva-2 -q '"prometheus-uri"'

The field holds a host and a port (9273), and is empty ({}) while no Prometheus endpoint is attached. Metrics are served at https://HOST:9273/metrics; a request without the basic-auth credentials gets 401 Unauthorized. Validate TLS with the CA certificate returned by exo dbaas ca-certificate -z ch-gva-2. The metric names are the same as in Managed Thanos and are listed in Service metrics.

Important

The service IP filter applies to the scrape endpoint as well. Add the public address of your Prometheus server to the filter, otherwise the scrape times out instead of returning an authentication error. See Restrict connections.

Detach an Integration

Find the integration ID, which differs from the endpoint ID, then detach it:

exo dbaas external-integration list my-postgresql
exo dbaas external-integration detach my-postgresql --integration-id INTEGRATION_ID

Parameters:

  • INTEGRATION_ID: the integration UUID reported by exo dbaas external-integration list.

The endpoint itself is kept and stays available for other services. prometheus-uri is empty again after the detach.

Query PostgreSQL’s Own Statistics

Platform metrics stop at the operating system. Everything below comes from inside the database, so connect as avnadmin with psql.

avnadmin has the privileges of pg_read_all_stats, so it sees the queries of every other user in the statistics views without being a superuser. Sessions of the platform’s own superuser roles, postgres and _aiven, show <insufficient privilege> in place of the query text, in pg_stat_activity as in pg_stat_statements. avnadmin also has the privileges of pg_signal_backend, so pg_cancel_backend() and pg_terminate_backend() work on the sessions of other users, but not on those of the platform’s superuser roles.

Find Long-Running and Idle-In-Transaction Sessions

SELECT pid,
       usename,
       application_name,
       state,
       now() - xact_start AS xact_age,
       now() - query_start AS query_age,
       left(query, 60) AS query
FROM pg_stat_activity
WHERE state <> 'idle'
ORDER BY xact_age DESC NULLS LAST;

A session stuck in idle in transaction holds back VACUUM across the whole database and causes table bloat. Cancel a single statement, or terminate the backend outright:

SELECT pg_cancel_backend(BACKEND_PID);
SELECT pg_terminate_backend(BACKEND_PID);

Parameters:

  • BACKEND_PID: the pid reported by pg_stat_activity.

To stop these sessions accumulating, set a server-side timeout:

exo dbaas update my-postgresql -z ch-gva-2 -f \
  --pg-settings '{"idle_in_transaction_session_timeout":600000}'

Watch Vacuum and Bloat

SELECT schemaname,
       relname,
       n_live_tup,
       n_dead_tup,
       n_mod_since_analyze,
       last_autovacuum,
       last_autoanalyze
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 20;

Watch Transaction ID Age

This is the one PostgreSQL counter that will take a service down if it is ignored. If a database’s transaction age approaches autovacuum_freeze_max_age, PostgreSQL forces aggressive vacuuming and eventually refuses new transactions.

SELECT datname,
       age(datfrozenxid) AS xid_age,
       current_setting('autovacuum_freeze_max_age')::bigint AS freeze_max_age
FROM pg_database
ORDER BY xid_age DESC;

Check Replication

SELECT client_addr,
       application_name,
       state,
       sync_state,
       pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_lag_bytes,
       replay_lag
FROM pg_stat_replication;

Warning

A service with no read replica still shows one row here, with application_name = pghoard and no client_addr. That is the platform’s WAL archiver feeding the backup system, not a replica.

Find the Most Expensive Statements

pg_stat_statements is not installed by default. Create it once per database, then query it:

CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
SELECT calls,
       round(total_exec_time::numeric, 1) AS total_ms,
       round(mean_exec_time::numeric, 2) AS mean_ms,
       rows,
       left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;

pg_stat_monitor can be created but its module is not loaded, so querying its view fails with Must be loaded via shared_preload_libraries; stay with pg_stat_statements. See Manage extensions for the full list and for how to install them, and Identify slow queries for working through the results.

To attribute time to disk I/O rather than CPU, enable track_io_timing:

exo dbaas update my-postgresql -z ch-gva-2 -f --pg-settings '{"track_io_timing":"on"}'

The value is a string, "on" or "off"; a JSON boolean is rejected. track_io_timing reads the operating system clock on every I/O call, which adds overhead on some platforms: turn it on while you investigate, then back off.

Point a Third-Party Collector at the Service

Third-party collectors connect over the normal PostgreSQL protocol. Give them a dedicated least-privilege role rather than avnadmin:

CREATE USER monitoring WITH PASSWORD 'MONITORING_PASSWORD';
ALTER ROLE monitoring CONNECTION LIMIT 3;
GRANT pg_read_all_stats TO monitoring;

Parameters:

  • MONITORING_PASSWORD: a strong password for the monitoring role.

With pg_read_all_stats, the role sees the query text of avnadmin and of the application users, like avnadmin does. Capping its connection limit matters: max_connections is set by the service plan (25 on hobbyist-2), and a misbehaving collector can otherwise starve the application. Read the current limit with SHOW max_connections;.

Dashboards built for self-hosted PostgreSQL may rely on superuser-only views, on pg_monitor, which avnadmin cannot grant, or on extensions whose module is not loaded here. Expect some of their panels to stay empty.

Related Pages

Last updated on