Database Connection Pooling: PgBouncer, HikariCP and Why It Matters

If you have ever watched a PostgreSQL primary fall over because max_connections was set to 2000, you understand why connection pooling is not an optional optimization. In my experience, most teams discover pooling only after their first real traffic spike, when latency explodes not because queries got slower, but because the database spends all its time creating and tearing down connections. On a recent platform migration, we moved from direct connections from 40 application pods to a two-layer pool with HikariCP inside each JVM and PgBouncer in front of Postgres, and p95 latency dropped by 60% while Postgres CPU utilization fell by almost half, with no query changes at all.

Connection pooling solves a fundamental mismatch: application servers want cheap, disposable, per-request connections, while databases want a small, stable set of long-lived backend processes. This article explains how that mismatch works, how PgBouncer and HikariCP solve it at different layers of the stack, and how I configure and monitor both in production without trading one bottleneck for another. If you are already tuning the database side, you will get even more out of pooling when combined with SQL Query Optimization: EXPLAIN Plans, Indexes and Join Strategies, but pooling alone often delivers the biggest immediate win.

The Real Cost of Establishing Database Connections at Scale

A new PostgreSQL connection is far more expensive than most developers expect. It is not just a TCP socket. For each connection, Postgres forks a backend process, allocates work memory, performs authentication, negotiates TLS if enabled, and initializes session state. On a moderately tuned host, I typically measure 2-8ms just for the handshake on a nearby network, and 10-30ms cross-AZ with TLS. That cost dwarfs a 1ms primary key lookup. Multiply that by hundreds of requests per second and you are burning CPU and memory before a single query runs.

Memory is the other hidden cost. Each backend consumes work_mem, maintenance_work_mem buffers and other session allocations. With work_mem = 16MB and 500 idle connections, you have committed gigabytes of memory that could have been used for shared_buffers or OS cache. I have seen teams raise max_connections to 1000 to accommodate more application replicas, only to hit OOM kills because Postgres overcommitted memory during sort operations.

Finally, there is contention. Postgres uses heavyweight locks and proc array scans that scale poorly with connection count. Past 200-300 active backends, throughput often decreases rather than increases. You get more context switches, longer lock waits, and checkpoint contention. Pooling keeps the active backend count in the sweet spot where the database is most efficient, while letting thousands of application threads think they each have a private connection.

Why Application Servers Make It Worse

Modern application frameworks are built for concurrency. A Spring Boot service with 200 worker threads, a Node.js cluster with 16 processes, or a Python ASGI server with 100 async workers will all happily open a connection per request if you let them. Autoscaling makes this exponential. When we scaled from 8 to 32 pods during a flash sale, direct connections went from 160 to over 640 and Postgres started queueing. The fix was not a bigger database; it was fewer real connections with aggressive reuse.

Even serverless and background job systems contribute. A burst of 500 Lambda invocations or 100 Sidekiq workers can create a thundering herd of new connections at once. Without pooling, you see the classic pattern: normal load is fine, but any deployment, retry storm, or cache stampede causes connection exhaustion and cascading failures.

Inside the Pool: How Connections Are Reused Without Breaking Isolation

A pool at its simplest is a queue of already-authenticated, warm connections. Instead of closing a connection after a query, the client returns it to the pool for the next request. The pool hands out idle connections in LIFO order, which keeps a small hot set in use and lets cold connections be reaped. This avoids fork, auth, and TLS costs on the hot path.

The tricky part is state. PostgreSQL session state includes SET parameters, temporary tables, prepared statements, advisory locks, and transaction status. If you simply hand the same backend to a different application user, that state leaks. Good poolers handle this by either restricting which features you can use or aggressively resetting state. This is why understanding pooling modes matters so much.

In my experience, the cleanest model is to treat pooled connections as strictly transactional and stateless. Avoid SET LOCAL that outlives a transaction, avoid session-level advisory locks, and avoid temporary tables if you plan to use transaction pooling. If you need those features, you must pin to session pooling and accept a higher backend count. There is no magic that lets you share a backend safely while preserving arbitrary session state.

Validation, Timeouts and Leaks: The Operational Details

A production pool needs more than a queue. It needs validation queries (SELECT 1), connection max lifetimes, idle timeouts, and leak detection. I always enable a max lifetime of 30 minutes to 1 hour to recycle connections before potential memory leaks or stale DNS entries become an issue. Idle timeout of 5-10 minutes lets the pool shrink during off-peak without churn. And leak detection — HikariCP's leakDetectionThreshold has saved me more than once by logging stack traces for connections held longer than 60 seconds.

