AI Hints
Home›PostgreSQL Tutorial›COPY, Pools and a Python Report
PostgreSQL · Lesson 86 of 120

Connection Pools

Reuse connections.

⏱ 2 min read▶ Video at 1:17:34🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Opening a Postgres connection takes time, and each one uses memory on the server. A web app shouldn't open a new one for every request. A pool keeps a few open, and lends them out.

  • Connecting is slow
  • Each uses memory
  • Pool them

A connection pool

The pool keeps between two and five connections open. Pool connection borrows one, and gives it back at the end of the with block. Run it. Ten requests, served by just a few connections.

pool.pypython
from psycopg_pool import ConnectionPool

URL = "postgresql://postgres:postgres@localhost:5432/riverside"
pool = ConnectionPool(URL, min_size=2, max_size=5, open=True)

pids = set()
for request in range(10):
    with pool.connection() as conn:
        pids.add(conn.execute("SELECT pg_backend_pid()").fetchone()[0])

print("requests: 10, connections used:", len(pids))
pool.close()
Output
requests: 10, connections used: 3

Pool tips

Create one pool when the app starts. Size it by your database's limits, not your traffic. Postgres handles hundreds of connections, not thousands, so for big systems, use PgBouncer in front.

keyvalue
One poolper app
max_sizefits the DB
PgBouncermany apps
Closeon shutdown

Summary

Connection pools reuse a few connections, saving time and server memory. Next, practise with a Python report.

Key takeaways
  • psycopg_pool
  • min / max
  • PgBouncer
Next up: Practice: A Python Report — query, then format