Database connection pooling on Kubernetes reuses backend database connections across application requests. For PostgreSQL, start with a connection budget that includes maximum pod replicas, processes, rollout overlap, and background jobs. A shared pooler can decouple application connections from backend connections, but its own replicas and limits must fit that budget.
Key takeaways
- Budget connections across replicas, processes, jobs, and rollout overlap.
- A Kubernetes Service does not impose one global pooler connection limit.
- Readiness failures remove traffic; they do not restart containers.
- Validate transaction-mode compatibility, queueing, and recovery before rollout.
Autoscaling can expose an undersized connection budget. Connection leaks, long transactions, and oversized application pools can cause similar symptoms. An idle transaction may retain locks or an old snapshot and interfere with cleanup. Diagnose the cause before changing limits; pooling does not automatically fix inefficient SQL or application behavior.
Why Kubernetes Makes Connection Exhaustion Worse
Consider a hypothetical checkout service with 12 pods, four worker processes per pod, and a maximum of five connections per worker. Its potential demand is 240 connections before rollout overlap. If HPA scales it to 48 pods, that ceiling becomes 48 ร 4 ร 5 = 960. These are configured maxima, not a measured incident or proof that every connection will be open.
When available database slots run out, new connection attempts fail. Unbounded retries can amplify load. A failed readiness probe removes a pod from normal Service traffic; it does not restart the container. Liveness or startup probe failures can trigger restarts, which may add reconnect pressure. See the Kubernetes pod lifecycle.
Five multipliers the database never sees
Include these consumers in the budget, even when the steady-state pod count looks safe:
- Rollout surge.
maxSurge: 25%runs old and new pods at once, and both hold sessions. - Canary and blue-green overlap. Two versions of one service count against one budget.
- Terminating pods. A pod that received SIGTERM holds its sessions until the driver closes them.
- CronJobs and workers. A nightly batch inherits the API pool config and runs during the largest scale-up.
- Multiple processes per pod. Gunicorn, uvicorn, and PHP-FPM each fork workers with their own pools.
CPU utilization alone may not reveal time spent waiting for a connection. HPA can also use custom or external metrics, but adding application replicas does not create database capacity. Monitor pool acquisition time, database saturation, and request latency together.
Distinguish application-pool waits from database connection exhaustion. Clients can wait inside HikariCP, pgx, or SQLAlchemy because their local pool is full, whether or not the database has headroom. Database exhaustion occurs when aggregate sessions reach its available slots. Increasing max_connections is not a substitute for finding which queue is limiting requests.
Connect through the pooler endpoint
A shared pooler sits between application clients and the origin database. Applications must use the pooler endpoint to benefit from it. The Cast AI PostgreSQL example below shows that distinction: DBO HOST is the application-facing proxy address, while Host identifies the origin database. Cast AI uses PgDog for PostgreSQL; this is not a PgBouncer configuration screen.

