Skip to content
← cd ~/writing

# production notes / article

PostgreSQL Doesn't Need More RAM. It Needs You to Stop Writing Terrible Queries.

Lessons from managing PostgreSQL performance in production: query optimization, memory pressure, connection pooling, and why scaling isn't always the answer.

17 October 2026 · 14 min read

PostgreSQL Doesn’t Need More RAM. It Needs You to Stop Writing Terrible Queries.

Lessons from spending an unreasonable amount of time convincing databases to behave.

It always starts with CPU utilization

If you’ve spent enough time managing production databases, you’ve probably experienced this sequence:

The application slows down.

Someone checks the monitoring dashboard.

PostgreSQL CPU utilization is sitting somewhere it has absolutely no business being.

And eventually, someone suggests:

“Can we just increase the database instance size?”

Sometimes that’s exactly what you need to do.

More often than I’d like, it’s an expensive way of postponing the actual problem.

I’ve spent a significant part of my engineering career managing PostgreSQL across Azure Database for PostgreSQL Flexible Server, AWS RDS, and self-hosted environments.

Along the way, I’ve dealt with memory-hungry queries, connection exhaustion, CPU spikes, long-running transactions, questionable indexing decisions, and databases that seemed perfectly content until actual users started using them.

This isn’t intended to be a comprehensive PostgreSQL tuning guide.

It’s a collection of things I learned while trying to keep databases reliable, performant, and reasonably affordable.

And occasionally succeeding.

1. The first lesson: CPU utilization is a symptom, not a diagnosis

Early on, I approached database performance problems the way many infrastructure engineers do.

High CPU? Check the instance size.

Memory pressure? Look at PostgreSQL configuration.

Too many connections? Increase max_connections.

There’s nothing inherently wrong with investigating infrastructure first. The mistake is assuming that resource saturation necessarily means insufficient resources.

One of the recurring challenges I encountered was PostgreSQL CPU usage climbing under relatively ordinary application workloads.

The instinctive response was to consider scaling the database.

But scaling only provides additional capacity. It doesn’t change how efficiently individual queries use that capacity.

A query performing a sequential scan across millions of rows doesn’t suddenly become a well-designed query because you gave PostgreSQL additional vCPUs.

It just gets more resources to perform the same work.

Finding the queries responsible

One of the most useful tools in my PostgreSQL troubleshooting workflow became pg_stat_statements.

Rather than looking at the database as one giant CPU-consuming process, I could examine how individual normalized queries contributed to overall execution time.

A typical starting point:

SELECT
    query,
    calls,
    ROUND(total_exec_time::numeric, 2) AS total_ms,
    ROUND(mean_exec_time::numeric, 2) AS avg_ms,
    rows
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

This query changed how I thought about database performance.

A query taking 800 milliseconds might look terrible, but if it’s executed twice a day, it’s probably not your biggest problem.

Meanwhile, a query taking 40 milliseconds and running 100,000 times can consume far more cumulative execution time.

Performance management isn’t just about making slow queries faster. It’s about identifying which queries consume the most resources at the scale at which they actually run.

One important detail: cumulative execution time is not the same as CPU time. It can include time spent waiting for I/O, so I correlate these statistics with wait events, system metrics, and query plans rather than treating them as a direct CPU breakdown.

That distinction becomes especially important under load.

2. EXPLAIN ANALYZE: where assumptions go to die

If there’s one PostgreSQL feature that fundamentally changed the way I approach query optimization, it’s EXPLAIN.

Specifically:

EXPLAIN (ANALYZE, BUFFERS)
SELECT *
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 100;

The query above is illustrative, not an actual production query.

SQL can look perfectly reasonable and still execute terribly.

A query plan can reveal things that aren’t obvious from reading SQL:

  • Sequential scans over large tables
  • Nested loops repeatedly processing unexpectedly large result sets
  • Expensive sorts
  • Incorrect row-count estimates
  • Temporary disk usage
  • Large numbers of buffer reads or hits

I learned to stop assuming that writing syntactically correct SQL meant writing efficient SQL.

Consider a query filtering records by customer and ordering them by creation time.

An index on customer_id might help with filtering.

But depending on the data distribution and access pattern, a composite index on (customer_id, created_at DESC) may allow PostgreSQL to satisfy both the filter and ordering more efficiently.

CREATE INDEX CONCURRENTLY idx_orders_customer_created
ON orders (customer_id, created_at DESC);

