Monitoring PostgreSQL with Prometheus and Grafana

Collect PostgreSQL metrics with postgres_exporter, a least-privilege monitoring role, Prometheus scraping and Grafana dashboards, planned for infrastructure you control.

On this page

Monitoring PostgreSQL with Prometheus and Grafana for your own servers

Prometheus stores and alerts on time-series metrics, postgres_exporter reads PostgreSQL's statistics and exposes them as metrics that Prometheus can scrape, and Grafana draws dashboards from the stored data. If you run self-hosted PostgreSQL, this stack is the usual way to watch capacity, replication health and connection pressure over time and to get alerted before a problem becomes an outage. Teams with several database servers, or with a need to review trends for capacity planning, get the most from it. It does not replace PostgreSQL logs, which record individual slow statements and errors, tracing for application requests, or backups and tested restores. Plan those as separate controls.

Prometheus collects metrics by pulling them over HTTP from targets it finds through service discovery or a static configuration, so each exporter must be reachable from the Prometheus server and the scrape interval is a deliberate choice. Its data is queried with the PromQL language, which is how alert rules and Grafana panels both read the same series. The Prometheus overview states that the project values reliability over precision and is not a good fit where 100% accuracy is required, such as per-request billing. For PostgreSQL metrics that means you should read rates and sampled values as trends and thresholds, not as exact transaction ledgers. Confirm the retention you need, since local storage is not clustered or replicated and should be handled like any other single-node database.

Before you deploy, decide how the exporter reaches the database. Create a dedicated monitoring role with only the privileges the exporter needs, and confirm the exact grants for your PostgreSQL version with the postgres_exporter documentation rather than reusing an administrative account. Then choose between a sidecar exporter next to each database and one exporter that scrapes several targets, and check the overhead of your chosen collectors on a staging server first. Grafana needs its own database for configuration in production, since its docs say SQLite does not scale and MySQL or PostgreSQL is required for high availability. Use Grafana's high availability guide when you plan that layer.

Sidecar or multi-target exporter layout

A sidecar layout runs one postgres_exporter process on each database host or in the same failure unit as the database, and it connects to that one local instance. Each exporter is configured against a single database endpoint, so the scrape target maps directly to one server and its health. Teams that already manage each database host as a unit often find this the simplest model to reason about, because installing, upgrading and restarting the exporter follows the same change path as the database itself.

  • Ownership: the team that runs the database host usually owns the exporter, which keeps monitoring changes next to database changes.
  • Failure domain: if the exporter fails, only that server loses metrics, and a database outage does not take down a shared collector.
  • Network path: Prometheus reaches each exporter over its own port, so every host needs a scrape path and a firewall rule.
  • Credentials: each exporter holds its own monitoring role credentials on the local host, which multiplies the number of secrets to rotate.
  • Discovery: static configuration or service discovery must list every host, and the list grows with the fleet.

Confirm who patches the exporter on each host, how credentials are rotated across the fleet, and whether your firewall policy allows Prometheus to reach every exporter port.",

How to set up the monitoring role and scrape configuration

