PostgreSQL monitoring with Prometheus postgres_exporter

Connect PostgreSQL to Prometheus with the community postgres_exporter using a least-privilege pg_monitor account, then add replication, WAL, statements and connection alerts and dashboards. This page covers the method, sequence, checks and effort drivers for your own team or a partner.

On this page

How PostgreSQL monitoring with postgres_exporter works

A team running PostgreSQL that needs replication, WAL, connection and query metrics in Prometheus usually starts by asking how the pieces fit together. The community postgres_exporter runs beside the database server, connects to PostgreSQL with a read-only monitoring role, translates database statistics into metrics, and exposes them on an HTTP endpoint that Prometheus scrapes on a schedule. The exporter does not change the database and does not store metrics. Prometheus keeps the time series, evaluates alert rules, and hands firing alerts to Alertmanager. This page covers the method, prerequisites, configuration sequence, security, testing and failure points for that chain. The exporter's collector list, flags and the statistics each collector reads depend on the version you choose, so confirm them against the exporter's own documentation before you write any configuration.

Each link in the chain needs a decision. The monitoring role determines which statistics the exporter can read, so it should hold the built-in pg_monitor membership rather than superuser rights, and it should be created before the exporter is first started. The exporter's data source name, collector selection and scrape interval determine what appears in Prometheus and how much load the scrapes add. Some collectors read views that are only populated when a feature is enabled, such as pg_stat_statements for query statistics, so a collector can run without error and still return empty results. Confirm that the database settings the collectors depend on are in place before you write alert rules against them.

Failure usually happens at the edges of this chain rather than in the middle. Network rules may block the scrape port between Prometheus and the exporter host, or the exporter may reach PostgreSQL through a connection pooler that hides the statistics you need. Credentials in the data source name can end up in process lists or shell history if they are passed carelessly, and the exporter's HTTP endpoint is unauthenticated by default in many setups, so it should sit on a protected network path. Each of these points is worth a test in a non-production environment, because a broken scrape looks the same as a healthy quiet database until someone checks the up metric.

What you need before connecting PostgreSQL to Prometheus

Most delays in a PostgreSQL monitoring rollout come from decisions made after the work starts, not from the exporter itself. Settle the database version, the Prometheus server, the exporter host, the network paths and the owner of the monitoring role before anyone edits a configuration file. Each card below is one item to confirm, and each should be written down in the scope.

A supported PostgreSQL major version

Confirm which PostgreSQL major version each instance runs and check it against the versioning policy. Versions 14 through 18 are listed as supported, with 14 ending November 12, 2026 and 18 running to November 14, 2030. Version 13 and earlier are unsupported, so plan an upgrade before connecting monitoring to them. Ask the exporter maintainers which release supports your exact version before you pin one.

Versioning policy

A running Prometheus server

Confirm that a Prometheus server already exists or that the scope includes deploying one. The exporter only produces metrics; Prometheus scrapes them, stores them and evaluates the alert rules. Check its version, its storage size and its retention setting, because the default 15 days may be too short for capacity planning or for investigating a slow month-end batch.

A host or container for the exporter

Decide where postgres_exporter runs: on the database host, on a separate monitoring host, or in a container next to the database. Each choice changes how the exporter reaches the database and who patches it. Record the host owner, the operating system, the resource limits and the service account that runs the process, so that the exporter is maintained like any other production component.

Network paths in both directions

Map two paths before configuration begins. Prometheus must reach the exporter's HTTP port, and the exporter must reach each PostgreSQL port with a valid connection. Firewall rules, security groups and TLS settings often block one of these paths. Document the ports, the source and destination addresses and whether traffic stays inside a private network, since the exporter exposes database metadata over HTTP.

A named owner for the monitoring role

Agree who creates and rotates the PostgreSQL login the exporter uses, and who approves its privileges. The role should be least-privilege, typically membership in the built-in pg_monitor role rather than superuser. Assign one owner for the password, the storage of its secret and the review date, so that a rotation does not break metrics silently during an incident.

Targets for every replica

Confirm the full list of PostgreSQL instances, including hot standby replicas, which serve read-only queries. Prometheus scrapes each instance separately, so each replica needs its own target, its own label set and its own alert scope. Replication lag metrics are only meaningful when the primary and each standby are both monitored, so do not treat the replicas as covered by the primary target.

How the exporter, PostgreSQL and Prometheus fit together

