Skip to content
Visual explainer 2h to learn 3 steps

Connection pooling & key config settings

Size connections with PgBouncer and tune memory settings sensibly.

By Invicly Tech, , in SQL & PostgreSQL. About 11 minutes to read.

Topic 28 of 30

In short

Each Postgres connection is a separate server process with its own memory, so thousands of connections hurt performance. A pooler like PgBouncer shares a few server connections among many clients, and memory settings decide how much is cached and used per query.

Explained simply

Every connection to Postgres starts a new process on the server. That process needs memory, takes a few milliseconds to start, and adds work for the server to track. A hundred connections are fine. Five thousand open connections, mostly doing nothing, make the whole server slower.

Modern apps open many connections: many app instances, each with its own pool, plus workers and cron jobs. A connection pooler sits in the middle. Apps connect to it, and it shares a small number of real server connections among them, like a few checkout lanes serving a long queue of shoppers.

PgBouncer is the most widely used pooler. It is small, fast and simple. In transaction mode it lends a server connection to a client only for one transaction, then gives it to someone else.

Memory settings decide how Postgres uses RAM: shared_buffers for its own cache of data pages, and work_mem for each sort or hash in a query. The defaults are tiny and safe; real servers need a few changes.

Press Play on a diagram to walk through it one step at a time.

LayersConnections and memory
  1. 1
    App instances

    Hundreds of client connections

  2. 2
    PgBouncer

    Hands out a small pool of server connections

  3. 3
    Postgres backends

    One process per server connection

  4. 4
    work_mem

    Per sort or hash step, per backend

  5. 5
    shared_buffers

    Shared page cache, often ~25% of RAM

  6. 6
    OS page cache & disk

    Everything not in shared buffers

SequenceTransaction pooling with two clients and one server connection
Client A
PgBouncer
Server conn 1
  1. 1BEGIN; UPDATE ...; COMMIT
    Client A to PgBouncer: BEGIN; UPDATE ...; COMMIT
  2. 2Runs on server conn 1
    PgBouncer to Server conn 1: Runs on server conn 1
  3. 3COMMIT done: conn 1 back in pool
    Server conn 1 to PgBouncer: COMMIT done: conn 1 back in pool
  4. 4Result to A (A stays connected, idle)
    PgBouncer to Client A: Result to A (A stays connected, idle)
  5. 5Client B's transaction now uses conn 1
    PgBouncer to Server conn 1: Client B's transaction now uses conn 1
  6. 6Done: conn 1 back in pool again
    Server conn 1 to PgBouncer: Done: conn 1 back in pool again

In depth

Why connections are expensive

Postgres uses one operating system process per connection. A new connection means a TCP handshake, often TLS, authentication, and starting a backend process, which usually takes a few milliseconds and some megabytes of memory, growing as the session caches catalog data and runs queries.

Idle connections are not free either. Every active transaction has to look at the state of all other backends when it takes a snapshot, and lock management and memory use grow with the number of connections. PostgreSQL 14 made snapshots with many idle connections much cheaper, but the server still does real work in parallel only up to about its number of CPU cores and disks.

That is why max_connections defaults to 100 and why raising it to several thousand rarely helps. A widely quoted starting point for the number of active connections is about two times the CPU core count, plus the number of disks. Beyond that, queries just queue inside the server instead of in the pooler.

  • One process per connection
  • Connection setup costs milliseconds
  • Throughput peaks near a few connections per core
  • Raising max_connections is not a scaling plan

PgBouncer pool modes

Session mode gives a client one server connection for as long as it stays connected. It is fully compatible with everything, but saves little if clients stay connected.

Transaction mode gives a client a server connection only for the length of each transaction. Hundreds of mostly idle app connections can then share 20 server connections. This is the mode most people mean when they say "use PgBouncer".

The catch: anything that lives in the session instead of the transaction can break, because your next transaction may run on a different server connection. That includes plain SET (use SET LOCAL instead), session-level advisory locks (use pg_advisory_xact_lock), LISTEN/NOTIFY listeners, temporary tables kept across transactions, and WITH HOLD cursors. Protocol-level prepared statements work in transaction mode since PgBouncer 1.21 if you set max_prepared_statements.