This sequence takes a PostgreSQL cluster from no monitoring to a Grafana dashboard fed by live metrics, with each step confirmed before the next begins. The monitoring login gets only the privileges the exporter needs, and the scrape path is verified end to end.

  1. Create a dedicated least-privilege monitoring role

    The database owner or a DBA creates a separate login role for the exporter, never reusing an application or superuser account. Grant only the privileges that the postgres_exporter documentation lists for the metrics you plan to collect, and confirm the exact grants against that documentation for your PostgreSQL version. Require SCRAM password authentication for the role, consistent with PostgreSQL's move away from MD5. Check: log in as the new role from the exporter host with psql and confirm it can read the statistics views but cannot modify data or create objects.

  2. Restrict the role in pg_hba.conf

    The DBA adds a pg_hba.conf entry that allows the monitoring role to connect only from the exporter's address, over TLS where your policy requires it, and only to the databases it needs. Keep the entry above any broader rule that would match the same connection. Reload the server configuration after editing. Check: a connection from any other host with the monitoring role is rejected, and the exporter host connects successfully.

  3. Install and configure postgres_exporter

    The platform or database team installs postgres_exporter on a host you control, or in a sidecar container, and passes the connection string for the monitoring role through an environment variable or a file with restricted permissions, not on the command line. Run it as a dedicated service account and keep the listen address on an internal interface. Check: request the exporter's metrics endpoint with curl from the exporter host and confirm lines beginning with pg_ are returned, including a pg_up value of 1.

  4. Decide sidecar or multi-target placement

    Before writing the scrape configuration, the team chooses whether each database server gets its own exporter (sidecar or host-local) or one exporter scrapes several targets. Each choice affects failure isolation, the number of scrape jobs and how much load lands on each server. Confirm the placement with the exporter documentation and your own network rules. Check: the chosen layout is written down with one exporter per target or a named mapping of targets to exporters, so every database has exactly one owner for its metrics.

  5. Add scrape targets to Prometheus

    The Prometheus administrator adds a scrape job to prometheus.yml with the exporter addresses, either as static configuration or through service discovery if your platform provides it. Set a job label that matches your naming convention so dashboards and alerts can filter by cluster. Validate the file with promtool before reloading Prometheus. Check: the promtool check reports no errors and Prometheus reloads without rejecting the configuration.

  6. Confirm every target is up

    The administrator opens the Prometheus targets page and confirms that each exporter shows a state of UP with a recent last scrape time. A query for the up metric with the job label should return one series per expected target. If a target is down, check the network path, the TLS or authentication settings and the exporter logs before changing anything else. Check: the count of targets in the UP state equals the number of databases in your layout.

  7. Connect Prometheus as a Grafana data source

    In Grafana, the administrator adds Prometheus as a data source pointing at your Prometheus server. Grafana's provisioning feature can define this data source in a YAML file loaded at startup, which keeps the configuration in version control and makes it reproducible across environments. Use a read-only Grafana account for dashboard viewers and keep administrative access separate. Check: the data source test in Grafana succeeds, and a simple query for the up metric returns the same targets seen in Prometheus.

  8. Load a first dashboard through provisioning

    The team imports a community or internally built PostgreSQL dashboard, then exports its JSON and places it in the dashboards provisioning directory so Grafana loads it at startup. This makes the dashboard an as-code artifact that can be reviewed and redeployed. Confirm the dashboard panels show data for each target, and compare two or three values, such as connections or database size, against a direct query on the server. Check: panels populate for all targets after a Grafana restart, with no manual edits in the UI.

Which Prometheus and Grafana options fit which setup

This table compares the main Prometheus, Alertmanager and Grafana choices for a PostgreSQL monitoring stack and shows the setup each one suits. Read each row against your retention, availability and access requirements, then check the trade-off column before settling the design.

DecisionOptionTrade-offWhen to choose it
Metric storageLocal Prometheus storage with default 15-day retentionSimple to run, but storage is not clustered or replicated and history is limited to the retention windowSmall estate, short investigation window, and acceptable loss of history if the node fails
Metric storageRemote write to external long-term storageLonger history and a separate system to operate, secure and sizeAudit or capacity planning needs that exceed the local retention window
Prometheus topologySingle Prometheus serverOne place to configure and query, but a single point of failure for scraping and alertingFew PostgreSQL targets and a monitoring gap is tolerable during a restart
Prometheus topologyPair of Prometheus servers with separate scrape scopesEach server holds its own data, so queries must span both, and scope boundaries need documentingLarge estates split by environment, network zone or team ownership
Alert routingAlertmanager cluster with every instance listed in PrometheusAdds instances to run and keep in step, but avoids a single notification pointAlerts for database outages must still reach on-call when one Alertmanager is down
Grafana configuration storageSQLite 3 (default)No extra database to run, but the installation docs say SQLite does not scale for productionEvaluation or a single-user test instance
Grafana configuration storagePostgreSQL 12 or laterRequires a database to back up and secure, and it is the storage used for high availabilityProduction instances and any design that will run more than one Grafana server
Grafana availabilitySingle Grafana serverSimplest upgrade and restart path, with dashboards unavailable during maintenanceInternal use where short interruptions are acceptable
Grafana availabilityTwo or more active-active servers behind a load balancerNeeds shared database, duplicate-alert configuration and limits on Grafana LiveTeams that depend on dashboards during incidents and can test failover before go-live
Dashboard managementUI-created dashboardsQuick to change, but changes are hard to review and reproduce after a rebuildEarly exploration before the panels are settled
Dashboard managementProvisioned dashboards and data sources from filesChanges go through review and rebuilds are repeatable, with more upfront setupProduction dashboards and any environment with change control or an audit trail