The flow starts with Prometheus, which pulls metrics over HTTP from postgres_exporter on a schedule. The exporter holds a database connection under a monitoring role with read-only access and queries both the primary and the hot standby, so each database has its own scrape path. Prometheus sends firing alerts to Alertmanager, and Grafana reads from Prometheus for dashboards. Check that the monitoring role stays inside the database trust boundary and that the exporter endpoint is reachable only from Prometheus.

Scrape path and database connection path, with the monitoring role inside the database boundary.

Configuring postgres_exporter for PostgreSQL, step by step

This sequence takes a PostgreSQL instance from no monitoring access to dashboards built on verified metrics, with a check at each step so problems surface before they reach Prometheus. It works the same way whether your team or a partner carries it out.

  1. Create the monitoring role and grant pg_monitor

    A database administrator creates a dedicated login role for the exporter, sets a strong password through a method your security policy allows, and grants it the built-in pg_monitor role, which gives read access to the statistics views the exporter needs without superuser rights. Keep the role out of application schemas and avoid reusing any existing account. Confirm the grant by connecting as that role and running a simple read against pg_stat_database. The step is done when the query returns rows and an attempt to change data is refused. Confirm the exact view set your PostgreSQL major version exposes to pg_monitor in the PostgreSQL documentation before you rely on specific collectors.

  2. Confirm the exporter host can authenticate

    A network or database administrator checks the pg_hba.conf entry that matches the exporter host address and the database it connects to. The method should be SCRAM-based password authentication or certificate authentication over TLS, not MD5, which PostgreSQL 18 deprecates. Reload the configuration after any change and then test from the exporter host with psql using the monitoring role. The step is done when the login succeeds from that host and fails from an unrelated host, which shows the rule is as narrow as intended. Record the exact rule so reviewers can trace which host may read statistics.

  3. Install and configure the exporter

    An engineer installs the community postgres_exporter binary or container image on the exporter host, from a release your team has chosen and tested. Configuration keys, connection string options and collector flags differ between releases, so take them from the documentation for the exact version installed rather than from older examples. Store the connection string with the password in a secret file or environment source your platform controls, enable only the collectors you need for replication, WAL and statements, and bind the listener to an address the Prometheus server can reach. The step is done when the service starts, logs show a successful database connection, and a request to the metrics endpoint returns PostgreSQL metrics.

  4. Add the scrape job to Prometheus

    A Prometheus administrator adds a scrape job for the exporter endpoint, either in the static configuration or through the service discovery method your estate already uses. Give the job a clear name and labels that identify the cluster, environment and role, so dashboards and alerts can filter by them later. Validate the configuration file with promtool before reloading Prometheus, and use the reload method your deployment allows. The step is done when the configuration validates and the reload completes without errors in the Prometheus logs.

  5. Verify the target and metric output

    An engineer opens the Targets page in Prometheus and confirms the new job shows as up with a recent last scrape. Then run a PromQL query for a PostgreSQL metric such as the number of active backends and compare the value with a direct query on the database, for example against pg_stat_activity, taken at about the same time. Repeat the comparison for one replication or WAL metric on a standby or primary where it applies. The step is done when the target is healthy and the values agree within the expected movement between the two readings. A mismatch usually points to the wrong database, a stale scrape interval or a collector that is not enabled.

  6. Build the first dashboards

    A monitoring engineer builds a small set of dashboards in Grafana or your chosen visualization tool, starting with connections, transaction rates, replication lag and WAL generation, then adding statement metrics once the collector is verified. Use PromQL queries that reference the labels set in the scrape job so each panel can be scoped to one instance or cluster. Check each panel against a value you can reproduce with a direct database query. The step is done when every panel on the first dashboard matches a manual reading and the dashboard loads for a reviewer who did not build it. Keep the dashboard definitions in version control so they can be reviewed and restored.

Which PostgreSQL data feeds which monitoring signal

This table maps each PostgreSQL data source to the monitoring signal it feeds, the team that usually owns it, the access the exporter role needs and what to confirm in the exporter release. Read it before granting any access, because several signals depend on server settings or extensions that a monitoring account cannot change.

