Why PostgreSQL Connection Pooling Gets Harder in Kubernetes
A routine deployment can exhaust PostgreSQL connections without any increase in traffic. New pods open their pools while terminating pods still hold database sessions. Add several worker processes per pod, and connection demand can grow much faster than the replica count suggests.
Connection pooling is supposed to absorb that churn. In Kubernetes, however, pool sizing, autoscaling and termination operate independently. Each component can behave as configured while the database runs out of capacity.
A useful connection budget includes pods that are already on their way out.
Budget for Every Connection Owner
Consider an API with 12 pods where there are four worker processes per pod and at most five database connections per worker process. If connecting directly to PostgreSQL, the ceiling is 240 sessions. The addition of three more pods to the deployment makes it possible to reach 300 connections before considering background tasks, migrations and terminations of pods. These values apply to pools connecting lazily. Even in cases where traffic and deployment coincide, the ceiling is important.
Kubernetes mentions that terminating pods may create situations where resources consumed exceed replicas + maxSurge. Connection slots consumed by these terminated pods need to be budgeted separately.
The starting point is the max_connections; after deducting any reserved connections and an operational buffer, distribute the rest among workloads. An increase in max_connections also means more allocations in PostgreSQL, including shared memory allocations. The number of connection slots available does not tell us the number of queries that the database will run efficiently.
An application allocation of 270 connections is below the ceiling in the example above. Before making this rollout, the number of per-worker pools should be decreased or connections made through transaction poolers.
PgBouncer Replicas Have Independent Limits
A PgBouncer sidecar gives each application pod a nearby pooler. Every new pod also adds independent backend pools. Shared PgBouncer Deployment allows application replicas to use a limited number of backends, but each PgBouncer replica has individual limits.
PgBouncer allocates pools based on database/user pairs. With reserve pools disabled and aggregate connection limits set to 0, the total capacity of three PgBouncer instances running four database/user pairs with the default value of default_pool_size=20 is equal to 240 backends. The parameter max_client_conn is responsible for incoming client connections; it does not set any ceiling for backends.
Configure max_db_connections and max_user_connections individually for each instance and calculate total capacity considering database aliases referring to the same PostgreSQL database and replicas sharing poolers while performing updates.
In case of using one PostgreSQL database from three instances limited to 60 server connections each, there are 180 available connections; deployment of the fourth instance increases the total exposure to 240. After failure of one of the poolers, other poolers should accommodate reconnecting clients within the current limits.
Unevenness of capacity is also possible. Kubernetes Service chooses a destination for a TCP connection. Current sessions are kept in the corresponding pooler, so deployment of an additional PgBouncer replica may be unused, while other replicas have queues. Evaluate each instance before deploying a new one.
Transaction Pooling Changes Session Assumptions
Under session mode, PgBouncer creates a backend for the lifetime of the client’s connection. Persistent application pools are capable of keeping PostgreSQL sessions alive even if they remain idle. Under transaction mode, PgBouncer releases the backend connection back to the pool after every transaction, allowing more clients to share fewer database sessions.
Explicit transactions are sticky between statements. Starting a transaction, fetching rows, invoking an external API and committing will keep a backend busy through the entire process. Try to move irrelevant network activity outside the transaction if possible, and set idle_in_transaction_session_timeout as a precaution.
This requires conducting an application compatibility check first. Features like session-level advisory locks, LISTEN subscriptions and temporary tables that must persist across transactions require the same backend throughout execution. Schedule such workloads using a separate pool of sessions or a dedicated connection.
Transaction-specific parameters should be set by running SET LOCAL within a transaction. Running session-level SET inside an init script cannot replicate this functionality.
Useful prepared statements have to be verified. PgBouncer supports protocol-level prepared statements under transaction mode only if max_prepared_statements parameter is greater than 0. This does not cover SQL PREPARE across multiple transactions. Conduct a proper test of the driver and ORM configuration.
Autoscaling Can Deepen the Queue
An autoscaler using request latency can respond to database contention by adding application pods. Each pod adds workers and client connections while database throughput stays constrained. CPU-based scaling can miss the incident when workers spend their time waiting.
Consider an illustrative workload completing 1,000 transactions per second with 20 milliseconds of average backend occupancy. Little’s Law gives roughly 20 occupied backend connections on average. If occupancy rises to 200 milliseconds at the same throughput, that becomes 200. These are steady-state averages, not pool-size recommendations. Lock waits and application pauses inside transactions count toward occupancy.
Measure waiting at each layer: application pool acquisition, PgBouncer backend assignment and PostgreSQL execution. SHOW POOLS exposes cl_waiting and maxwait; pg_stat_activity exposes transaction start times and wait events.
Fit application acquisition limits, PgBouncer’s query_wait_timeout and execution timeouts within the request’s overall deadline. PostgreSQL’s statement_timeout cannot cover time spent waiting outside PostgreSQL. Bound retries and propagate cancellation so expired requests do not continue consuming database capacity.
With multiple poolers behind a TCP load balancer, configure PgBouncer peering when needed. Cancellation travels over a separate connection and may reach another instance.
Keep liveness probes independent of ordinary pool exhaustion. Restarting healthy application processes because database checkout times out discards their pools and triggers fresh connections against an overloaded dependency. Apply admission limits or return controlled failures while capacity recovers.
Treat Draining as Part of Pooling
Readiness changes affect new traffic. Existing client sockets need an explicit shutdown policy.
During application termination, stop accepting work, finish or cancel transactions, and close the client pool. Keep a PgBouncer sidecar alive until application work drains. Kubernetes native sidecars, defined as init containers with restartPolicy: Always, provide shutdown ordering; ordinary containers do not guarantee it.
For pooler updates, remove the instance from new-connection routing and drain its clients within terminationGracePeriodSeconds. A preStop hook consumes that same grace period.
PgBouncer 1.23 and later treat SIGTERM as waiting for clients to disconnect. Long-lived client pools can therefore prevent shutdown from completing. Older versions terminate immediately on that signal. Check the deployed version and arrange bounded, staggered client reconnection before Kubernetes reaches SIGKILL.
During database failover, established backend sockets can break. Reconnect with bounded backoff, and replay only transactions the application can safely retry.
Conclusion
Test pooling with a rollout under load, a slow database and long-lived clients. Measure peak backend connections, acquisition delays and completed transaction throughput. Repeat with a pooler replica unavailable.
Connection pooling in Kubernetes becomes manageable when replica limits, per-instance pool budgets and shutdown behavior form one capacity plan. The deployment must stay within that plan while pods start, drain and disappear.


