--- title: "PostgreSQL Query Planner Secrets: How EXPLAIN ANALYZE Lies to You" published: true description: "Why PostgreSQL's EXPLAIN ANALYZE misleads even senior engineers, how stale pg_statistic data triggers catastrophic plan regressions, and what to do in multi-tenant SaaS schemas." tags: postgresql, architecture, performance, api canonical_url: https://blog.mvpfactory.co/postgresql-query-planner-secrets --- ## What We Are Building By the end of this workshop, you will understand why the row estimates in `EXPLAIN ANALYZE` are the single most impactful — and most misunderstood — variable in PostgreSQL query plan quality. We will diagnose stale statistics in a live schema, understand why autovacuum silently fails at scale, and apply three concrete fixes that recover real production performance. ## Prerequisites - PostgreSQL 13+ with superuser or monitoring access - A multi-tenant SaaS schema (or willingness to follow along conceptually) - Familiarity with `EXPLAIN ANALYZE` output --- ## Step 1: Recognize the Lie You Trust Every Day Let me show you a pattern I see in every production incident review. Engineers run this query:
sql
EXPLAIN ANALYZE SELECT * FROM events WHERE tenant_id = 42 AND created_at > now() - interval '7 days';
And get output like this:
plaintext
Seq Scan on events (cost=0.00..48234.12 rows=14 width=312)
(actual rows=182,441 loops=1)
That `rows=14` estimate versus `182,441` actual is not a rounding error. It is a 13,000x miss — and the reason the planner chose a sequential scan over an index that would have made this query 400x faster. `EXPLAIN ANALYZE` shows you what *happened*, not what the planner *thought* would happen. That gap is where production disasters hide. --- ## Step 2: Understand Where Estimates Come From The planner derives row estimates from `pg_statistic`, populated by `ANALYZE`. It uses four key signals: - **`most_common_vals` / `most_common_freqs`** — frequency of top N values - **`histogram_bounds`** — distribution across the value range - **`correlation`** — physical vs. logical ordering alignment - **`n_distinct`** — estimated unique value count For `tenant_id` in a SaaS schema, distribution is inherently skewed. Your top 10 tenants may own 70% of rows. `pg_statistic` captures this — but only if `ANALYZE` has run recently enough to reflect current data. --- ## Step 3: Diagnose Stale Statistics in Production Here is the minimal setup to get this working. Run this query to find tables with dangerous staleness ratios:
sql
SELECT
schemaname,
relname,
n_live_tup,
n_dead_tup,
last_analyze,
last_autoanalyze,
(n_mod_since_analyze::float / NULLIF(n_live_tup, 0)) AS staleness_ratio
FROM pg_stat_user_tables
WHERE n_mod_since_analyze > 10000
ORDER BY staleness_ratio DESC;
A `staleness_ratio` above `0.1` on a high-traffic table is a red flag. Then cross-reference with `pg_stats` to verify your actual tenant distribution is reflected:
sql
SELECT most_common_vals, most_common_freqs
FROM pg_stats
WHERE tablename = 'events' AND attname = 'tenant_id';
If your largest tenant is not in `most_common_vals`, the planner is flying blind. --- ## Step 4: Fix Autovacuum Defaults on Large Tables The docs do not mention this prominently enough: autovacuum's trigger threshold is proportional to table size, not tenant data growth rate. | Table rows | Default threshold | Rows changed before trigger | |------------|------------------|-----------------------------| | 1M | 20% + 50 rows | ~200,050 | | 50M | 20% + 50 rows | ~10,000,050 | | 500M | 20% + 50 rows | ~100,000,050 | A 500M-row `events` table needs 100 million row changes before autovacuum triggers. A single large tenant's ingestion spike rewrites the data distribution — and the planner operates on months-old statistics. No errors. No alerts. Just queries that were fast in January becoming 60-second timeouts in March. Apply targeted fixes at the table level:
sql
ALTER TABLE events SET (
autovacuum_analyze_scale_factor = 0.01,
autovacuum_analyze_threshold = 1000
);
Dropping `autovacuum_analyze_scale_factor` from `0.2` to `0.01` alone has recovered 30–50% query performance in production systems I have worked on. --- ## Step 5: Increase Statistics Targets on Skewed Columns
sql
ALTER TABLE events ALTER COLUMN tenant_id SET STATISTICS 500;
ANALYZE events;
This gives the planner 10x more histogram buckets. The improvement in estimate accuracy on skewed distributions is immediate and measurable. For hot tenants, targeted partial analysis also helps:
sql
ANALYZE events (tenant_id, created_at);
--- ## Gotchas **Alert on row estimate divergence, not just slow queries.** If you are not flagging queries where `actual rows / estimated rows > 10`, you are missing the leading indicator. `pg_stat_statements` combined with `auto_explain` at a threshold gives you this cheaply. **Global statistics mask per-tenant skew.** In shared-schema multi-tenant architectures, the planner sees average behavior across all tenants. A tenant with 50M rows runs the same query plan as one with 500 rows. There is no built-in solution — you manage this through statistics targets and autovacuum tuning. **`ANALYZE` is not free, but stale statistics are more expensive.** Running targeted `ANALYZE` on large tables during off-peak hours is a tradeoff worth making. A 60-second production timeout costs more than a 2-second `ANALYZE` pass. --- ## Conclusion The query planner is not your enemy — but it is only as good as the data you feed it. Row estimate accuracy is the variable most teams never monitor and the one most likely to cause silent, catastrophic regressions at scale. Three actions to take today: 1. Alert on estimate divergence greater than 10x using `pg_stat_statements` + `auto_explain` 2. Override autovacuum defaults on any table over 10M rows with tenant-scoped access patterns 3. Set `STATISTICS 500` on high-cardinality filter columns and run `ANALYZE` **Relevant docs:** - [PostgreSQL EXPLAIN documentation](https://www.postgresql.org/docs/current/sql-explain.html) - [pg_statistic system catalog](https://www.postgresql.org/docs/current/catalog-pg-statistic.html) - [Autovacuum tuning](https://www.postgresql.org/docs/current/routine-vacuuming.html#AUTOVACUUM)