pg_profile PostgreSQL Extension

repository·master·Indexed 43 days ago

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

A PostgreSQL extension written in pl/pgsql that identifies resource-intensive database activities by collecting and analyzing historical statistics samples. It leverages pg_stat_statements and pg_stat_kcache to generate reports and provides integration with Grafana for visualizing database load, waits, I/O, and session activity.

Tokens
19.3K
Snippets
39
Records
83
Agent score
56%

What's inside pg_profile

  1. Use Wait Sampling for deep performance analysis

    master

    If the pg_wait_sampling extension is installed, pg_profile can provide granular wait event data. This allows you to see exactly what backends are waiting for (e.g., I/O, locks, or network).

    • Wait Event Types: Summarizes time spent in different wait event categories for both statements and all backends.
    • Top Wait Events (Statements): Shows the most frequent wait events encountered during SQL execution (using _pg_profile.topn_ filter).
    • Top Wait Events (All): Shows the most frequent wait events across the entire cluster, including background processes.
  2. How pg_profile works

    master

    pg_profile is a PostgreSQL extension designed to identify resource-consuming activities by utilizing PostgreSQL statistic views and several contrib extensions. It operates by taking periodic 'samples' of database performance data and storing them in a 'Historic repository' (a set of extension tables).

    Key concepts:

    • Samples: Data snapshots captured by calling the take_sample() function. To automate this, you must use an external scheduler like cron.
    • Historic Repository: The storage for all sampling data.
    • Servers: Remote PostgreSQL clusters that pg_profile can monitor. A local server is automatically created for the cluster where the extension is installed.
    • Side Effects: When a sample is taken, pg_stat_statements_reset() is called to prevent data loss from reaching pg_stat_statements.max. If pg_wait_sampling is present, it also resets pg_wait_sampling_profile. These resets may affect other monitoring systems.
    • Extension Architecture: Composed of a Historic repository, a Sample management engine, a Report engine, and Administrative functions (for managing servers and baselines).
  3. Understand pg_profile Grafana dashboard metrics

    master

    The pg_profile Grafana dashboard provides several views to analyze PostgreSQL performance. The metrics are derived from pg_stat_statements and other extensions. Key metrics include:

    • Query ID: Hexadecimal queryid from pg_stat_statements. A compatible identifier for pgcenter is also provided in square brackets (hash of dbid, userid, and queryid).
    • Time (s): Total time spent in a statement, broken down into:
      • Elapsed: total_plan_time + total_exec_time.
      • Plan: total_plan_time.
      • Exec: total_exec_time.
    • JIT time (s): Sum of jit_generation_time, jit_inlining_time, jit_optimization_time, and jit_emission_time.
    • I/O time (s): Sum of blk_read_time and blk_write_time.
    • CPU time (s): User (Usr) and Kernel (Sys) space time, provided by the pg_stat_kcache extension.
    • Plan types: Indicates if the statement used a Generic or Custom plan.
    • %Cvr: Coverage, representing the statement stats collection duration as a percentage of the report duration.
  4. How pg_profile works and collects statistics

    master

    pg_profile is a PostgreSQL extension written in pure pl/pgsql that identifies resource-intensive activities by leveraging PostgreSQL statistics views and the pg_stat_statements and pg_stat_kcache extensions.

    Core Concepts

    • Historic Repository: The extension creates a repository in your database to hold statistics "samples".
    • Sampling: A sample is captured by calling the _take_sample() function. Because PostgreSQL lacks a built-in job engine, you must use a tool like cron to call this function periodically.
    • Reporting: You can generate reports between two samples to analyze the load profile during a specific period (e.g., during a performance degradation event).
    • Automatic Resets: Every time a sample is taken, pg_stat_statements_reset() is called. This prevents statistics from being lost due to reaching the pg_stat_statements.max limit, but it will affect statistics collected by other monitoring tools that rely on the pg_stat_statements view.
    • Multi-Server Monitoring: A single pg_profile installation can collect data from remote clusters (called servers). You define these servers by providing names and connection strings. A local server is automatically created for the cluster where the extension resides.
    -- Conceptually, you trigger sampling via:
    SELECT _take_sample();
  5. Understand Checkpoint and Buffer statistics

    master

    The pg_profile report provides detailed metrics regarding PostgreSQL checkpointing and buffer management. This helps in identifying if checkpoints are occurring too frequently or if the background writer is struggling to keep up with dirty buffers.

    Key metrics include:

    • Checkpoints: Distinguishes between Scheduled checkpoints (checkpoints_timed) and Requested checkpoints (checkpoints_req).
    • Write/Sync Times: checkpoint_write_time and checkpoint_sync_time track the duration of these operations.
    • Buffer Activity: Tracks buffers_checkpoint (written during checkpoints), buffers_clean (written by background writer), and buffers_backend (written by backends).
    • WAL Generation: Monitors total WAL generated and archived status.
  6. Understand pg_profile report sections and filtering

    master

    The pg_profile report is organized into several sections that provide deep visibility into PostgreSQL performance.

    Key Capabilities:

    • Object Highlighting: Most objects mentioned in a report can be selected to highlight all related entries across different sections.
    • Sub-string Filtering: You can use a sub-string based filter to limit the report content to specific objects (e.g., a specific database or user).

    Main Report Categories:

    • Server Statistics: High-level overview including Database, Cluster I/O, Cluster SLRU, and Cluster-wide statistics.
    • Database Statistics: Granular metrics per database, including transactions, checksums, block I/O, tuples, parallel workers, and temporary files.
    • Session Statistics: Data regarding session timings and session counts (established, abandoned, fatal, killed).
    • Statement Statistics: Aggregated data from pg_stat_statements, including execution/planning times, I/O, and WAL usage.
    • JIT Statistics: Metrics on JIT compilation, inlining, optimization, and emission.
  7. Identify tables needing indexes (Sequential Scans)

    master

    Use the Top tables by estimated sequentially scanned volume section to find tables that may lack efficient indexing. It uses pg_stat_all_tables data.

    Key metrics:

    • ~SeqBytes: Estimated volume read via sequential scans.
    • SeqScan: Total number of sequential scans.
    • IxScan / IxFet: Number of index scans and live rows fetched via indexes.
  8. Analyze Vacuum and Analyze operations

    master

    The dashboards provide visibility into maintenance workloads:

    Vacuum Statistics

    • Top tables by vacuum operations: Tracks manual vs. autovacuum counts and total time spent (including sleep time due to cost-based delays).
    • Top tables by vacuum time spent: Identifies tables consuming the most maintenance time.
    • Top indexes by estimated vacuum load: Estimates the implicit vacuum load caused by indexes by multiplying the underlying table's vacuum count by the index size. If pg_relation_size() data is unavailable, it uses pg_class.relpages (noted in square brackets).

    Analyze Statistics

    • Top tables by analyze operations: Tracks manual vs. autovacuum analyze counts.
    • Top tables by analyze time spent: Tracks total time spent performing analyze operations.
  9. Interpret Cluster settings and Extension versions in reports

    master

    Reports include metadata about the PostgreSQL environment during the sampling interval.

    Cluster Settings

    Tracks PostgreSQL GUC parameters and system functions (version(), pg_postmaster_start_time(), etc.).

    • Setting: Parameter name.
    • reset_val: The reset_val field from the pg_settings view. Bold font indicates settings that changed during the report interval.
    • Source: The configuration file and line number where the setting is defined.
    • Notes: Timestamp of the first time this value was observed in the interval.

    Extension Versions

    Tracks changes in database extension versions.

    • Name: Extension name.
    • Version: The specific version name.
    • First seen / Last seen: Timestamps of version appearance (only shown if the version changed during the interval).