Of course, indexes aren’t free.

Every additional index consumes storage, adds maintenance overhead, and potentially increases the cost of inserts and updates.

I’ve learned to think of indexes as workload-specific optimizations, not decorations to attach to every column appearing in a WHERE clause.

The best index is the one justified by actual query plans and workload measurements.

And sometimes the correct optimization isn’t adding an index at all.

It’s rewriting the query.

When the database is doing exactly what you asked

Working with complex application queries and PL/pgSQL functions has reinforced an uncomfortable truth:

Sometimes PostgreSQL isn’t slow.

It’s executing an unnecessarily complicated request very efficiently, considering what you’ve asked it to do.

Repeated subqueries, unnecessary joins, poorly scoped aggregations, and expensive function calls can introduce enormous amounts of work.

When reviewing these queries, I’ve found it useful to ask:

“How much of this data does the application actually need?”

Not how much data the query can return.

How much it actually needs.

Those are surprisingly different questions.

3. The memory problem: PostgreSQL doesn’t allocate memory the way you might expect

One of my more memorable tuning exercises involved PostgreSQL memory utilization on Azure Flexible Server.

Memory-consuming queries were contributing to pressure on the database, and I started investigating both query behavior and server configuration.

Among the parameters I worked with were:

  • shared_buffers
  • statement_timeout
  • idle_in_transaction_session_timeout

After the changes and associated tuning work, I observed memory utilization around 35% in the environment I was monitoring.

That’s a useful outcome, but I wouldn’t attribute the improvement to any single parameter without a controlled before-and-after comparison.

The more interesting lesson was understanding how PostgreSQL consumes memory.

shared_buffers isn’t your entire memory budget

shared_buffers controls PostgreSQL’s shared buffer cache.

It’s important, but it isn’t a setting for limiting all PostgreSQL memory usage.

Backend processes also consume private memory, operating-system caching matters, and query execution can allocate additional memory for sorting, hashing, and other operations.

The parameter that deserves particular attention is work_mem.

It’s tempting to look at a server with plenty of RAM and conclude that increasing work_mem will make everything faster.

Except work_mem isn’t a global allocation shared by all queries.

Multiple execution nodes within a query can each receive their own memory allowance. Parallel workers and concurrent sessions can increase total consumption further.

Consequently, a configuration that looks perfectly reasonable for one query can create significant memory pressure when dozens of queries run simultaneously.

The lesson?

Never tune database memory parameters without considering concurrency.

A configuration isn’t safe simply because one query executes successfully.

It needs to behave under the actual workload.

Idle transactions are an underrated problem

Another parameter I became particularly interested in was:

idle_in_transaction_session_timeout

An application can open a transaction, execute a statement, and then leave the transaction open.

It may appear inactive, but the transaction can continue holding locks and an old snapshot. Depending on the workload, this can interfere with vacuum cleanup and contribute to table bloat.

Setting a sensible timeout can help prevent these forgotten transactions from lingering indefinitely.

But timeouts aren’t a substitute for fixing transaction handling in the application.

They’re guardrails.

And guardrails exist because someone, somewhere, will eventually do something interesting.

Usually in production.

4. Connection pooling: 500 connections do not mean 500 units of performance

Connection management deserves its own category of database incidents.

PostgreSQL uses a process-per-connection architecture, so maintaining a large number of active connections has real resource costs.

Applications running across multiple services or replicas can make connection counts grow surprisingly quickly.

Imagine 20 application instances, each configured with a maximum pool of 50 connections.

That’s a potential 1,000 database connections.

And that’s before considering administrative sessions, background jobs, reporting workloads, or additional services.

The database may have plenty of processing power, but that doesn’t mean it should have 1,000 active queries competing for CPU, memory, locks, and I/O.

I spent time looking at connection behavior and exploring pooling approaches, including PgBouncer, alongside application-side connection management.

A basic diagnostic query:

SELECT
    state,
    COUNT(*) AS connections
FROM pg_stat_activity
GROUP BY state
ORDER BY connections DESC;

This is useful for understanding connection state distribution.

From there, the questions become more interesting.

Are connections actually executing queries?

Are they waiting?

Are transactions being left open?

Are application pools configured based on measured workload, or did somebody pick a number that looked sufficiently enterprise-grade?

The goal isn’t to maximize connections.

The goal is to maintain enough concurrency to serve the workload without overwhelming the database.