SignalSource in PostgreSQLOwner and access neededConfirm in the exporter release
Replication state on primariesReplication views on the primary that list connected standbys and their positionsDatabase platform team; read access through the monitoring role, which should be a member of pg_monitorWhich replication metrics are emitted for primaries and whether they need a specific role grant beyond pg_monitor
Replication lag on standbysRecovery status and replay position on hot standby servers, which serve read-only queriesDatabase platform team; the monitoring role must connect to each standby, not only the primaryWhether lag is reported in bytes, seconds or both, and how it behaves when a standby is paused
WAL generation and archivingWAL position and archiver status views, which show archive successes and failuresDatabase platform team with backup owner; needs pg_monitor and access to archiver statusWhether archive failure counters are exposed, and whether WAL size metrics depend on the server version
Connection counts against limitsActivity view counting sessions by state, compared with the configured connection limitApplication owners and DBA; needs pg_monitor so sessions from other roles are visibleWhether the exporter reads the configured limit itself or whether a separate max_connections alert is needed
Query statisticsStatements view, which requires the pg_stat_statements extension to be installed and loadedDBA installs the extension; exporter role reads it. Confirm the extension is in shared_preload_librariesWhether statement metrics are collected by default, how the query text is handled, and the label cardinality it creates
Database size and lockingDatabase size functions and lock information in the activity and lock viewsDBA and application owners; size checks may need read access to each database, not just the default oneWhether size collection runs per database and how often, and whether lock metrics are optional and their cost on large clusters
Server version and settingsVersion and configuration parameters read at scrape timeDatabase platform team; read-only access through the monitoring roleWhich PostgreSQL major versions the release supports, given that 14 reaches end of support in November 2026

Securing the exporter, its credentials and the metrics endpoint

The exporter sits between your database and your monitoring server, so it needs the same care as any privileged database client. The cards below cover the database role, the secret, the network path and the HTTP endpoint, plus the labels that can leak data into your metrics store.

Grant only pg_monitor

Create a dedicated login role for the exporter and grant it pg_monitor and nothing else. That built-in role gives read access to the statistics views the exporter needs, so the role should have no write privileges, no superuser flag and no ownership of application schemas. Review the role's attributes after each PostgreSQL upgrade, because a role created for an old version can accumulate grants over time. Confirm the exact privileges your PostgreSQL version provides with your DBA before you rely on them.

PostgreSQL authentication docs

Keep the connection secret out of config

The exporter reads its data source name from the environment or a file, so the password should never be typed into a unit file, a Helm values file or a Git repository. Store it in your team's secrets store and inject it at start-up, with rotation and access logs owned by the same process as your other service credentials. Check that the process environment is not printed in diagnostic dumps, and that the secret file is readable only by the exporter's service account.

Restrict pg_hba.conf to the exporter host

Add a pg_hba.conf entry that matches only the exporter role, the monitored database and the exporter's source address, and place it above any broader rule that would match first. Use an authentication method that does not send reusable passwords in cleartext, such as SCRAM, and avoid the deprecated MD5 method. Test the rule by connecting from an unlisted host and confirming it is refused, because a wide host all all line silently undoes the restriction.

Encrypt the database connection

Set sslmode=verify-full in the data source name, point it at the certificate authority your database uses, and make the database accept only TLS connections from the exporter host with the hostssl record type. Without verification, an attacker on the path can present a fake server and capture the password. Confirm with your PostgreSQL administrator which certificate chain is in use and how it will be renewed.

Protect the exporter's HTTP port

The exporter serves metrics over HTTP, and anyone who can reach that port can read database statistics. Bind it to a management interface where possible, allow inbound connections only from the Prometheus servers through a host firewall or security group, and remove any default route that exposes it to user networks. If you need encryption or authentication on the scrape path, use the TLS and basic authentication options described in the Prometheus security model. Basic authentication sends credentials in cleartext unless TLS is also enabled, so do not enable it on plain HTTP.

Prometheus security model

Keep query text and identifiers out of labels

Metric labels are stored and displayed by Prometheus, so a label that carries raw SQL, user names, email addresses or customer schema names spreads that data to every dashboard and alert. Review the exporter's enabled collectors and any custom queries, and remove those that return text or personal identifiers as labels. Keep label values to bounded categories such as database name, state or replication role, and check the target's series count after changes so that query text cannot grow cardinality either.

Alert rules for replication lag and connection exhaustion

The purpose of these alert rules is to page someone only when a condition needs action: a standby falling behind in a way that threatens recovery, connections approaching the configured maximum, or WAL that is not being archived. Each rule should name the metric it reads from the postgres_exporter, the threshold, the evaluation window and the person or runbook that receives it. For connections, compare pg_stat_activity_count against the server's max_connections setting so the threshold scales with the instance rather than a fixed number. For replication, alert on replay lag or lag in bytes on standbys that the team depends on for reads or failover, and keep the replication role metrics separate from primary-side alerts so a single primary problem does not fire a dozen duplicate pages.

