Okay, the user is asking for help with PostgreSQL tuning at scale, specifically mentioning pooling, autovacuum, partitioning, index-only scans, and plan regression alerts. They’re likely a database administrator or a developer managing a large PostgreSQL deployment, and they want operational best practices for high-load environments.
First, I should break down each of their points into actionable advice. Pooling is about connection management—PgBouncer in transaction pooling mode is standard for scale. Autovacuum needs tuning because default settings don’t work for large tables; I should mention cost-based vacuuming, thresholds, and parallel vacuum. Partitioning is key for large tables, but they need to understand declarative partitioning, effective strategies like range or list, and constraints for partition pruning. Index-only scans depend on covering indexes and visibility map settings; I should explain how to design indexes for this and adjust vm_freeze. Plan regressions are tricky—pg_stat_statements for spotting regressions, pg_hint_plan for control, and automated testing with pg_regress or tools like PoWA.
The user might not have said it, but they probably want a balance between performance and maintenance overhead. They might also be worried about silent performance drops or outages from misconfiguration. I should emphasize monitoring and gradual changes. They didn’t mention hardware, but I should touch on that too—like SSD for I/O, RAM for caching.
I’ll structure it by topic, starting with connection pooling since it’s the first line of defense, then move to storage, autovacuum, partitioning, index tuning, and finally plan stability. Each section should have clear configurations and why they matter. Avoid diving too deep into one thing unless it’s critical, like autovacuum thresholds. Also, remind them to test changes in staging first.
Wait, they said “at scale,” so I should assume they’re dealing with terabytes or billions of rows. That means partitioning is non-negotiable, and autovacuum must be aggressive but controlled. Index-only scans can save I/O but need careful index design. Plan regressions are the sneaky ones—they happen after data changes or stats updates. Tools like pg_stat_statements and auto_explain are must-haves.
I’ll wrap up with a checklist: monitor, test, iterate. They might need a summary table for quick reference, but the response should be narrative. No need for fluff—just concrete steps and explanations. Let’s keep it practical.
Excellent question. Tuning PostgreSQL for scale is about systemic optimization, not just isolated knob-turning. Here is a battle-tested, actionable guide covering each of your points in order of operational impact.
1. Connection Pooling (The First Line of Defense)
Problem:max_connections is not for application connections. Each PostgreSQL backend consumes ~10MB RAM + overhead. At 1,000 connections, that's 10GB+ idle RAM.
Solution: PgBouncer in Transaction Pooling Mode
Why Transaction Pooling? Maximizes backend reuse. A client holds a connection only for the duration of a single transaction. This is ideal for web apps with short transactions.
Avoid Session Pooling: Only use if you rely heavily on session-level settings (e.g., SET commands, temporary tables, NOTIFY/LISTEN). Session pooling ties up a backend for the full client connection.
Key pgbouncer.ini Settings:
ini
pool_mode = transaction
max_client_conn = 1000 # Total client connections accepted
default_pool_size = 50 # Maximum *server* connections per database/user
reserved_pool_size = 10 # For superuser/urgent connections
min_pool_size = 10 # Keep at least 10 backends warm
server_idle_timeout = 300 # Recycle idle backends after 5 mins
server_check_delay = 10 # Health check interval
Application Layer: Ensure apps close connections on commit/rollback. Use PgBouncer as the single endpoint.
2. Autovacuum Tuning (The Silent Performance Killer)
Problem: Defaults are for small, rarely updated databases. At scale, tables bloat, transaction IDs wrap, and performance collapses.
Solution: Proactive, Table-Specific Configuration
Global postgresql.conf Adjustments:
conf
autovacuum = on
autovacuum_max_workers = 6 # Or # of vCPUs / 2, max 8-10
autovacuum_naptime = 10s # Reduce from default 1min for faster reaction
autovacuum_vacuum_scale_factor = 0.05 # Vacuum when 5% of rows changed
autovacuum_analyze_scale_factor = 0.02 # Analyze when 2% changed
autovacuum_vacuum_cost_delay = 2ms # Increase slightly to reduce I/O impact
autovacuum_vacuum_cost_limit = -1 # Disable cost limit (use with care)
Per-Table Overrides (CRITICAL for large tables):
For a 1TB table with 10M daily inserts:
sql
-- Disable autovacuum for archival partitions (no updates)
ALTER TABLE measurements_2024_01 SET (autovacuum_enabled = false);
-- For hot, large tables: more aggressive
ALTER TABLE events SET (
autovacuum_vacuum_scale_factor = 0.01, -- Vacuum at 1% changed
autovacuum_vacuum_threshold = 5000, -- +5k rows (min rows to trigger)
autovacuum_vacuum_cost_delay = 5ms -- Be more I/O friendly
);
Monitor Bloat: Use pgstattuple extension.
sql
SELECT schemaname, tablename,
pg_size_pretty(pg_total_relation_size('"'||schemaname||'"."'||tablename||'"')) as size,
round(100 * (deadtuple_count / (heap_tuple_count + dead_tuple_count))::numeric, 2) as dead_pct
FROM pg_stat_user_tables
WHERE schemaname NOT IN ('pg_catalog', 'information_schema');
Run Manual VACUUM (FULL, ANALYZE) only during maintenance windows on heavily bloated tables. Regular VACUUM (without FULL) is non-blocking and should be autovacuum's job.
3. Partitioning (Manageability & Performance at Scale)
Problem: Single huge tables (>100M rows) degrade DML, index maintenance, and query planning.
Time-Series:RANGE on timestamp (most common). Partition by day/week/month.
Multi-Tenant:LIST or HASH on tenant_id.
Avoid: Partitioning on non-pruning columns.
Example: Monthly Time-Series
sql
CREATE TABLE metrics (
ts timestamptz NOT NULL,
sensor_id int,
value float
) PARTITION BY RANGE (ts);
-- Create partitions ahead of time (automate this!)
CREATE TABLE metrics_202401 PARTITION OF metrics
FOR VALUES FROM ('2024-01-01') TO ('2024-02-01');
Critical Rules:
Partition Pruning Must Happen: Ensure WHERE clause includes partition key. Check EXPLAIN for "Append" with only relevant partitions.
Primary Keys/Unique Constraints must include the partition key.
Foreign Keys referencing partitioned tables are not supported (as of PG15). Consider denormalization or app-level integrity.
Indexes: Create local indexes per partition (default). Avoid global indexes (not supported until PG15+ for unique, and even then rare).
Maintenance: Detach old partitions for archiving (DETACH PARTITION), don't DROP. Use ATTACH PARTITION for new data.
4. Index-Only Scans (Avoiding Heap Access)
Problem: Even with an index, PostgreSQL often must visit the heap (table) to check visibility (MVCC). At scale, this is I/O-heavy.
Design Covering Indexes: Include all WHERE, JOIN, and SELECT columns in the index.
sql
-- Query: SELECT user_id, status FROM orders WHERE created_at > ? AND status = 'shipped'
CREATE INDEX idx_orders_covering ON orders (created_at, status) INCLUDE (user_id);
Ensure Visibility Map (VM) is Set: For a partition/index to be used for an index-only scan, all pages must be marked "all visible" in the VM. This requires:
Frequent VACUUM: Autovacuum must keep up. See Section 2.
vm_freeze Tuning: For very large tables, increase the age at which tuples are "frozen" to reduce vacuum frequency (trade-off with XID wrap risk).
Calculate:SELECT 2000000000 - age(datfrozenxid) FROM pg_database WHERE datname='yourdb'; Must stay > vacuum_freeze_table_age.
Check Usage:EXPLAIN (ANALYZE, BUFFERS) – look for "Index Only Scan" and "Heap Fetches: 0".
5. Plan Regression Alerts (Prevent Silent Performance Degradation)
Problem: PostgreSQL's planner is cost-based. Data distribution changes (even slightly) can cause catastrophic plan shifts (e.g., seq scan instead of index scan).
CREATE EXTENSION pg_stat_statements;
-- In postgresql.conf:
pg_stat_statements.max = 10000
pg_stat_statements.track = all
Query: Find high-call, high-latency queries that changed plan.
sql
SELECT query, calls, total_exec_time, rows,
mean_exec_time,
(total_exec_time / calls) as avg_ms
FROM pg_stat_statements
ORDER BY avg_ms DESC
LIMIT 10;
Tool 2: Store & Compare Plans
Use auto_explain to log slow queries with their plans.
conf
auto_explain.log_min_duration = 5000 # Log plans for queries >5s
auto_explain.log_analyze = true # Actual runtime stats
auto_explain.log_verbose = true
Tool 3: pg_hint_plan (Nuclear Option)
Extension to force specific plans via comments. Use sparingly for known problematic queries after thorough testing.
Indexes: Covering indexes for hot queries. Index-only scans enabled via aggressive vacuuming.
Monitoring & Alerting:
pg_stat_statements top 100 queries.
Bloat percentage > 20%.
pg_stat_user_tablesn_tup_upd + n_tup_del vs n_live_tup (churn).
Plan changes for high-impact queries.
Replication lag (if replicating).
Testing: Use pg_regress or a staging copy with pg_simulate to test plan changes under load.
Final Advice: Change one thing at a time and measure. Use EXPLAIN (ANALYZE, BUFFERS) religiously. At scale, the biggest wins are often reducing I/O via better indexing/partitioning and eliminating connection storms via pooling.
Would you like a deep dive on any specific tool (e.g., pg_stat_statements query analysis) or a sample Grafana dashboard for these metrics?