Pooling is especially useful when applications create connections faster than PostgreSQL can efficiently manage them.

However, transaction pooling comes with compatibility considerations around session-level behavior and prepared statements. It’s something to test against the application rather than enabling blindly.

5. Autovacuum: the maintenance process you’ll notice when it isn’t working

PostgreSQL uses Multi-Version Concurrency Control (MVCC).

It’s one of the reasons PostgreSQL handles concurrent reads and writes so effectively.

It’s also why vacuum maintenance matters.

Updates and deletes can leave behind dead tuples that need to be reclaimed.

If cleanup cannot keep up with table churn, you can end up with:

  • Increasing table and index bloat
  • More pages scanned during query execution
  • Higher storage and cache pressure
  • Degrading query performance

I spent time investigating vacuum and analyze settings, particularly in environments with high database activity.

Useful indicators include:

SELECT
    schemaname,
    relname,
    n_live_tup,
    n_dead_tup,
    last_autovacuum,
    last_autoanalyze
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 20;

The dead-tuple counters are estimates, so they should be treated as investigation signals rather than exact measurements.

One thing I came to appreciate is that PostgreSQL maintenance shouldn’t be treated as a separate housekeeping concern.

It’s directly connected to application performance.

And tuning autovacuum doesn’t simply mean making it more aggressive everywhere.

More frequent vacuuming has costs of its own. The right settings depend on table size, update frequency, available I/O capacity, and workload behavior.

Sometimes the real blocker is a long-running transaction preventing cleanup from progressing.

Which brings us back to application behavior.

Everything is connected.

Unfortunately.

6. Moving between Azure, AWS, and self-hosted PostgreSQL

Over time, my work expanded beyond optimizing individual queries into evaluating the infrastructure running PostgreSQL.

I’ve worked with Azure Flexible Server, AWS RDS, and self-hosted PostgreSQL designs.

Each comes with different operational trade-offs.

Managed databases are excellent at removing a significant amount of infrastructure overhead.

Backups, patching options, platform monitoring, recovery capabilities, and availability features can all be considerably easier to manage.

But managed doesn’t mean self-optimizing.

You can still have inefficient queries, connection leaks, expensive execution plans, and application designs that create more database load than necessary.

When scaling stopped being the obvious solution

In one non-production environment, recurring CPU spikes, database instability, and infrastructure costs pushed me to evaluate an alternative deployment approach.

Simply scaling the managed instance wasn’t addressing the underlying workload behavior.

I explored a leaner self-hosted PostgreSQL architecture on AWS EC2, with supporting components for backups, monitoring, and administration.

The proposed stack included PostgreSQL, Pgpool-II, pgBackRest with S3-backed recovery storage, and Prometheus/Grafana observability.

This was a staging-oriented architecture exercise, not a claim that self-hosting is universally better than managed PostgreSQL.

In fact, the exercise reinforced how much operational responsibility managed services absorb.

Once you self-host, you own far more of the database lifecycle:

  • Backup integrity and restoration
  • Patch management
  • Storage capacity
  • Monitoring and alerting
  • Recovery procedures
  • Security hardening

You have more control.

You also have more ways to ruin your weekend.

The important question isn’t “Which platform is faster?”

It’s:

Which deployment model gives this workload the right combination of performance, reliability, operational control, and cost?

The answer can be different for development, staging, and production.

And it should be.

7. Observability changed how I approached database incidents

One of the biggest changes in my approach to PostgreSQL performance management was moving from reactive troubleshooting toward consistent observability.

A database dashboard showing CPU, memory, and disk utilization is useful.

But it doesn’t explain enough on its own.

When investigating a database issue, I want to understand several layers simultaneously.

Infrastructure: CPU saturation, memory availability, storage IOPS, throughput, and latency.

Database activity: Active sessions, wait events, blocked queries, and long-running transactions.

Query behavior: Execution frequency, cumulative execution time, query plans, buffer activity, and temporary file usage.

Application behavior: Connection pool saturation, request latency, timeouts, and changes in traffic patterns.

An application timeout doesn’t necessarily mean a query was executing slowly.

It might have spent time waiting for a connection.

Or waiting for a lock.

Or the database might have been overloaded by entirely unrelated requests.

A useful PostgreSQL diagnostic is:

SELECT
    pid,
    state,
    wait_event_type,
    wait_event,
    now() - query_start AS query_age,
    query