The central trade-off is noise against lateness. A short threshold with a short for duration fires on normal bursts such as batch jobs, vacuum activity or a brief network blip, and teams learn to ignore it. A long window avoids that noise but can report exhaustion after applications have already started failing. Set the first thresholds from your own baseline: collect at least a representative period of lag, connection counts and archiver activity, look at their peaks and daily patterns, then choose values that sit clearly above normal load. Confirm the exact metric names and labels against the postgres_exporter version you deploy, because collectors are renamed between releases. Test each rule before trusting it, using a controlled condition in a non-production cluster, and verify that the alert reaches the intended receiver through the Alertmanager routing and inhibition rules already in place, as described in the Alertmanager documentation.

Prometheus is built for reliability over precision, so these rules should detect conditions, not account for individual transactions or exact byte counts. Lag and connection figures are sampled at scrape intervals and can be briefly stale, so a rule that depends on a single sample is fragile. Use rate and averages over a window, accept that a spike between scrapes may be missed, and keep audit-grade accounting in PostgreSQL logs or the database's own mechanisms. Review the rules after each major PostgreSQL upgrade, since the statistics views and the replication behavior you monitor may change, and record each threshold change with the reason so the next on-call engineer can judge whether the alert still reflects the workload.

Common failures when scraping PostgreSQL metrics

This table lists the failures teams most often hit when postgres_exporter feeds Prometheus, with the likely cause, a check to run and a fix for each. Work down the rows when a scrape looks wrong, and confirm exact settings in the PostgreSQL and exporter documentation before changing production.

FailureLikely cause and checkFix
Exporter logs a connection or authentication errorThe exporter role cannot log in from the exporter host. Check the data source name, the role's login privilege and the pg_hba.conf rule matching the exporter's address and method, including whether the method is SCRAM.Correct the connection string, grant login to the monitoring role, and add a narrow pg_hba.conf entry for the exporter host. Confirm the exact syntax in the PostgreSQL authentication docs.
Replica or standby metrics are missingThe exporter points at the primary only, or the standby does not expose replication views the way you expect. Check which instance each target scrapes and whether replication metrics are present on that target.Run one exporter target per instance, including each standby, and label them by role. Confirm which replication metrics appear on standbys in the exporter documentation.
Scrape target is downThe exporter process is not running, its port is blocked by a firewall, or Prometheus cannot resolve the target. Check the target page in Prometheus, the exporter service status and a direct HTTP request from the Prometheus host.Restart or fix the service, open the exporter port only from the Prometheus server, and correct the target address in the scrape configuration.
Metrics disappear after a major upgradeMonitoring views or functions were not recreated in the new cluster, or the role lost privileges during restore. Compare the exporter's query errors with the new major version's catalog after the upgrade.Rerun the monitoring role grants on the new cluster, reinstall any monitoring extension, and confirm the exporter version supports the new major version. Check the PostgreSQL upgrading docs for what the upgrade method carries over.
Statements data is emptyThe statistics extension is not installed in the monitored database, or the server settings that load it are absent or require a restart. Check the extension list and the preload setting in the server configuration.Create the extension in the database that holds the statements view, add it to the preload list, restart PostgreSQL, and grant the monitoring role access. Confirm the exact setting names in the PostgreSQL and exporter docs.
Label cardinality grows with many databasesPer-database and per-table collectors multiply series as databases or tables are added, and temporary objects create new labels. Check series counts per metric name in Prometheus and identify the collectors enabled.Disable collectors you do not alert on, restrict database and table selection with the exporter's filter options, and set series limits in the scrape job. Confirm available filter flags in the exporter documentation.
Scrapes are slow or time outA collector runs an expensive query on a large catalog or on a busy server. Check the scrape duration metric and the exporter log for slow collector messages.Turn off the slow collector, raise the scrape timeout only within the scrape interval, and run the exporter against a lightly loaded standby if the query cost is unavoidable.

Questions teams ask before monitoring PostgreSQL with postgres_exporter

Can our internal team set up PostgreSQL monitoring with postgres_exporter on its own?

Yes, a team that already runs Prometheus and PostgreSQL can usually do the first deployment in-house, because the exporter is a single service that connects to the database with a read-only role. The work that tends to stretch out is not the install but the decisions around it: which collectors to enable, which alerts page someone at night, how alerts route to the right on-call group, and who owns the dashboards afterward. Check whether your team has someone who knows both PostgreSQL internals (replication, WAL, statistics views) and Prometheus alerting. If one of those skills is missing, a partner is worth comparing against training your own people, and the written scope should name who does each step.

What drives the cost of monitoring PostgreSQL in our environment?

