SQLAlchemy 2.0 create_async_engine Reference: Tuning pool_size, max_overflow, asyncpg & PgBouncer
Deploying FastAPI or Litestar services on PostgreSQL with SQLAlchemy 2.0 (create_async_engine + AsyncSession) and asyncpg routinely triggers three production failure modes under burst traffic: QueuePool limit of size X overflow Y reached timeouts, DuplicatePreparedStatementError crashes behind transaction-pooled PgBouncer, and MissingGreenlet exceptions after session.commit(). As a Senior Backend Engineer and Cloud Engineer, here is the complete configuration and sizing blueprint I ship for sub-10ms p99 PostgreSQL workloads.
1. Complete create_async_engine Parameter Reference & Sizing Formula
When using postgresql+asyncpg://, SQLAlchemy wraps AsyncAdaptedQueuePool by default. Every Uvicorn/Gunicorn worker process maintains its own independent connection pool, meaning total PostgreSQL backend sockets equal pods × workers_per_pod × (pool_size + max_overflow):
| Parameter | Default | Production Recommendation | Engineering Rationale |
|---|---|---|---|
pool_size |
5 |
10–25 per worker (direct DB) or 5–15 (via PgBouncer) |
Steady-state warm TCP/TLS connections kept open inside each Python event loop |
max_overflow |
10 |
5–15 (never exceed pool_size) |
Burst connections closed immediately upon return; excessive overflow triggers PostgreSQL CPU thrashing |
pool_timeout |
30.0s |
3.0–5.0s |
Fail fast before load balancer 30s timeouts cause cascading retry storms |
pool_recycle |
-1 (off) |
1800 (30 min) |
Gracefully rotates connections before NAT gateways, Cloud SQL proxies, or firewalls drop idle sockets |
pool_pre_ping |
False |
True (direct DB) / False (local PgBouncer sidecar) |
Issues lightweight liveness check on checkout so primary HA failovers recover transparently |
pool_use_lifo |
False |
True |
Reuses the most recently active socket so idle warm connections can be reclaimed cleanly by upstream poolers |
2. Production create_async_engine + Transaction-Mode PgBouncer Configuration
By default, asyncpg creates protocol-level unnamed/named prepared statements per physical PostgreSQL session. When PgBouncer (or Supabase Supavisor / RDS Proxy) runs in pool_mode = transaction, backend PostgreSQL connections are multiplexed across clients between transactions—causing DuplicatePreparedStatementError: prepared statement "__asyncpg_stmt_1__" already exists unless statement_cache_size=0 is explicitly passed inside connect_args:
# app/db/engine.py
import uuid
from collections.abc import AsyncGenerator
from sqlalchemy.ext.asyncio import (
AsyncEngine,
AsyncSession,
async_sessionmaker,
create_async_engine,
)
DATABASE_URL = "postgresql+asyncpg://app_rw:secret@pgbouncer.internal:6432/ledger_prod"
engine: AsyncEngine = create_async_engine(
DATABASE_URL,
pool_size=15,
max_overflow=10,
pool_timeout=4.0,
pool_recycle=1800,
pool_pre_ping=True,
pool_use_lifo=True,
echo=False,
connect_args={
"statement_cache_size": 0, # Mandatory for PgBouncer transaction/statement mode
"prepared_statement_name_func": lambda: f"__asyncpg_{uuid.uuid4().hex}__",
"command_timeout": 8.0,
"server_settings": {
"application_name": "ledger-api-async",
"statement_timeout": "5000", # 5s hard query ceiling
"lock_timeout": "1500", # 1.5s fail-fast on row lock contention
"idle_in_transaction_session_timeout": "10000", # Reclaim leaked open transactions
},
},
)
AsyncSessionFactory = async_sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False, # Prevents post-commit MissingGreenlet attribute reloads
autoflush=False,
)
async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
async with AsyncSessionFactory() as session:
try:
yield session
except Exception:
await session.rollback()
raise
3. Preventing Connection Starvation & MissingGreenlet Under Load
The #1 hidden cause of QueuePool limit of size 20 overflow 10 reached in async Python APIs is holding a checked-out AsyncSession open while awaiting slow external HTTP or LLM calls. Always commit or close your database transaction before calling external webhooks, Stripe/payment APIs, or Vertex AI/OpenAI endpoints—or decouple side effects completely with our PostgreSQL Transactional Outbox Pattern:
# Exporting live SQLAlchemy AsyncAdaptedQueuePool saturation metrics to Prometheus
from prometheus_client import Gauge
POOL_CHECKED_OUT = Gauge("db_pool_checked_out", "Active checked-out asyncpg connections")
POOL_OVERFLOW = Gauge("db_pool_overflow", "Current overflow connections above pool_size")
def record_pool_telemetry(async_engine: AsyncEngine) -> None:
sync_pool = async_engine.sync_engine.pool
POOL_CHECKED_OUT.set(sync_pool.checkedout())
POOL_OVERFLOW.set(max(0, sync_pool.overflow()))
4. Frequently Asked Questions — SQLAlchemy create_async_engine & asyncpg
How should I calculate pool_size and max_overflow for Kubernetes or Cloud Run?
Divide your PostgreSQL max_connections (minus 15% reserved for superuser, replication, and migrations—or your PgBouncer max_client_conn) by max_pods × uvicorn_workers_per_pod. For example, 8 pods running 2 Uvicorn workers each with pool_size=10, max_overflow=5 consumes at most 8 × 2 × 15 = 240 connections at peak burst.
Should I use NullPool or AsyncAdaptedQueuePool behind PgBouncer?
Use NullPool only in short-lived serverless functions (AWS Lambda) where event loops freeze between invocations, or when PgBouncer runs as a localhost Unix-socket sidecar on the exact same pod. Over VPC networks, keeping a modest AsyncAdaptedQueuePool (pool_size=10, max_overflow=5, pool_use_lifo=True) eliminates per-request TCP/TLS handshake latency to PgBouncer.
Why does asyncpg raise DuplicatePreparedStatementError with SQLAlchemy 2.0?
SQLAlchemy passes queries to asyncpg, which caches protocol-level prepared statements per connection by default. In transaction-pooled PgBouncer, Supavisor, or Neon pooled endpoints, two Python sessions share the same physical PostgreSQL backend sequentially, colliding on statement names unless you set connect_args={"statement_cache_size": 0}.
Can I book a 1-Day PostgreSQL & SQLAlchemy Performance Audit?
Yes. Book a fixed-price $100 USD / Rp 1,000,000 1-Day Backend Engineering Sprint to resolve asyncpg pool exhaustion, tune PgBouncer, and optimize slow PostgreSQL queries, or explore our Backend Engineer Pillar Guide and GCP Professional Data Engineer Guide.