Software Studio
Back to Articles

PostgreSQL Performance: Queries That Scale

PostgreSQLDatabasePerformance
Cover illustration for PostgreSQL Performance: Queries That Scale

PostgreSQL is remarkably capable out of the box. But as your data grows from thousands to millions of rows, the queries that worked fine in development start timing out in production. Here's how to prevent that.

Start with EXPLAIN ANALYZE

EXPLAIN ANALYZE is your most important tool. Not EXPLAIN. EXPLAIN ANALYZE. The difference is that ANALYZE actually executes the query and shows real execution times, not estimates.

EXPLAIN ANALYZE
SELECT * FROM orders
WHERE user_id = 42
ORDER BY created_at DESC
LIMIT 20;

Every slow query investigation starts here. Look for:

  • Sequential scans on large tables.
  • Nested loops with high row counts.
  • Sort operations that spill to disk.

Because it runs the query, be careful with statements that modify data. Wrap those in a transaction and roll it back.

Build indexes around query patterns

Index strategy requires understanding your query patterns. A common mistake is adding indexes reactively: a query is slow, so you add an index on the WHERE clause column. Do that for a year and you have a dozen overlapping indexes slowing down every write.

Instead, analyze your application's query patterns as a whole. Composite (multi-column) indexes often serve multiple queries.

CREATE INDEX idx_orders_user_created
  ON orders (user_id, created_at DESC);

That one index serves both "find a user's recent orders" and "find a user's order on a date." Column order matters: lead with the column you filter on by equality.

Use partial indexes

Partial indexes are underused. If you frequently query WHERE published = true, index only those rows:

CREATE INDEX idx_published_articles
  ON articles (published_at)
  WHERE published = true;

This is smaller and faster than indexing the entire table. It works especially well when the filtered subset is much smaller than the full table, such as unprocessed jobs in a queue table or active rows among years of archived ones.

Pool your connections

Connection pooling is essential for serverless and container-based architectures. Each PostgreSQL connection consumes roughly 10MB of memory. Cloud Run or Lambda can spawn hundreds of instances, each wanting its own connection.

PgBouncer in transaction mode sits between your application and PostgreSQL, multiplexing many application connections over a smaller pool of database connections. The application believes it has a connection of its own, and the database sees a small, steady number.

Find and fix N+1 queries

The N+1 query problem is the most common performance issue in ORM-based applications. Loading a list of articles, then loading tags for each article individually, produces N+1 queries. It is invisible in development with ten rows and painful in production with ten thousand.

Prisma's include directive, or a JOIN in raw SQL, loads everything in one or two queries.

const articles = await prisma.article.findMany({
  where: { published: true },
  include: { tags: true },
});

Always check your ORM's query log in development. If one page load prints dozens of nearly identical queries, you've found one. More on structuring this in Prisma Patterns for Next.js Applications.

Paginate with cursors, not OFFSET

Pagination with OFFSET is a trap. OFFSET 10000 means PostgreSQL reads and discards 10,000 rows before returning your page. The deeper the page, the slower the query.

Cursor-based pagination is constant time regardless of how deep into the dataset you are:

SELECT * FROM articles
WHERE id > 10432   -- the last id from the previous page
ORDER BY id
LIMIT 20;

The database jumps straight to the right place in the index. The trade-off is that you can't jump to an arbitrary page number, which most interfaces don't need anyway.

Batch writes; don't loop

Inserting 1,000 rows one at a time means 1,000 round trips. A single INSERT with multiple VALUES clauses is dramatically faster.

INSERT INTO events (user_id, type)
VALUES (1, 'login'), (2, 'login'), (3, 'signup');

Prisma's createMany and updates with WHERE IN patterns handle this. The time saved is almost entirely network round trips, so the gain grows with the distance between your application and your database.

Monitor slow queries in production

PostgreSQL's pg_stat_statements extension tracks query performance statistics. Set log_min_duration_statement to capture queries above a threshold.

SELECT query, calls, mean_exec_time
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

Sorting by total time, not just average time, surfaces the fast query that runs a million times a day as well as the slow one that runs twice.

Review these weekly. Performance degradation is gradual and easy to miss until it becomes critical.

A quick checklist

  • Run EXPLAIN ANALYZE before changing anything.
  • Design composite indexes from real query patterns.
  • Use partial indexes for small, frequently queried subsets.
  • Put a pooler in front of the database on serverless platforms.
  • Check the query log for N+1 patterns.
  • Replace OFFSET with cursor pagination.
  • Batch inserts and updates.
  • Review pg_stat_statements every week.

Most slow databases are suffering from one or two of these. Measure first, fix the worst offender, and measure again.