Sub topic 1
Why PostgreSQL connections are expensive
Prerequisites
This chapter assumes you know basic SQL and can use the psql client. You should understand PostgreSQL roles, databases, and the max_connections setting. You should also be comfortable editing a configuration file on Linux and have a general idea of how TCP client and server connections work.
Why PostgreSQL connections are expensive
PostgreSQL uses a process-per-connection model. When a client connects, the server starts a dedicated backend process for it. Each backend holds its own memory for session state, caches, and sort or hash work areas. Starting the process and completing authentication also takes time, so an application that opens a new connection for every web request pays that cost on every request.
Idle connections still consume memory and scheduler time. A few hundred idle backends can use a large share of RAM and slow down the queries that do real work. The max_connections setting caps how many backends can exist at once. When that limit is reached, new clients are refused.
What connection pooling does
A connection pool keeps a set of open server connections and lends them to clients when they need one. A client borrows a connection for a transaction and returns it afterward. The application can have many clients, while PostgreSQL sees only a small, steady number of connections.
How PgBouncer works: clients, servers, and pools
PgBouncer is a lightweight proxy that sits between applications and PostgreSQL. Applications connect to PgBouncer as if it were the database. PgBouncer keeps a pool of server connections to PostgreSQL for each database and user pair.
Your first pgbouncer.ini
PgBouncer reads its settings from pgbouncer.ini. The [databases] section maps a name the application uses to the real PostgreSQL target. The [pgbouncer] section sets how PgBouncer listens and how it pools.
[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 = 20Here, clients connect to port 6432. PgBouncer allows up to 1000 client connections and opens at most 20 server connections per user and database pair. To use it, the application changes only its port from 5432 to 6432.
Exercise
In the ini file above, what happens when 1000 clients are connected and all of them are waiting for a query to finish?
Show answer
They share the 20 server connections for appdb. Clients beyond the 20 active ones wait until a server connection is free, because only 20 server connections exist per user and database pair.