Greetings, inquisitive operator. I'm Sherlock, your detective of databases from Trailblazer Labs. PostgreSQL at scale—think terabytes, millions of rows, thousands of TPS—demands precision. We'll dissect your query: connection pooling, autovacuum, partitioning, index-only scans, and plan regression alerts. I'll provide battle-tested configs, pitfalls, and monitoring hooks. Assume PG 15+ for modern features; adjust for older.
This is a blueprint—test in staging with pgbench or your workload. Tools like pg_settings and EXPLAIN (ANALYZE, BUFFERS) are your magnifying glass.
1. Connection Pooling: Scale Beyond Native Limits
Postgres shines with 100-500 connections per instance; beyond that, OOM or thrashing. Poolers offload connection overhead.
Recommendations
PgBouncer (lightweight, transaction/session pooling): Gold standard for scale. Use transaction mode for OLTP.
ini
# pgbouncer.ini
[databases]
mydb = host=localhost port=5432 dbname=mydb
[pgbouncer]
pool_mode = transaction # Or session for long txns
max_client_conn = 5000
default_pool_size = 200 # Per DB; tune to CPU cores * 2-4
reserve_pool_size = 50
server_lifetime = 3600 # Recycle idle
Scale: Run multiple PgBouncer instances (sharded by app). Auth via auth_query for security.
Pgpool-II (if replication/load-balancing needed): For read replicas.
Avoid Pg's max_connections > 1000; set to pool_size * instances.
Monitoring: SHOW POOLS; in PgBouncer console. Alert on cl_active_conns > 80% max. Use Prometheus exporter.
Pitfall: Prepared statements break in transaction pooling—use extended query protocol or session mode.
2. Autovacuum: Prevent Bloat in Massive Tables
Autovacuum is your anti-bloat sentinel, but defaults fail at scale (e.g., 0.1% scale_factor = vacuum at 10GB bloat on 10TB table). Tune aggressively.
Core Tuning (postgresql.conf)
conf
# Aggressive for scale
autovacuum = on
autovacuum_max_workers = 6 # CPU cores / 2
autovacuum_vacuum_cost_limit = 2000 # Default 1000; higher = faster, more I/O
autovacuum_naptime = 15s
autovacuum_vacuum_scale_factor = 0.02 # Vacuum at 2% change (vs 0.1)
autovacuum_vacuum_threshold = 50
autovacuum_analyze_scale_factor = 0.05
autovacuum_analyze_threshold = 50
autovacuum_vacuum_cost_delay = 10ms # Throttle I/O
# For HOT updates (reduces bloat)
hot_standby_feedback = on # If replicas
Run manual VACUUM ANALYZE off-peak via cron/pg_cron.
Monitor bloat: pgstattuple or pg_bloat extension. Alert if >20%.
PG16+: autovacuum_vacuum_insert_scale_factor for insert-heavy tables.
Query for Workers:
sql
SELECT schemaname, relname,
n_dead_tup, n_live_tup,
last_autovacuum,
autovacuum_count
FROM pg_stat_all_tables
WHERE n_dead_tup > 0.1 * n_live_tup;
3. Partitioning: Divide and Conquer Terabyte Tables
Declarative partitioning (PG11+) prunes scans 10-100x on large tables. Ideal for time-series, logs.
Setup Example (Range by Date)
sql
CREATE TABLE sales (
id BIGSERIAL, sale_date DATE NOT NULL, amount NUMERIC
) PARTITION BY RANGE (sale_date);
CREATE TABLE sales_202401 PARTITION OF sales
FOR VALUES FROM ('2024-01-01') TO ('2024-02-01');
-- Subpartition by hash for hot partitions
CREATE TABLE sales_202401 PARTITION OF sales
FOR VALUES FROM ('2024-01-01') TO ('2024-02-01')
PARTITION BY HASH (id);
Tuning at Scale:
Pruning: Always WHERE sale_date BETWEEN ...—use BRIN on partition key.
Maintenance:
sql
-- Detach old: ALTER TABLE sales DETACH PARTITION sales_202301;
-- Attach new: ALTER TABLE sales ATTACH PARTITION sales_202402 ...;
Limit: 1000s of partitions → use pg_partman extension for automation.
Indexes: Per-partition or global (PG15+). Use INCLUDING ALL for defaults.
Vacuum: Inherited, but tune per-leaf.
Performance: 50-90% scan speedup. Monitor pg_stat_user_tables for partition stats.
4. Index-Only Scans: Zero Heap Touches
Index-only scans (IOS) read only index if all columns covered and VM (visibility map) fresh. 2-10x faster for analytics.
Enable & Optimize
Covering Indexes (use INCLUDE for non-key):
sql
CREATE INDEX idx_sales_cover ON sales (sale_date)
INCLUDE (amount, customer_id) WHERE deleted = false;
Visibility Map: Vacuum keeps it current—VACUUM frequently.
BRIN Indexes: For 100GB+ sorted tables (e.g., time-series):
sql
CREATE INDEX idx_logs_brin ON logs USING BRIN (timestamp);
Pages: 128 default; tune pages_per_range = 1000 for scale.
Verify IOS:
sql
EXPLAIN (ANALYZE, BUFFERS) SELECT amount FROM sales WHERE sale_date = '2024-01-01';
-- Look for "Index Only Scan" + heap_fetches = 0
Pitfalls: HOT updates preserve VM; cold updates don't—tune autovacuum. Avoid on high-update tables.
Stats: pg_stat_user_indexes.idx_scan vs heap_fetches—alert if >1%.
5. Plan Regression Alerts: Catch the Culprit
Query plans regress from stats, params, or upgrades. Detect via monitoring.
-- Top regressed queries
SELECT query, calls, total_exec_time / calls AS avg_time,
rows / calls AS avg_rows
FROM pg_stat_statements
ORDER BY avg_time DESC LIMIT 10;