Skip to main content
PostgreSQL & High-Scale Data Engineering 8 min readPublished November 3, 2026By Shiva Vinodkumar

PostgreSQL at Scale: Connection Pooling (PgBouncer vs. Supavisor), Partitioning & Indexing for 100M+ Rows

PostgreSQL is the undisputed database standard for modern software engineering. However, when an application graduates from early traction to hundreds of millions of rows and thousands of concurrent microservice connections, classical defaults backfire: connection exhaustion stalls queries, bloated B-Trees evict cache memory, and unmanaged autovacuum cycles trigger emergency database freezes. Here is an architectural blueprint for scaling PostgreSQL to 100M+ rows with zero downtime.

Share:

Core Architectural Pillars

  • Process-per-Connection Overhead: Why Postgres forks a dedicated 2-10MB OS process per connection, and how connection poolers prevent kernel context switching bottlenecks.
  • PgBouncer vs. Supavisor: Comparing battle-tested C-based PgBouncer with Supabase's new Rust-based Supavisor capable of multiplexing 100,000+ client connections.
  • Declarative Partitioning: Slicing 100M+ row tables into monthly or hash partitions to ensure hot data fits entirely within RAM (Shared Buffers).
  • BRIN Indexes: Slashing index size by 99% on append-only timeseries tables compared to standard B-Trees.

1. The Connection Exhaustion Cliff: PgBouncer vs. Supavisor

Unlike threaded databases (like MySQL), PostgreSQL runs on a process-based connection model. Every time a client connects, the OS forks a separate backend process.

When 50 serverless Lambda functions or Kubernetes pods scale out, spawning 3,000 idle connections:

  • Each connection consumes between 3 MB and 10 MB of RAM, burning gigabytes of memory on idle socket handles.
  • The Linux kernel scheduler spends up to 35% of its CPU time context switching between competing processes.
FeaturePgBouncer (C)Supavisor (Rust / Elixir)
ArchitectureSingle-threaded event loop (libevent)Multi-threaded Rust asynchronous engine
Connection ScaleUp to ~10,000 clients per instance100,000+ client connections across CPU cores
Pooling ModesSession, Transaction, StatementSession, Transaction with tenant isolation
Prepared StatementsLimited in transaction modeNative named prepared statement caching

By placing a connection pooler in Transaction Pooling Mode, 10,000 client frontend connections can be multiplexed down to just 64 physical backend connections on the Postgres server, keeping CPU cache hit rates near 100%.

2. Declarative Table Partitioning for 100M+ Rows

When a single table grows past 100 million rows (e.g., financial audit ledgers or API request logs), vacuuming takes hours, and sequential scans lock disks.

With Declarative Range Partitioning, data is split into independent physical tables based on dates:

-- 1. Create partitioned master table
CREATE TABLE financial_transactions (
    id UUID NOT NULL,
    user_id UUID NOT NULL,
    amount NUMERIC(18, 4) NOT NULL,
    created_at TIMESTAMPTZ NOT NULL,
    status VARCHAR(20) NOT NULL
) PARTITION BY RANGE (created_at);

-- 2. Create monthly physical child partitions
CREATE TABLE transactions_2026_10 PARTITION OF financial_transactions
    FOR VALUES FROM ('2026-10-01 00:00:00+00') TO ('2026-11-01 00:00:00+00');

CREATE TABLE transactions_2026_11 PARTITION OF financial_transactions
    FOR VALUES FROM ('2026-11-01 00:00:00+00') TO ('2026-12-01 00:00:00+00');

-- 3. Querying automatically executes Partition Pruning!
EXPLAIN SELECT * FROM financial_transactions 
WHERE created_at >= '2026-11-03 00:00:00+00' AND user_id = 'c4d1...';
-- Result: Scans ONLY transactions_2026_11, skipping all other historical partitions!

3. The Secret Weapon: BRIN Indexes vs. B-Tree

Standard B-Tree indexes store every single row pointer. For a 100M row table, a B-Tree index on created_at typically consumes 30 GB to 45 GB of disk space—larger than the server's entire RAM capacity! When the index no longer fits in memory, every query requires random disk I/O reads.

For append-only timeseries data, use a Block Range Index (BRIN):

  • How BRIN Works: Instead of indexing individual rows, BRIN records only the minimum and maximum value for each physical 128-page block range on disk.
  • Storage Footprint: A BRIN index on 100M rows consumes only 35 Megabytes (a 99.9% reduction compared to a 35GB B-Tree).
  • Zero Memory Eviction: The entire BRIN index stays permanently pinned in RAM, allowing lightning-fast range queries with zero cache churn.

