PostgreSQL Query Planner Secrets: When EXPLAIN Lies to You
Meta description: Learn 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.
TL;DR
EXPLAIN ANALYZE shows you what happened — not what the planner thought would happen. The gap between estimated and actual rows is where production disasters hide. In multi-tenant SaaS schemas, stale statistics from infrequent autovacuum cycles silently corrupt query plans at scale. Diagnose it and fix it before your on-call rotation does.
The lie you trust every day
In my experience building production systems, there is one piece of output that engineers treat as gospel and probably should not: the row estimate in EXPLAIN ANALYZE.
EXPLAIN ANALYZE SELECT * FROM events WHERE tenant_id = 42 AND created_at > now() - interval '7 days';
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 rows is not a minor rounding error. It is a 13,000x miss. And it is the reason the planner chose a sequential scan over an index that would have made this query 400x faster.
Row estimate accuracy is the single most impactful variable in query plan quality, and most teams do not monitor it at all.
Where estimates come from
The planner derives row estimates from pg_statistic, populated by ANALYZE. Specifically, it uses:
most_common_vals/most_common_freqs— frequency of top N valueshistogram_bounds— distribution of values across the rangecorrelation— physical ordering alignment with logical orderingn_distinct— estimated unique value count
For a column like tenant_id in a SaaS schema, the distribution is inherently skewed. Your top 10 tenants may own 70% of the rows. pg_statistic captures this — but only if ANALYZE has run recently enough to reflect current data.
Autovacuum is not your friend at scale
Most teams get this wrong: autovacuum’s trigger threshold is proportional to table size, not tenant data growth.
| Table rows | Default autovacuum 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 an ANALYZE. Meanwhile, a single large tenant’s ingestion spike rewrites the data distribution completely — and the planner is operating on months-old statistics.
The regression is catastrophic and silent. No errors. No alerts. Just queries that were fast in January becoming 60-second timeouts in March.
Diagnosing stale statistics in production
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. Cross-reference with pg_stats to check if most_common_freqs reflects your actual tenant distribution:
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.
Multi-tenant schemas: the statistics problem multiplied
In a shared-schema multi-tenant architecture, global statistics mask per-tenant skew. The planner sees average behavior across all tenants — but query patterns are anything but average. A tenant with 50M rows runs the same query plan as one with 500 rows.
Partial indexes with per-tenant ANALYZE targeting help here:
-- Targeted analyze on a hot tenant's partition or partial index
ANALYZE events (tenant_id, created_at);
-- Or tune autovacuum per-table
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 on large tables alone has recovered 30–50% query performance in production systems I have worked on.
What to actually do about it
Three things worth doing now:
-
Alert on row estimate divergence. If you are not flagging queries where
actual rows / estimated rows > 10, you are not alerting on query plan quality — and those queries are your next outages.pg_stat_statementscombined withauto_explainat a threshold gives you this for free. -
Override autovacuum defaults on large, skewed tables. The defaults were designed for balanced workloads. SaaS schemas are not balanced. Set
autovacuum_analyze_scale_factor = 0.01andautovacuum_analyze_threshold = 500on any table over 10M rows with tenant-scoped access patterns. -
Increase statistics targets on high-cardinality filter columns.
ALTER TABLE events ALTER COLUMN tenant_id SET STATISTICS 500;gives the planner 10x more histogram buckets. RunANALYZEafter. The improvement in estimate accuracy on skewed distributions is immediate and measurable.
The query planner is not your enemy — but it is only as good as the data you feed it. Feed it well.
#backend #saas #architecture #microservices