The Sizing Math: Budget Divided by Maximum Replicas
Start from what Postgres will actually grant your applications, not from the raw setting.
SELECT name, setting, source
FROM pg_settings
WHERE name IN ('max_connections',
'superuser_reserved_connections',
'reserved_connections');Read the actual settings rather than assuming a default. max_connections is a startup setting; reserved slots are included within it. reserved_connections is available in PostgreSQL 16 and later. Keep separate headroom for ordinary monitoring, migration, and operational sessions. Account for replication according to its connection type and provider configuration rather than subtracting an arbitrary number twice. See PostgreSQL connection settings.
For illustration, a 100-slot server with three superuser-reserved slots, no additional reserved slots, and seven ordinary operational connections leaves:
100 max_connections
-3 superuser_reserved_connections
-0 reserved_connections
-7 ordinary operational headroom
---
90 application connection budgetThis is a worst-case capacity model. Application pools may retain idle connections, so count configured limits rather than assuming connections exist only during a request. Percentage surge values need integer rounding; count terminating pods separately. If services have different pool limits, calculate each service separately.
potential_connections = SUM over services of
(max_replicas + surge_pods) * processes_per_pod * pool_max
+ job_connections + terminating_pod_connections
For one common pool_max across services:
pool_max <= floor((budget - fixed_consumers) /
SUM((max_replicas + surge_pods) * processes_per_pod))A worked example you can substitute
Consider a checkout service, a payments service, and a reporting worker on one cluster, all pointing at the primary above. Each row multiplies four factors: maxReplicas, the surge factor, processes per pod, and pool_max per process. The surge factor is 1 plus the allowance, so 1.25 here.
service maxRepl surge_f procs pool_max potential connections
checkout 48 1.25 4 1 240
payments 16 1.25 4 1 80
reporting 4 1.00 1 2 8
---
subtotal 328
illustrative termination allowance: ceil(10%) 33
---
total 361The subtotal is 328, and a rounded-up 10% allowance adds 33, for 361 potential connections. That exceeds the example budget of 90. The 10% allowance is an illustration: replace it with the overlap your termination and rollout behavior permit. A one-connection pool serializes work within each worker, not across the entire service; whether that is sufficient depends on concurrency and latency requirements.
With a shared pooler, budget backend connections across every pooler process, database alias, and direct connection. A Service is a stable endpoint, not a global connection limiter. The following example assumes one database alias and controlled one-at-a-time replacement:
90 application connection budget
3 steady pooler pods x 20 backend connections = 60
4 overlapping pooler pods x 20 = 80
remaining headroom at that overlap = 10
If more than 4 pooler processes can overlap, recalculate.The limit of 20 is per pooler process for the configured database alias. All user pools for that alias share that cap. Multiple aliases pointing to the same PostgreSQL database can multiply it. Client admission limits and queues are separate: application scale-out may increase waiting time even when backend connections stay within budget.
Why raising max_connections is usually the wrong lever
A higher max_connections increases shared resource requirements and permits more concurrent backend work. Memory use also depends on active queries, session state, and other settings; it does not follow a universal fixed cost per slot. Verify available CPU, memory, I/O, and workload throughput before raising the limit.
Past a point, more connections also make the database slower. Sessions compete for the same cores, lock waits rise, and throughput flattens. No universal number exists, since the answer depends on whether your workload is CPU-bound, I/O-bound, or lock-heavy. Measure latency and throughput under representative load instead.
An application replica cap can be a useful guardrail, but include worker processes, other services, rollout overlap, and jobs in the calculation. Choose a capacity and admission-control design that meets request targets instead of assuming that either more pods or a pooler removes the bottleneck.
PgBouncer on Kubernetes: Sidecar vs Centralized Deployment
Both sidecars and centralized poolers need an aggregate budget. The difference is which replica count multiplies backend pools: application pods for sidecars, or pooler replicas for a shared Deployment.
Sidecar: the per-pod pooling pattern
A PgBouncer sidecar lets the application connect over localhost. It couples pooler capacity and configuration to each application pod. With one database/user pool per sidecar, 50 sidecars configured for 10 backends each can allow 500 backend connections. Additional user or database pools can increase that total. Sidecars can work when their maximum aggregate demand is explicitly bounded.
Centralized: one Deployment behind a Service
A shared PgBouncer Deployment behind a ClusterIP Service gives applications a stable endpoint and separates pooler replicas from HPA-driven application replicas. Set backend caps for each PgBouncer process and account for rollout overlap. Spread replicas across failure domains where capacity allows. Topology-aware routing may reduce cross-zone traffic, but placement and routing behavior need verification; cross-zone connections are not inevitable.
The replica-count threshold
Choose by the aggregate backend limit, operational ownership, and failure isolation. Centralizing is useful when many services need one managed endpoint; it still requires capacity planning and high availability.
There is no universal 10- or 15-pod threshold. With a budget of 90 and one five-connection backend pool per sidecar, the arithmetic permits 18 sidecars before other consumers or overlap. Different users, databases, pool sizes, and operational headroom change that result.
| Criterion | Sidecar PgBouncer | Shared PgBouncer Deployment |
|---|---|---|
| Backend budget | Sum across application pods and database/user pools | Sum across pooler replicas and database aliases |
| Scaling relationship | Pooler count follows application pods | Pooler count can be managed separately |
| Network path | Localhost from application to sidecar | Service endpoint to a pooler pod |
| Failure scope | Usually the colocated application pod | Clients on the failed replica must reconnect |
| Operations | Config and upgrades across workloads | Centralized configuration; HA still required |
The example below illustrates placement and connection limits. Before deployment, replace the database hostname and image placeholder, create the referenced authentication and TLS Secrets, and test the imageโs process and shutdown behavior. Use a maintained, patched PgBouncer build; check the release notes. Resource values are starting examples, not sizing recommendations.
A PgBouncer configuration and Kubernetes deployment example
apiVersion: v1
kind: ConfigMap
metadata:
name: pgbouncer-conf
data:
pgbouncer.ini: |
[databases]
app = host=postgres-primary.internal port=5432 dbname=app
[pgbouncer]
listen_addr = 0.0.0.0
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer-auth/userlist.txt
client_tls_sslmode = require
client_tls_key_file = /etc/pgbouncer-tls/tls.key
client_tls_cert_file = /etc/pgbouncer-tls/tls.crt
server_tls_sslmode = verify-full
server_tls_ca_file = /etc/pgbouncer-tls/ca.crt
pool_mode = transaction
max_client_conn = 800
default_pool_size = 20
min_pool_size = 5
; one database alias: 3 x 20 = 60; 4 overlapping processes = 80
max_db_connections = 20
reserve_pool_size = 5
reserve_pool_timeout = 3
server_idle_timeout = 300
query_wait_timeout = 30
max_prepared_statements = 200
---
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
name: database-pooler-critical
value: 1000000
globalDefault: false
description: "Keeps the connection pooler scheduled ahead of application pods."
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: pgbouncer
spec:
replicas: 3
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 0
maxUnavailable: 1
selector:
matchLabels: {app: pgbouncer}
template:
metadata:
labels: {app: pgbouncer}
spec:
priorityClassName: database-pooler-critical
terminationGracePeriodSeconds: 60
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels: {app: pgbouncer}
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels: {app: pgbouncer}
containers:
- name: pgbouncer
image: YOUR_REGISTRY/pgbouncer:YOUR_APPROVED_PATCHED_VERSION
ports:
- containerPort: 6432
readinessProbe:
tcpSocket: {port: 6432}
initialDelaySeconds: 3
periodSeconds: 5
resources:
requests: {cpu: 100m, memory: 64Mi}
limits: {cpu: 500m, memory: 256Mi}
volumeMounts:
- name: conf
mountPath: /etc/pgbouncer
readOnly: true
- name: auth
mountPath: /etc/pgbouncer-auth
readOnly: true
- name: tls
mountPath: /etc/pgbouncer-tls
readOnly: true
volumes:
- name: conf
configMap:
name: pgbouncer-conf
- name: auth
secret:
secretName: pgbouncer-auth
- name: tls
secret:
secretName: pgbouncer-tls
---
apiVersion: v1
kind: Service
metadata:
name: pgbouncer
annotations:
service.kubernetes.io/topology-mode: Auto
spec:
selector: {app: pgbouncer}
ports:
- port: 6432
targetPort: 6432The example sets a 20-connection backend cap per configured database alias per process. Three steady replicas allow 60; four overlapping processes allow 80. The rollout disables surge, but terminating processes still need monitoring. Recalculate if more overlap is possible. Client connection limits require sufficient file descriptors and memory separately from the backend cap.
The authentication Secret must contain a valid userlist.txt for your chosen authentication flow. A SCRAM verifier alone is not a universal substitute for backend credentials; validate the documented pass-through requirements or use an approved authentication setup. Configure TLS on both application-to-pooler and pooler-to-database hops, verify server names, and restrict access with network policy.
Removing a pod from Service endpoints stops normal routing of new connections but does not close existing TCP connections. A preStop delay alone is not a drain protocol. Modern PgBouncer handles SIGTERM by waiting for clients to disconnect; arrange bounded client reconnection and a sufficient grace period. Older releases differ. See PgBouncer shutdown behavior.
Budget settings and the drain sequence
pool_mode = transaction returns a backend after the transaction, not after each statement in a multi-statement transaction. Reserve connections become eligible after a client waits for reserve_pool_timeout; the timeout is not their lifetime. In this example the database cap still bounds total backend connections. Check PgBouncer configuration semantics for the installed release.
High Availability for the Pooler Itself
A shared endpoint needs multiple healthy pooler replicas and sufficient surviving capacity. PgBouncerโs event loop is single-threaded, but the limiting resource can be CPU, TLS work, sockets, queueing, or the database itself. Measure before deciding how many replicas to run.
Replicas, disruption budgets, and spread
This example uses three replicas and minAvailable: 2. A PodDisruptionBudget limits supported voluntary evictions; it does not prevent crashes, guarantee capacity, or govern the Deploymentโs own rolling-update strategy. Test loss of a replica and a node while observing client errors and queueing.
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: pgbouncer
spec:
minAvailable: 2
selector:
matchLabels: {app: pgbouncer}Failover, draining, and what PgBouncer cannot do
PgBouncer does not elect a PostgreSQL primary. Your database operator or managed service owns that failover. server_round_robin changes reuse order, not write-routing policy. Use a backend endpoint and reconnection design that follow the current primary.
Drain one replica at a time and confirm clients reconnect to healthy replicas. server_idle_timeout applies to unused server connections; it is not a deadline for all clients to leave. Test planned shutdown and database failover separately, including retry limits and transaction recovery.
What to alert on
Read SHOW POOLS and SHOW STATS, or expose them through a compatible PgBouncer Prometheus exporter. Track waiting clients, wait duration, active/idle server connections, client errors, and database saturation. Confirm metric names and labels from the installed exporter.
For an exporter exposing this waiting-client metric, a Prometheus rule can alert on sustained queueing. Adapt the labels and duration to your deployment:
groups:
- name: pgbouncer
rules:
- alert: PgBouncerClientsWaiting
expr: sum by (instance) (pgbouncer_pools_client_waiting_connections) > 0
for: 2m
labels:
severity: warning
annotations:
summary: "PgBouncer clients have been waiting for two minutes"Compare those signals with pg_stat_activity, transaction age, lock waits, and application pool metrics. Idle connections are normal in many pools and do not by themselves prove a leak. For broader diagnosis, see database observability and the PostgreSQL slow-query workflow. For MySQL workloads, use the slow MySQL query troubleshooting guide.
psql -h pgbouncer -p 6432 -U admin pgbouncer -c "SHOW POOLS;"
psql -h pgbouncer -p 6432 -U admin pgbouncer -c "SHOW STATS;"The Prepared-Statement Trap
PgBouncer defaults to pool_mode = session, which behaves like a direct connection and supports every PostgreSQL feature. Transaction mode releases the server connection at the end of each transaction. That is what makes pooling effective, and it is what breaks session-scoped features. Prepared statements are the complaint that sends teams back to session mode with a shrug.
PgBouncer 1.21 introduced support for named protocol-level prepared statements in transaction pooling when max_prepared_statements is nonzero. Its default changed to 200 in 1.24. Check the actual release and configuration rather than assuming an ORM is compatible without testing.
Drivers and ORMs still need validation before you rely on it. Some issue SQL-level PREPARE instead of protocol-level prepares, and PgBouncer never tracks that form, so it still breaks. Check your ORM’s connection mode first. The setting also costs server-side memory per connection, so 200 is a default, not a target.
What still breaks, and how to route around it
Transaction pooling does not preserve an arbitrary PostgreSQL session across transactions. Features such as LISTEN, session advisory locks, holdable cursors, and session-persistent temporary tables need special handling. Some parameters are tracked, so โevery SET command breaksโ is too broad. Use the PgBouncer feature matrix and test the applicationโs actual session behavior.
For PgBouncer workloads that require a persistent session, use an appropriate session-mode endpoint. Do not transfer PgBouncer limitations automatically to other poolers: Cast AIโs current PgDog documentation explicitly supports LISTEN/NOTIFY, while warning that session modifiers do not persist across transactions. For product differences, see PgBouncer vs RDS Proxy vs ProxySQL.
Rightsizing Pods Changes the Pool Math Too
With a CPU-utilization HPA target, utilization is measured against the CPU request. Changing requests changes that denominator. It does not change the configured maxReplicas value. Coordinate rightsizing, HPA targets, and connection limits using the HPA calculation.
At 80m CPU usage and a 300m request, utilization is about 26.7%. With a 120m request and the same usage, it is about 66.7%. Against a 65% utilization target, lowering the request increases measured utilization and may increase desired replicas, subject to tolerance and stabilization. Rightsizing does not automatically reduce connection demand.
Pod replacement and node consolidation can also create overlapping connections. Include terminating pods in the budget and close application pools cleanly. The Kubernetes overprovisioning guide provides the broader resource context; it does not replace database capacity planning.
When You Do Not Want to Run the Pooler Yourself
Cast AI Database Optimizer combines read-only query and index recommendations with optional caching and connection pooling. Pooling uses PgDog for PostgreSQL and ProxySQL for MySQL. The pooler is deployed in your infrastructure, and applications route through its endpoint. Enabling pooling requires a deployment change, not only a dashboard toggle.
In the Connections view, compare application-side and database-side counts over the same time window. A lower backend count demonstrates connection reuse in that view; it does not prove lower latency, savings, or a universal safe ratio. Set pool capacity against database headroom and validate behavior during peak load and failover.
DBO manages pooler configuration, while your team still owns application compatibility, capacity choices, deployment validation, and recovery testing. Do not assume that adopting it removes all responsibility for credentials, availability, or upgrades. The connection pooling documentation describes the current deployment model.
Current Cast AI PostgreSQL documentation supports LISTEN/NOTIFY through PgDog and warns about session state spanning transactions. Validate session modifiers, temporary tables, advisory locks, and your driverโs prepared-statement behavior before rollout. Confirm supported versions in the current setup documentation rather than relying on a fixed version range in this article.
Conclusion
Write down the database budget, then include all application workers, pooler replicas, rollout overlap, and direct clients. Test the failure modes that matter: a traffic spike, a deployment, a lost pooler, and database failover. Track waiting time and request errors alongside the connection count.
For related decisions, use the connection pooling comparison and database optimization guide. Pooling controls connections; query optimization techniques and database caching address different sources of database work.
Frequently asked questions
There is no universal number. Divide an explicit application budget across maximum replicas and processes, including jobs and rollout overlap, then validate the resulting concurrency against latency and throughput.
Sidecars couple pooler count to application replicas. A shared Deployment separates those counts, but all pooler replicas and database aliases still need one aggregate backend budget.
No. A readiness failure removes the pod from normal Service traffic. Liveness or startup probe failures can restart a container, subject to its restart policy.
In compatible PgBouncer releases, named protocol-level prepared statements can work with max_prepared_statements enabled. SQL-level PREPARE and other session features have different constraints. Test the exact pooler, version, driver, and settings.
No. For a utilization-based HPA target, reducing CPU requests raises measured utilization at the same CPU usage and may increase desired replicas. Recalculate connection demand after rightsizing.
Cast AI Database Optimizer uses PgDog for PostgreSQL and ProxySQL for MySQL. Pooling is optional and requires application traffic to use the proxy endpoint.