For external protocol references, the handshake and authentication flow that pools avoid re-doing is documented in the PostgreSQL wire protocol, but for general connection handling and socket reuse patterns the Python Documentation provides a clear explanation of TCP socket lifecycle, and the MDN Web Docs covers the analogous HTTP keep-alive optimization that inspired database pooling in the first place.

PgBouncer in Transaction Mode: Handling 10,000 Clients on 100 Postgres Connections

PgBouncer is the most common server-side pooler for PostgreSQL because it is lightweight, stable, and sits transparently between your applications and Postgres. It speaks the Postgres wire protocol on both sides and multiplexes thousands of client connections onto a small number of server connections. In our current stack, a single PgBouncer instance with 4 vCPUs handles about 8,000 client connections and 150 server connections at p99 under 2ms overhead.

PgBouncer runs as a single-process event loop, similar to Nginx. It does not fork per connection, so its memory footprint stays flat. This architecture is why it scales to tens of thousands of clients. The trade-off is that it does not parse queries deeply; it relies on pooling mode rules rather than inspecting SQL semantics.

Session vs Transaction vs Statement Pooling Modes

PgBouncer offers three modes, and choosing wrong breaks your application silently.

Session pooling assigns a server connection to a client for its entire session. State is preserved, but concurrency is limited to the pool size. Use this only when you need session features like LISTEN/NOTIFY, temporary tables, or session advisory locks.

Transaction pooling is what most web workloads want. A server connection is assigned only for the duration of a transaction. Between transactions, the connection returns to the pool and the next client gets it. This allows massive multiplexing. The constraint is that you cannot use session-level features that span multiple transactions on the same connection. I mandate transaction mode for all stateless HTTP services.

Statement pooling releases the connection after each statement, even outside an explicit transaction. It is the most aggressive multiplexing but breaks multi-statement transactions entirely. I rarely recommend it except for very specific auto-commit analytics workloads.

Practical pgbouncer.ini Tuning I Actually Use

Defaults are conservative. Here is a starting point I have tuned for a typical 4-core PgBouncer in front of a db.r6g.xlarge Postgres with max_connections = 200. We only expose 120 of those to PgBouncer and reserve 80 for admin, replication and maintenance.

[databases]
app_db = host=postgres-primary.internal port=5432 dbname=app_db

[pgbouncer]
listen_port = 6432
listen_addr = *
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt

pool_mode = transaction
max_client_conn = 10000
default_pool_size = 40
reserve_pool_size = 10
reserve_pool_timeout = 3
max_db_connections = 120
max_user_connections = 120

server_idle_timeout = 30
server_lifetime = 3600
server_reset_query = DISCARD ALL

query_wait_timeout = 15
query_timeout = 60
client_idle_timeout = 0
idle_transaction_timeout = 30

Key takeaways from this config: default_pool_size is the number of server connections per database/user pair. With one pair, 40 connections does most of the work. reserve_pool_size allows bursting under load without queueing immediately. server_reset_query = DISCARD ALL is critical in transaction mode — it cleans session state before returning a connection to the pool. Never disable it unless you have audited every code path. query_wait_timeout prevents clients from waiting forever when the pool is saturated; I prefer to fail fast and retry with backoff rather than pile up threads.

One lesson I learned the hard way: PgBouncer does not support prepared statements in transaction mode when using the legacy protocol. If your driver uses prepared statements by default (JDBC does), you must either use session pooling or set prepareThreshold=0 in the JDBC URL. Otherwise you get the infamous prepared statement does not exist error under load.

Tuning HikariCP to Match Your JVM Workload and Postgres Limits

HikariCP is a client-side pool that lives inside your Java application. It is exceptionally fast because it uses lock-free data structures and bytecode optimization, but its job is different from PgBouncer's. While PgBouncer protects the database from too many backends, HikariCP protects the application from waiting too long for a connection and gives you fine-grained control per service.

In a typical microservice architecture, I run HikariCP in each JVM with a small pool (10-20 connections) and point it at PgBouncer, not directly at Postgres. This two-layer setup gives you both local agility and global protection. Each service can tune its own pool without coordinating with other services, while PgBouncer enforces a global cap. If you point HikariCP directly at Postgres, you must coordinate pool sizes across all services so the sum never exceeds max_connections, which becomes fragile as the service count grows.

Key HikariCP Parameters That Actually Move the Needle

HikariCP exposes many settings, but only a handful dominate behavior. I start with this template for a service with 50 Tomcat threads handling ~500 RPS:

spring:
  datasource:
    url: jdbc:postgresql://pgbouncer.internal:6432/app_db?prepareThreshold=0
    username: app_user
    password: ${DB_PASSWORD}
    driver-class-name: org.postgresql.Driver
    hikari:
      maximum-pool-size: 15
      minimum-idle: 5
      connection-timeout: 3000
      idle-timeout: 300000
      max-lifetime: 1800000
      keepalive-time: 30000
      leak-detection-threshold: 60000
      validation-timeout: 1000
      pool-name: app-pool

maximum-pool-size should be slightly smaller than the number of threads that need the database concurrently, not equal to it. With 50 Tomcat threads but only ~20% executing a DB query at any moment, 15 connections is plenty and prevents threads from holding DB connections while doing downstream HTTP calls. I also set minimum-idle lower than maximum to let the pool shrink; setting them equal hides connection creation latency but wastes server connections 24/7.

connection-timeout of 3000ms is deliberate. A shorter timeout surfaces pool exhaustion quickly in metrics rather than letting requests queue for 30 seconds before failing. Combine this with proper retries and circuit breakers in your service mesh. max-lifetime of 30 minutes ensures connections are recycled even if the database load balancer silently changes the backend IP.

Right-Sizing HikariCP Against max_connections

The math I use: sum(HikariCP maximumPoolSize across all pods) <= PgBouncer max_db_connections * 0.8. The 0.8 factor leaves headroom for bursts and reserve pools. For example, 20 pods * 15 connections = 300 logical connections, but PgBouncer multiplexes them onto 40-60 real server connections. If you are not using PgBouncer, the sum must be <= Postgres max_connections minus overhead. I have seen teams with 30 pods at pool size 20 hit 600 direct connections and then wonder why remaining connection slots are reserved for non-replication superuser connections appears.

Equally important is isolating pools by workload. I create a separate small pool for migrations or batch jobs. You do not want a nightly ETL job with 50 threads to starve your user-facing API pool. This isolation is harder without a client-side pooler, which is one reason I prefer HikariCP over relying solely on a centralized proxy. For teams evaluating broader Postgres capabilities that affect how you use connections, PostgreSQL Advanced Features: CTEs, Window Functions and JSONB is a useful companion read.

Where Should Pooling Live? Comparing PgBouncer, HikariCP and Sidecar Proxies

The most common question I get is whether to use PgBouncer, HikariCP, or both. The answer depends on where you want the control plane and how many languages are in your stack. In a polyglot environment with Java, Python and Go services, a centralized PgBouncer cluster is almost mandatory because not every driver has a good pool. In a pure Java shop, you can often start with HikariCP alone and add PgBouncer only when you scale past ~100 backends.

There is also the sidecar pattern: running PgBouncer as a sidecar container alongside each pod, or using a proxy like Odyssey or AWS RDS Proxy. Sidecars reduce network hops but add operational complexity. In my experience, a dedicated PgBouncer tier of 2-3 nodes behind a TCP load balancer is simpler to operate and monitor than 50 sidecars. RDS Proxy is convenient if you are on AWS, but it has its own pooling limits and latency characteristics you should load test.

When you start thinking about pooling at the proxy layer, you are also approaching the limits of a single primary. At that point, Database Sharding and Partitioning: Scaling Beyond a Single Node becomes the next architectural decision, and pooling remains relevant on every shard.

Pooler / Layer Runs Where Multiplexing Ratio Best For Limitation to Watch
PgBouncer (transaction mode) Server-side, centralized 50:1 to 200:1 Polyglot fleets, high client counts No session state; prepared statements need care
HikariCP Client-side, in JVM 1:1 (local reuse) Java services needing fast, tunable pools Sum across services can exceed DB limits
RDS Proxy / Odyssey Managed proxy / sidecar 20:1 to 100:1 Serverless, IAM auth, autoscaling fleets Added latency, vendor-specific quirks
Direct connections (no pool) Application only None Prototypes, single-host apps Fails beyond ~100 concurrent clients

My default recommendation for teams running Java plus other languages against Postgres: run HikariCP in each JVM with a 10-20 pool pointing to a PgBouncer tier with default_pool_size = 25-40. This gives you two knobs to tune — local latency with HikariCP and global backend count with PgBouncer — without either layer becoming a bottleneck.

What Breaks in Production: Sizing, Timeouts and Observability Lessons