FROM pg_stat_activity
WHERE state <> 'idle'
ORDER BY query_start;

The important caveat here is that query_age isn’t always pure execution time. A backend may be waiting, and transaction state requires separate interpretation.

The more I worked on database observability, the more I realized that database performance is an end-to-end systems problem.

The database, application, connection pool, underlying storage, and traffic patterns all influence one another.

You can’t fully understand one by ignoring the others.

8. Why I stopped treating configuration tuning as the first solution

PostgreSQL has an impressive number of configuration parameters.

And it’s easy to spend an afternoon reading about the perfect values for shared_buffers, effective_cache_size, work_mem, and autovacuum settings.

I’ve done it.

More than once.

But I’ve gradually settled on a different order of operations:

  1. Understand the symptom. Is the problem latency, throughput, memory, CPU, connections, or lock contention?
  2. Identify the workload. Which queries, services, or transactions are responsible?
  3. Inspect execution plans. Are we reading too many rows, sorting unnecessarily, or using unsuitable access paths?
  4. Fix unnecessary work. Improve SQL, indexing, transaction handling, or connection usage.
  5. Tune PostgreSQL settings. Adjust parameters when the workload provides a reason.
  6. Evaluate scaling. Add capacity when measurements demonstrate that it’s needed.
  7. Verify the outcome. Compare representative workloads before and after the changes.

This approach isn’t always glamorous.

Sometimes the solution is a single index.

Sometimes it’s rewriting a function.

Sometimes you genuinely need more RAM.

And sometimes the problem is a service opening far more connections than it has any reason to.

The important part is knowing which problem you’re solving before changing things.

9. The biggest lesson: database reliability is a shared responsibility

One of the more interesting parts of my work has been supporting application developers while also being responsible for the infrastructure running their workloads.

Working alongside a development organization of around 20 developers reinforced that database performance can’t be owned exclusively by either the development team or the infrastructure team.

Developers influence query patterns, transaction scope, schema design, and application-side pooling.

Database and platform engineers influence configuration, capacity, monitoring, recovery, and operational safeguards.

Neither side can compensate indefinitely for poor decisions on the other.

A perfectly configured PostgreSQL instance won’t rescue an application that executes unnecessarily expensive queries at scale.

Likewise, beautifully optimized SQL won’t help much if the underlying database regularly runs out of resources or suffers from unresolved storage and availability problems.

Performance management works best when both sides understand the system they’re building.

Not when one team writes queries and the other team buys bigger servers.

10. Things I’d tell myself when I first started working with PostgreSQL

Looking back, a few principles have become particularly important to me.

Measure before tuning. If you don’t have a baseline, you won’t know whether your change actually improved anything.

Execution plans matter more than intuition. A query that looks efficient isn’t necessarily efficient.

Concurrency changes everything. A configuration that works for five sessions may behave very differently for five hundred.

Timeouts are safeguards, not optimizations. They can limit the damage caused by bad behavior, but they rarely address its root cause.

Indexes should be justified, not accumulated. Every index introduces a maintenance trade-off.

Database health isn’t just CPU and RAM. Locks, transaction age, vacuum progress, storage latency, and application connection behavior are equally important.

Scaling isn’t failure. Scaling without understanding the workload is the problem.

And finally:

Always test the recovery plan. A database that performs brilliantly but cannot be restored reliably isn’t a production-ready database.


Closing thoughts

I’ve spent years working with PostgreSQL, and I still find new ways to underestimate how complicated a seemingly simple database problem can become.

What initially looks like a CPU issue might be an indexing problem.

What looks like insufficient RAM might be excessive query concurrency.

What looks like a slow query might actually be lock contention.

And what looks like an infrastructure problem might turn out to be an application problem wearing an infrastructure-shaped disguise.

That’s what makes PostgreSQL performance management interesting to me.

It’s not about memorizing configuration values or collecting optimization tricks.

It’s about understanding how a system behaves, finding the real bottleneck, and making deliberate changes that can be measured and explained.

And if there’s one thing I’ve learned from all of this:

PostgreSQL is usually quite good at doing exactly what you ask it to do.

The interesting part is figuring out whether you should have asked it to do that in the first place.


Written by a DevOps/SRE engineer who has spent entirely too much time staring at pg_stat_activity, execution plans, and graphs that looked considerably better five minutes ago.

← Back to all notes · See the systems behind these notes ↗