Which PostgreSQL metrics to watch first

A first Prometheus and Grafana dashboard for PostgreSQL should answer six questions: is the target reachable, are standbys keeping up, how close are connections to their limit, how old is the oldest transaction ID, how well is memory being used, and how much checkpoint and WAL work is happening. The groups below tie each question to what to confirm in the exporter version you run, because metric names change between releases.

Exporter and target availability

Start with whether Prometheus can scrape the exporter and whether the exporter can reach PostgreSQL. A failed scrape looks like a metric gap, so the up series for each target is the first signal to alert on. Confirm which metric reports the exporter's own connection status to the database, since a running exporter with a failed database connection is easy to miss. Check that scrape intervals are long enough for the queries the exporter runs against large catalogs.

Prometheus overview

Replication state and lag

On the primary, the replication view shows each standby's write, flush and replay positions. Lag matters most where a standby is a failover target or a read replica that users query. Confirm the exporter's replication metric names and labels for your version, and whether it exposes lag in bytes, in time, or both. Alert thresholds should follow the recovery point you have committed to, so agree those numbers before you set them.

Connection count against limits

Track active and idle connections against max_connections, and watch for idle-in-transaction sessions that hold locks and block vacuum. A pooler such as PgBouncer changes what PostgreSQL sees, so the connection metrics you chart should come from the layer that holds the server connections. Confirm whether your exporter reports pooler statistics separately, because a pooled application can look quiet at the database while its clients queue.

Transaction ID age

The age of the oldest transaction ID per database is the metric that warns of wraparound risk. Chart it per database and per table where the exporter provides it, and check that long-running transactions or stalled replication slots are not holding it back. Confirm the metric name in your exporter release, because older and newer exporter versions have expressed this value differently. Vacuum behavior determines the trend, so pair the chart with autovacuum activity.

Cache hit and I/O behavior

Buffer cache hit ratios and block read and write counts show whether queries are served from memory or from disk. A falling hit ratio after a workload change, a larger dataset or a restart is worth investigating, but it is a trend signal rather than a fault. Read these counters as rates over time, since cumulative totals since the last statistics reset tell you little on their own. Confirm which statistics views the exporter reads and whether it reports them per database.

Checkpoint and WAL activity

Checkpoint counts, checkpoint write and sync time, and WAL generation rate show how much write pressure the server absorbs. Frequent requested checkpoints can indicate that WAL volume is outrunning settings, and WAL growth affects disk planning and archiving. Confirm which checkpoint statistics view your PostgreSQL major version exposes, since the counters have moved between versions, and make sure the exporter's version can read it.

What exporter overhead and storage cost look like

The cost of this setup is mostly infrastructure and people, not licenses. The Prometheus project is licensed under Apache-2.0 and has no paid enterprise edition, so the money goes to the servers and storage that run Prometheus and Grafana, the implementation work, and the staff who keep them patched and alerting correctly. Grafana is also open source, but Grafana Cloud is a separate option with its own tiers: a free tier, a Pro tier with a monthly platform fee plus usage, and an Enterprise tier with a stated minimum annual commitment, as listed on the Grafana pricing page. Ask any partner or vendor to price self-hosted and hosted options side by side against the same scope. Infrastructure and implementation are largely one-time costs, while storage growth, patching and on-call effort recur.

Overhead on the database host comes from the exporter's queries, and overhead on the monitoring side comes from storage and query load. Storage grows with the number of active series, the scrape interval and retention. Prometheus keeps local data for 15 days by default, and retention can be set by time or size, so the retention decision directly sets the disk you need. Local storage is not clustered or replicated, so plan backups or remote write to long-term storage as a deliberate choice. Shorter scrape intervals, more databases, more tables when per-table metrics are enabled, and heavy dashboards that run wide queries all raise cost. Confirm each figure against your own environment rather than assuming it.