Authored by Shiva Vinodkumar, Founder & Software Architect at HelloAIHub. To explore high-throughput streaming pipelines, read our Kafka vs. Redpanda vs. Pulsar Guide or visit the Shiva Vinodkumar Blog.

PgBouncer vs. Supavisor in High-Concurrency Benchmarks

PostgreSQL allocates a dedicated OS process for each client connection (~10MB RAM per socket). Connecting 5,000 application worker pods directly to Postgres triggers CPU context switching collapse. The benchmark below compares leading connection poolers:

Connection PoolerLanguage & ConcurrencyMax Client SocketsMemory per 10k Sockets
PgBouncerC (Single-threaded event loop)10,000~25 MB
SupavisorElixir / OTP (Multi-core actors)50,000+~65 MB

Declarative Range Partitioning & BRIN Index Optimization

Scaling PostgreSQL tables past 100 million rows requires partitioning large datasets to fit indexes into server RAM:

  • Partition Pruning: Range partitioning tables by timestamp (PARTITION BY RANGE (created_at)) enables the query planner to skip scanning older historical tables entirely when executing date-bounded lookups.
  • BRIN (Block Range Index): For naturally ordered append-heavy datasets (audit logs, time-series metrics), BRIN indexes consume less than 1% of the disk space of traditional B-tree indexes while providing near-identical sequential query performance.

Write-Ahead Log (WAL) Tuning & High-Throughput Checkpointing

Under sustained write-heavy workloads, default PostgreSQL checkpoint settings cause severe I/O spikes when dirty shared memory buffers are flushed to disk simultaneously. Production database administrators tune three core parameters:

  • max_wal_size & min_wal_size: Increasing max_wal_size to 16GB or 32GB on modern NVMe drives spaces out automatic checkpoints, allowing background writers to smooth out disk write spikes.
  • checkpoint_completion_target: Setting this to 0.9 instructs PostgreSQL to spread I/O writes across 90% of the checkpoint interval, preventing disk saturation stalls.
  • shared_buffers Sizing: Allocating 25% of total server RAM to shared_buffers keeps frequently accessed database pages and B-tree root nodes cached directly in memory, minimizing expensive physical disk reads.

Autovacuum Tuning for High-Update OLTP Databases

In write-heavy applications executing tens of thousands of updates and deletes per second, default PostgreSQL autovacuum settings are far too conservative, causing dead tuple bloat that inflates disk usage and slows down index scans:

  • autovacuum_vacuum_scale_factor: Lowering this from the default 0.20 (20%) to 0.05 (5%) forces vacuum workers to reclaim dead tuple space frequently before table bloat accumulates.
  • autovacuum_vacuum_cost_limit: Increasing the cost limit from 200 to 2,000 allows vacuum workers on modern NVMe storage arrays to clean dirty pages at full I/O capacity without hitting arbitrary throttling pauses.
  • autovacuum_max_workers: Increasing concurrent workers from 3 to 6 ensures that multiple large partitioned tables can be vacuumed concurrently without starving smaller transactional tables.

Authoritative References & Standards

PgBouncer Transaction Pooling Caveats & Prepared Statements

Deploying PgBouncer in transaction pooling mode is essential for scaling PostgreSQL beyond several thousand concurrent client connections. Because PostgreSQL allocates a dedicated OS process (consuming approximately 10MB of memory) for each connection, unpooled connections will rapidly exhaust system RAM.

However, transaction pooling reassigns the server backend connection to a different client between transactions. This architecture breaks session-level state, including session-scoped temporary tables, advisory locks, and server-side prepared statements (PREPARE / EXECUTE).

Modern applications overcome this by enabling PgBouncer's protocol-level prepared statement support (max_prepared_statements) or utilizing client-side named prepared statement caches, maintaining extreme query performance without compromising connection density.

Declarative Partition Pruning & BRIN Index Optimization

For multi-terabyte timeseries and event logging tables, standard B-Tree indices become computationally inefficient as index trees outgrow available buffer pool memory. PostgreSQL declarative range partitioning divides massive tables into manageable weekly or monthly partitions.