The main cost drivers are the number of clusters, replicas, databases and environments, because each adds targets, labels and alert conditions to design and review. Alert routing matters as much: a single on-call channel is simple, while separate paths for database, application and platform owners add configuration and testing. Your Prometheus setup also matters, since a new server costs less to extend than a federated or long-term storage design. Ask any provider to price these items separately so you can see which ones your environment actually triggers.

What is one-time work and what recurs after go-live?

The one-time work is the initial design, exporter deployment, least-privilege role creation, dashboards and the first set of alert rules. Recurring work includes keeping the exporter current, reviewing alert noise and tuning thresholds as workloads change, updating dashboards when schemas or services change, and planning PostgreSQL upgrades. PostgreSQL minor releases come at least once every three months and replace executables without changing the storage format, so they are a routine patching task. Major upgrades are a planned project, and your monitoring must be checked against the new version. Ask for the recurring items to be listed in the quote with an owner for each.

What should we ask for in a quote for this work?

Ask for a written scope that lists each cluster, environment and replica in scope, the collectors enabled, and the alert rules and routing targets included. Request the deliverables explicitly: deployed exporter configuration, the database role and its grants, dashboards, alert rules with documented thresholds, and a runbook for each alert. Also ask who performs testing, how alert firing is verified, and what happens to changes requested after the scope is agreed. Confirm what training, handover and post-go-live support are included, and whether any ongoing support is a separate retainer.

Does PostgreSQL itself give us automatic failover, and how is it monitored?

No. PostgreSQL does not include software that detects a primary failure and promotes a standby, so automatic failover needs external tools. Monitoring cannot replace that tooling, but it should show whether the standbys are healthy enough to promote, including replication lag and connection state. Confirm which failover tool you use, how it reports its state, and which metrics and alerts reveal a stalled standby before a failover is needed. Also confirm the failover design with your own database owners, since the tool choice affects which exporter metrics matter.

Is PostgreSQL free to use, and does the license affect monitoring?

PostgreSQL is released under the PostgreSQL License, a permissive open source license similar to the BSD and MIT licenses, so there is no license fee for running the database. The postgres_exporter is a separate community project, and you should confirm its license in its own repository before deploying it. Your recurring costs are infrastructure, storage for metrics, and the people who run the system. Have your legal or procurement team confirm the license terms of every component in the stack, including the exporter and any dashboard or alerting tools you add.

Which PostgreSQL version should we monitor, and how long is it supported?

Monitor whichever versions your estate runs, but plan around the support dates. PostgreSQL 18 was first released on September 25, 2025 and is supported until November 14, 2030. PostgreSQL 14 is supported until November 12, 2026, and versions 13 and earlier are no longer supported. Check your exporter against the version you run, because statistics view names and columns can change between major releases. Plan your PostgreSQL upgrades alongside your monitoring changes so dashboards and alerts are updated together.

Does PostgreSQL monitoring need its own database account, and what access does it need?

Yes. The exporter should connect with a dedicated login role rather than an administrator account. PostgreSQL provides the built-in pg_monitor role for reading monitoring statistics, which avoids granting superuser rights. Confirm the exact grants against the exporter documentation, store the password in your secrets system, and restrict the connection with host-based access rules and TLS. Review the role periodically, because a monitoring account with broad access is a common finding in security reviews.

How DeployOpen scopes and delivers PostgreSQL monitoring

DeployOpen plans and builds PostgreSQL monitoring with postgres_exporter inside infrastructure you control, starting from a written scope. The work covers the exporter account, collectors, alert rules, dashboards and the runbooks your team needs to operate them.

How we scope

  • We inventory every PostgreSQL cluster, its versions and replicas, and which teams receive its alerts.
  • We agree in writing which collectors, alert rules and dashboards are in scope before work starts.
  • We confirm the monitoring account's privileges and how credentials will be stored and rotated.

How we build

  • We create a least-privilege monitoring role, grant pg_monitor membership, and test that it cannot change data.
  • We configure and test replication, WAL and statement collectors against each cluster in a non-production environment first.
  • We write alert rules for replication lag and connection exhaustion, then test each rule against a deliberately induced condition.

How we hand over

  • We deliver the exporter configuration, Prometheus scrape jobs, rule files and dashboards as versioned files your team owns.
  • We document each alert with its meaning, expected response and the checks an on-call engineer should run first.
  • We walk your operators through a restart, a credential rotation and an alert test so the setup is run by your staff.

How we support

  • Engagements are fixed-scope, with scope, deliverables and timelines agreed in writing before work starts.
  • Ongoing support, upgrades and continuous testing are available as a retainer after handover.
  • We can review the monitoring setup again when PostgreSQL minor or major versions change, so collectors stay aligned with the running version.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.