skip to content

In PostgreSQL, a food-delivery microservice fleet hits 'sorry, too many clients already' at the lunch peak; why can raising max_connections from 200 to 2000 make things worse, and what do you do instead?

level: seniorimportance: should knowfreq 56%

answer

  1. the error is a symptom
  2. pods times pool size
  3. a process with its own memory
  4. restart, shared memory, standbys
  5. budget, pooler, per-role limits

basics

~20 s

Each admitted connection is a PostgreSQL backend process with its own memory, and more active backends than cores only add contention. Raising the cap needs restarts and invites memory exhaustion; budget per-service connections, cap roles and put a pooler in front instead.

solid answer

~40 s

The error says the fleet's demand, pods times pool size, outgrew the budget, not that the server is short of slots. At 2000, every admitted connection is a separate backend process with private catalog caches, prepared plans and up to `work_mem` per sort or hash node, so a busy peak can exhaust RAM. Once active backends outnumber cores, throughput flattens and latency rises from contention, and snapshot work grows with the number of connected backends. The change itself needs a restart, standbys must be raised first, and shared memory such as the lock table grows with it. Instead: sum the pools against `max_connections` minus the reserves, cap each service with `ALTER ROLE … CONNECTION LIMIT`, reclaim leaked sessions with `idle_in_transaction_session_timeout`, and multiplex through a pooler.

code

sql · 9 lines
sql
ALTER ROLE dispatch_api CONNECTION LIMIT 60;
ALTER ROLE courier_tracking CONNECTION LIMIT 40;
ALTER ROLE menu_service CONNECTION LIMIT 30;

SELECT usename, state, count(*) AS backends
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY usename, state
ORDER BY backends DESC;

go deeper

for a junior

Remember that each PostgreSQL connection is its own server process, so connections are expensive and the limit is kept low on purpose.

for a middle

Explain what grows with the cap and with admitted connections: shared memory at startup, private memory per backend, work_mem per node and the restart.

for a senior

Turn the error into a connection budget per service, enforce it with role limits and pool sizes, and know when a pooler is the only fix that scales.

for a principal

Argue capacity in active backends per core rather than connection counts, and own the cross-team budget so autoscaling cannot outgrow it.

## Read the error as a budget overrun At the lunch peak the fleet autoscales. If 40 pods each run a pool of 10 connections to the order-dispatch database, demand is 400 client backends against a cap of 200, and new pods start failing with `FATAL: sorry, too many clients already` (SQLSTATE `53300`). The tempting fix is to set `max_connections = 2000`. That treats the cap as the problem, when the cap is what stopped the server from being overloaded by connections it cannot serve well. ## What the setting itself costs - **A restart, in order.** `max_connections` has `postmaster` context. On a replicated cluster every standby must run with a value at least as high as the primary's, so the standbys are raised and restarted first, then the primary: a planned operation, not an incident fix. - **Shared memory sized per slot.** The server sizes its per-process entries and the shared lock table at startup, and the lock table holds `max_locks_per_transaction` (default 64) entries per server process or prepared transaction. Ten times the slots means a correspondingly larger allocation, whether or not the slots are used. Those costs are modest. The serious cost is what the higher cap **admits**. ## What the extra connections cost Each admitted connection is a separate **backend process** (the process model is covered under the architecture topic), and in PostgreSQL that has concrete consequences: - **Private memory per backend.** Every backend builds its own caches of catalog rows and relation descriptors, which grow with the number of tables and partitions it touches, plus its own cached plans for prepared statements and, if it uses temporary tables, its own temporary buffers. - **Query memory multiplies.** Each sort or hash node in a running query may use up to `work_mem` (hash nodes more, via `hash_mem_multiplier`), so the worst case scales with active backends times nodes per plan. Sizing those settings belongs to the memory topic, but 2000 busy backends turn a safe `work_mem` into a memory-exhaustion risk. - **CPU contention.** When far more backends are active than there are cores, they queue for CPU and for shared lightweight locks; throughput stops rising and latency climbs. - **Snapshot cost.** Building a snapshot scans the shared array of connected backends, so each statement does work proportional to how many are connected, idle ones included. - **Idle is not free.** An idle backend still holds its memory and its process slot, and one left **idle in transaction** keeps locks and holds back vacuum's cleanup of dead rows. The manual's own advice for memory pressure says it directly: it may be better to reduce `max_connections` and use external connection-pooling software. ## What to do instead 1. **Budget the connections.** Available ordinary slots are `max_connections` minus `superuser_reserved_connections` minus `reserved_connections`. Subtract headroom for migrations and jobs, then divide by the maximum pod count to get the per-pod pool size, and enforce it in configuration. 2. **Cap each service.** `ALTER ROLE dispatch_api CONNECTION LIMIT 60` stops one service starving the others; the limit counts regular backends, is approximate under races, and does not apply to superusers. 3. **Keep an operator path open** with `reserved_connections` and the `pg_use_reserved_connections` role. 4. **Reclaim leaks** with `idle_in_transaction_session_timeout` for the application roles, and `idle_session_timeout` for interactive users. 5. **Multiplex** many client connections onto few server connections with an external pooler; its pool modes and settings belong to the PgBouncer topic. | Lever | What it changes | Restart? | |---|---|---| | `max_connections` | the server-wide cap | yes, standbys first | | `reserved_connections` | the operator band inside the cap | yes | | `ALTER ROLE … CONNECTION LIMIT` | one service's share | no | | `idle_in_transaction_session_timeout` | how long a stuck transaction may idle | no | | external pooler | how many server backends serve the fleet | no | ## Verifying the fix After the change, count client backends per role during the next peak and compare them with each role's limit. A healthy result is a server whose active backends stay near a small multiple of its cores, with the waiting done in the pools rather than inside PostgreSQL. Watch for the failure moving rather than disappearing: if a role now hits `too many connections for role`, its pods are still sized for more than their share, and the fix belongs in that service's pool configuration, not in another increase.

  • The fleet scales from 20 to 60 pods at lunch; how do you size each pod's pool against max_connections = 200?
    Start from ordinary slots: 200 minus `superuser_reserved_connections` (3) minus `reserved_connections` (say 10) is 187. Keep about 17 for migrations, jobs and operators, leaving 170, then divide by the peak pod count: 170 / 60 is under 3 per pod. That is too small to be useful, which is the signal that the fleet needs a pooler between the pods and PostgreSQL rather than a higher cap.
  • If you do raise max_connections on a primary with streaming standbys, what order must the restarts follow?
    Raise it on every standby and restart them first, then raise it on the primary and restart it. A standby must run with a `max_connections` at least as high as the primary's, otherwise it will not allow queries. Lowering the value runs the other way round: primary first, then the standbys.
  • Why is a per-role CONNECTION LIMIT described as approximate?
    A new backend claims its process slot before it counts the role's existing sessions, so two logins arriving at the same moment can both see the role over its limit and both be refused, where ideally one would succeed. PostgreSQL accepts that race instead of locking, and superusers are not counted at all, so treat the limit as a guard rail, not an exact quota.

Raising max_connections is like letting more cooks into a kitchen that still has the same eight burners: each cook brings their own knives and board and takes up space, and once every burner is busy the newcomers only get in the way, so meals come out slower, not faster.

  • Idle connections cost PostgreSQL nothing, so a high max_connections is harmless.
  • PostgreSQL serves each connection with a lightweight thread, so 2000 is cheap.
  • Raising max_connections takes effect on reload, so it is a quick incident fix.
  • More connections always mean more throughput while CPU is below 100%.
  • The standbys can keep their old max_connections after the primary is raised.