How to build an Oracle AWR-equivalent diagnostics stack in PostgreSQL (step-by-step guide with code)

Comments 0

Share to social media

Moving from Oracle to PostgreSQL means losing one of Oracle’s most-loved diagnostic tools: the Automatic Workload Repository (AWR). The good news? Most of AWR’s core capabilities – snapshot history, wait event sampling, Top SQL analysis, and buffer cache inspection – have direct, open-source equivalents in PostgreSQL.

This guide translates Oracle AWR concepts into practical PostgreSQL diagnostics using extensions like pg_profile, pg_wait_sampling, and pg_stat_statements – complete with runnable SQL you can apply to your own environment today.

As a multi-platform database specialist it’s safe to say that, if there’s one feature from Oracle I would like to migrate to other databases, it would be the Automatic Workload Repository (AWR).

Introduced in version 10.2.0.3, it’s been welcome with open arms as it includes the highly valued STATSPACK performance tuning tool, as well as several other enhancements. These include its own background processes, memory allocation, and a configurable data repository. 

Also included with the AWR is Active Session History (ASH), the Automatic Database Diagnostic Monitor (ADDM), and a group of out-of-the-box reports available to the user.

In this guide, based on one of my previous presentations, I’ll demonstrate how to translate some of the concepts from the Oracle AWR into PostgreSQL performance diagnostics. I’ve turned much of it into runnable SQL and configuration steps for the database enthusiast.

Think of this like a cookbook, where every recipe can be applied directly to your PostgreSQL environment to build a persistent performance repository and replicate the most valuable Oracle AWR capabilities.

Before we jump in, just remember that every database workload is unique! Test all queries for the most optimal implementation – and never simply run in a production environment.

This cookbook is based on Kellyn Gorman’s presentation “Bridging Oracle’s Diagnostics Power with PostgreSQL’s Native Performance Views”.

Who is this guide for?

This guide is for:

  • PostgreSQL DBAs building who want to know more about environment performance

  • Platform engineers designing observability stacks

  • Architects comparing database total cost of ownership

  • Anyone who has said “I miss AWR” after moving to PostgreSQL

Did you know?
pg_stat_* views cover ~70% of AWR use cases natively, out of the box. The remaining gaps are filled by a small set of open-source extensions, all at zero licensing cost.

Feature comparison: Oracle AWR vs. PostgreSQL

The table below maps major AWR capabilities to their PostgreSQL equivalent and flags where custom work is needed. There are considerable advances in PostgreSQL extensions in recent years, all of which provide valuable performance data for the database specialist.

Although this table is detailed, it’s not exhaustive. Plus, new extensions become available on a regular basis.

CapabilityOracle AWRPostgreSQLDelta
Snapshot-based history✓ Native (AWR)✓ pg_profile extExtension required
Configurable retention✓ 1-50,000 snaps✓ ConfigurableFeature parity
Named baselines✓ Fixed & moving✗ Manual buildCustom SQL needed
Wait event detail (sampled)✓ 1,200+ events✓ pg_wait_samplingExtension + sampling
SQL elapsed time ranking✓ AWR Top SQL✓ pg_stat_statementsNo plan per exec
Per-execution plan capture✓ AWR SQL Plan✓ pg_store_plansExtension required
Segment-level I/O stats✓ v$segment_statistics✓ pg_statio_*Good parity
Buffer cache inspection✓ v$bh, x$bh✓ pg_buffercacheExtension required
Latch / mutex contention✓ v$latch detail△ Limited visibilityNo latch equiv
Blocking / lock waits✓ v$session history✓ pg_locks + ASH-likeNeeds sampling ext
Time-model statistics✓ v$sess_time_model✗ Not nativeCustom build
Compare Periods report✓ AWRDiff✗ Manual SQLNo equivalent
OS / system metrics✓ Included in AWR△ External (Prometheus)Agent required
Zero licensing cost✗ Diagnostics Pack ~$7.8k/DB✓ Fully open sourcePG wins here

Why one is not simply ‘better’ than the other

