Sub topic 12
Connection limits and connection pooling
This chapter assumes you can edit PostgreSQL and MySQL configuration files, restart the service with systemctl, and run basic SQL. It also assumes you have read the earlier chapters on memory tuning and client authentication. Here you will learn why a database server caps its connections, how to read and change those caps, and how to put a pooler in front of the server when many clients need to connect.
Why connections are limited
Every client connection costs the server resources. PostgreSQL starts a separate operating system process for each connection. MySQL runs one thread per connection. Each connection holds memory for its session state, and any query that sorts or hashes data can claim additional working memory.
A server that accepts unlimited connections can run out of memory, or spend its time switching between sessions instead of running queries. A cap makes the failure visible and early: new clients get an error, and the sessions already running keep working.
The limit also ties back to the memory chapter. Per-session memory multiplied by the number of busy sessions has to fit in RAM alongside the shared buffers (PostgreSQL) or the InnoDB buffer pool (MySQL).
| Setting | Engine | Default | Meaning |
|---|---|---|---|
| `max_connections` | PostgreSQL | 100 | Total client connection slots, including reserved ones |
| `superuser_reserved_connections` | PostgreSQL | 3 | Slots only superusers can use |
| `work_mem` | PostgreSQL | 4MB | Memory per sort or hash operation, per query node |
| `max_connections` | MySQL | 151 | Total client connections allowed at once |
| `max_user_connections` | MySQL | 0 (no limit) | Per-account connection cap |
| `thread_cache_size` | MySQL | autosized | Idle threads kept for reuse |
MySQL allows one extra connection beyond max_connections for an account with the CONNECTION_ADMIN privilege (or SUPER on older versions). Use that account for emergencies, not for applications.
Setting the limits
In PostgreSQL, set the values in postgresql.conf. Changing max_connections needs a full restart, not a reload.
# postgresql.conf
max_connections = 200
superuser_reserved_connections = 3
work_mem = 8MBIn MySQL, put the values in the [mysqld] section. max_connections can also be changed at runtime, but a value set with SET GLOBAL is lost at restart unless you also write it to the file (or use SET PERSIST on MySQL 8).
# MySQL configuration file, [mysqld] section
[mysqld]
max_connections = 200
max_user_connections = 150You can also cap one account or database instead of the whole server. PostgreSQL does this with ALTER ROLE ... CONNECTION LIMIT and ALTER DATABASE ... CONNECTION LIMIT. MySQL does it with MAX_USER_CONNECTIONS on the account.
-- PostgreSQL: the application role may hold at most 150 connections
ALTER ROLE appuser CONNECTION LIMIT 150;
-- MySQL: same cap on the account
ALTER USER 'appuser'@'10.0.0.%' WITH MAX_USER_CONNECTIONS 150;Per-account caps stop one misbehaving application from using every slot. Keep the sum of the caps at or below the server limit minus the reserved slots, so an administrator can still log in.
Checking current usage
Before you raise a limit, look at how many connections are in use and what they are doing.
-- PostgreSQL: connections by state
SELECT state, count(*)
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY state
ORDER BY count(*) DESC;
SHOW max_connections;-- MySQL: current, peak and limit
SHOW GLOBAL STATUS LIKE 'Threads_connected';
SHOW GLOBAL STATUS LIKE 'Max_used_connections';
SHOW GLOBAL VARIABLES LIKE 'max_connections';In PostgreSQL, many sessions in the idle state mean clients are holding connections open without using them. In MySQL, Max_used_connections close to max_connections means you have already hit the ceiling at some point since the last restart.
Recognizing the error
When the limit is reached, clients see an explicit message.
| Engine | Error text |
|---|---|
| PostgreSQL | `FATAL: sorry, too many clients already` |
| PostgreSQL (reserved slots only left) | `FATAL: remaining connection slots are reserved for non-replication superuser connections` |
| MySQL | `ERROR 1040 (08004): Too many connections` |
| MySQL (per-account cap) | `ERROR 1226 (42000): User 'appuser' has exceeded the 'max_user_connections' resource` |
Raising the limit is not always the right response. If the application opens a connection per request and leaves it idle, a higher cap only postpones the same failure and increases memory pressure. The better fix is to reduce the number of server connections the application needs, which is what a pooler does.
How pooling works
A connection pooler is a small proxy that keeps a limited set of real connections open to the database and lends them to many clients. Clients connect to the pooler as if it were the database. The pooler assigns each client a server connection only when the client needs one.
The diagram below shows the flow.
Pooling can happen in two places. Many application frameworks include a client-side pool inside each process. A separate pooler process on the database host or a middle tier shares connections across all application instances. Client-side pools are simple, but their sizes add up: 20 application instances with a pool of 20 each can demand 400 server connections. A shared pooler enforces one total.
Pooling modes
PgBouncer, the common pooler for PostgreSQL, offers three modes. The mode decides when a server connection returns to the pool.
| Mode | Connection returns to pool | Trade-off |
|---|---|---|
| `session` | When the client disconnects | Safest, saves the least |
| `transaction` | When the transaction ends | Best sharing, breaks session state |
| `statement` | After each statement | Forbids multi-statement transactions |
Transaction mode gives the largest reduction in server connections, and most deployments use it. It has a cost: anything that lives in the session may land on a different server connection next time. Session-level SET commands, advisory locks, LISTEN/NOTIFY, temporary tables, and in some versions protocol-level prepared statements do not work reliably. Test the application before switching.
MySQL has no pooler bundled with the server. The usual choices are client-side pools and ProxySQL, a proxy placed between the application and the server. The ideas are the same: cap the server-side connections and let clients queue.
A PgBouncer example
Install PgBouncer on the database host or a nearby host, then write its configuration.
sudo apt install pgbouncer# /etc/pgbouncer/pgbouncer.ini
[databases]
appdb = host=127.0.0.1 port=5432 dbname=appdb
[pgbouncer]
listen_addr = 10.0.0.5
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 20
reserve_pool_size = 5
server_idle_timeout = 600The settings that matter:
max_client_connis how many clients may connect to PgBouncer. It can be far larger than the database limit.default_pool_sizeis how many server connections PgBouncer opens per database and user pair. This is the number that counts againstmax_connections.reserve_pool_sizeadds extra server connections for short bursts.auth_fileholds the user names and password hashes PgBouncer checks. Restrict its permissions, since it contains credentials.
Note that the pooler listens on port 6432 and the database stays on 5432. Open 6432 to the application subnet in the firewall, and consider closing 5432 to everything except the pooler. Applications then change only the port in their connection string.
Start it and verify.
sudo systemctl enable --now pgbouncer
ss -ltnp | grep 6432
psql -h 10.0.0.5 -p 6432 -U appuser appdb -c 'SELECT 1'PgBouncer also has an admin console, reached by connecting to the special database pgbouncer. The command SHOW POOLS; lists active and waiting clients per pool. A growing cl_waiting count means clients are queuing for a server connection, so the pool is too small or queries are too slow.
Sizing the pool
More server connections do not mean more throughput. Once the number of active queries exceeds the CPU cores and disk parallelism of the host, extra sessions only compete with each other. A common starting point is a pool size of roughly two to four times the core count, then measure.
Use this process:
- Count the CPU cores on the database host.
- Set the total server-side connections near two to four times that number.
- Run a realistic load and watch queue time (
cl_waitingin PgBouncer, or application latency). - Raise the pool size only if the database still has idle CPU and disk capacity.
Then set max_connections above the sum of all pool sizes plus the reserved superuser slots, plus a margin for monitoring, backup, and replication connections.
Common problems
- Idle in transaction sessions. A session that opened a transaction and then stalled holds locks and a connection slot. In PostgreSQL, set
idle_in_transaction_session_timeoutto end these automatically. - Connection storms after a restart. Hundreds of clients reconnect at once and hit the limit. A pooler absorbs this because it queues clients instead of rejecting them.
- Raising
max_connectionswithout raising memory. Each extra slot increases worst-case memory use. Recheckwork_memand total RAM after any increase. - Prepared statements and transaction pooling. Clients that rely on server-side prepared statements may fail with "prepared statement does not exist". Disable them in the driver, or use a PgBouncer release that supports protocol-level prepared statements.
- Forgotten backups and monitors. These tools also take connections. Count them when you size the limit.
Exercise
A PostgreSQL server has max_connections = 100 and superuser_reserved_connections = 3. Twenty application servers each run a client-side pool of 10 connections, and you see "sorry, too many clients already". You install PgBouncer in transaction mode with default_pool_size = 20 for one database and one user. How many server connections can the application now use, and what must you check in the application before switching?
Show answer
The application can use at most 20 server connections, plus up to the reserve_pool_size if one is set, instead of the 200 it could demand before. That fits well inside the 97 slots available to non-superusers. Before switching, check whether the application depends on session state, such as session-level SET commands, advisory locks, LISTEN/NOTIFY, temporary tables, or server-side prepared statements, because transaction mode can hand each transaction a different server connection.
Exercise
Which command shows, on a MySQL server, the highest number of simultaneous connections since the last restart, and what does it tell you if the value equals max_connections?
Show answer
SHOW GLOBAL STATUS LIKE 'Max_used_connections'; returns the peak. If it equals max_connections, the server has hit its ceiling at least once since the restart, so clients were probably refused with error 1040. Check whether a pooler or smaller client pools can reduce demand before raising the limit.