1 Core Concepts
MVCC
Multi-Version Concurrency Control — PostgreSQL never locks rows for reads. Each transaction sees a consistent snapshot. Writers create new row versions; VACUUM reclaims dead tuples. This enables high concurrency without read locks.
JSONB
Binary JSON column type with full indexing support. Store semi-structured agent tool results, LLM responses, and metadata. Use GIN indexes for fast containment queries (@>) and path operators (->>).
CTEs
Common Table Expressions (WITH clauses) break complex queries into readable named subqueries. Recursive CTEs traverse tree structures like agent conversation histories and org hierarchies.
Window Functions
Compute aggregates across row sets without collapsing groups. ROW_NUMBER(), RANK(), LAG(), LEAD(), SUM() OVER(). Essential for time-series analysis on agent execution logs.
Index Types
B-tree (default, equality/range), GIN (JSONB containment, full-text, arrays), GiST (geometric, range types), BRIN (large sequential data like time-series). Choose based on query patterns.
Partitioning
Split large tables into smaller partitions by range (date), list (category), or hash (even distribution). Enables partition pruning in queries, faster VACUUM, and independent partition maintenance.
LISTEN / NOTIFY
Built-in pub/sub messaging. Agents can LISTEN on channels and receive real-time NOTIFY events from triggers or other transactions — no external message broker required for simple event-driven workflows.
Extensions
PostgreSQL's plugin architecture. Key extensions: pgvector (vector search), pg_cron (scheduled jobs), pg_stat_statements (query analytics), PostGIS (geospatial), pgcrypto (encryption).
2 Index Types Comparison
3 Setup Guide
Docker
macOS (Homebrew)
Ubuntu / Debian
4 Usage Examples
JSONB Agent State Store
CTEs & Window Functions
5 Best Practices
Connection Pooling
Each PostgreSQL connection consumes ~10 MB of RAM. Use PgBouncer (transaction-mode pooling) in front of Postgres. Set max_connections=100 on the server, pool size 20–30 in the application.
EXPLAIN ANALYZE
Always profile slow queries with EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT). Look for Seq Scans on large tables, high Rows Removed by Filter, and Sort Method: external merge (insufficient work_mem).
Autovacuum Tuning
Never disable autovacuum. For write-heavy agent tables, lower autovacuum_vacuum_scale_factor to 0.05 (5%) and increase autovacuum_vacuum_cost_limit to 1000+ for faster dead tuple cleanup.
Partial Indexes
Index only the rows you query: CREATE INDEX ON agent_runs(started_at) WHERE status = 'running'. Partial indexes are dramatically smaller and faster to maintain than full-table indexes.
pg_stat_statements
Enable this extension to track query execution statistics. Identify top queries by total_exec_time, calls, and mean_exec_time. Reset stats periodically after optimization rounds.
Streaming Replication
Configure synchronous or async streaming replicas for HA and read scaling. Route agent read queries to replicas, writes to primary. Use pg_basebackup for initial replica setup and WAL archiving for PITR.
6 Scaling & Production
Read Replicas
Scale reads horizontally with streaming replicas. Route agent read queries to replicas via PgBouncer or application-level routing. Each replica adds ~100% read throughput. Async replication lag is typically <100ms.
Citus (Horizontal Sharding)
Citus extends PostgreSQL with distributed tables. Shard by tenant_id or agent_id to distribute writes across nodes. Supports co-located joins within the same shard and reference tables for small lookup data.
Partitioning at Scale
Range-partition agent logs by month. Detach and archive old partitions to cold storage. pg_partman automates partition creation and retention. Queries on recent data only scan the latest partition — 10–100× faster on tables with 1B+ rows.
Logical Replication
Replicate specific tables between databases (unlike streaming replication which copies everything). Ideal for multi-datacenter deployments, zero-downtime major version upgrades, and feeding analytics databases from production.
Connection Scaling
Each PostgreSQL connection uses ~10 MB RAM. At 1000 agent workers, that's 10 GB just for connections. Use PgBouncer in transaction mode to multiplex 1000 app connections onto 30–50 server connections.
Managed Services
Cloud SQL (GCP), RDS/Aurora (AWS), Flexible Server (Azure) handle replication, backups, and patching. Aurora PostgreSQL supports 15 read replicas with shared storage and up to 128 TB per database.
7 FAQ
PostgreSQL vs. MySQL — when to choose Postgres?→
How do I optimize JSONB query performance?→
CREATE INDEX ON t ((data->>'status')). Avoid jsonb_path_query on unindexed columns. For large documents, extract frequently queried fields into regular columns.