
Connection pooling means an app opens a few database connections once, keeps them open, and lends one to each request that needs it. When the request finishes, the connection goes back to the pool instead of being closed. Requests skip the slow setup of a new connection, and the database never has to hold more connections than the pool allows.
In this post we stay with the shop from the database migrations post. Its orders table is indexed and safely changed, and now a festival sale brings thousands of shoppers at once. First we see what a new database connection costs, measured on a real PostgreSQL server, then how a pool works, using supermarket trolleys and then the real thing. Then we build a small pool in plain Python and race it against opening a new connection each time. We finish with how big a pool should be, the leak that drains a pool, and where pools live: inside the app, or in a separate pooler such as PgBouncer.
A few words first. A connection is an open line between the app and the database, which the app sends its queries down. A query is one question or command the app sends to the database. A request is one visit to a page, such as Asha opening "My orders". A thread is one line of work inside a program; a web app often runs many threads, so it can serve many requests at the same time. A CPU core is one worker inside a computer's processor, and each core does one thing at a time. And ms means millisecond, a thousandth of a second.
Key takeaways
- Opening a database connection is slow work. The two computers exchange network messages, PostgreSQL starts a new process (a separate running program) for the connection, and checks the password. In our test, that took 19.4 ms, almost 80 times longer than the query itself.
- A pool opens connections once and lends them out. A request borrows one, uses it, and gives it back. On PostgreSQL 18.6, reusing connections managed 40,689 queries a second; a new connection for each query managed 432.
- A pool has a maximum size. When every connection is out, a request waits, but only up to a timeout, and then it gets an error instead of hanging for ever.
- More connections doesn't make each request faster. Once the database server's cores are busy, extra connections mostly wait inside it: the total work stops growing, every query takes longer, and each connection still uses its memory.
- A leak is a connection that's borrowed and never given back, usually because an error skipped the line that returns it. A few leaks drain the pool and every page stops. Use a
withblock so the connection always goes back. - Pools live inside the app (SQLAlchemy has one built in, and psycopg offers one in a separate package) or in a separate pooler such as PgBouncer, which sits in front of PostgreSQL and, in its transaction mode, shares a few real connections among many app processes.
What is connection pooling in simple words?
Picture a supermarket during a sale. At the door stands a row of trolleys. You take one, fill it, pay, and leave it back at the door for the next shopper. The shop doesn't build a new trolley for each customer and scrap it at the till. That would be slow and wasteful. It buys, say, 50 trolleys once, and they go round and round.
Three more things about trolleys matter here. If all 50 are out, the next shopper waits at the door, and if the wait gets too long, they give up and leave. Buying 500 trolleys wouldn't help, because the aisles and tills can only take so many shoppers before everyone is stuck in a jam. And a shopper who wheels a trolley out to their car and never brings it back takes one trolley out of the pool for good. A few of those every day, and one morning the row at the door is empty.
A connection pool is that row of trolleys. The trolleys are database connections. The shoppers are requests. Taking a trolley is borrowing a connection, and leaving it at the door is giving it back. The waiting, the jam and the trolley that never came back are the three things we'll measure in this post: timeouts, sizing and leaks. The docs of psycopg, a PostgreSQL library for Python, put it this way: "A connection pool is an object managing a set of connections and allowing their use in functions needing one."
What does opening a database connection cost?
When the shop app opens a connection to PostgreSQL, three slow things happen before the first query can run:
- The network handshake. The app and the database server exchange messages to set up a TCP connection, the standard way two computers open a reliable line between them. The TCP standard (RFC 9293) says: "The "three-way handshake" is the procedure used to establish a connection." That is three messages, and the first query must wait for the first two to go there and back.
- A new process on the database server. PostgreSQL gives every connection its own process. Its docs: "In this model, every client process connects to exactly one backend process." And: "Whenever it detects a request for a connection, it spawns a new backend process." (A backend process is the program on the server that runs one connection's queries.) Starting a process takes time and memory.
- The password check. PostgreSQL's most secure password method,
scram-sha-256, is in its docs' words "a challenge-response scheme that prevents password sniffing on untrusted connections". The server sends a challenge, the app answers with a value worked out from the password, and the server checks the answer, so the password can't be read off the network. That's more messages, and more work on both sides.
How slow is all that? We measured it on PostgreSQL 18.6, running in Docker (a tool that runs programs in isolated containers) on a laptop. We used pgbench, the benchmark tool that comes with PostgreSQL. It has an option made for this question: "Establish a new connection for each transaction, rather than doing it just once per client session. This is useful to measure the connection overhead." (Here, each transaction is one SELECT that reads one row.) Ten clients, each on its own pgbench thread, ran for 15 seconds each way, connecting over TCP with a password:
| How each query got its connection | Queries in 15 s | Queries a second |
|---|---|---|
| Reused the same open connection | 610,746 | 40,689 |
| Opened a new connection each time | 6,489 | 432 |
Reusing connections did about 94 times as much work. pgbench also reported each new connection taking 19.4 ms on average, with 10 clients connecting at once, while one query on an open connection took 0.246 ms. So with a new connection each time, a request took 23.2 ms instead of 0.246 ms, and almost all of that went on the connection, not on the question the shop actually asked. And our test ran on one machine, where the network handshake costs almost nothing. Across a real network, each of those messages has to travel there and back, and an encrypted connection adds a handshake of its own.
There's a second cost: a limit. PostgreSQL's max_connections setting "Determines the maximum number of concurrent connections to the database server." And "The default is typically 100 connections". It isn't free to raise: "PostgreSQL sizes certain resources based directly on the value of max_connections. Increasing its value leads to higher allocation of those resources, including shared memory." Once the limit is reached, a new connection is refused with an error whose code, in PostgreSQL's list of error codes, is 53300, named too_many_connections. On the shop's sale day, with a new connection per page view, that's the error shoppers would see.
How does a connection pool work?
A pool keeps a store of open connections and lends them out. Every pool, in every language, does the same four things:
- Borrow. A request asks for a connection. If one is free, it gets it straight away, already open, with no handshake, no new process and no password check.
- Give back. When the request is done, the connection goes back into the store, still open, ready for the next request.
- Wait, with a maximum size. The pool never opens more than its maximum. When every connection is out, the next request waits in line. psycopg's docs describe it: "if no connection is available, the client is put in a queue, and will be served a connection once one becomes available".
- Time out. The wait has a limit. SQLAlchemy, a database toolkit for Python, calls it
pool_timeout: "number of seconds to wait before giving up on getting a connection from the pool." Its default is 30 seconds. After that, the request gets an error, which is better than a page that hangs with no answer.

SQLAlchemy's docs sum up why: "A connection pool is a standard technique used to maintain long running connections in memory for efficient reuse, as well as to provide management for the total number of connections an application might use simultaneously." Notice the two halves. A pool makes requests faster, and it also puts a cap on how many connections the app can open, which protects the database on a busy day, much as rate limiting protects an API.
How do you build a connection pool in Python?
We need a database to connect to. Installing PostgreSQL just for this would be a lot, so we'll build a pretend one that behaves like the real thing in the ways that matter here. It runs on your own computer and listens for TCP connections. Each new connection costs it 10 ms of work (the process and the password check), and each query costs 2 ms. Like a server with 4 CPU cores, it can work on only 4 things at once. Everything here is in Python's standard library, so there's nothing to install.
# fake_db.py
"""A pretend database server on your own computer, and a client connection to it."""
import socket
import socketserver
import threading
import time
SETUP = 0.010 # 10 ms of database work to set up each new connection
QUERY = 0.002 # 2 ms of database work for each query
CORES = 4 # the database can work on 4 things at once, like a server with 4 CPU cores
cores = threading.Semaphore(CORES)
lock = threading.Lock()
stats = {"opened": 0, "open_now": 0}
class Database(socketserver.StreamRequestHandler):
def handle(self): # runs once for each new connection
with cores:
time.sleep(SETUP) # a real one starts a process and checks the password here
with lock:
stats["opened"] += 1
stats["open_now"] += 1
try:
self.wfile.write(b"ready\n")
for line in self.rfile: # one line in = one query
with cores:
time.sleep(QUERY)
self.wfile.write(b"paid\n")
finally:
with lock:
stats["open_now"] -= 1
class Server(socketserver.ThreadingTCPServer):
daemon_threads = True # the program can end while connections are still open
request_queue_size = 128 # let many new connections wait to be accepted
def start_database():
server = Server(("127.0.0.1", 0), Database) # port 0: any free port
threading.Thread(target=server.serve_forever, daemon=True).start()
Connection.address = server.server_address
class Connection:
"""One connection: a TCP socket to the database, set up once, then used for many queries."""
address = None
def __init__(self):
self.sock = socket.create_connection(self.address)
self.file = self.sock.makefile("rwb")
self.file.readline() # wait until the database says "ready"
def query(self, sql, *params):
self.file.write(f"{sql} {params}\n".encode())
self.file.flush()
return self.file.readline().decode().strip()
def close(self):
self.file.close()
self.sock.close()
socketserver.ThreadingTCPServeraccepts TCP connections and runshandlein a new thread for each one, a bit like PostgreSQL's process per connection. A socket is the program's end of a network connection.- A semaphore is a counter that lets only a fixed number of threads through at once.
with cores:lets 4 threads work, and the rest wait their turn. That's our 4 CPU cores.time.sleepstands in for the work. Connectionis the app's side. Creating one does the slow part: connect, then wait forready. After that, eachquerysends one line and reads one answer. Every order in our pretend shop ispaid.
Now the pool itself. It's the part to learn, and it's short, because Python's queue module does the hard work. Its docs: "The queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads." Many threads can take connections out and put them back at the same moment, and none of them ever gets the same connection as another.
# pool.py
"""A tiny connection pool: open a few connections once, then lend them out."""
import queue
from contextlib import contextmanager
from fake_db import Connection
class Pool:
def __init__(self, size, timeout=1.0):
self.timeout = timeout
self.idle = queue.Queue() # the connections nobody is using right now
for _ in range(size):
self.idle.put(Connection()) # open them all now, so no request pays for it
def borrow(self):
try:
return self.idle.get(timeout=self.timeout) # none free? wait, but not for ever
except queue.Empty:
raise TimeoutError(f"no free connection within {self.timeout} s") from None
def give_back(self, conn):
self.idle.put(conn)
@contextmanager
def connection(self):
conn = self.borrow()
try:
yield conn
finally:
self.give_back(conn) # always runs, even if the code using it fails
- The pool opens
sizeconnections at the start. That's the maximum size: it never opens more. borrowtakes a free connection out of the queue. If none is free,getwaits. Python's docs: "If timeout is a positive number, it blocks at most timeout seconds and raises the Empty exception if no item was available within that time." We turn that into a clearTimeoutError.give_backputs the connection back, still open.connectionwraps both in awithblock, which we'll need when we get to leaks.
Real pools do more. SQLAlchemy's pool opens connections only when they're first needed ("none of them "pre create" connections"), can open a few extra on a busy moment, and can test a connection before lending it, in case the database closed it. Ours opens everything up front to keep it short.
Last, a test. Twenty shoppers each view 10 pages, all at the same time: 200 page views, each running one query. First each view opens its own connection and closes it, then they share a pool of 4:
# measure.py
"""200 page views, 20 at a time: first a new connection for each one, then a pool.
Run: python measure.py, or python measure.py 1 2 4 8 16 to try pool sizes."""
import sys
import threading
import time
from fake_db import Connection, start_database, stats
from pool import Pool
USERS, VIEWS = 20, 10 # 20 people at once, 10 page views each
def run(page_view):
"""Start every user at the same moment, wait for all of them. Returns the seconds taken."""
def user():
for _ in range(VIEWS):
page_view()
threads = [threading.Thread(target=user) for _ in range(USERS)]
start = time.perf_counter()
for t in threads:
t.start()
for t in threads:
t.join()
return time.perf_counter() - start
def no_pool():
conn = Connection() # set up a new connection...
conn.query("SELECT status FROM orders WHERE id = ?", 101)
conn.close() # ...use it once, and throw it away
start_database()
if len(sys.argv) == 1:
before = stats["opened"]
seconds = run(no_pool)
print(f"new connection each time: {seconds:.2f} s, connections opened: {stats['opened'] - before}")
for size in [int(s) for s in sys.argv[1:]] or [4]:
before = stats["opened"]
pool = Pool(size)
def pooled():
with pool.connection() as conn:
conn.query("SELECT status FROM orders WHERE id = ?", 101)
seconds = run(pooled)
print(f"{f'pool of {size}:':25} {seconds:.2f} s, connections opened: {stats['opened'] - before}")
Make a new folder and save the three files in it, each under the name in its first line. Open a terminal (a command-line window) in that folder, and run this. In the output blocks, a line starting with $ is what you type, without the $; the lines under it are what it prints:
$ python measure.py
new connection each time: 0.69 s, connections opened: 200
pool of 4: 0.14 s, connections opened: 4
Your times will differ a little, but the gap won't. The pool was about 5 times faster, and the database set up 4 connections instead of 200. The sums explain it. With no pool, each page view costs the database 10 ms of setup plus 2 ms of query: 200 views make 2,400 ms of work, shared among 4 cores, so at least 600 ms. With the pool, the setup happens 4 times before the test starts, and only the queries are left: 400 ms of work over 4 cores, at least 100 ms. The rest is Python's own overhead.
The real PostgreSQL gap was bigger, 94 times, because there a request with a new connection took 23.2 ms against 0.246 ms for the query alone, while our pretend database spends 2 ms on each query. The cheaper your queries, the more of each request a new connection eats.
How many connections should a pool have?
If 4 connections were 5 times faster than a new one each time, are 16 faster still? Let's try pool sizes 1, 2, 4, 8 and 16:
$ python measure.py 1 2 4 8 16
pool of 1: 0.52 s, connections opened: 1
pool of 2: 0.27 s, connections opened: 2
pool of 4: 0.14 s, connections opened: 4
pool of 8: 0.13 s, connections opened: 8
pool of 16: 0.13 s, connections opened: 16
Up to 4, each doubling halves the time, because each extra connection puts another core to work. After 4, nothing. That wall is one we built in on purpose with CORES = 4, so this run shows the idea rather than proving it. The database has 4 cores, so with 8 or 16 connections, only 4 queries run at any moment, and the rest wait inside the database instead of waiting in the pool. The page views are no faster, but the database now holds 4 times as many connections.
A real database has no sharp wall like our pretend one. But the trade gets bad quickly. Each connection is a process with its own memory, and busy processes compete for the same cores. In our pgbench test (one 10-second run for each size, on a laptop with 12 cores, with pgbench on the same machine), the most work came from 16 connections: 48,373 queries a second. With 32, 64 and 90 connections the total was lower, while each query took longer: 1.948 ms with 90 connections against 0.331 ms with 16, almost 6 times as long. That's why psycopg's docs answer "What's the right size for the pool?" with: "Big question. Who knows. However, probably not as large as you imagine." A sensible way to choose:
- Start small, with your library's default. SQLAlchemy's
pool_sizeis "the number of connections to keep open inside the connection pool", and it defaults to 5. Itsmax_overflow, 10 by default, is "the number of connections to allow in connection pool "overflow", that is connections that can be opened above and beyond the pool_size setting". - Count every server, not just one. Each app server, and each worker process on it (a copy of the app that serves requests on its own), has its own pool. The database sees the sum. 10 processes with a pool of 5 plus 10 overflow can open up to 150 connections, more than PostgreSQL's default limit of 100.
- Measure under real load. Raise the size while the time per request keeps falling, and stop when it doesn't. If requests often wait for a connection, the database is usually the slow part, and the fix is faster queries (an index, for example), not more connections.
What mistake do beginners make with connection pools?
A connection leak. That's a connection that's borrowed and never given back. It isn't broken, and it isn't closed. It's just gone from the pool, like the trolley in someone's car park. It's easy to write, because the code looks fine when everything goes well:
# leak.py
"""A page that forgets to give its connection back when something goes wrong, and the fix."""
from fake_db import start_database
from pool import Pool
def order_page(order_id):
conn = pool.borrow()
if not order_id.isdigit():
raise ValueError("not an order number") # leaves here, so give_back below never runs
status = conn.query("SELECT status FROM orders WHERE id = ?", order_id)
pool.give_back(conn)
return status
def order_page_fixed(order_id):
with pool.connection() as conn: # given back however the block ends
if not order_id.isdigit():
raise ValueError("not an order number")
return conn.query("SELECT status FROM orders WHERE id = ?", order_id)
start_database()
for page in (order_page, order_page_fixed):
pool = Pool(size=2, timeout=0.5)
print(page.__name__)
for order_id in ("101", "abc", "102", "xyz", "103"):
try:
print(f" {order_id}: {page(order_id)}")
except (ValueError, TimeoutError) as e:
print(f" {order_id}: {type(e).__name__}: {e}")
print(f" free connections left: {pool.idle.qsize()} of 2")
Five shoppers open an order page. Two of them type something that isn't an order number, such as abc. Save it next to the other files and run it:
$ python leak.py
order_page
101: paid
abc: ValueError: not an order number
102: paid
xyz: ValueError: not an order number
103: TimeoutError: no free connection within 0.5 s
free connections left: 0 of 2
order_page_fixed
101: paid
abc: ValueError: not an order number
102: paid
xyz: ValueError: not an order number
103: paid
free connections left: 2 of 2
In order_page, each bad order number raises an error after borrow and before give_back, so the error skips the line that returns the connection. Two bad requests, two leaks, and the pool of 2 is empty. Order 103 is a perfectly good request, and it fails anyway. On a real site, the errors would happen hours before the outage, so the logs at the moment pages stop loading show only timeouts, not the cause.
The fix is the with block. Our connection method gives the connection back in a finally, which runs however the block ends: normally, with return, or with an error. Python's contextlib docs explain why that works: "If an unhandled exception occurs in the block, it is reraised inside the generator at the point where the yield occurred." (The generator is our connection method, and yield is the line where it hands the connection to the with block.) So the error passes through our try, and the finally gives the connection back before the error carries on. psycopg's docs warn about the manual way too. If you call its getconn(), "you must call a corresponding putconn(): failing to do so will deplete the pool. A depleted pool is a sad pool: you don't want a depleted pool."
Two more slips to watch for:
- Holding a connection while doing something slow. A page that borrows a connection, then calls a payment service and waits 3 seconds for an answer, keeps that connection out of the pool for those 3 seconds, doing nothing. Borrow as late as you can and give back as early as you can.
- A pool with no timeout. Without one, a drained pool doesn't fail, it hangs, and so does every page waiting for it. You'll see this in "Try it".
Where should the pool live: in the app or in PgBouncer?
So far the pool has lived inside the app. That's the usual place, and you rarely write it yourself: SQLAlchemy gives every engine a pool, and psycopg has one in its psycopg_pool package, which its docs say is "distributed in a package separate from the main psycopg package".
The trouble starts when there are many apps. Say the shop runs 6 servers with 4 worker processes each, and every process has its own pool of 5. That's 120 connections, and most of them sit idle most of the time, each one a process on the database server. That's where a separate pooler helps. The best known for PostgreSQL is PgBouncer. Its docs: "pgbouncer is a PostgreSQL connection pooler. Any target application can be connected to pgbouncer as if it were a PostgreSQL server, and pgbouncer will create a connection to the actual server, or it will reuse one of its existing connections." The apps connect to PgBouncer, which is light on memory (its features page lists "Low memory requirements (2 kB per connection by default)."), and, in transaction mode (below), PgBouncer shares a few real connections among all of them. Its max_client_conn, "Maximum number of client connections allowed.", defaults to 100. Its default_pool_size, "The maximum number of server connections to allow per user/database pair.", defaults to 20.

The key setting is pool_mode, which decides when PgBouncer takes a real connection back from a client:
- Session (the default): the client keeps its server connection until it disconnects. Everything works, but an app that keeps its connections open all day holds a server connection all day too.
- Transaction: "A server connection is assigned to a client only during a transaction." (A transaction is a group of changes the database treats as one.) Between transactions, the same server connection serves other clients, so a few connections can serve many apps. This is the mode that saves the most.
- Statement: the connection goes back after every single query, so transactions of more than one statement aren't allowed.
Transaction mode has a catch, in PgBouncer's words: ""transaction" pooling breaks client expectations of the server by design and can be used only if the application cooperates by not using non-working features." Anything that's meant to last for the whole connection, such as a SET command that changes a setting, LISTEN (wait for messages from the database) or PREPARE (save a query to run again later), can end up on a different server connection from the next query. PgBouncer's features table lists them as never working in transaction mode. So check your library's settings for PgBouncer before you switch.
A pooler and an app pool often work together. The app keeps a small pool of connections to PgBouncer, which are cheap, and PgBouncer keeps the few real connections to PostgreSQL.
When don't you need a connection pool?
- When your library already has one. SQLAlchemy and psycopg's pool package do it for you, and many other database libraries do too. Use theirs, and tune the size; don't write your own. Ours is for learning how they work.
- When one program makes one connection and keeps it. A script that imports a file or a nightly job that runs a report can open one connection, run all its queries, and close it at the end. A pool solves the cost of opening many connections; it adds nothing when you only open one.
- When the database has no server. SQLite, which comes with Python, is a file that your program opens directly. There's no network handshake, no server process and no password, so the costs a pool saves mostly aren't there.
- When the app can't keep anything open. Some hosting runs your code fresh for each request and stops it after, so an in-app pool is thrown away every time. That's the case for a pooler in the middle, such as PgBouncer, which stays running while the app comes and goes.
1) In leak.py, change timeout=0.5 to timeout=None and run it again. What happens at order 103, and why is that worse than the error?
2) The shop grows to 10 app servers with 4 worker processes each. Every process uses SQLAlchemy's default pool: 5 connections plus up to 10 overflow. How many connections could the database be asked for on a busy day? What happens with PostgreSQL's default limit, and what are two ways to fix it?
3) In fake_db.py, change CORES = 4 to CORES = 8 and run python measure.py 1 2 4 8 16 again. Where does it stop getting faster now?
Show the answers
1) The program stops at order 103 and never finishes. You have to press Ctrl+C. With timeout=None, get waits until a connection comes back, and no connection is ever coming back. On a live site, every page that needs the database would hang like this. There's no error in the logs, just pages that never load. A timeout turns a silent hang into an error you can see and fix.
2) Each process can open 5 + 10 = 15 connections, so 10 × 4 × 15 = 600, six times the default limit of 100. Once the limit is reached, every new connection is refused with too_many_connections, and pages fail. Two fixes: make the pools smaller, such as 2 connections each with no overflow, which is 80 in total; or put PgBouncer in front in transaction mode, so all 40 processes share, say, 20 real connections. Raising max_connections to 600 isn't a good fix: each connection is a process with its own memory, and as we measured, more connections don't do more work.
3) It now keeps getting faster up to a pool of 8, then stops. One run printed:
$ python measure.py 1 2 4 8 16
pool of 1: 0.52 s, connections opened: 1
pool of 2: 0.26 s, connections opened: 2
pool of 4: 0.13 s, connections opened: 4
pool of 8: 0.08 s, connections opened: 8
pool of 16: 0.08 s, connections opened: 16
The right pool size follows what the database can do at once, not how many users the app has. A bigger database server can use a bigger pool; a bigger pool can't make the database server bigger.
Questions people ask
What is connection pooling in simple words?
Connection pooling means keeping a few database connections open and sharing them. Each request borrows a connection, runs its queries, and gives it back, instead of opening a new connection and closing it. Requests skip the slow setup, and the database never holds more connections than the pool allows.
Why is opening a database connection slow?
The app and the server exchange network messages to set up the connection, then PostgreSQL starts a new process for it and checks the password, which takes more messages. In our test on PostgreSQL 18.6, a new connection took 19.4 ms on average, almost 80 times longer than a simple query on a connection that was already open.
Is a bigger connection pool faster?
Only up to a point. Once the database server's cores are busy, extra connections mostly wait inside the database: the total work stops growing while each query gets slower, and each connection still uses memory. Start with your library's default, such as SQLAlchemy's 5, and raise it only while measuring shows requests getting faster.
What is a connection leak?
A connection leak is a connection that's borrowed from the pool and never given back, usually because an error skipped the line that returns it. Each leak shrinks the pool for good, until none are left and every request waits. Use a with block, which your pool library supports, so the connection goes back however the code ends.
Do I need PgBouncer if my app already has a pool?
Not for one or two app servers: an in-app pool is enough. PgBouncer helps when many servers or processes each keep their own pool and the total gets close to PostgreSQL's connection limit, or when the hosting starts your code fresh for each request. In transaction mode, it shares a few real connections among many apps.
Keep going
- Previous in this System Design series: Database migrations, how to change the orders table on a live database in safe steps.
- Next: Soft delete, why many apps mark a row as deleted instead of removing it, and what that costs.
- When the pool is busy because queries are slow: Database indexing, how an index finds one customer's orders among 2 million rows.
Checked on 14 November 2026 against the 15 sources below.
Sources
- PostgreSQL documentation: How Connections Are Established (a process per connection)
- PostgreSQL documentation: Connections and Authentication (max_connections)
- PostgreSQL documentation: Password Authentication (scram-sha-256)
- PostgreSQL documentation: pgbench (measuring connection overhead)
- PostgreSQL documentation: PostgreSQL Error Codes (too_many_connections)
- IETF: RFC 9293, Transmission Control Protocol (the three-way handshake)
- PgBouncer documentation: Usage
- PgBouncer documentation: Configuration (pool_mode, max_client_conn, default_pool_size)
- PgBouncer documentation: Features (what works in each pool mode)
- SQLAlchemy documentation: Connection Pooling
- SQLAlchemy documentation: Engine Configuration (pool_size, max_overflow, pool_timeout)
- psycopg documentation: Connection pools
- psycopg documentation: The psycopg_pool package (getconn and putconn)
- Python documentation: queue
- Python documentation: contextlib (contextmanager)
Every Python sample in this post was run in Python 3.13 before publishing, and the pgbench test on PostgreSQL 18.6 on 14 November 2026.