Postgresql optimization

From curiositech/windags-skills · View interactive version

Postgresql optimization is an AI agent skill from the GitHub repository curiositech/windags-skills. Expert in PostgreSQL performance tuning, query optimization, and database administration. Specializes in EXPLAIN analysis, indexing strategies, connection pooling, partitioning, and production-grade PostgreSQL operations. Use when the user explicitly needs postgresql optimization help. NOT for unrel

How to use this skill

Skill file

PostgreSQL Optimization

Overview

Expert in PostgreSQL performance tuning, query optimization, and database administration. Specializes in EXPLAIN analysis, indexing strategies, connection pooling, partitioning, and production-grade PostgreSQL operations.

Decision Points

Index Type Selection Decision Tree

Query Pattern Analysis:
├── Equality lookups (=, IN)?
│   ├── High cardinality column → B-tree index
│   └── Low cardinality (<100 unique) → Consider partial indexes or skip
├── Range queries (>, <, BETWEEN)?
│   ├── Date/time columns → B-tree index (created_at DESC for recent data)
│   ├── Large table (>1M rows) + sparse data → BRIN index
│   └── Regular ranges → B-tree index
├── Full-text search or JSONB containment?
│   ├── JSONB @>, ?, ?& operators → GIN index with jsonb_path_ops
│   ├── Full-text search (tsvector) → GIN index
│   └── JSONB keys/values extraction → GIN index
├── Array operations (ANY, ALL)?
│   └── GIN index on array column
└── Exact hash lookups only?
    ├── Large table + no range queries → HASH index
    └── Default → B-tree index (more flexible)

Query Optimization Strategy

| EXPLAIN Output Indicator | Decision Path | Action |

|--------------------------|---------------|---------|

| "Seq Scan" on large table (>10k rows) | Missing index | Create B-tree index on WHERE clause columns |

| "Nested Loop" with high cost | Inefficient join | Add index on join keys, consider hash/merge join |

| "Sort" with "external merge" | Insufficient memory | Increase work_mem or add index to avoid sort |

| High "Rows Removed by Filter" | Late filtering | Move WHERE conditions earlier, use partial index |

| "Bitmap Heap Scan" with low selectivity | Index not selective enough | Create multi-column index or partial index |

Connection Pool Sizing

Application Analysis:
├── Request pattern: Burst traffic?
│   ├── Yes → pool_mode = transaction, max_client_conn = 5x default_pool_size
│   └── No → pool_mode = session, max_client_conn = 2x default_pool_size
├── Query duration: Long-running queries (>30s)?
│   ├── Yes → pool_mode = session, higher reserve_pool_size
│   └── No → pool_mode = transaction for better throughput
└── Database connections available:
    ├── max_connections > 200 → default_pool_size = max_connections / 4
    └── max_connections ≤ 200 → default_pool_size = 20-25

Failure Modes

Index Bloat Death Spiral

Connection Pool Exhaustion

Query Plan Regression

Deadlock Cascade

Memory Configuration Mismatch

Worked Examples

Optimizing a Slow Analytics Query

Scenario: Dashboard query taking 45 seconds to load monthly sales data

-- Initial slow query
SELECT 
  u.name, 
  COUNT(o.id) as order_count,
  SUM(o.total_amount) as revenue
FROM users u
JOIN orders o ON o.user_id = u.id 
WHERE o.created_at >= '2024-01-01' 
  AND o.created_at < '2024-02-01'
GROUP BY u.id, u.name
ORDER BY revenue DESC;

Step 1: Analyze current plan

EXPLAIN (ANALYZE, BUFFERS) [query above];
-- Result: Seq Scan on orders (cost=0.00..450000 rows=2000000)
-- Shows: scanning 2M rows to find 50k matching rows

Expert catches: Date range filter eliminating 95% of rows suggests need for date index

Novice misses: Might try to optimize the JOIN first instead of the WHERE filter

Step 2: Create targeted index

-- Index for date filtering and JOIN
CREATE INDEX CONCURRENTLY idx_orders_created_user 
ON orders (created_at, user_id) 
INCLUDE (total_amount);

Step 3: Re-analyze

EXPLAIN (ANALYZE, BUFFERS) [query];
-- New result: Index Scan using idx_orders_created_user (cost=0.43..15000 rows=50000)
-- Query time: 45s → 1.2s

Expert catches: INCLUDE clause enables index-only scan, eliminating table lookup

Novice misses: Would create separate indexes instead of one covering index

Quality Gates

NOT-FOR Boundaries

Do NOT use this skill for:

Delegate when:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.