Run a trial before you size anything. On the database host, watch CPU, memory and I/O during scrapes with postgres_exporter enabled and disabled, and check how long a scrape takes at your chosen interval. In Prometheus, track the number of ingested samples, head series and disk growth per day, and check that the Grafana dashboards answer your questions without slow queries. Ask the implementer for a written sizing estimate built on those measurements, the retention policy, and the hours needed for patching and upgrades, since Prometheus minor releases only receive bug fixes for a limited window.

Securing the monitoring path

A monitoring stack holds detailed information about your database, its queries and its hosts, and it often has credentials to reach them. The controls below cover the database account, the network paths, the Grafana front end and the identity behind Grafana sign-in, so each layer is reviewed before the dashboards go live.

Least-privilege monitoring role

Create a dedicated login role for postgres_exporter instead of reusing an administrator account. Grant only the built-in monitoring privileges it needs, and confirm in your own environment which of them the exporter version you deploy requires. Store the password in a secrets manager or a file readable only by the exporter's service account, and rotate it on the same schedule as other service credentials. Test that the role cannot write, alter roles or read application tables.

Authentication methods

Scram authentication for the exporter

Require SCRAM password authentication for the monitoring role in pg_hba.conf, and restrict it to the exporter's host address. PostgreSQL 18 deprecated MD5 password authentication in favor of SCRAM, so an MD5 entry left over from an older cluster is a finding to fix. Enable TLS on the connection if the exporter and database sit on different hosts, and confirm the sslmode setting the exporter uses.

Restricting the metrics endpoint

Each exporter and the Prometheus server expose HTTP endpoints that reveal database names, version details and query-level information. Bind exporters to a private interface, allow scrapes only from the Prometheus server address, and block the port at the host firewall. If your Prometheus version supports web configuration for TLS or basic authentication, enable it and confirm the setting against the release you run.

Prometheus has no built-in access control

Prometheus does not authenticate users who open its web interface or query its API, so anyone who reaches the port can read every stored series. Place it behind a reverse proxy with authentication, or on a network segment reachable only by operators and Grafana. Review the Prometheus security model before deciding which endpoints, including the admin API, are exposed and how Alertmanager is reached.

Prometheus security model

Grafana cookies and content policy

Turn on secure and SameSite cookie settings so session cookies are not sent over plain HTTP or to other sites. Set a Content Security Policy and Trusted Types, hide the Grafana version from unauthenticated users, and require authentication for the metrics endpoint. Verify the root URL and domain settings so DNS rebinding attempts are rejected. Check each setting in grafana.ini after upgrades, because defaults can change between releases.

Security hardening docs

Grafana sign-in through your identity provider

Connect Grafana to your central identity provider using an OAuth, LDAP or other method that the edition you run supports, so accounts follow your joiner and leaver process. All editions support generic OAuth, Entra ID, Okta, GitHub, GitLab, Google, LDAP, auth proxy and JWT. SAML, team sync, active sync and SCIM provisioning are limited to Grafana Enterprise and Grafana Cloud, so confirm your edition before you design group mapping and deprovisioning.

Authentication docs

How metrics flow from PostgreSQL to alerts

The flow starts in the database network, where postgres_exporter connects to PostgreSQL with a dedicated monitoring role and exposes metrics over HTTP. Prometheus finds that endpoint through static configuration or service discovery and pulls the samples into its local time series store. From there, Prometheus sends firing alerts to Alertmanager and can optionally remote write samples to external long-term storage, while Grafana queries Prometheus for dashboards. Check that the exporter's role is read-only, that the scrape path crosses the trust boundary only where you intended, and that Prometheus points at every Alertmanager instance.

Metric and alert hand-offs from PostgreSQL through Prometheus to Grafana.

Limits to confirm before you commit

Prometheus and Grafana are free to use under open-source licenses, but several of their limits shape the architecture before any dashboard is built. The cards below cover the storage, accuracy, release, high availability and licensing questions to settle with your team and your vendors ahead of a monitoring rollout for PostgreSQL.