It’s essential to not view one as ‘better’ than the other – they’re just different. Where Oracle has 40 years of enterprise and expensive features built-in, PostgreSQL is open-source and lightweight. What’s added to building out similar functionality to Oracle’s AWR should be expected – and may require additional work.

The PostgreSQL AWR-equivalent extension stack (what you need to get started)

A majority of the work will be covered with pg_stat_statements and pg_profile, so you’ll need to install these if you haven’t already. Add any others, incrementally, as needed.

Top SQL workload analysis in PostgreSQL: pg_stat_statements

Understanding resource consumption by top SQL is a requirement for any database specialist. The top SQL workload analysis is built into PostgreSQL’s core and simply requires us to query the information and present it in an easily readable format.

The query below tracks cumulative execution statistics for every unique query fingerprint.

How to receive AWR-equivalent snapshots in PostgreSQL: pg_profile

The extension pg_profile is the closest open-source equivalent to Oracle’s AWR for PostgreSQL.

It captures periodic deltas of all pg_stat_* views into a set of persistent tables, then generates HTML reports comparable to an AWR report. We can then use these to provide like-for-like results.

It’s available at github.com/zubkov-andrei/pg_profile

Important note: Always install pg_stat_statements before pg_profile, since the former needs to be installed first.

Get started with PostgreSQL – free book download

‘Introduction to PostgreSQL for the data professional’, written by Grant Fritchey and Ryan Booz, covers all the basics of how to get started with PostgreSQL.
Download your free copy

Using pg_wait_sampling for ASH/wait event history in PostgreSQL

pg_wait_sampling is the PostgreSQL equivalent of Oracle’s ASH.

Along with the snapshot data retained in the AWR, samples of session information is also retained, this time in Active Session History (ASH). By default, only one out of every ten samples is collected in the long-term AWR history, but this data creates valuable information on average active session (AAS) that a DBA can use to understand how sessions behave over time.

Active Session information from pg_wait_sampling provides sample wait events at a configurable interval (default 10ms) and stores them in a ring buffer and persistent history table.

It’s available at github.com/postgrespro/pg_wait_sampling

pg_buffercache (buffer pool/segment inspection in PostgreSQL)

The pg_buffercache extension is the PostgreSQL equivalent to Oracle’s v$bh view and buffer cache segment analysis.

The pg_buffercache extension exposes the contents of the shared_buffers pool so you can identify which relations are consuming the most cache.

pg_store_plans for execution plan history in PostgreSQL

The extension for pg_store_plans is incredibly valuable to PostgreSQL.

It explores a plan per (queryid, planid) pair, enabling you to detect plan regressions similar to Oracle’s SQL Plan baseline capture (part of the Oracle AWR).

You can download it at github.com/ossc-db/pg_store_plans

PostgreSQL slow query plan logging with auto_explain

You can use auto_explain to logs execution plans for any queries exceeding a time threshold. 

This is the PostgreSQL feature equivalent (and is similar to) enabling Oracle trace event 10053.

You must enable track_io_timing = on in postgresql.conf to get I/O timing data in pg_stat_statements and pg_stat_io. Without it, read_time and write_time columns stay at zero.

How to build the snapshot repository in PostgreSQL with pg_profile

Having performance data history is one of the most valuable features of the AWR. By default, 8 days is retained, but most production databases extend this retention to 30-60 days. With pg_profile, we’re able to handle the snapshot capture, delta calculation, retention, and HTML report generation automatically.

Our main challenge is to retain the information over an extended period of time or when a reset is issued. Introducing pg_profile assists in addressing this challenge – however, it doesn’t solve it completely.

The recommended setup of pg_profile is as follows:

Install and configure

Take snapshots

Schedule snapshots with pg_cron

Install pg_cron from your OS package manager and add it to shared_preload_libraries before using the schedule below:

Generate an AWR-style HTML report

How to navigate a pg_profile report (and what the report provides)

A pg_profile report contains high-level information about the PostgreSQL server – including stats on the cluster, database and SQL, then schema objects, functions and settings.

Each of these section headers, shown in the image below, are also links to connect to the section in the report they refer to:

an image showing a pg_profile report in PostgreSQL - in particular, the table of contents of an example report.
A pg_profile report in PostgreSQL – here, we see the table of contents.

The database statistics section highlights important information for all databases in the cluster, including the number of commits, rollbacks, Cache hit%, rate of change, and more.

an image showing the database statistics section of a pg_profile report in PostgreSQL.
The database statistics section of a pg_profile report in PostgreSQL.

The ‘Top SQL’ section contains information that is easily recognizable to Oracle DBAs. This includes the queryID, which database in the cluster the query belongs to, elapsed time, number of rows, calls, and the min and max time.

image showing the 'top SQL by elapsed time' section of a pg_profile report in PostgreSQL.
The ‘top SQL by elapsed time’ section of a pg_profile report in PostgreSQL.

Full SQL text is displayed for each of the query IDs, and then the data is presented in various orders – e.g by planning time, execution time, I/O wait time, gets, temp usage, just in time(JIT) activity, and WAL size. This is similar to an Oracle AWR report – just, in this case, we’re getting information vital to the management of a PostgreSQL database.

The report concludes with vacuum, index usage, and settings information, along with links to take the reader back to the top of the report. Here, the links navigate to different sections, making the process seamless for users to explore the report once they’ve identified an issue.

How to create your own repository in PostgreSQL

pg_profile should always be your first option for performance data in PostgreSQL.

However, if for some reason you can’t install pg_profile, don’t worry – there are other ways to create a minimal snapshot table.

Here, I’ll show you how to build one manually that can be used to capture deltas with a scheduled procedure.

How to create the snapshot table

The capture procedure

The delta report between two snapshot times

This table and scheduled job can now collect snapshot performance data in any PostgreSQL environment. Additionally, querying the table now allows you to inspect performance impacts without the pg_profile extension.

SQL ranking and workload analysis in PostgreSQL

One of the biggest challenges when using performance data is understanding how to query quantities and time. The queries in this section mirror Oracle’s AWR Top SQL report using pg_stat_statements and serve as an example of how to calculate it correctly in PostgreSQL.

Note the examples for total_exec_time, mean_exec_time, blk_read_time, etc.

Top SQL by total execution time

Top SQL by I/O (disk reads)

Top SQL by average execution time (worst per-call performance)

Top SQL by row throughput

Wait event analysis in PostgreSQL

Wait classes serve as high-level categories that help identify pain points in performance, and wait events are more detailed events that belong to each category.

These are the cornerstone of method tuning in Oracle and much of it can be duplicated in PostgreSQL from version 16 onwards.

Current wait events (live sessions)

The point-in-time snapshot is the PostgreSQL equivalent of querying Oracle’s v$session for wait events. It’ll look familiar to any Oracle DBA and will provide value to even the newest PostgreSQL user.

It shows event type (like wait class, which is the category), and then the corresponding breakdown of wait events (the things causing the majority of time and resource consumption in the database.)

Historical wait event profile (pg_wait_sampling)

Sampled wait history is the PostgreSQL equivalent of the Oracle AWR Top 5 Wait Events report.

It requires the pg_wait_sampling extension and gives us a clear picture of what percentage of what event type (category) is consuming database time (broken down to the exact wait event detail).

Wait events over a time window

A key PostgreSQL gap versus Oracle

Oracle samples waits natively at ~10x/sec via ASH, but PostgreSQL has no built-in equivalent. pg_wait_sampling with a bgworker is the closest alternative. Without this, you’ll only see instantaneous waits from pg_stat_activity.

Free desktop tool for fast PostgreSQL monitoring and diagnostics

Stay in control of PostgreSQL performance with Redgate pgNow – a free desktop tool for fast, focused diagnostics. No agents, no setup, just actionable insights when you need them.
Learn more & download now

How to detect I/O bottlenecks in PostgreSQL

There are a few methods for detecting I/O bottlenecks in PostgreSQL. Here, I’ll run through a few of them.

System-wide I/O accounting using pg_stat_io (PostgreSQL 16 onwards)

