Psycopg Connection Pool

3.3.0 · active · verified Sun Apr 05

psycopg-pool provides efficient connection pooling implementations for Psycopg 3, the PostgreSQL adapter for Python. It includes both synchronous (`ConnectionPool`) and asynchronous (`AsyncConnectionPool`) pools, designed to manage a limited number of PostgreSQL connections, reduce connection overhead, and optimize resource usage in multi-threaded or async applications. The current version is 3.3.0, and it follows an independent release cycle from the main `psycopg` package.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a `ConnectionPool` using a connection string, obtain a connection using a context manager, execute a simple query, and ensure proper connection handling (returning to pool, transaction management). It also highlights how the pool manages connections for multiple requests.

import os
from psycopg_pool import ConnectionPool

# Get connection string from environment variable for security
DB_URL = os.environ.get('DATABASE_URL', 'postgresql://user:password@host:port/dbname')

# Create a connection pool as a context manager
# The pool is opened and closed automatically
with ConnectionPool(DB_URL, min_size=1, max_size=5) as pool:
    print("Connection pool created.")

    # Get a connection from the pool as a context manager
    with pool.connection() as conn:
        # The connection context handles transaction commit/rollback
        # and returns the connection to the pool.
        with conn.cursor() as cur:
            cur.execute("SELECT 1 + 1")
            result = cur.fetchone()
            print(f"Result: {result[0]}")

    # Example of getting multiple connections (will block if pool exhausted)
    print("Attempting to get another connection...")
    with pool.connection() as conn2:
        with conn2.cursor() as cur2:
            cur2.execute("SELECT 'Hello from conn2'")
            result2 = cur2.fetchone()
            print(f"Result from conn2: {result2[0]}")

print("Pool is closed after exiting the 'with' block.")

view raw JSON →