,

How to Optimize a Database: The Complete Guide to the Six Levers

Optimize PostgreSQL and MySQL across six levers: queries, connections, caching, configuration, workload design, and measurement.

Cast AI diagram of six database optimization levers: queries, connections, caching, configuration, workload design, and measurement.

Database optimization is the process of reducing unnecessary database work and improving latency, throughput, reliability, and cost. For PostgreSQL and MySQL, the main levers are queries and indexes, connections, caching and read scaling, configuration, application workload patterns, and measurement. Start with the bottleneck your workload actually exhibits.

This guide explains how to choose among those six levers and validate the result. It covers managed and self-hosted databases, including databases serving Kubernetes applications. Cast AIโ€™s database optimization solution combines read-only recommendations with optional caching and connection pooling; the sections below explain where those capabilities fit.

Key takeaways

  • Optimize measured database work before buying more capacity.
  • Choose among six levers; no single configuration knob fixes every bottleneck.
  • Validate query correctness, transaction behavior, and consistency alongside latency.
  • Projected improvements and freed capacity are not the same as realized savings.

The six database optimization levers

LeverLook forFirst action
Queries and indexesHigh cumulative execution time or excessive examined rowsInspect plans and request-level statement counts.
ConnectionsPool waits, connection churn, too many idle backendsBudget pools across all replicas.
Caching and read scalingRepeated eligible reads or read-heavy contentionValidate result reuse and consistency needs.
Configuration and capacityMemory, CPU, I/O, or storage constraintsTest changes within a workload-wide budget.
Schema and workload patternsLong transactions, unbounded jobs, excessive data workReview data design and application behavior.
MeasurementUnclear regressions or unproven savingsCompare representative before-and-after windows.

What is database optimization, and how is it different from tuning?

Database tuning usually refers to adjusting configuration, queries, or execution behavior. Database optimization is the broader workflow: measure the workload, reduce unnecessary work, choose suitable architecture and capacity, and validate the outcome. A faster query is useful, but lower cost requires a separate capacity or billing change that preserves your service targets.

Begin by ranking statements by cumulative database execution time, alongside frequency and request latency. A moderately slow statement called often can matter more than an occasional slow report. Compare deltas over a representative window; cumulative counters can hide recent changes or resets.

-- PostgreSQL: requires pg_stat_statements to be installed and collecting statistics.
SELECT calls,
  round((100 * total_exec_time
    / NULLIF(sum(total_exec_time) OVER (), 0))::numeric, 1) AS pct_of_db_time,
  left(query, 100) AS query
FROM pg_stat_statements
WHERE queryid IS NOT NULL
ORDER BY total_exec_time DESC
LIMIT 20;

1. Queries and indexes: reduce work per request

Read the execution plan before changing SQL. Estimated plan cost is not elapsed time. PostgreSQL EXPLAIN (ANALYZE, BUFFERS) and MySQL EXPLAIN ANALYZE execute the statement, so use a controlled environment or an assessed diagnostic window. See the engine-specific workflow for slow PostgreSQL queries.

  • Compare estimated and actual row counts. Large differences can justify investigating statistics, data skew, or correlated predicates.
  • Look for unnecessary scanning, repeated subplans, and expensive joins. A sequential scan can be the correct choice when many rows are needed.
  • Inspect sort or hash spills, but do not automatically raise memory globally. First assess query shape, concurrency, and the resource budget.

Rewrite SQL when execution evidence shows avoidable work. Preserve NULL handling, duplicate rows, grouping, ordering, and pagination. Compare results as well as performance; a faster query returning different data is not an optimization.

Fix repeated fetching before adding more indexes

An N+1 pattern loads a set of parent rows, then issues a query per parent to fetch a relationship. Each query may be fast while the request remains slow. Use suitable eager loading or batching and verify request-level statement counts. See finding and fixing N+1 queries.

Add indexes on evidence; remove them cautiously

An appropriate index can reduce examined rows or avoid a sort, but increases storage and write maintenance. Use execution plans and representative traffic to justify additions. Low scan counts alone do not justify removal: statistics can reset, replica traffic is separate, and constraints or infrequent business-critical queries may depend on an index.