By combining partition pruning (where the query planner excludes non-matching partition tables entirely) with Block Range Indexes (BRIN), storage consumption is slashed by 95%. BRIN indexes store only the minimum and maximum values for physical disk block ranges (typically 128 blocks), allowing lightning-fast sequential scans across billions of historical records with minimal index maintenance overhead.

Zero-Downtime Schema Migrations & Lock Timeout Guardrails

Operating PostgreSQL databases with tables exceeding 100 million rows requires extreme caution when executing Data Definition Language (DDL) migrations. In PostgreSQL, commands like altering table columns, adding foreign keys, or creating secondary indexes acquire strong table locks. While the command itself might only take milliseconds to execute once active, it must wait for all prior concurrent SELECT and UPDATE transactions on that table to complete.

If a long-running reporting query is currently reading the table, the pending DDL command waits in the lock queue. In PostgreSQL, a waiting exclusive lock blocks all subsequent read and write queries behind it in the queue, creating a connection pile-up that can exhaust connection pools and crash production services within seconds. To prevent catastrophic outages, production database engineers enforce strict migration guardrails: setting a short lock timeout before any DDL statement, creating all secondary indexes concurrently, and adding foreign key constraints using NOT VALID followed by an asynchronous validation command.

PgBouncer Transaction Muxing & Declarative Partition Pruning

PostgreSQL allocates a dedicated backend operating system process for every active client connection, consuming several megabytes of RAM and triggering CPU context switching overheads under high concurrency. Senior database engineers resolve connection saturation by deploying PgBouncer in transaction pooling mode. Transaction pooling decouples application client connections from server connections, allowing thousands of microservices to share a small pool of fifty to one hundred physical PostgreSQL backends.

For multi-terabyte append-only datasets, declarative range partitioning by timestamp divides monolithic tables into manageable physical shards. When queries include timestamp range filters in their WHERE clauses, PostgreSQL's query optimizer applies partition pruning, completely excluding non-relevant partitions from disk I/O scans and maximizing cache hit ratios.

Connection Pooling Internals: PgBouncer vs Odyssey and Declarative Partitioning

Operating PostgreSQL at hyper-scale—processing tens of thousands of transactions per second (TPS) across multi-terabyte datasets—requires confronting the fundamental process-based concurrency architecture of the PostgreSQL database engine. Unlike multi-threaded database systems (such as MySQL or Microsoft SQL Server) that allocate lightweight operating system threads for incoming client connections, PostgreSQL spawns a dedicated, independent OS process for every active connection (the postmaster fork architecture).

Each backend connection process consumes between 5 to 10 Megabytes of RAM simply for process metadata, internal memory caches, and connection state. When client application fleets open thousands of direct connections, server memory is rapidly exhausted. More critically, operating system context switching overhead and PostgreSQL internal lock contention (specifically spinlocks on shared memory data structures like the ProcArray) cause database throughput to collapse precipitously once active connections surpass a few hundred:

  • Transaction-Level Connection Pooling with PgBouncer: To eliminate connection exhaustion, production topologies deploy connection poolers like PgBouncer or Odyssey in transaction pooling mode. Client microservices maintain thousands of persistent connections to the pooler; the pooler multiplexes these requests across a compact pool of dedicated backend connections (typically 50 to 100 connections per primary node), releasing backend connections immediately upon transaction completion.
  • Declarative Range and Hash Partitioning: As relational tables grow past 100 million rows, B-tree indexes outgrow physical server RAM, causing read and write operations to incur high-latency NVMe disk I/O. Declarative partitioning divides monolithic tables into discrete child partitions based on timestamp ranges or tenant ID hashes.
  • Partition Pruning Optimization: PostgreSQL query planner executes static and run-time partition pruning. Queries filtering by partition keys scan only the specific child partitions holding relevant data, completely bypassing billions of unrelated rows and slashing query latencies from seconds to single-digit milliseconds.
  • BRIN vs B-Tree Indexing on Append-Only Datasets: For massive append-only time-series datasets (such as audit logs or financial ledgers), classical B-tree indexes consume gigabytes of storage. Block Range Indexes (BRIN) store only the minimum and maximum values per physical disk page range, reducing index storage footprints by over 98 percent while delivering fast sequential scan performance.

Lock Contention Mitigation, Autovacuum Tuning, and Horizontal Sharding

