PostgreSQL Performance Optimization: How One Composite Index Reduced Query Time from 160ms to Under 1ms
By Ali Abbas Shah | Backend Architect
🚨 Your database might be the reason your API is slow. And buying a bigger server won't necessarily fix it.
One of the most common mistakes in backend performance optimization is scaling infrastructure before understanding what's actually happening inside the database.
Imagine a PostgreSQL query that executes in less than one millisecond with 500 test records.
Everything looks perfect during development.
Now deploy the same application with two million production records.
Suddenly:
- API response times increase dramatically.
- Database CPU utilization reaches 100%.
- Queries that previously took milliseconds start taking seconds.
- Application performance becomes unpredictable under load.
What changed?
The problem might not be your application server, framework, or infrastructure.
It could be a missing database index.
In this PostgreSQL performance optimization demonstration, I'll show how to identify an inefficient query execution plan and fix it using a simple composite index.
1. Understanding the Problem: Sequential Scan
PostgreSQL uses different execution strategies to retrieve data.
One of them is a Sequential Scan.
A Sequential Scan reads through the table to identify records matching the query conditions.
For a small table, this can be perfectly reasonable.
But when a table contains millions of records, repeatedly scanning large portions of the dataset can become expensive.
Consider an orders table containing two million records.
Suppose an application frequently executes queries filtering orders by customer and status.
Without an appropriate index, PostgreSQL may need to examine a large number of rows to find the matching records.
The result?
Increased disk I/O, CPU utilization, and query execution time.
This is why a query that performs well with a small development dataset can become a serious production bottleneck.
2. Diagnosing the Issue with EXPLAIN ANALYZE
Instead of immediately increasing server resources, I started by examining PostgreSQL's actual query execution plan.
The command:
EXPLAIN (ANALYZE, BUFFERS)
SELECT *
FROM orders
WHERE customer_id = 123
AND status = 'completed';
This provides valuable information about how PostgreSQL executes the query.
EXPLAIN ANALYZE helps identify:
- Actual execution time
- Rows examined and returned
- Sequential scans versus index scans
- Query planning and execution costs
BUFFERS provides information about shared buffer activity, including cache hits and disk reads.
The execution plan revealed that PostgreSQL was performing a Sequential Scan.
That was the bottleneck I needed to investigate.
3. The Fix: Create a Composite Index
The query frequently filtered records using two columns:
customer_idstatus
Instead of relying on repeated table scans, I introduced a composite index.
CREATE INDEX idx_orders_cust_status
ON orders (customer_id, status);
A composite index stores index entries based on multiple columns, allowing PostgreSQL to efficiently locate records matching the indexed conditions.
The column order matters.
It should reflect the application's actual query patterns, filtering conditions, and other index usage requirements.
For this particular demonstration, the composite index was designed around the customer and status filters.
4. The Execution Plan Changed
After creating the index, I ran the same query again using:
EXPLAIN (ANALYZE, BUFFERS)
SELECT *
FROM orders
WHERE customer_id = 123
AND status = 'completed';
The execution plan changed from:
Before: Sequential Scan
After: Bitmap Index Scan
PostgreSQL could now use the composite index to locate matching records instead of scanning the entire table.
The improvement was significant.
5. Performance Results
Here are the results observed in this demonstration:
| Performance metric | Before | After |
|---|---|---|
| Query execution | ~160 ms | Under 1 ms |
| Database CPU | ~100% | ~11% |
| Load-test latency | Seconds | ~1.5 ms |
| Infrastructure cost | — | No increase |
These are demonstration-specific results, not guaranteed improvements for every PostgreSQL workload.
The important takeaway is that we achieved a substantial performance improvement without upgrading the infrastructure.
A carefully selected database index addressed the underlying query execution problem.
6. Why This Matters for Backend Architecture
Database optimization isn't simply about adding indexes everywhere.
Indexes introduce their own costs:
- Additional disk storage
- More work during INSERT operations
- Additional maintenance during UPDATE and DELETE operations
- Index maintenance and vacuum considerations
Creating unnecessary indexes can actually hurt write-heavy workloads.
As a backend architect, I prefer to understand the application's query patterns before deciding which indexes to introduce.
My usual optimization approach:
- Identify the slow endpoint or database query.
- Capture the actual SQL being executed.
- Run
EXPLAIN (ANALYZE, BUFFERS). - Identify inefficient scans and excessive buffer reads.
- Review existing indexes and query selectivity.
- Introduce an appropriate index or optimize the query.
- Run the same test again.
- Compare execution plans and load-test results.
This approach helps solve the actual bottleneck rather than spending money on infrastructure without understanding the problem.
7. Final Thoughts: Optimize Before You Scale
A bigger server isn't always the answer to a slow application.
Sometimes, the problem is a missing index, an inefficient JOIN, excessive database queries, or a poorly designed data access pattern.
In this demonstration, a single composite index changed PostgreSQL's execution strategy and reduced query execution time from approximately 160 milliseconds to under one millisecond.
No infrastructure upgrade was required.
My Golden Rule: Before scaling your infrastructure, understand what your database is actually doing.
One well-designed index can sometimes deliver more performance improvement than an expensive server upgrade.
Watch the Complete Demonstration
See how PostgreSQL's execution plan changes from Sequential Scan to Bitmap Index Scan, and how a composite index improves query performance.
About the Author
Ali Abbas Shah is a Backend Architect and Senior Software Engineer specializing in scalable backend systems, PostgreSQL optimization, database performance, and production application architecture.
Website: https://aliabbasshah.com