The pg_stat_io extension is the closest PostgreSQL-native equivalent to Oracle’s v$filestat. It breaks down reads, writes, hit rates, and evictions by backend type and object context. As the natural life of a database is growth, understanding how IO is impacting performance is essential to database management.

pg_stat_io is only available in PostgreSQL 16 onwards. For PG 15 (and earlier), use pg_stat_bgwriter and pg_stat_io_* views instead.

Checkpoint & buffer manager stats in PostgreSQL with pg_stat_bgwriter

The pg_stat_pgwriter extension is currently available in every version of PostgreSQL. It shows checkpoint frequency, buffer writes, and clean/dirty eviction patterns.

Tip: If checkpoints_req is high (relative to checkpoints_timed), your checkpoint_completion_target or max_wal_size may need tuning. Frequent requested checkpoints increase I/O spikes.

Hot buffer/segment inspection in PostgreSQL with pg_buffercache

The pg_buffercache extension is the PostgreSQL equivalent to Oracle’s v$bh buffer cache segment report, identifying which relations occupy the most shared_buffers pages.

Per-table I/O stats with pg_statio_user_tables in PostgreSQL

Blocking and concurrency detection in PostgreSQL

We already know how important active session information is, but understanding blocking sessions is also valuable.

Active session and blocking tree

While multi-version concurrency control (MVCC) helps to eliminate some blocking we experience in other database platforms, blocking is still an important area to monitor in PostgreSQL.

Knowing how to show all non-idle sessions, identify which session are blocked, and show the blocking PID chain, is essential. The following query mirrors Oracle’s v$session blocking analysis.

Long-running transactions and idle-in-transaction sessions

The following query displays sessions in the idle-in-transaction state, hold row locks, and block VACUUM. This query can also be used as a basis to build alerts longer than 5 minutes.

Lock detail for a specific session

Lock wait summary

Important note!
idle in transaction sessions hold row locks and can prevent VACUUM from reclaiming dead tuples, causing table bloat. Set idle_in_transaction_session_timeout in postgresql.conf to automatically terminate such sessions.

Named baselines and period comparison in PostgreSQL

Oracle AWR provides fixed and moving-window baselines natively. In PostgreSQL, meanwhile, you’ll build these manually by tagging snapshot ranges and comparing deltas, as I demonstrate below.

How to create a baseline registry table

How to compare the current period against the baseline

This process allows you to easily monitor, compare, and manage baseline performance.

WAL and replication monitoring in PostgreSQL

WAL (Write-Ahead Logging) is the mechanism PostgreSQL uses to keep your data safe and consistent.

The core idea is simple: before PostgreSQL makes any changes to the actual data files on disk, it first records those changes in a sequential log – the write-ahead log. Because the change is safely written to this log before it’s applied, the database can always recover after a crash or power failure by replaying the log and reconstructing any work that hadn’t yet been fully saved to the data files.

This “log first, write later” approach also makes the database faster, since appending to a sequential log is quicker than constantly updating scattered data files. It also underpins important features like point-in-time recovery and streaming replication to standby servers.

It’s essential for any database specialist to understand the following:

  • How much WAL is being generated

  • If there’s any latency in WAL generation

  • If there’s any lag in replication of WAL to replicas

  • The overall health of the WAL replication

WAL generation rate

Replication lag

Table and index health in PostgreSQL

The health of objects in PostgreSQL can refer to numerous things, but one of the areas of concern is around the amount of bloat a database has. Bloat refers to the wasted, unused space that accumulates inside tables and indexes over time, caused by how PostgreSQL handles updates and deletes. Why is this?

Well, rather than overwriting or immediately removing a row, PostgreSQL marks the old version as ‘dead’ and writes a new version elsewhere. This is a side effect of its MVCC design, which allows many transactions to read and write at the same time, without blocking each other. ‘Dead’ rows can’t simply disappear on their own – they linger in the table, taking up disk space and making queries slower because of how PostgreSQL has to scan past them.