SELECT s.relname, s.indexrelname, s.idx_scan
FROM pg_stat_user_indexes s
JOIN pg_index i ON i.indexrelid = s.indexrelid
WHERE NOT i.indisunique AND NOT i.indisprimary
  AND s.idx_scan < 50
ORDER BY s.idx_scan;

Before you drop anything, treat that output as a candidate list. Confirm the stats window was not reset, check that no constraint depends on it, and ask whether a monthly close runs a query that needs it; a unique index backing ON CONFLICT is load-bearing at zero scans. When you cannot answer that, wait a full business cycle. The storage you save is small next to the incident you would buy.

On PostgreSQL, CREATE INDEX CONCURRENTLY can reduce write blocking, but performs additional work and may leave an invalid index after failure. Check completion and validity. MySQL online DDL has operation-specific restrictions; explicit unsupported algorithm or locking requirements return an error. Schedule and monitor either approach.

Cast AI PostgreSQL demo showing a suggested index and the recommendation reason.
A PostgreSQL index suggestion and its explanation in the Cast AI demo. Review and test the suggested SQL before applying it; this screen does not show an executed change.

2. Connections: budget concurrency across applications

An application autoscaler can multiply database connections as replicas increase. Budget the total across every service, worker, replica, user, and database pool. Compare active work, idle connections, and pool acquisition time with the databaseโ€™s actual capacity and configured limits.

An application-side pool may be sufficient for a stable workload. An additional pooler can help decouple client connection churn from backend connections, but it does not remove CPU or I/O limits. Increasing max_connections alone can add resource pressure instead of useful throughput.

Choose pooling mode according to session semantics. Transaction pooling can require changes for session variables, temporary objects, advisory locks, or prepared statements, depending on the pooler and version. For the alternatives and compatibility questions, see the connection pooling comparison.

3. Caching and read scaling: avoid or distribute reads

Caching avoids repeated database execution when the same results can safely be reused. A normalized statement with many calls is not necessarily cacheable: its parameter values and results may differ. Define freshness, invalidation, tenant isolation, and read-after-write behavior before enabling a cache.

Read replicas can offload suitable reads, but do not directly increase the primaryโ€™s write capacity. Replication lag and routing affect consistency. Keep reads that require the latest committed write on an appropriate path, and monitor lag under representative load.

SELECT client_addr, state, write_lag, flush_lag, replay_lag
FROM pg_stat_replication;
Cast AI PostgreSQL demo cache panel separating observed cache hits from projected cache hits.
The Cast AI PostgreSQL demo separates observed cache hits from projected cache potential. Projected values are estimates, not measured improvements or customer results.

4. Configuration and capacity: tune within a resource budget

PostgreSQL settings such as shared_buffers and work_mem, and MySQLโ€™s innodb_buffer_pool_size, influence memory and I/O behavior. Avoid treating a percentage of RAM as a universal answer. PostgreSQL operation-level memory can multiply across query nodes, workers, and concurrent sessions. Budget for the whole process and operating system, then test one change at a time.

Database scaling is different from application scaling

Scaling application pods changes database demand; it does not automatically scale database capacity. Database resizing can involve connection disruption, failover, or a warm-up period, depending on the service and operation. Check the provider or operatorโ€™s supported behavior and recovery plan.

For a managed database, reduced load can create room for a smaller instance or a different capacity setting. For a self-hosted database on Kubernetes, workload and node sizing require separate safeguards for persistence, availability, and disruption. Neither outcome follows automatically from a query rewrite.

Check storage latency, throughput, and capacity separately

A volume with ample free space can still be constrained by IOPS or throughput. Correlate database wait events and latency with storage metrics before provisioning more capacity. Local and network-attached storage have different durability and operational properties; compare them only within an explicit replication and recovery design.

For a practical diagnostic sequence, see disk capacity versus IOPS bottlenecks. If you run supported persistent volumes on Kubernetes, the storage autoscaling guide explains safe expansion. Volume growth is distinct from database query optimization.

5. Schema and workload patterns: reduce avoidable demand

Review data types, relationships, retention, batch sizes, and transaction scope. Avoid keeping a transaction open while calling an unrelated external service. Bound background jobs and retries so they do not amplify load during an incident. Schema changes and batching must preserve application semantics and business requirements.

