Ruby PostgreSQL 数据库性能分析。锁、索引使用情况、缓存命中率、真空统计数据等。
Ruby port of Heroku PG Extras with several additions and improvements. The goal of this project is to provide powerful insights into the PostgreSQL database for Ruby apps that are not using the Heroku PostgreSQL plugin.
Queries can be used to obtain information about a Postgres instance, that may be useful when analyzing performance issues. This includes information about locks, index usage, buffer cache hit ratios and vacuum statistics. Ruby API enables developers to easily integrate the tool into e.g. automatic monitoring tasks.
You can check out this blog post for detailed step by step tutorial on how to optimize PostgreSQL using PG Extras library.
Alternative versions:
In your Gemfile
gem "ruby-pg-extras"calls and outliers queries require pg_stat_statements extension.
You can check if it is enabled in your database by running:
RubyPgExtras.extensionsYou should see the similar line in the output:
| pg_stat_statements | 1.7 | 1.7 | track execution statistics of all SQL statements executed |ssl_used requires sslinfo extension, and buffercache_usage/buffercache_usage queries need pg_buffercache. You can enable them all by running:
RubyPgExtras.add_extensionsGem expects the ENV['RUBY_PG_EXTRAS_DATABASE_URL'] or ENV['DATABASE_URL'] value in the following format:
ENV["DATABASE_URL"] = "postgresql://postgres:secret@localhost:5432/database_name"Alternatively you can set it using the module class method:
RubyPgExtras.database_url = "postgresql://postgres:secret@localhost:5432/database_name"You can run queries using a simple Ruby API:
RubyPgExtras.cache_hit+----------------+------------------------+
| Index and table hit rate |
+----------------+------------------------+
| name | ratio |
+----------------+------------------------+
| index hit rate | 0.97796610169491525424 |
| table hit rate | 0.96724294813466787989 |
+----------------+------------------------+By default the ASCII table is displayed, to change to format you need to specify the in_format parameter ([:display_table, :hash, :array, :raw] options are available):
RubyPgExtras.cache_hit(in_format: :hash) =>
[{"name"=>"index hit rate", "ratio"=>"0.97796610169491525424"}, {"name"=>"table hit rate", "ratio"=>"0.96724294813466787989"}]
RubyPgExtras.cache_hit(in_format: :array) =>
[["index hit rate", "0.97796610169491525424"], ["table hit rate", "0.96724294813466787989"]]
RubyPgExtras.cache_hit(in_format: :raw) =>
#Some methods accept an optional args param allowing you to customize queries:
RubyPgExtras.long_running_queries(args: { threshold: "200 milliseconds" })
You can customize the default public schema by setting ENV['PG_EXTRAS_SCHEMA'] value.
The simplest way to start using pg-extras is to execute a diagnose method. It runs a set of checks and prints out a report highlighting areas that may require additional investigation:
RubyPgExtras.diagnoseKeep reading to learn about methods that diagnose uses under the hood.
new_page_updatesThis is a diagnose check, not a standalone query method. On PostgreSQL 16 and newer, it uses the update_stats breakdown to flag tables where a significant share of updates placed the new row version on another heap page instead of staying on the original page. Those tables are worth reviewing for page-space pressure, row growth, and whether a lower table fillfactor would help.
By default, a table is reported when it has at least 10,000 cumulative updates and 20% or more of its updates are new-page updates. The report includes each table's new-page ratio, current fillfactor, and the percentage of same-page updates that were HOT. A low HOT-among-same-page value suggests indexed-column changes are also preventing HOT, so lowering fillfactor alone may not be enough.
You can override the default thresholds with environment variables:
ENV["PG_EXTRAS_NEW_PAGE_UPDATES_MIN_SAMPLE"] = "5000"
ENV["PG_EXTRAS_NEW_PAGE_UPDATES_MAX_PERCENT"] = "15"The underlying counters are cumulative, so compare their values over time rather than treating a single snapshot as definitive.
low_hot_same_pageThis is a diagnose check, not a standalone query method. On PostgreSQL 16 and newer, it uses the update_stats breakdown to flag tables where updates that stayed on the original heap page were almost never HOT. That usually means those updates modified indexed columns, so lowering fillfactor alone will not help.
By default, a table is reported when it has at least 10,000 cumulative updates and fewer than 10% of its same-page updates were HOT. The report includes each table's HOT-among-same-page ratio, same-page and new-page ratios, and current fillfactor. Review which columns your application updates and which indexes cover them; removing or adjusting indexes on frequently updated columns (or avoiding updating those columns) can restore HOT updates.
You can override the default thresholds with environment variables:
ENV["PG_EXTRAS_LOW_HOT_SAME_PAGE_MIN_SAMPLE"] = "5000"
ENV["PG_EXTRAS_LOW_HOT_SAME_PAGE_MIN_PERCENT"] = "5"The underlying counters are cumulative, so compare their values over time rather than treating a single snapshot as definitive.
missing_fk_indexesThis method lists actual foreign key columns (based on existing foreign key constraints) which don't have a supporting index. It's recommended to always index foreign key columns because they are commonly used for lookups and join conditions.
Composite indexes only support a foreign key when the foreign key column is the leftmost key column. For example, an index on (user_id, topic_id) supports user_id lookups, but topic_id still needs its own index or an index that starts with topic_id. Partial indexes are ignored for this check unless their predicate is exactly the foreign key column IS NOT NULL, because foreign key checks only need non-null values.
You can add indexes on the columns returned by this query and later check if they are receiving scans using the unused_indexes method. Please remember that each index decreases write performance and autovacuuming overhead, so be careful when adding multiple indexes to often updated tables.
RubyPgExtras.missing_fk_indexes(args: { table_name: "users" })
+---------------------------------+
| Missing foreign key indexes |
+-------------------+-------------+
| table | column_name |
+-------------------+-------------+
| feedbacks | team_id |
| votes | user_id |
+-------------------+-------------+
You can also exclude known/intentional cases using ignore_list (array or comma-separated string), with entries like:
"posts.topic_id" (ignore a specific table+column)"topic_id" (ignore this column name for all tables)"posts.*" (ignore all columns on a table)"*" (ignore everything)RubyPgExtras.missing_fk_indexes(args: { ignore_list: ["users.company_id", "posts.*"] })table_name argument is optional, if omitted, the method will display missing fk indexes for all the tables.
missing_fk_constraintsThis method shows columns that look like foreign keys but don't have a corresponding foreign key constraint yet. Foreign key constraints improve data integrity in the database by preventing relations with nonexisting objects. You can read more about the benefits of using foreign keys in this blog post.
Heuristic notes:
_id and the related table exists (underscored prefixes like account_user_id are supported)._id + _type) are ignored since they cannot be expressed as real FK constraints.You can also exclude known/intentional cases using ignore_list (array or comma-separated string), with entries like:
"posts.category_id" (ignore a specific table+column)"category_id" (ignore this column name for all tables)"posts.*" (ignore all columns on a table)"*" (ignore everything)RubyPgExtras.missing_fk_constraints(args: { table_name: "users", ignore_list: ["users.customer_id", "posts.*"] })
+---------------------------------+
| Missing foreign key constraints |
+-------------------+-------------+
| table | column_name |
+-------------------+-------------+
| feedbacks | team_id |
| votes | user_id |
+-------------------+-------------+
table_name argument is optional, if omitted, method will display missing fk constraints for all the tables.
table_infoThis method displays metadata metrics for all or a selected table. You can use it to check the table's size, its cache hit metrics, and whether it is correctly indexed. Many sequential scans or no index scans are potential indicators of misconfigured indexes. This method aggregates data provided by other methods in an easy to analyze summary format.
RubyPgExtras.table_info(args: { table_name: "users" })
| Table name | Table size | Table cache hit | Indexes cache hit | Estimated rows | Sequential scans | Indexes scans |
+------------+------------+-------------------+--------------------+----------------+------------------+---------------+
| users | 2432 kB | 0.999966685701511 | 0.9988780464661853 | 16650 | 2128 | 512496 |
table_schemaThis method displays structure of a selected table, listing its column names, together with types, null constraints, and default values.
…table_foreign_keysThis method displays foreign key constraints for a selected table. It lists foreign key name, source and target columns, and related table name.
RubyPgExtras.table_foreign_keys(args: { table_name: "users" })
+------------+---------------------+-------------+--------------------+---------------------+
| table_name | constraint_name | column_name | foreign_table_name | foreign_column_name |
+------------+---------------------+-------------+--------------------+---------------------+
| users | fk_rails_b2bbf87303 | team_id | teams | id |
+------------+---------------------+-------------+--------------------+---------------------+
index_infoThis method returns summary info about database indexes. You can check index size, how often it is used, whether it is unique/primary/partial, what predicate it uses, and what percentage of its total size are NULL values. Like the previous method, it aggregates data from other helper methods in an easy-to-digest format.
Index columns are read from PostgreSQL catalog metadata instead of parsing CREATE INDEX strings. This keeps expression indexes, operator classes, sort order, collations, partial predicates, and INCLUDE columns represented correctly. Columns shows the display form of key columns, while Included columns shows non-key columns added with INCLUDE (...).
…cache_hit
RubyPgExtras.cache_hit
name | rat暂无开放 Issues,或尚未同步最近议题。