Normally, the PostgreSQL autovacuum process cleans up dead rows and makes that space reusable. However, if updates and deletes happen faster than vacuum can keep up, or if vacuum isn’t tuned well, the dead space piles up as bloat. Left unchecked, bloat increases storage usage, degrades query performance, and can sometimes require maintenance operations like VACUUM FULL – or tools such as pg_repack – to physically reclaim the space.

Subscribe to the Simple Talk newsletter

Get selected articles, event information, podcasts and other industry content delivered straight to your inbox.
Subscribe

Table statistics: bloat indicators

Unused indexes

The next point of focus is unused indexes. When index usage is monitored, you know exactly if an index is providing value, or if it’s just consuming space and resources. Unfortunately, PostgreSQL doesn’t feature index monitoring.

It’s common for a few objects in a database to become larger than average. Tables that hold transactional information for customer data or inventory can become much larger than the majority, and understanding what objects may be creating performance issues is another aspect of monitoring. The indexes on these tables also can become very large, especially if bloat is involved.

Largest tables and indexes

The implementation roadmap you should follow

Now that we understand what to inspect for performance impact, we now need to implement it in the least disruptive way possible, but also in the way that provides the most value.

Consider following this phased rollout to reach enterprise-grade PostgreSQL diagnostics without disrupting your environment.

Day 1: BaselineWeek 1: HistoryMonth 1: Deep DiagQuarter: Baselines
Enable pg_stat_statementsInstall pg_profileAdd pg_wait_sampling (wait history)Register peak-load baselines
Set track_io_timing = onSchedule snapshot every 30 min (pg_cron)Add pg_buffercache (cache inspection)Build compare-period delta reports
Verify pg_stat_io (PG 16+)Set retention to 14+ daysAdd pg_store_plans (plan history)Integrate with Prometheus / Grafana
Baseline with pg_stat_bgwriterReview first AWR-style HTML reportBuild alerting on blocking sessionsDocument tuning runbooks
Review current Top SQLTune postgresql.conf based on findingsCreate idle_in_transaction alertSchedule quarterly baseline reviews

Reference and resources

Below are the numerous GitHub and document references I used to build my presentation and, in turn, this very cookbook you’re now reading.

Extension repositories

  • pg_profile:           github.com/zubkov-andrei/pg_profile

  • pg_wait_sampling:     github.com/postgrespro/pg_wait_sampling

  • pg_store_plans:       github.com/ossc-db/pg_store_plans

Official PostgreSQL documentation

  • pg_stat_statements:   postgresql.org/docs/current/pgstatstatements.html

  • pg_buffercache:       postgresql.org/docs/current/pgbuffercache.html

  • Monitoring Stats Ref: postgresql.org/docs/current/monitoring-stats.html

  • pg_stat_io (PG 16+):  postgresql.org/docs/current/monitoring-stats.html#MONITORING-PG-STAT-IO-VIEW

Quick-reference: postgresql.conf settings

Finally, here’s an excellent example of a postgresql.conf file configuration:

Conclusion

Using these extensions, along with scripts and reporting features, offers the PostgreSQL DBA the opportunity for insight into database performance covering over 70% of what is offered by Oracle’s enterprise Automatic Workload Repository (AWR).

Going forward, I expect significant extension enhancements and improvements that will close the gap between enterprise and open-source tooling to diagnose and identify performance issues in PostgreSQL.

This cookbook is based on Kellyn Gorman’s presentation “Bridging Oracle’s Diagnostics Power with PostgreSQL’s Native Performance Views”.

This document contains proprietary information and is protected by copyright law.

Copyright © 2026 Red Gate Software Limited. All rights reserved

Article tags

About the author

Kellyn Pot'Vin-Gorman

DBAKevlar

See Profile

Kellyn Gorman is the multi-platform database and AI advocate at Redgate. She's been in the tech industry for a quarter of a century, specializing in Oracle, SQL Server, MySQL and PostgreSQL. Her focus on Azure and Google Cloud for high IO workloads on IaaS has been of exceptional interest for data-infra specialists in the tech world. Her content is highly respected under her handle DBAKevlar. She is co-leader of the Data Platform DEI group, an executive board core member for DZone, and mentors around half a dozen people at any given time in multiple communities.