Statement mode is stricter still and does not allow multi-statement transactions; it is rarely used.

ComparePgBouncer pool modes
session
  • Server conn held for the whole session
  • Everything works
  • Little sharing
  • Good for admin tools
transaction
  • Server conn held per transaction
  • Big sharing, most common
  • Use SET LOCAL, xact advisory locks
  • No LISTEN, no session temp tables
statement
  • Server conn per statement
  • No multi-statement transactions
  • Rarely used

Sizing pools end to end

Count connections from the outside in. If 10 app instances each keep a client-side pool of 20, that is 200 client connections. Add workers, cron jobs and admin tools. Without a pooler, all of them hit Postgres directly.

With PgBouncer: max_client_conn is how many clients it accepts (it can be thousands, because idle clients cost PgBouncer almost nothing), and default_pool_size is how many server connections it opens per database and user pair (20 by default). reserve_pool_size adds a few extra for bursts. Keep the sum of all server pools comfortably under max_connections, leaving room for superuser_reserved_connections, replication and maintenance.

Watch it through the admin console: psql -p 6432 -U pgbouncer_admin pgbouncer, then SHOW POOLS. cl_waiting greater than zero for long periods means clients are queueing; either queries are too slow or the pool is too small. Many managed platforms provide a built-in pooler, such as RDS Proxy, or PgBouncer variants.

FlowCounting connections from app to server
  1. 1
    10 app instances

    Each with a client pool of 20

  2. 2
    200 client connections

    Plus workers and cron jobs

  3. 3
    PgBouncer

    max_client_conn = 1000

  4. 4
    20 to 30 server connections

    default_pool_size + reserve_pool_size

  5. 5
    Postgres

    max_connections = 100, plenty of headroom

The memory settings that matter

shared_buffers is Postgres's own page cache, shared by all backends. The default of 128MB is tiny; about 25 percent of RAM is the usual starting point on a dedicated server. The rest of RAM still helps, because the operating system caches files too. Changing it needs a restart.

effective_cache_size does not allocate anything. It tells the planner how much memory is available for caching in total (shared_buffers plus OS cache), so it can judge index scans fairly; 50 to 75 percent of RAM is typical.

work_mem (default 4MB) is the memory for each sort or hash operation in each query, before it spills to disk. One query can use several, and parallel workers each get their own, so total use is roughly work_mem times operations times active connections. Keep the global value moderate, such as 16 to 64MB, and raise it per session or per role for heavy reports.

maintenance_work_mem (default 64MB) is used by VACUUM, CREATE INDEX and similar; 512MB to 1GB speeds them up. On SSDs, lowering random_page_cost from 4 to about 1.1 helps the planner choose indexes.

  • shared_buffers ~25% of RAM (restart)
  • effective_cache_size ~50-75% of RAM (planner hint)
  • work_mem per sort or hash, per query
  • maintenance_work_mem for VACUUM and CREATE INDEX
  • random_page_cost about 1.1 on SSD

Learn it in 3 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Explain why connections are expensive~40m
  2. 2
    Set up PgBouncer~40m
  3. 3
    Tune shared_buffers and work_mem~40m

Key points

  • Opening a connection forks a process; reuse connections instead.
  • PgBouncer transaction mode gives a server connection only for each transaction.
  • Transaction mode can break session features like SET or advisory locks across transactions.
  • work_mem applies per operation, so one query can use it several times over.

Key terms

Tap a card to flip it. 0/5 known

Examples

ini
; pgbouncer.ini
[databases]
shop = host=127.0.0.1 port=5432 dbname=shop

[pgbouncer]
listen_port = 6432
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 20

; postgresql.conf (16 GB server, starting points)
; shared_buffers = 4GB
; work_mem = 32MB
; max_connections = 100

Putting PgBouncer in front of Postgres