Single-node Prometheus storage

Prometheus keeps its time series in a local database that is not clustered or replicated, so it should be managed like any other single-node database. If a Prometheus server fails, metrics for that window are lost unless another instance scrapes the same targets. Decide early whether you will run paired Prometheus servers scraping the same postgres_exporter targets, add remote write to long-term storage, or accept a gap during restarts. Default local retention is 15 days, so check whether that matches your capacity planning and incident review needs.

Prometheus storage docs

Reliability over precision

The Prometheus documentation says the project values reliability over precision and is not a good fit where 100% accuracy is required. Scrapes can be missed, and rate calculations over short windows can smooth or distort spikes in PostgreSQL metrics such as lock waits or replication lag. Do not use Prometheus as the record for anything that must be exact, such as billing or audit evidence. Use PostgreSQL logs or database-native records for those needs and confirm which metrics your alert thresholds depend on.

Short minor release support

Prometheus starts a new minor release cycle every 6 weeks, and a minor release generally stops receiving bug fixes after those 6 weeks. Plan your upgrades around the long-term support line instead of chasing each minor release. The current LTS line is 3.13, supported until July 31, 2027, and LTS 3.5 reached end of life on July 31, 2026. Confirm the LTS line you will run and your patch cadence before you commit to a version.

Release cycle page

Grafana HA alerting setup

Grafana high availability runs two or more active-active servers behind a load balancer, sharing a PostgreSQL or MySQL database. The documentation notes that alerting needs additional configuration to avoid duplicate notifications when several nodes evaluate the same rules. Grafana Live also has limitations in HA mode, so live dashboard updates may not behave the same on every node. Test alert routing and live panels on your HA layout before you rely on them for on-call paging.

Grafana HA docs

SAML and SCIM licensing

Grafana's authentication docs list LDAP, generic OAuth, Entra ID, Okta, GitHub, GitLab, Google OAuth, auth proxy and JWT as available in all editions. SAML, team sync, active sync and SCIM provisioning are available only in Grafana Enterprise and Grafana Cloud. If your identity provider requires SAML or you need automated user provisioning, budget for Enterprise or Cloud before design begins. Confirm the exact edition terms with Grafana Labs, since the commercial options are separate from the open-source project.

Authentication docs

Exporter and PostgreSQL version match

The postgres_exporter collects metrics from system views whose columns change between PostgreSQL major versions, and some metrics only exist on newer releases. Confirm that the exporter build you deploy supports every PostgreSQL major version in your fleet, including versions approaching end of support. Check this again before any PostgreSQL major upgrade, because dashboards and alert rules that query renamed or removed metrics can go silent without an error. Test the exporter against a staging cluster on the target version first.

Questions buyers ask before hiring help

What does monitoring PostgreSQL with Prometheus and Grafana cost?

The software is free to use. Prometheus is released under Apache-2.0 and has no paid enterprise edition, so the cost comes from the infrastructure that runs it, the storage for metrics, the implementation work and the people who operate it afterward. Implementation is usually a one-time cost tied to the number of PostgreSQL servers, the number of environments, how many dashboards and alert rules are needed, and whether Prometheus must reach hosts behind network controls. Ongoing costs are storage growth, upgrades and time spent reviewing alerts. Ask any partner for a quote built from a written scope that lists the targets, environments, dashboards, alert routing and the systems that must be integrated.

How long does a first working PostgreSQL monitoring setup take?

The duration depends on your environment, and the best source is a written scope rather than a general figure. The main drivers are the number of PostgreSQL clusters, whether exporters can be installed on the database hosts or must run as separate targets, how many people must approve the monitoring role and network rules, and whether an identity provider must be connected to Grafana. A single-cluster proof of concept moves faster than a multi-environment rollout with change control. Ask for milestones that separate exporter deployment, dashboard build, alert testing and handover.

What does our team need to provide before monitoring work starts?

