Performance: find what is slow before you buy a bigger server

When a database gets slow, the answer is rarely more RAM. It is almost always one or two queries without the right index, a table full of dead rows, or too many connections. These are the queries we start with.

Last checked:

On this pageWhat this page covers
  1. Step 1: measure before you guess
  2. Step 2: find tables read end to end
  3. Step 3: text search with LIKE '%…%'
  4. Step 4: unused indexes cost on every write
  5. Step 5: dead rows and VACUUM
  6. Step 6: connections and PgBouncer

Step 1: measure before you guess

pg_stat_statements collects time and call counts for every query. The module is loaded at start-up, so it needs one restart.

# postgresql.conf – needs a restart
shared_preload_libraries = 'pg_stat_statements'
compute_query_id = on
pg_stat_statements.max = 10000
pg_stat_statements.track = all
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

-- The 15 queries using the most time in total
SELECT round(total_exec_time::numeric / 1000, 1) AS total_s,
       calls,
       round(mean_exec_time::numeric, 1)          AS mean_ms,
       rows,
       left(regexp_replace(query, '\s+', ' ', 'g'), 100) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 15;

Sort by total_exec_time, not just the average. A 5 ms query running a million times a day costs more than a 20-second report once a night. Reset with SELECT pg_stat_statements_reset(); after a change so you can see the effect.

Step 2: find tables read end to end

-- Large tables with many sequential scans = candidates for an index
SELECT relname, seq_scan, seq_tup_read, idx_scan, n_live_tup
FROM pg_stat_user_tables
WHERE n_live_tup > 10000
ORDER BY seq_tup_read DESC
LIMIT 15;

Then take the actual query and look at the plan:

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total, created_at
FROM orders
WHERE customer_id = 4711 AND status = 'open'
ORDER BY created_at DESC
LIMIT 20;

-- Composite index in the same order as WHERE + ORDER BY.
-- CONCURRENTLY does not block writes to the table.
CREATE INDEX CONCURRENTLY orders_customer_status_created_idx
    ON orders (customer_id, status, created_at DESC);

-- Partial index when you almost always query one status
CREATE INDEX CONCURRENTLY orders_open_created_idx
    ON orders (created_at) WHERE status = 'open';

If the plan shows Seq Scan on a large table and the estimated rows is far from the actual number, you are missing either an index or fresh statistics (ANALYZE orders;).

Step 3: text search with LIKE ‘%…%’

LIKE '%word%' cannot use a normal index and reads the whole table. In our own systems such queries ended up hitting a 30-second timeout. We moved search to Meilisearch, which returns ids, after which rows are fetched by primary key – that answers in 5–15 ms. The index is rebuilt every night; after an optimisation it takes 9–26 minutes against about 7.7 hours before, for 2.6 million addresses.

If you do not need a separate search engine, PostgreSQL handles a lot with trigram indexes:

CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX CONCURRENTLY customers_name_trgm_idx
    ON customers USING gin (name gin_trgm_ops);
-- Now this can use the index:
SELECT id, name FROM customers WHERE name ILIKE '%hansen%';

For text and vectors in one database, jajob uses tsvector and pgvector side by side.

Step 4: unused indexes cost on every write

-- Indexes never used since the last statistics reset
SELECT s.relname AS table_name, s.indexrelname AS index_name,
       pg_size_pretty(pg_relation_size(s.indexrelid)) AS size
FROM pg_stat_user_indexes s
JOIN pg_index i ON i.indexrelid = s.indexrelid
WHERE s.idx_scan = 0 AND NOT i.indisunique AND NOT i.indisprimary
ORDER BY pg_relation_size(s.indexrelid) DESC;

Do not drop on one day of statistics. Look at a full month including month-end, and check the index is not used on a replica.

Step 5: dead rows and VACUUM

PostgreSQL does not overwrite rows; an UPDATE creates a new version, and autovacuum cleans up the old one. On tables with many updates, the clean-up can fall behind.

SELECT relname, n_live_tup, n_dead_tup,
       round(100.0 * n_dead_tup / nullif(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,
       last_autovacuum, last_autoanalyze
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 15;

-- More frequent clean-up on one busy table (defaults are 20 % / 10 %)
ALTER TABLE events SET (autovacuum_vacuum_scale_factor = 0.02,
                        autovacuum_analyze_scale_factor = 0.01);

Do not run VACUUM FULL during working hours; it locks the table completely. Plain VACUUM and autovacuum do most of the work.

Step 6: connections and PgBouncer

Every PostgreSQL connection is a process. A web app with many workers can run out of connections before it runs out of CPU. Supabase shows this clearly in its plans: the smallest compute gives 60 direct connections but 200 through the pooler. On your own server, PgBouncer does the same:

; /etc/pgbouncer/pgbouncer.ini
[databases]
app = host=127.0.0.1 port=5432 dbname=app

[pgbouncer]
listen_addr = 127.0.0.1
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 500
default_pool_size = 20

pool_mode = transaction gives the most connections per server, but features that live in the session – SET, LISTEN and advisory locks – behave differently. Test the application against PgBouncer before switching.

MySQL and MariaDB: slow log and a time limit

-- Turn on the slow query log (until restart; also set it in my.cnf)
SET GLOBAL slow_query_log = ON;
SET GLOBAL long_query_time = 1;

-- MariaDB: 5-second limit on one query
SET STATEMENT max_statement_time = 5 FOR
SELECT id, plate FROM vehicles WHERE make = 'Toyota' ORDER BY id LIMIT 50;

-- MySQL 8: the same with an optimizer hint (milliseconds)
SELECT /*+ MAX_EXECUTION_TIME(5000) */ id, plate FROM vehicles WHERE make = 'Toyota' ORDER BY id LIMIT 50;

The last two look alike but are not. On MariaDB the MySQL hint does nothing. We found out when a browse over 12.6 million vehicles took 16–20 seconds or hung; only SET STATEMENT max_statement_time set a limit. It is one of the reasons we keep large datasets in MySQL and spend effort on indexes and limits rather than a migration.

When is it the server?

When the heavy queries have indexes, tables are cleaned up and connections go through a pooler, look at hardware. Only then does more RAM make sense, typically so the most-used tables and indexes fit in memory. In our CRM JaKun – our own product – the slowest p95 was 25.9 ms at 200,000 records and 107 fields on PostgreSQL 17, without special hardware.

Sources

Last reviewed: 2026-12-03

Questions about performance

How do I find the slowest query in PostgreSQL?

Enable pg_stat_statements and sort by total_exec_time. That shows the queries that use the most time in total, not just the slowest single ones.

Do more indexes always help?

No. Every index is updated on every write and takes disk space. Create them from measured queries and remove the ones that are not used.

Should we run VACUUM manually?

Usually not. Autovacuum handles it. Tune it for the few tables with many updates, and use VACUUM FULL only in a planned window.

Why does MariaDB ignore MAX_EXECUTION_TIME?

Because the hint is MySQL’s. On MariaDB use SET STATEMENT max_statement_time=N FOR ….

Fixed price, no commitment

Get a fixed price for your database task

Tell us briefly what you use today and what you want to achieve. A person answers by e-mail with a proposal and a fixed price before any work starts.

  • A fixed price before we start
  • An answer by e-mail, no calls
  • Your details are used only to answer you

Fields marked with * are required.

What is it about?