Sub topic 3
How PgBouncer works: clients, servers, and pools
This chapter explains the working model of PgBouncer: what it accepts, what it opens, and how it decides which client gets which server connection. It assumes you know basic SQL and psql, what PostgreSQL's max_connections setting controls, and how TCP client/server applications connect. The previous chapters covered why a PostgreSQL connection is expensive and what pooling does in general. Here you learn the machinery that makes it work.
PgBouncer as a protocol-aware proxy
PgBouncer is a small, single-process program that speaks the PostgreSQL wire protocol on both sides. To your application it looks like a PostgreSQL server. To PostgreSQL it looks like an ordinary client. Because it understands the protocol, it can tell when a transaction starts and ends, and that knowledge is what lets it hand a server connection to someone else at the right moment.
PgBouncer is single-threaded and event-driven. One process handles thousands of sockets with very little memory per connection, which is why it can hold many client connections cheaply. The trade-off is that one PgBouncer process uses one CPU core. At very high throughput the core becomes the limit, and you run several PgBouncer processes (see the chapter on deployment topology).
Two kinds of connections
Every PgBouncer deployment has two sets of connections, and keeping them apart in your head is the most important idea in this chapter.
- A client connection is a connection from your application to PgBouncer. The application opens it with the same driver and connection string it would use for PostgreSQL.
- A server connection is a connection from PgBouncer to PostgreSQL. Each one is a real PostgreSQL backend process, and each one counts against
max_connections.
Client connections are cheap and numerous. Server connections are expensive and few. PgBouncer's job is to multiplex many clients onto few servers.
What a pool is
A pool is the set of server connections that PgBouncer keeps for one user and database pair. If app_user connects to appdb, PgBouncer creates a pool named appdb/app_user. If report_user also connects to appdb, that is a second, separate pool with its own server connections.
This has a practical consequence for sizing. The limit default_pool_size applies per pool, not to the whole PgBouncer instance. With default_pool_size = 20, three user and database pairs can open up to 60 server connections in total. When you count how many connections PostgreSQL must accept, multiply by the number of pools.
The pool key uses the user name that PgBouncer uses to connect to PostgreSQL. By default, that is the same user the client authenticated as. You can override it per database, and when you do, clients that log in as different users can share a pool. This is covered in the authentication chapter.
The `[databases]` section maps names to targets
The client asks for a database name. PgBouncer looks that name up in the [databases] section of pgbouncer.ini and learns where the real database lives.
[databases]
appdb = host=127.0.0.1 port=5432 dbname=appdb
analytics = host=10.0.0.12 port=5432 dbname=warehouse pool_size=5The name on the left is what clients use. The dbname on the right is what PgBouncer sends to PostgreSQL. They do not have to match, which lets you move a database to another host without changing application connection strings. Parameters such as pool_size on a line override the global defaults for that one database.
A client that asks for a name not listed here is rejected, unless a * fallback entry exists.
The life of a connection
Follow one client from connect to disconnect.
- Connect. The application opens a TCP connection to PgBouncer on port 6432 and sends a startup message with a user and database name.
- Authenticate. PgBouncer checks the credentials itself, using
auth_fileorauth_query. It does this without contacting PostgreSQL, so a login is cheap. No server connection has been used yet. - Wait for work. The client is now logged in, but PgBouncer does not assign it a server connection. An idle client costs a socket and a small buffer, nothing more.
- Get a server connection. When the client sends a query, PgBouncer looks at the pool for that user and database pair. It takes an idle server connection if one exists. Otherwise it opens a new one, if the pool is under its limit. If the pool is full, the client's request waits in a queue.
- Run. PgBouncer forwards the client's messages to PostgreSQL and the replies back.
- Release. When the pool mode says the server connection is free, PgBouncer returns it to the pool. The next waiting client can use it immediately.
- Disconnect. The client closes its connection. PgBouncer discards the client entry. The server connection stays open for reuse.
Step 6 is where pool modes differ. In session mode the server connection is released when the client disconnects. In transaction mode it is released when the transaction ends. In statement mode it is released after each statement. The next chapter compares these in detail. The configuration used throughout this tutorial sets pool_mode = transaction.
Client states and server states
PgBouncer tracks each connection in a state, and you will see these states in the admin console. Knowing them lets you read SHOW POOLS output later.
| Side | State | Meaning |
|---|---|---|
| Client | `active` | The client currently has a server connection and is using it. |
| Client | `waiting` | The client sent a request and is queued for a server connection. |
| Server | `idle` | The server connection is open and free. |
| Server | `used` | The server connection was released but has not yet been reset or reused. |
| Server | `active` | The server connection is serving a client. |
A healthy pool shows few or no waiting clients. A steadily growing waiting count means the pool is too small for the load, or that queries are holding connections too long.
How the limits fit together
Several settings bound this model. Each one limits a different thing.
| Setting | What it limits | Scope |
|---|---|---|
| `max_client_conn` | Total client connections PgBouncer accepts | Whole instance |
| `default_pool_size` | Server connections for one user and database pair | Per pool |
| `reserve_pool_size` | Extra server connections allowed when clients wait too long | Per pool |
| `max_db_connections` | Server connections to one database | Per database (all users) |
| `max_user_connections` | Server connections for one user | Per user (all databases) |
| PostgreSQL `max_connections` | All backend processes | Whole PostgreSQL server |
The chain of reasoning is this. max_client_conn can be large, such as 1000, because clients are cheap. default_pool_size should be small, such as 20, because servers are expensive. The sum of all pools, plus reserves, plus connections that bypass PgBouncer (such as superuser sessions, replication, and monitoring), must stay below PostgreSQL's max_connections. The sizing chapter turns this into a method.
A client that connects when max_client_conn is reached is refused with a no more connections allowed error. This is a different failure from a full pool. When a pool is full, clients connect fine and then wait.
What PgBouncer does to a server connection between clients
When a server connection moves from one client to another, PgBouncer must make sure the next client does not inherit leftovers. After a client releases a connection, PgBouncer runs a reset query, set by server_reset_query. In session mode the default is DISCARD ALL, which drops session state such as temporary tables, prepared statements, and SET values.
In transaction mode, the default reset query is empty, because the client is expected to leave nothing behind after the transaction ends. This is the reason that session-level features are unsafe in that mode. The reset does not clean them, so they leak to the next client. The transaction pooling chapter covers the failures this causes.
A minimal working setup
The following file puts the model together. It accepts up to 1000 clients and gives each user and database pair at most 20 server connections.
[databases]
appdb = host=127.0.0.1 port=5432 dbname=appdb
[pgbouncer]
listen_addr = 127.0.0.1
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 20Point an application at it by changing only the host and port in the connection string.
DATABASE_URL=postgresql://[email protected]:6432/appdbTo observe the model at work, open the admin console and list the pools.
psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer -c "SHOW POOLS;"Each row is one pool. The cl_active and cl_waiting columns count clients, and sv_active, sv_idle, and sv_used count server connections. If you open 200 client connections and run queries from them, you will see cl_active rise toward 200 while the sv_* columns stay at or below 20.
Common mistakes in the mental model
- Treating
default_pool_sizeas a global cap. It is per pool. Several users or databases multiply it. - Expecting one client to hold one server connection. In transaction mode a client may use a different server connection for each transaction.
- Counting only application connections against
max_connections. Administrative tools, migrations, and anything that connects directly to port 5432 also use slots. - Assuming PgBouncer hides slow queries. It queues clients behind long-running transactions. A slow query does not consume less of the pool because PgBouncer is present.
- Forgetting that PgBouncer is one core. The proxy itself can become the bottleneck before PostgreSQL does.
Exercises
Exercise
PgBouncer is configured with maxclientconn = 500 and defaultpoolsize = 10. Two applications connect, one as user web to database shop and one as user jobs to database shop. Each opens 200 client connections and keeps them busy. What is the maximum number of server connections PgBouncer opens to PostgreSQL, ignoring the reserve pool, and how many clients are accepted?
Show answer
There are two pools, shop/web and shop/jobs, and each is limited to 10 server connections, so PgBouncer opens at most 20 server connections. The 400 total clients are under maxclientconn = 500, so all are accepted. Most of them wait in the queue for one of the 20 server connections.
Exercise
A client logs in to PgBouncer successfully but its first query hangs. SHOW POOLS shows clwaiting = 12 and svactive equal to defaultpoolsize. Is this a maxclientconn problem? What does it indicate?
Show answer
No. The client was accepted, so maxclientconn is not exceeded. The pool for that user and database pair is full and all its server connections are busy, so the client is queued. It indicates the pool is too small for the load or that transactions are holding server connections for too long.