Pooling introduces its own failure modes. The most frequent is pool exhaustion, which shows up as HikariCP Connection is not available, request timed out after 3000ms or PgBouncer no more connections allowed. The root cause is almost never too few connections; it is connections held too long. I instrument every service to track pool usage, pending threads, and connection acquisition time. If pending threads is consistently > 0, your pool is too small or your transactions are too long. Look for N+1 queries, missing transaction boundaries, or HTTP calls made while holding a DB connection.

Timeouts need to be layered. I configure timeouts from outermost to innermost: load balancer > application request timeout > HikariCP connectionTimeout > PgBouncer query_wait_timeout > Postgres statement_timeout and idle_in_transaction_session_timeout. Each layer should time out slightly faster than the one above it, so the lowest layer fails first and provides a clear error. Setting only an application timeout hides where the bottleneck lives.

Observability You Should Add From Day One

Export these metrics for every pool. For HikariCP, I scrape via Micrometer: hikaricp_connections_active, hikaricp_connections_pending, hikaricp_connections_acquire_seconds, and hikaricp_connections_usage_seconds. For PgBouncer, I scrape SHOW POOLS and SHOW STATS every 15 seconds. The critical signals are cl_waiting (clients queued), sv_active vs sv_idle, and average query_wait time. If cl_waiting stays above 10 for minutes, your default_pool_size or max_db_connections is too low, or a downstream query is slow and holding backends hostage.

-- Run on the PgBouncer admin console
SHOW POOLS;
-- sample output columns: database, user, cl_active, cl_waiting, sv_active, sv_idle, maxwait

SHOW STATS;
-- columns: database, total_xact_count, total_query_count, avg_xact_time, avg_query_time

# Example Prometheus alert for pool saturation
- alert: PgBouncerPoolSaturated
  expr: pgbouncer_pools_client_waiting > 20
  for: 2m
  labels:
    severity: warning
  annotations:
    summary: "PgBouncer pool {{ $labels.database }} has {{ $value }} waiting clients"

Finally, plan for zero-downtime changes. Rotating PgBouncer config, restarting a JVM fleet, or failing over Postgres all interact with pooling. PgBouncer supports SIGHUP reloads for most settings, but pool_mode changes require a restart. HikariCP can refresh pools on config reload without restarting the whole service. I always roll PgBouncer restarts behind a load balancer with pause and resume, and I test failover by killing one PgBouncer node and watching client retries. If your migrations also involve schema changes, coordinate pooling concerns with Database Migrations Without Downtime: Expand-Contract Pattern so long-running migrations do not hold pooled connections open.

The payoff for getting this right is stability. With proper pooling, your database sees a flat, predictable number of backends regardless of how many application instances you run. Deployments, autoscaling events and retry storms become boring. In my experience, that predictability is what lets you scale the rest of the system with confidence.

Frequently Asked Questions

Can I use PgBouncer transaction pooling with prepared statements?

Not safely with protocol-level prepared statements. PgBouncer in transaction mode reassigns backends between transactions, so a prepared statement created on one backend will not exist on the next. In Java, set prepareThreshold=0 in your JDBC URL to use unnamed prepared statements, or switch to session pooling if you need named prepares. Odysseys protocol-aware pooling is an alternative, but it adds complexity.

What pool size should I set for HikariCP if I have 100 application threads?

Start much smaller than 100. In most web services, only a fraction of threads need a DB connection at once. Measure your active connections under load and set maximum-pool-size to that peak plus 20-30% headroom. For 100 Tomcat threads at moderate query latency, I usually land on 15-25. A pool that is too large creates more server connections than Postgres handles efficiently, while a pool that is too small shows up immediately as pending threads and can be increased incrementally.

Do I need both HikariCP and PgBouncer, or is one enough?

One can be enough depending on your stack. A pure Java fleet under 100 total connections can often run HikariCP alone. A polyglot fleet with Python, Go and Java, or any setup scaling past 200 concurrent clients, benefits strongly from PgBouncer as a global throttle. I run both in production because HikariCP gives per-service control and fast local reuse, while PgBouncer enforces a hard global limit that no single misconfigured service can breach.

Why does my pool report connections are available but queries still queue?

Two common reasons. First, the pool may have idle connections but all server backends are busy on slow queries, so PgBouncer shows sv_active = max and cl_waiting grows even though HikariCP looks healthy. Second, you may be leaking connections by holding them while making HTTP calls or sleeping, so the pool appears full but throughput is low. Check idle_in_transaction in pg_stat_activity and enable HikariCP leak detection to find transactions that hold connections far longer than their query time.

Related Articles

References & Standards: Python Documentation · MDN Web Docs · IETF RFC Standards