Step 1: install PgBouncer and list the database in pgbouncer.ini. Step 2: choose transaction mode and pool sizes. Step 3: use scram-sha-256 authentication with a userlist file (or auth_query to look users up in Postgres). Step 4: point the app at port 6432 instead of 5432. Step 5: check SHOW POOLS in the admin console under load.

ini
; /etc/pgbouncer/pgbouncer.ini
[databases]
shop = host=10.0.0.5 port=5432 dbname=shop

[pgbouncer]
listen_addr = 0.0.0.0
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 2000
default_pool_size = 25
reserve_pool_size = 5
admin_users = pgbouncer_admin
max_prepared_statements = 100

Starting settings for a 32 GB dedicated server

Step 1: set the memory values with ALTER SYSTEM, which writes them to postgresql.auto.conf. Step 2: check pg_settings: settings whose context is postmaster (like shared_buffers) need a restart, and pending_restart shows which ones are waiting. Step 3: reload for the others. Step 4: give the reporting role a bigger work_mem instead of raising it for everyone. Treat these as starting points and adjust from monitoring.

sql
ALTER SYSTEM SET shared_buffers = '8GB';          -- restart needed
ALTER SYSTEM SET effective_cache_size = '22GB';
ALTER SYSTEM SET work_mem = '32MB';
ALTER SYSTEM SET maintenance_work_mem = '1GB';
ALTER SYSTEM SET random_page_cost = 1.1;          -- SSD storage
SELECT pg_reload_conf();

SELECT name, setting, unit, context, pending_restart
FROM pg_settings
WHERE name IN ('shared_buffers', 'work_mem', 'effective_cache_size');

ALTER ROLE reporting SET work_mem = '256MB';

Quick reference

  • PgBouncer listens on 6432 by default; point apps there instead of 5432
  • pool_mode = transaction for web apps; use SET LOCAL, not SET
  • SHOW POOLS; in the pgbouncer admin console: cl_waiting > 0 means clients queue
  • Sum of all server pools must stay well under max_connections
  • shared_buffers about 25% of RAM; needs a restart
  • work_mem applies per sort or hash; raise it per role, not globally
  • ALTER SYSTEM SET x = y; SELECT pg_reload_conf(); pg_settings.context tells if a restart is needed
  • SHOW max_connections; default 100

Common mistakes

  • Raising max_connections to thousands instead of adding a pooler.
  • Setting a huge work_mem globally and running out of memory under load.
  • Using session features with transaction pooling and getting odd behaviour.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1With PgBouncer in transaction mode, the app runs SET search_path = tenant_5 once after connecting. What can go wrong?

Question 2

2A server has 16 GB RAM, work_mem = 256MB, and 100 active connections running queries with 3 sorts each. What is the risk?

Question 3

3What does effective_cache_size do?

Question 4

4The app has 3,000 mostly idle connections and the server is slow. What is the usual fix?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Show current values of max_connections, shared_buffers, work_mem and effective_cache_size, and how many connections are in use.

  2. Exercise 2medium

    Show how many connections each application and user holds, split by state, to find who uses the most.

  3. Exercise 3hard

    A job uses a session advisory lock to make sure only one copy runs. After moving to PgBouncer transaction mode, two copies sometimes run. Fix it.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I still need PgBouncer if my app has a connection pool?
Often yes. An app pool limits connections per instance, but many instances, workers and serverless functions add up. PgBouncer caps the total that reaches Postgres.
What is the best value for shared_buffers?
About 25 percent of RAM is the common starting point on a dedicated server. Going much higher rarely helps, because the operating system cache also holds data.
Does PgBouncer support prepared statements?
In transaction mode, protocol-level prepared statements work since PgBouncer 1.21 when max_prepared_statements is set above zero. Older versions needed session mode or turning prepared statements off in the driver.
Are there alternatives to PgBouncer?
Yes, for example Pgpool-II, PgCat, Odyssey, and managed options like Amazon RDS Proxy. PgBouncer remains the simplest and most common choice.

Go deeper

ShareXLinkedInWhatsApp