Read Medium logo
No Results
Translate to
Read Medium Logo
Free OpenAI o1 chatTry OpenAI o1 API
Read Medium logo
No Results
Translate to
avatarCode Geass

Summary

The article outlines a methodical approach to optimizing a PostgreSQL query from a 150-second execution time to under 2 seconds for a dataset with billions of records.

Abstract

The article addresses the challenge of optimizing a slow-running SQL query on a PostgreSQL database with billions of records. Initially, the query took over 150 seconds to calculate the total transaction amount per user. The optimization process began with adding an index on the user_id column, reducing the execution time to approximately 80 seconds. Subsequent partitioning of the table by transaction date further improved performance, dropping the time to around 20 seconds. The final and most effective optimization involved creating a materialized view to pre-calculate and store the aggregated sums, resulting in a query time of less than 2 seconds. The article also discusses handling edge cases such as skewed data distribution, high cardinality columns, frequent data updates, and join performance issues, emphasizing the importance of considering these factors for consistent performance. The author concludes with best practices for indexing, partitioning, and materialized views, and suggests exploring further optimizations like automated partition management, parallel query execution, and caching layers for even larger datasets.

Opinions

  • The author believes that traditional relational databases like PostgreSQL can handle large datasets efficiently with proper optimization.
  • Indexing is considered a fundamental step in query optimization, but it may not be sufficient on its own for very large datasets.
  • Table partitioning is a powerful technique to reduce query execution time by limiting the amount of data scanned.
  • Materialized views are highly effective for pre-computing complex aggregates, thereby saving query execution time.
  • The author emphasizes the importance of considering and addressing edge cases to ensure optimal query performance.
  • The article suggests that even the most demanding datasets can be managed efficiently in PostgreSQL by employing the right strategies and tools.

Optimizing PostgreSQL Queries: From 300 Seconds to 2 Seconds for Billions of Records

https://readmedium.com/intro-to-postgresql-c8da31335c34

Handling data in the billions is challenging and often pushes the limits of traditional relational databases. PostgreSQL, while robust, requires careful optimization to handle such large datasets efficiently. This article explores various strategies for optimizing PostgreSQL queries to reduce execution time dramatically — from over 150 seconds to just 2 seconds — when dealing with billions of records.

Disclaimer: GPT-4 assisted me in writing this article, combining its insights with my personal experience.

Table of Contents

  1. Understanding the Problem
  2. Generating Billions of Records
  3. Original SQL Query
  4. First Optimization: Indexes
  5. Second Optimization: Partitioning
  6. Third Optimization: Materialized Views
  7. Handling Edge Cases
  8. Final Results and Best Practices

Understanding the Problem

When working with massive datasets in PostgreSQL, poor table design, lack of indexing, and suboptimal query structures can lead to significant performance issues. In this scenario, we are optimizing a query that must process billions of records from a single table.

Without optimization, this query was initially taking more than 150 seconds to execute, which is far from acceptable in a production environment.

Generating Billions of Records

To simulate this scenario, let’s first generate a table with billions of records using PostgreSQL’s powerful data generation capabilities. The following table structure will be used:

CREATE TABLE transactions (
  transaction_id serial PRIMARY KEY,
  user_id int NOT NULL,
  transaction_date date NOT NULL,
  amount decimal(10,2) NOT NULL
);

Data Generation

The following stored procedure will generate 1 billion records:

DO $$
BEGIN
    FOR i IN 1..1000000 LOOP
        INSERT INTO transactions (user_id, transaction_date, amount)
        SELECT
            trunc(random() * 10000 + 1),
            '2020-01-01'::date + trunc(random() * 1000),
            trunc(random() * 1000 + 1)::decimal(10,2)
        FROM generate_series(1, 1000);
    END LOOP;
END $$;

This script inserts 1 billion transaction records, simulating a real-world, large-scale database.

Original SQL Query

Our initial query attempts to calculate the total transaction amount for each user:

SELECT user_id, SUM(amount) AS total_amount
FROM transactions
GROUP BY user_id;

Without any indexes, this query takes over 150 seconds to complete. The Explain output shows a full table scan, which is highly inefficient.

First Optimization: Indexes

Adding Indexes

To improve performance, we start by adding an index to the user_id column, which is used in the Group By clause:

CREATE INDEX idx_user_id ON transactions (user_id);

Revised Query Execution

After adding the index, the query’s execution time dropped to around 80 seconds. While this is an improvement, it’s still not fast enough. The Explain output shows that the index is being used, but the process remains I/O-bound due to the sheer volume of data.

Second Optimization: Partitioning

Implementing Table Partitioning

To further optimize the query, we introduce partitioning based on transcation_date. Partitioning allows PostgreSQL to divide the table into smaller, more manageable pieces, thereby reducing the data each query needs to scan.

CREATE TABLE transactions_partitioned (
  transaction_id serial PRIMARY KEY,
  user_id int NOT NULL,
  transaction_date date NOT NULL,
  amount decimal(10,2) NOT NULL
) PARTITION BY RANGE (transaction_date)
;
CREATE TABLE transactions_2020 PARTITION OF transactions_partitioned
FOR VALUES FROM ('2020-01-01') TO ('2021-01-01');

CREATE TABLE transactions_2021 PARTITION OF transactions_partitioned
FOR VALUES FROM ('2021-01-01') TO ('2022-01-01');

Query Execution on Partitioned Tables

After partitioning, the query execution time decreased significantly to around 20 seconds. The Explain plan now shows that only the relevant partitions are being scanned, which reduces the amount of data processed.

