What we design around your workflow
A slow database is rarely one bad query. More often it is a cheap query run constantly, an index that matches the filter but not the sort, planner statistics that no longer fit the data, or a migration that locked a busy table at peak hours. A larger server postpones the problem without explaining it. We start from the database's own workload records and check each change against the plan that justified it.
Workload analysis
Rank query shapes by total time from pg_stat_statements or the MySQL slow query log.
Plan reading
Run EXPLAIN ANALYZE on costly queries and compare estimated with actual rows.
Index and schema design
Add composite, covering, and partial indexes that match real queries, and drop unused ones.
ORM query fixes
Replace N+1 loops and over-fetching with eager loading, joins, or set-based statements.
Safe schema changes
Build indexes concurrently and backfill in batches, so busy tables stay available.
Find the queries that cost the most in total
The slowest single query is often not the costliest. A lookup taking a few milliseconds on every page view can outweigh a slow monthly report, and an ORM loop issuing one query per row looks harmless until a large customer arrives. PostgreSQL's pg_stat_statements records calls and total execution time per normalized query; MySQL's slow query log captures statements above a time threshold. We rank by total time, then run EXPLAIN ANALYZE on the leaders. Large gaps between estimated and actual rows usually mean stale statistics or a query the planner misreads.
Total time first
Weigh call count against mean time, so frequent small queries are not overlooked.
Estimates against reality
Find the plan node where predicted and actual rows part ways; the problem usually starts there.
Safe plan capture
Wrap EXPLAIN ANALYZE of a write in a transaction that rolls back, because the statement really runs.
Primary sources
- PostgreSQL documentation: pg_stat_statementsTracks calls and execution time per normalized statement.
- PostgreSQL documentation: Using EXPLAINEXPLAIN ANALYZE runs the query and shows actual rows beside the estimates.
- MySQL 8.4 Reference Manual: The Slow Query LogLogs statements slower than long_query_time; off by default.
Index and shape the schema for real queries
An index helps only when it matches how a query filters and sorts. PostgreSQL scans a composite B-tree index most efficiently when its leading columns carry the conditions, so column order follows the query. A covering index adds payload columns with INCLUDE so the index alone can answer, and a partial index holds only the rows queries want, such as open orders. Every index slows writes, so unused ones go. Schema choices matter as much: right-sized data types, summary tables for heavy reports, and deliberate denormalization where reads dominate.
Column order
Put equality-filtered columns first and the range or sort column after them.
Narrow indexes
Index the small, hot subset of rows and keep payload columns few and slim.
Precomputed reads
Move heavy aggregates into summary tables or materialized views refreshed on a schedule.
Primary sources
- PostgreSQL documentation: Multicolumn IndexesMost efficient with constraints on the leading columns.
- PostgreSQL documentation: Index-Only Scans and Covering IndexesINCLUDE enables index-only scans but enlarges the index.
Keep connections, locks, and cleanup under control
Many slowdowns are queues rather than slow queries. PostgreSQL runs a separate backend process per connection, so hundreds of idle application connections waste memory; a pooler such as PgBouncer serves the same traffic with far fewer. A transaction left open keeps its locks and stops vacuum from removing recently dead rows, so tables bloat. Autovacuum and ANALYZE keep space reusable and statistics current, and busy tables often need tighter settings. When reads outgrow one server, replicas and caches relieve the primary, if the code tolerates slightly stale data.
Capped concurrency
Keep active connections near what the server can run at once; the pooler queues the rest.
Short transactions
Set idle-in-transaction and lock timeouts so one stuck session cannot block a table or hold back cleanup.
Replica-aware reads
Send reports and search to replicas, and keep read-after-write paths on the primary.
Primary sources
- PostgreSQL documentation: Client Connection DefaultsLock and idle-transaction timeouts; an open transaction prevents vacuuming recently dead rows.
- PostgreSQL documentation: Hot StandbyStandby data is eventually consistent with the primary.
Change large tables without taking the application down
Schema changes on big, busy tables need the most care. In PostgreSQL, most forms of ALTER TABLE take an ACCESS EXCLUSIVE lock, and a change that rewrites a large table, such as a column type change, keeps other sessions waiting while it runs. Safe migrations set a short lock timeout and retry, build indexes with CREATE INDEX CONCURRENTLY, add columns with constant defaults that need no rewrite, and backfill in small batches. Renames follow expand and contract: add the new shape, write to both, move readers, then drop the old.
Concurrent index builds
Build without blocking writes, then check for and drop any invalid index a failed build leaves behind.
Batched backfills
Update rows in small, throttled batches so replication and vacuum keep pace.
Expand and contract
Ship schema and code in steps that can each be rolled back on their own.
Primary sources
- PostgreSQL documentation: CREATE INDEXCONCURRENTLY avoids locking out writes but can leave an invalid index on failure.
- PostgreSQL documentation: ALTER TABLEMost forms lock ACCESS EXCLUSIVE; non-volatile defaults avoid a rewrite.
Realistic limits and operator controls
Faster reads can mean slower writes
Indexes, summary tables, and denormalized columns add write work, so each is weighed against the write load.
Managed databases limit access
Hosted services may restrict extensions, settings, or server access, narrowing the options.
Growth moves the target
A good plan today can change as tables grow, so monitoring continues after the fixes ship.
Frequently asked questions
Which databases do you work with?
Mainly PostgreSQL and MySQL, self-hosted or managed. The method carries over to other relational databases.
Can you fix slow queries without changing application code?
Partly. Indexes, statistics, and settings need no code change, but N+1 loops and over-fetching live in the application and are fixed there.
Will adding indexes slow down our writes?
Each index adds work to inserts and updates, so we add the few that serve important queries and remove ones the statistics show are unused.
Can MySQL tables change without downtime?
Many changes, yes. InnoDB online DDL performs instant and in-place alterations while other sessions keep reading and writing.
