---
title: "psycopg"
description: "Connect Python applications using psycopg to PgBeam for connection pooling, caching, and global routing. Includes SQLAlchemy integration."
canonical: "https://pgbeam.com/docs/psycopg"
last-updated: "2026-09-14T19:37:21.000Z"
---

# psycopg

> Connect Python applications using psycopg to PgBeam for connection pooling, caching, and global routing. Includes SQLAlchemy integration.

URL: https://pgbeam.com/docs/psycopg

Connect your Python application to PgBeam by updating the connection string. This guide covers psycopg 3, psycopg connection pools, and SQLAlchemy integration.

## Setup

## Set the connection string

## Connect with psycopg

## Set up connection pooling (recommended)

Use psycopg's built-in pool with a small pool size:

## Pool sizing

PgBeam handles upstream connection pooling, so keep your application-side pool small:

Deployment type

Recommended `max_size`

Single process (Gunicorn)

5-10

Multiple workers

2-3 per worker

Serverless (Lambda)

1-2

With PgBeam in transaction pool mode, each psycopg connection only holds an
upstream connection during active transactions. A small pool handles high
concurrency efficiently.

## SQLAlchemy integration

psycopg works as the default PostgreSQL driver for SQLAlchemy. Update your engine configuration to point at PgBeam:

Set `max_overflow=0` to prevent SQLAlchemy from creating connections beyond
the pool size. PgBeam handles overflow at the proxy level.

## Caching

## Automatic caching via cache rules

For ORM queries (SQLAlchemy, Django ORM), PgBeam tracks the SQL shapes automatically. Enable caching for specific shapes through Cache Rules in the dashboard.

## SQL annotations for fine-grained control

## Read replicas

Route reads to replicas with the `/* @pgbeam:replica */` annotation:

Standard ORM queries always go to the primary. For replica routing with SQLAlchemy, use `text()` or raw SQL execution.

See Read Replicas for replica setup and routing details.

## Error handling

psycopg maps PostgreSQL SQLSTATE codes to specific exception classes:

See Error Codes for the full reference.

## Django integration

Django uses psycopg as its default PostgreSQL backend. Update `DATABASES` in `settings.py`:

## Migrations

Run migrations directly against your origin database:

## Debugging

Enable debug mode to see cache and routing details:

## Common issues

Issue

Cause

Fix

"too many connections"

Pool too large

Set `max_size=5` in ConnectionPool

`OperationalError` on connect

Cold start after inactivity

Normal: first connection is slower

Stale data after writes

Cache returning old results

Adjust TTL or use `noCache` annotation

## Further reading

Connection Pooling: Pool modes, sizing, and lifecycle

Caching: TTL, SWR, cache layers, and cache rules

Error Codes: SQLSTATE reference for PgBeam errors