Third Optimization: Materialized Views

Creating a Materialized View

To push the optimization further, we introduce a materialized view to pre-calculate the sums for each user, reducing the need to repeatedly aggregate the entire dataset

CREATE MATERIALIZED VIEW user_transaction_sums AS
SELECT user_id, SUM(amount) AS total_amount
FROM transactions_partitioned
GROUP BY user_id;

Final Query Using Materialized View

The final query is now a simple SELECT from the materialized view:

SELECT * FROM user_transaction_sums;

This query executes in less than 2 seconds, achieving the performance target.

Handling Edge Cases

While the above optimizations significantly improved performance, there are several edge cases that need to be considered to ensure consistent results and avoid unexpected performance degradation.

1. Handling Skewed Data Distribution

In cases where the data is heavily skewed, with certain user_ids having a disproportionate number of transactions, partitioning and indexing strategies might not be sufficient. To address this, consider:

  • Hash Partitioning: Use hash partitioning on user_id to evenly distribute data across partitions.
  • Partial Indexes: Create partial indexes on frequently accessed users, e.g., users with the most transactions.
CREATE INDEX idx_high_activity_users ON transactions (user_id) 
WHERE user_id IN (SELECT user_id FROM transactions GROUP BY user_id HAVING COUNT(*) > 1000000);

2. High Cardinality Columns

If the dataset includes high-cardinality columns (e.g., transaction_id), indexing these may lead to large index sizes that negatively impact performance. In such cases:

  • Composite Indexes: Use composite indexes combining high-cardinality columns with lower-cardinality columns to improve selectivity.
CREATE INDEX idx_composite_user_date ON transactions (user_id, transaction_date);
  • Clustered Indexing: Consider clustering the table by user_id, allowing sequential reads, which are faster for grouped queries.

3. Frequent Data Updates

For databases with frequent updates or inserts, maintaining materialized views and indexes can become costly. In such scenarios:

  • Incremental Updates: Use PostgreSQL’s Refresh Materialized view concurrently to update materialized views without locking the table.
REFRESH MATERIALIZED VIEW CONCURRENTLY user_transaction_sums;
  • Avoid Over-Indexing: Balance the number of indexes with the write workload. Too many indexes can slow down inserts and updates.

4. Join Performance Issues

When dealing with joins between large tables, PostgreSQL’s query planner may not always choose the most efficient plan, especially with complex queries. Solutions include:

  • Join Hints: While PostgreSQL doesn’t natively support optimizer hints like some other databases, restructuring queries to encourage nested loop joins or hash joins based on your dataset can improve performance.
  • Query Rewriting: Rewrite queries to simplify joins, possibly using Common Table Expressions (CTEs) to break down complex queries into more manageable parts.
WITH user_sums AS (
  SELECT user_id, SUM(amount) AS total_amount
  FROM transactions
  GROUP BY user_id
)
SELECT u.user_id, u.name, us.total_amount
FROM users u
JOIN user_sums us ON u.user_id = us.user_id;

5. Query Timeouts

For particularly long-running queries, it’s essential to handle potential timeouts gracefully:

  • Query Cancellation: Implement logic to catch and handle query cancellations, especially in client applications.
BEGIN;
SET statement_timeout = '30s';
SELECT user_id, SUM(amount) FROM transactions GROUP BY user_id;
COMMIT;
  • Progressive Aggregation: Break down large aggregations into smaller batches or stages, potentially using temporary tables to store intermediate results.

Final Results and Best Practices

The combination of indexing, partitioning, materialized views, and handling edge cases transformed a 150-second query into a sub-2-second query. Here are the key takeaways:

  1. Indexes: Start with proper indexing on columns used in Where, Join , and Group By clauses.
  2. Partitioning: Use table partitioning to break down large tables, reducing the data scanned by queries.
  3. Materialized Views: Pre-compute complex aggregates to save query execution time.
  4. Edge Case Handling: Be aware of and address edge cases like skewed data, high cardinality, frequent updates, and complex joins.

Next Steps

For even larger datasets, consider:

  • Using pg_partman for automated partition management.
  • Exploring parallel query execution and tuning PostgreSQL’s settings for optimal performance.
  • Leveraging caching layers like Redis for frequently accessed data.

By applying these strategies, PostgreSQL can handle even the most demanding datasets efficiently.

Postgresql
Database
Software Development
Software Engineering
Distributed Systems
Recommended from ReadMedium
avatarDylan Smith
Interview: How to Check Whether a Username Exists Among One Billion Users?

My articles are open to everyone; non-member readers can read the full article by clicking this link.

9 min read
avatarRabinarayan Patra
Should You Use UUIDs for Database Keys?

UUIDs offer uniqueness in databases but come with performance costs. Learn when to use them, their drawbacks, and alternatives loved by…

5 min read
avatarOliver Foster
Why do many people not recommend using JWT?

My article is open to everyone; non-member readers can click this link to read the full text.

5 min read
avatarJacob Bennett
The 5 paid subscriptions I actually use in 2025 as a Staff Software Engineer

Tools I use that are cheaper than Netflix

5 min read
avatarManjula Piyumal
Mastering Kafka: Advanced Concepts Every Senior Software Engineer Should Know

Photo by Pietro Jeng on Unsplash

12 min read
avatarProbir Sarkar
Database Performance Benchmark: PostgreSQL 17 vs. MySQL 9 vs. MongoDB 8

Not a member? Read for free

7 min read