Prepare access and approvals before the engagement starts, because they usually set the pace. You will need administrative access to the PostgreSQL servers or the platform that hosts them, permission to create a least-privilege monitoring role, a list of hosts and ports that Prometheus must reach, and firewall or network rules that allow scraping. Grafana needs an identity provider decision if you want single sign-on, along with the connection details and group mappings. You also need a place to store Grafana's configuration database, since SQLite is not suitable for production, and named owners who will receive alerts.

Can an internal team set this up alone, and where do they usually stall?

An experienced internal team can deploy Prometheus, postgres_exporter and Grafana without outside help, since all three are open source and documented. Teams usually stall in three places: creating a monitoring role that exposes only what is needed, choosing a retention and storage plan (Prometheus keeps local data for 15 days by default and is not clustered or replicated), and turning raw metrics into alerts that do not flood the on-call channel. Teams also struggle with keeping Prometheus and Grafana patched on schedule. Assess your team against those three points before deciding.

Do we need Grafana Enterprise or Grafana Cloud for this?

No. Grafana is licensed under AGPLv3 and the open-source edition supports dashboards, data sources and alerting, and the authentication docs list LDAP, generic OAuth, Entra ID, Okta, GitHub, GitLab and Google OAuth for all editions. SAML, team sync, active sync and SCIM provisioning are available only in Grafana Enterprise and Grafana Cloud. Choose Enterprise only if your identity requirements need those features. Grafana Cloud's pricing page lists a free tier, a Pro tier with a 19 US dollar monthly platform fee plus usage, and an Enterprise tier with a minimum commitment of 25,000 US dollars per year. Confirm current pricing with Grafana before you budget.

How are Grafana dashboards and Prometheus alert rules kept under version control?

Keep dashboards, data sources and alerting resources as code. Grafana provisioning loads data sources, dashboards, plugins and alerting resources from YAML or JSON files at startup, so they can live in a Git repository and be reviewed like any other change. Grafana also documents Terraform and Git Sync as further as-code options. Prometheus alert rules and scrape configuration are plain files, so they can follow the same review process. Ask for the repository layout, the review workflow and a rule that changes reach production only through the pipeline.

What do Prometheus and Grafana upgrades involve over time?

Upgrades are recurring work and should be planned as a standing task. Prometheus minor releases follow a six-week cycle, and a minor release generally stops receiving bug fixes after those six weeks. Long-term support releases receive fixes for one year, and the current LTS line is 3.13, supported until July 31, 2027. Grafana ships major releases once a year, minor releases every other month and patches at least monthly, with each minor release supported for 9 months. Plan a regular review window, test upgrades in a non-production environment, and confirm which release line your team will commit to.

How DeployOpen scopes and delivers this monitoring stack

DeployOpen plans and implements this monitoring stack inside your own infrastructure, whether that is your cloud accounts, data centers or an air-gapped network. The Prometheus server, Alertmanager, Grafana, the postgres_exporter deployment and the monitoring role on each PostgreSQL instance all run where your security team can review them. Most engagements are fixed-scope, so the written scope sets the list of targets, the dashboards and alert rules, the retention and storage design, the authentication settings for Grafana and the handover material before any build work begins. Scope, deliverables and timelines are agreed in writing first, and a quote follows from that written scope rather than from a standard package.

The decisions that most affect the quote are the ones your team should settle early. These include how many PostgreSQL clusters and nodes are in scope, whether exporters run as sidecars or from a shared host, how long metrics must be kept locally and whether long-term storage through remote write is needed, whether Grafana uses PostgreSQL as its configuration database for a high availability pair, and how Grafana's identity integration is set up (SAML and team sync are listed in the Grafana authentication docs as Enterprise features, so confirm the edition you plan to run). Ask for each of these to be written into the scope so the quote and the delivery plan match what you actually operate.

Ongoing work is usually a separate, recurring decision. Prometheus, Grafana and exporter versions move on their own release cycles, so an upgrade and support retainer can cover patching, dashboard and alert rule maintenance and periodic review of thresholds. To start, send your current PostgreSQL versions, hosting model, identity provider and retention requirements to DeployOpen and request a written scope with deliverables, a timeline and a quote. Confirm with us what is included in any retainer before signing, including response expectations, since these are agreed in writing and not assumed.

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.