At extreme transactional velocity, database performance bottlenecks rarely originate in CPU or memory capacity; they emerge from relational lock contention and table bloat. In PostgreSQL Multi-Version Concurrency Control (MVCC) architecture, updating a row does not overwrite existing data on disk; it writes a new version of the row while marking the old version as dead. If dead tuples are not reclaimed continuously, tables and indexes bloat, exhausting disk cache and degrading query throughput.

Production database architects implement rigorous maintenance and concurrency engineering:

  • Aggressive Autovacuum Daemon Calibration: Default PostgreSQL autovacuum settings are notoriously conservative, designed for small servers. In high-write environments, architects tune autovacuum_vacuum_cost_limit from default 200 to 2000, and reduce autovacuum_vacuum_scale_factor from 0.20 to 0.02, ensuring that background vacuum workers reclaim dead tuples continuously without causing high-latency I/O spikes.
  • Lock Contention Diagnostics via pg_stat_activity: DDL migrations (such as adding table columns or creating indexes) acquire ExclusiveLocks that block all read and write traffic. Engineers execute schema migrations using zero-downtime patterns: utilizing CREATE INDEX CONCURRENTLY, setting strict lock_timeout limits, and employing tools like pg_repack to eliminate bloat without exclusive table locks.
  • Horizontal Sharding with Citus: When single-node vertical scaling reaches its physical ceiling (surpassing 10 Terabytes of active data), architectures deploy horizontal sharding via Citus. Citus distributes tables across multiple PostgreSQL worker nodes, routing queries transparently and executing parallel aggregations across distributed clusters.

Write-Ahead Log (WAL) Tuning, Checkpoint Spacing, and SSD Optimization

Under high-velocity write workloads, PostgreSQL performance is governed by the Write-Ahead Log (WAL) subsystem. In ACID-compliant relational databases, data modifications must be flushed to the WAL before being committed to primary table files. If the WAL subsystem is misconfigured, database throughput fluctuates wildly as checkpoint flushes choke NVMe storage controllers.

Production database engineers eliminate I/O checkpoint spikes through precise kernel and WAL calibration:

  • Checkpoint Spacing Calibration: Extend checkpoint intervals by increasing max_wal_size from default 1 GB to 32 GB or 64 GB, and setting checkpoint_completion_target to 0.9. This spreads disk write operations smoothly across the checkpoint window, eliminating catastrophic I/O stalls.
  • WAL Buffers and Asynchronous Commit: Tune wal_buffers to 64 MB to absorb heavy burst writes in memory. For non-critical telemetry logging, enabling synchronous_commit = off provides massive throughput boosts while bounding potential transaction loss to a tiny 50ms window.
  • Linux Kernel I/O Tuning for NVMe Storage: Configure Linux kernel I/O schedulers to none or mq-deadline for NVMe drives, adjust dirty_background_ratio to 5 percent, and mount filesystems with noatime, maximizing hardware throughput across enterprise cloud databases.

B-Tree Index Bloat, Page Fillfactor, and Zero-Downtime Reindexing Runbooks

In high-throughput relational databases experiencing heavy concurrent updates, B-tree index bloat is a silent performance killer. When rows are updated or deleted, PostgreSQL marks dead index entries, but B-tree index pages can only be reused for keys falling within the exact key range of that specific page. Over months of high-velocity operations, index pages become sparse, forcing the database engine to traverse bloated tree structures that exhaust memory buffers and saturate disk bandwidth.

Production database architects maintain index health through proactive tuning and zero-downtime maintenance:

  • Page Fillfactor Calibration: On tables with frequent UPDATE transactions, configure index fillfactor to 85 or 90 rather than default 100 (e.g., ALTER TABLE orders SET (fillfactor = 85)). Reserving 15 percent free space on each 8 KB disk page enables Hot-Update (Heap-Only Tuples) optimizations, allowing updates to execute without touching index structures.
  • Zero-Downtime REINDEX CONCURRENTLY: When index bloat exceeds 25 percent, execute reindexing using the CONCURRENTLY keyword: REINDEX TABLE CONCURRENTLY accounts. This builds a fresh B-tree index in the background while concurrent client read and write transactions continue uninterrupted, swapping the index pointer atomically upon completion.
  • Monitoring Index Bloat via pg_stat_user_indexes: Automated monitoring queries inspect index scan counts against tuple read volumes. Unused or redundant indexes are dropped safely, liberating gigabytes of shared memory and accelerating write throughput.

Logical Replication Topologies, Failover Protocols, and Database Resilience

