Traffic climbs, the HPA does its job, and your pod count doubles in under a minute. Then latency gets worse instead of better, and the logs fill with FATAL: sorry, too many clients already. Kubernetes autoscaling and database connections grow in different ways: every new pod brings its own connection pool, while the database has a fixed number of slots. The fix starts with a number many teams never write down.
Quick answer: every pod opens its own database connection pool, so total connections grow with each replica. When the Horizontal Pod Autoscaler adds pods, it adds connections the database may not have. Set maxReplicas from your database's max_connections backward, leave room for rollouts, workers and admin access, and add PgBouncer or RDS Proxy when the budget gets tight.
Defaults in this post were checked against the current Kubernetes, PostgreSQL, PgBouncer, KEDA 2.21 and Amazon RDS documentation in December 2026.
How Kubernetes Autoscaling Multiplies Database Connections
Your application doesn't share one connection pool across the cluster. Each pod runs its own, and a pod with several worker processes (Gunicorn, Puma, or Node in cluster mode) can run one pool per process. HikariCP, a common Java pool, defaults to a maximum of 10 connections and keeps all 10 open even when they're idle. So 20 pods can hold 200 connections, while a stock PostgreSQL server allows about 100.
The Kubernetes HPA knows none of this. It watches CPU, memory or a custom metric, and by default it has no stabilization window on the way up. It can double the pod count, or add four pods if that's more, every 15 seconds (Kubernetes HPA docs). A spike can take your API from 6 pods to 24 in well under a minute, and with HikariCP's defaults, each new pod fills its pool as it starts.
It gets worse when the database is the reason traffic looks heavy. If you scale on request latency or queue depth, one slow query makes every pod look overloaded, so the HPA adds pods, the pods add connections, and PostgreSQL (one process per connection) has even less room to finish the slow queries. Autoscaling is also only one of the things adding connections behind your back.
Rolling Updates, Workers and Other Hidden Connections
A rolling update runs old and new pods side by side for a while. By default, a Deployment can create 25% more pods than its replica count during an update, and pods that are still terminating don't count toward that limit. Kubernetes warns that the total can run above replicas + maxSurge until their grace period ends (Kubernetes Deployments docs). Ship a release during a traffic peak, with the HPA already at its ceiling, and you're above the maximum you planned for.
Then there's everything that connects besides your API:
Queue workers and background consumers, often with their own Deployment and their own HPA
CronJobs for reports, cleanups and billing runs
Database migrations that run at deploy time
Monitoring agents, BI tools, and the engineer with a psql session open
PostgreSQL also holds back superuser_reserved_connections (3 by default), and PostgreSQL 16 and later add reserved_connections (0 by default), so your applications get fewer than max_connections. On Amazon RDS for PostgreSQL, the default limit comes from instance memory: LEAST({DBInstanceClassMemory/9531392}, 5000) (Amazon RDS quotas). Run SHOW max_connections; and use the real value, because that number is the top of your connection budget.
How to Calculate a Database Connection Budget
A connection budget is the database limit, split ahead of time between everything that connects. You work it from the database backward:
(maxReplicas + surge pods + terminating pods) × pools per pod × pool size
+ the same line for every other Deployment on this database
+ job and migration connections
+ reserved slots and an admin buffer
≤ max_connectionsAs an illustration, say SHOW max_connections; returns 200. You set aside 20 for the reserved superuser slots, admin access, migrations and monitoring, counting each slot once. Queue workers run at most 4 pods with one pool of 5 each, which takes another 20. That leaves 160 for the API.
The API's HPA tops out at 12 replicas. A 25% surge adds 3 pods during a rollout (Kubernetes rounds the surge up), and you allow 2 more for old pods that are slow to shut down, so you plan for 17. With one pool per pod, 160 divided by 17 is a little over 9, so each pool gets a maximum of 9. If every pod ran two worker processes, that would drop to 4.
Treat that number as a ceiling, not a target. HikariCP's own pool-sizing guide argues that smaller pools often give better throughput, so load test below it and raise the pool only when measurements show a gain. Then put the result in the manifest, next to the number it protects:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: api
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: api
minReplicas: 3
maxReplicas: 12 # budget: 17 pods (incl. surge + terminating) x pool 9 = 153 of 160
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
behavior:
scaleUp:
policies:
- type: Pods
value: 2
periodSeconds: 60The comment tells the next engineer why maxReplicas is 12, so nobody raises it during an incident without checking the database. The behavior block adds at most 2 pods a minute, trading some speed in a sudden spike for a database that stays up. Add the connection count to your release checks too, next to the steps in our release rollback checklist for SaaS teams.
Sometimes the math doesn't work, though. The budget allows 17 pods and peak traffic needs 40, and at that point the pods have to share database connections.
Connection Pooling With PgBouncer or RDS Proxy
An external pooler sits between your pods and the database. Pods open client connections to the pooler, and the pooler keeps a smaller set of real connections to PostgreSQL. In PgBouncer's transaction mode, a server connection is assigned to a client only for the length of a transaction, then goes back to the pool. Its default_pool_size is 20 server connections per user and database pair unless you change it (PgBouncer config).
That's how 40 pods can share a few dozen database connections. Transaction mode has a cost: PgBouncer's feature table lists SET/RESET, LISTEN and session-level advisory locks as unsupported in that mode, so test your application against it in staging first. A PgBouncer sidecar in every pod brings the multiplication back, because each sidecar opens its own server connections. A shared PgBouncer Deployment keeps the count fixed, as long as the budget counts each replica's pool.
On AWS, RDS Proxy does the same job as a managed service. MaxConnectionsPercent caps how much of the database's max_connections the proxy can use, and session pinning, which ties a client to one database connection, cuts the reuse you added it for.
PgBouncer | RDS Proxy | |
Where it runs | In your cluster or on a VM, managed by you | Managed by AWS |
Main limit | default_pool_size per user and database pair, per PgBouncer instance | MaxConnectionsPercent of max_connections |
Watch for | Session features in transaction mode, sidecar multiplication | Pinning, which stops connection reuse |
Cost | Your compute and your team's time | $0.015 per vCPU-hour of the database instance (2 vCPU minimum) |
The budget still applies one layer up. The pooler's server connections count against max_connections, and the pods' small pools count against what the pooler accepts. Pooling also doesn't change why the HPA added those pods.
Scale on Signals Your Database Can Handle
CPU tells the HPA how busy a pod is. It says nothing about whether the database can take more work. For queue workers, queue depth is often a better trigger, and KEDA, the CNCF event-driven autoscaler, feeds metrics like queue length into the HPA. KEDA also has a PostgreSQL scaler that scales on the result of a SQL query you write, such as a count of pending jobs (KEDA PostgreSQL scaler).
Avoid scaling pods up because database CPU or connection count is rising, since more pods add load to the system that's already struggling. Let pending work drive scaling and let the database cap it. KEDA's maxReplicaCount defaults to 100 if you leave it out, so set it from the same budget. Then make sure you'll know when that budget is close to running out.
Monitor Database Connections Before Users Notice
Watch connections in use against max_connections, connections per application, sessions stuck idle in transaction, and how long pods wait to get a connection from their pool. Alert early enough to act before too many clients errors reach users. If you run PgBouncer, SHOW POOLS; reports cl_waiting, the clients that sent a query and are still waiting for a server connection. This query shows who's holding connections in PostgreSQL:
SELECT usename, application_name, state, count(*)
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY usename, application_name, state
ORDER BY count(*) DESC;Then test the worst case on purpose. In staging, push the HPA to maxReplicas, run a rolling deploy, start the workers, and watch running and terminating pods next to the connection count. If it stays under budget, your numbers hold. If not, you found the problem on a quiet afternoon instead of during a launch.
When we moved a Middle East fintech client's .NET backend to Kubernetes on Oracle Cloud, autoscaling for fluctuating traffic was one of the requirements. We enabled it together with centralized logging and monitoring, then ran end-to-end tests before go-live (fintech Kubernetes migration case study). We treat them as one design, because Kubernetes autoscaling, database connections and monitoring each change the limits of the other two.
When to Bring In Outside Help
Most teams can do this themselves. Run SHOW max_connections;, add up every pod, process, worker and job that connects, and set maxReplicas from the result. It takes an afternoon and one comment in a manifest.
Outside help makes sense when several services share one database and nobody owns the total, when you need to choose PgBouncer or RDS Proxy under a deadline, or when a spike already took the database down. Our DevOps consulting and automation team reviews autoscaling, pooling and alerting together, and if your budget already adds up, we'll tell you that.
Frequently Asked Questions
What happens if your database connection pool is full?
New requests wait for a free connection until the pool's timeout runs out, then fail with a timeout error. In Kubernetes, that wait often shows up first as rising latency, which can make the HPA add pods and open even more connections.
What is the right database connection pool size in Kubernetes?
There's no single number. Take the connections your API can use after workers, jobs and reserved slots, and divide by your peak pod count (maxReplicas plus surge and terminating pods) times the pools in each pod. That gives the ceiling. Load testing tells you how far below it to run.
Why do I get "sorry, too many clients already" after a deployment?
During a rolling update, new pods open their pools while old pods, including ones still terminating, keep theirs. Once every non-reserved slot is taken, PostgreSQL rejects new connections with SQLSTATE 53300 (too_many_connections). Budget for surge and terminating pods, shrink the pools, or add a pooler.
Should I just increase max_connections?
Only after checking that the database can handle it. PostgreSQL runs a process for each connection, so more connections use more memory. A pooler usually gives more headroom than a higher limit.
Scale your Kubernetes workloads, not your database bottlenecks.
