Problem:
After deleting tens of millions of rows from a table, the client performed a VACUUM FULL and REINDEX on the table. Following these maintenance operations, the performance of large joins involving this table has significantly deteriorated, with query execution times increasing from minutes to hours. The task is to identify the cause of this performance regression and recommend solutions to restore the original performance levels.
The initial investigation established the following:
- The table is large and is regularly cleaned up with bulk deletes.
- The slowdown started after a PostgreSQL minor upgrade from 11.5 to 11.18: since then, queries using merge joins took hours rather than minutes.
- The affected query and the database logs were analyzed to find the cause.
Solution:
To improve query performance, the experts suggested the following optimizations:
- Index Optimization: Ensured that tables had appropriate indexes on columns used in filters and joins to speed up data retrieval.
- Partitioning: Aligned the partitioning scheme with query predicates to minimize partition scans.
- Limit Result Set: Added a LIMIT clause to reduce the data volume for sorting and joining.
- Rewrite the Query: Tried using Nested Loop Joins or Hash Joins instead of Merge Joins, depending on data distribution and join conditions.
- Aggregate Data: Used materialized views or summary tables for pre-aggregated data to reduce processing.
- Optimize Sort: Increased work_mem for sorting operations and optimized the Sort Key to reduce sorted columns.
- Analyze Query Plan: Reviewed the query plan to identify and address potential bottlenecks or costly operations. An optimized version of the query was also provided as an example.
Conclusion:
The client faced significant performance degradation after deleting tens of millions of rows and running VACUUM FULL and REINDEX on a table. Queries that previously took minutes now took hours, and merge-join queries slowed down after the upgrade from PostgreSQL 11.5 to 11.18. Based on the query and database logs, the experts recommended optimizations like index adjustments, partitioning alignment, limiting result sets, query rewriting, data aggregation, sort optimization, and query plan analysis to restore and enhance performance.