Maintaining 99.999% availability for enterprise PostgreSQL clusters processing tens of thousands of transactions per second requires engineering robust replication and automated failover topologies. Physical streaming replication replicates the exact binary state of the database from primary to standby instances via the WAL stream; however, physical replication replicates entire database clusters monolithically, preventing zero-downtime major version upgrades or selective cross-region data distribution.

Modern enterprise database architectures deploy hybrid replication topologies:

  • Logical Replication for Zero-Downtime Upgrades: Logical replication decodes WAL streams into logical SQL transactions (INSERT, UPDATE, DELETE). This allows organizations to replicate data continuously to a new PostgreSQL major version cluster (e.g., upgrading from v15 to v17), switching application traffic over in sub-second windows with zero data loss.
  • High-Availability Consensus with Patroni and etcd: High-availability clusters utilize Patroni backed by a distributed consensus store (etcd or Consul). If a primary node suffers a kernel panic or hardware failure, Patroni nodes execute a deterministic leader election, re-configuring replication topologies and updating connection pooler routes in under 10 seconds.
  • Disaster Recovery and Continuous WAL Archiving: Enterprise runbooks deploy pgBackRest for continuous WAL archiving and multi-threaded snapshot backups pushed directly to object storage (AWS S3, Google Cloud Storage), enabling Point-In-Time Recovery (PITR) to any historical second with absolute data fidelity.

Disaster Recovery Topologies, Point-in-Time Recovery, and Citus Scaling

Achieving absolute data durability and sub-second failover in enterprise PostgreSQL deployments requires orchestrating disaster recovery pipelines and distributed scaling architectures. In mission-critical financial applications processing millions of ledger updates daily, data loss is catastrophic. Enterprise runbooks mandate continuous, multi-region WAL streaming combined with automated snapshot backups managed by pgBackRest.

Should a primary data center experience catastrophic hardware failure, automated consensus daemons (Patroni backed by etcd) execute deterministic failover in under 10 seconds:

  • Split-Brain Prevention: Distributed consensus ensures that exactly one primary node can hold the master lock at any time. Fencing mechanisms (STONITH / watchdog timers) forcibly isolate failed primary nodes, completely preventing split-brain data corruption.
  • Horizontal Sharding with Citus: When monolithic databases surpass single-server memory and storage limits, Citus extends PostgreSQL into a distributed relational cluster. Tables are distributed across worker nodes using hash sharding on tenant IDs, delivering linear scalability across petabyte-scale analytical workloads.
  • The Gold Standard of Relational Engineering: By mastering transaction-level connection pooling with PgBouncer, declarative range partitioning, BRIN and B-tree indexing, and automated vacuum maintenance, database architects ensure that PostgreSQL delivers unassailable reliability, deterministic sub-millisecond query performance, and infinite enterprise scalability.

Lock Contention Elimination and Advanced Index Maintenance Runbooks

Operating PostgreSQL clusters supporting tens of thousands of write operations per second requires systematic elimination of catalog lock contention. Dynamic table partitioning, while essential for managing multi-terabyte datasets, introduces exclusive locks on parent tables during partition creation. In production environments, database engineers eliminate this vulnerability by scheduling automated partition pre-creation crons days in advance, ensuring that real-time transactional writes never block on DDL lock acquisitions.

Similarly, index bloat on high-throughput B-tree indexes severely degrades query cache efficiency. Running REINDEX concurrently requires strict operational guardrails: configuring maintenance_work_mem appropriately, pacing background I/O to avoid saturating NVMe storage arrays, and monitoring lock queues to prevent cascading transaction deadlocks. By pairing declarative partition management with continuous pgstattuple bloat telemetry, database architects ensure predictable single-digit millisecond query latencies across enterprise scale deployments.

Implementing statement timeout limits alongside automated connection recycling prevents rogue analytical queries from consuming shared buffer resources, preserving database responsiveness under peak transactional concurrency.

Automated vacuum cost limit tuning dynamically throttles autovacuum background workers during peak business hours, preventing disk I/O bottlenecks while maintaining vacuum frequency to avert transaction ID wraparound crises.

Configuring streaming physical replication with synchronous standby servers guarantees zero data loss recovery point objectives (RPO=0) while keeping transaction commit latencies within sub-millisecond network round trips.

Share:
Up Next: Recommended Deep Dives

Continue Exploring Architecture Masterclasses