Managed services automate some infrastructure operations, but teams still own schema, queries, access, capacity choices, and recovery requirements. For self-hosted databases, also validate backups, restore tests, replication, failover, storage behavior, and disruption controls. There is no single replica count or free-space percentage suitable for every deployment.

6. Measurement: prove the improvement and catch regressions

Track query time and frequency, execution plans, lock waits, connections, resource use, and cost alongside application latency and errors. Preserve the measurement window and note statistics resets. The database observability guide explains how these signals work together.

When a database serves Kubernetes workloads, correlate changes in pod count and application connection pools with database activity. If database execution does not explain request latency, investigate client pool wait, network time, retries, and downstream calls rather than assuming the database is responsible.

How to measure the financial result

Separate observed technical improvement from realized savings. Compare equivalent workload windows and record instance, storage, I/O, replica, and commitment charges. A faster query can free headroom without changing a fixed instance bill.

After validating reliability and latency, evaluate the capacity or billing changes that could convert headroom into savings. Use current provider pricing and your actual workload instead of applying a generic savings percentage.

How Cast AI supports the optimization workflow

Observe and recommend. Cast AI Performance Advisor analyzes supported PostgreSQL and MySQL query statistics and metadata through read-only access. It surfaces query and index recommendations, with SQL and plan evidence for review. Projected improvement is an estimate to validate. The advisor does not execute DDL or silently modify application code.

Reduce suitable repeated work. Optional proxy caching can serve eligible repeated reads and apply supported invalidation behavior. Validate query compatibility, transactions, freshness, and write routing before enabling it. Begin with observation or passthrough as appropriate; do not assume every query or workload should be cached.

Manage backend connections. Cast AI uses ProxySQL for MySQL and PgDog for PostgreSQL. Pooling can reuse backend connections independently of client connections, subject to session and transaction behavior. Size and test it against the real application rather than assuming a fixed multiplexing ratio.

These capabilities address different parts of the same workload. Start with read-only recommendations, review the highest-impact changes, and enable proxy features where they fit. The Database Optimizer product page describes the current offering; use the setup documentation to check deployment prerequisites.

What remains your responsibility

Keep ownership of configuration changes, application fetching, transaction boundaries, schema migrations, backups, recovery, and capacity decisions. Performance Advisorโ€™s read-only recommendation workflow does not automatically apply these changes. A cache or pooler also cannot guarantee that every latency or cost problem disappears.

Conclusion: optimize in the order the evidence supports

Measure first, identify the bottleneck, make one controlled change, and compare the result. Fix unnecessary query and application work, then assess indexing, pooling, caching, configuration, and capacity as the evidence warrants. Treat reliability and correctness as acceptance criteria alongside speed.

For implementation-level examples, continue with database optimization techniques. If you need help selecting a platform for the workflow, compare database optimization tools.

Frequently asked questions

What is database optimization?

It is the process of reducing unnecessary database work and improving performance, reliability, and cost. It includes queries and indexes, connections, caching, configuration, workload design, and measurement.

What is the difference between database optimization and tuning?

Tuning usually means adjusting queries, settings, or execution behavior. Optimization is broader: it includes workload design, architecture, capacity, and validating business outcomes.

Where should I start with a slow database?

Measure a representative workload and rank statements by cumulative execution time. Check plans, request-level query counts, connections, and lock waits before selecting a fix.

Do indexes always improve performance?

No. An appropriate index can reduce read work, but indexes consume storage and add write maintenance. Use execution plans and workload evidence, and check dependencies before removing one.

Does connection pooling fix slow queries?

Pooling can reduce connection churn or backend connection pressure. It does not by itself repair inefficient SQL, N+1 fetching, or lock contention.

When should I use caching or read replicas?

Use caching when results can safely be reused under defined consistency rules. Use read replicas for eligible read workloads, accounting for lag and routing. Neither directly solves every write bottleneck.

Does Cast AI automatically apply database recommendations?

Performance Advisor analyzes query statistics and metadata with read-only access and provides changes for review. It does not execute DDL. Optional proxy capabilities provide caching and connection pooling for compatible workloads.

How do I verify database optimization savings?

First validate correctness, latency, errors, and resource use over comparable workload windows. Then measure actual billing after any capacity or pricing change. Faster queries or projected gains alone are not realized savings.

Cast AI โ€บ Blog โ€บ How to Optimize a Database: The Complete Guide to the Six Levers