Connection pooling helps your FastAPI app reuse database connections. This makes your app faster and uses fewer resources.
Connection pooling in FastAPI
Start learning this pattern below
Jump into concepts and practice - no test required
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession from sqlalchemy.orm import sessionmaker engine = create_async_engine( "postgresql+asyncpg://user:password@localhost/dbname", pool_size=5, # Number of connections to keep in the pool max_overflow=10, # Extra connections allowed beyond pool_size ) async_session = sessionmaker( engine, expire_on_commit=False, class_=AsyncSession )
Use create_async_engine to create a database engine with connection pooling.
pool_size controls how many connections stay open ready to use.
engine = create_async_engine(
"postgresql+asyncpg://user:password@localhost/dbname",
pool_size=10,
max_overflow=20
)async_session = sessionmaker(
engine, expire_on_commit=False, class_=AsyncSession
)This FastAPI app uses connection pooling to talk to a SQLite database asynchronously. The get_session function provides a session from the pool. The endpoint runs a simple query and returns the result.
from fastapi import FastAPI, Depends from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession from sqlalchemy.orm import sessionmaker from sqlalchemy import text app = FastAPI() DATABASE_URL = "sqlite+aiosqlite:///./test.db" engine = create_async_engine( DATABASE_URL ) async_session = sessionmaker( engine, expire_on_commit=False, class_=AsyncSession ) async def get_session() -> AsyncSession: async with async_session() as session: yield session @app.get("/items") async def read_items(session: AsyncSession = Depends(get_session)): result = await session.execute(text("SELECT 1 as number")) number = result.scalar_one() return {"number": number}
Connection pools keep connections open so your app can reuse them quickly.
Adjust pool_size and max_overflow based on your app's load and database limits.
Always close sessions properly to return connections to the pool.
Connection pooling speeds up database access by reusing connections.
FastAPI with SQLAlchemy supports connection pooling easily.
Configure pool size to balance performance and resource use.
Practice
Solution
Step 1: Understand connection pooling purpose
Connection pooling keeps database connections open and reuses them instead of opening new ones each time.Step 2: Identify the benefit in FastAPI context
This reuse reduces the time spent opening connections, speeding up database access in FastAPI apps.Final Answer:
It reuses database connections to improve performance -> Option BQuick Check:
Connection pooling = reuse connections = better speed [OK]
- Confusing pooling with encryption
- Thinking pooling creates tables automatically
- Mixing pooling with API response caching
Solution
Step 1: Recall SQLAlchemy pool size parameter
The correct parameter to set max pool size ispool_size.Step 2: Match parameter with options
Only engine = create_engine(DB_URL, pool_size=10) usespool_size=10, which is valid syntax.Final Answer:
engine = create_engine(DB_URL, pool_size=10) -> Option AQuick Check:
pool_size sets max connections in SQLAlchemy [OK]
- Using incorrect parameter names like max_connections
- Confusing pool_size with connection_limit
- Trying to set max_pool which is invalid
from sqlalchemy import create_engine
engine = create_engine('sqlite:///test.db', pool_size=5, max_overflow=0)
# Each request uses engine.connect()Solution
Step 1: Understand pool_size effect
Setting pool_size=5 means the engine keeps up to 5 connections open for reuse.Step 2: Behavior on multiple requests
When more than 5 requests come, new ones wait until a connection is free; no new connections beyond 5 are created.Final Answer:
Up to 5 connections are reused; new requests wait if all are busy -> Option CQuick Check:
pool_size=5 means max 5 reusable connections [OK]
- Assuming each request creates a new connection
- Thinking only one connection is shared
- Believing the app crashes when pool is full
engine = create_engine('postgresql://user:pass@localhost/db', pool_size=5, max_overflow=0)
connection = engine.connect()
# forgot to close connection after use
What problem will this cause?Solution
Step 1: Identify missing connection close
Not closing connections means they stay checked out and unavailable for reuse.Step 2: Effect on connection pool
Since pool_size=5, after 5 connections are checked out and not closed, no free connections remain, causing new requests to wait indefinitely.Final Answer:
Connections will be exhausted causing new requests to hang -> Option DQuick Check:
Not closing connections exhausts pool causing hangs [OK]
- Assuming connections close automatically without code
- Thinking database rejects connections immediately
- Believing app auto-closes connections after timeout
Options: A) pool_size=20, max_overflow=10 B) pool_size=1, max_overflow=50 C) pool_size=5, max_overflow=0 D) pool_size=0, max_overflow=0
Solution
Step 1: Understand pool_size and max_overflow roles
pool_size sets fixed connections; max_overflow allows extra temporary connections beyond pool_size.Step 2: Analyze options for many short requests
Too large pool_size wastes resources; too small with high overflow risks overhead. pool_size=5, max_overflow=0 with moderate pool_size=5 and no overflow balances reuse and resource use well.Final Answer:
pool_size=5, max_overflow=0 -> Option AQuick Check:
Moderate pool_size with no overflow balances performance and resources [OK]
- Choosing very high pool_size wasting resources
- Using zero pool_size disables pooling
- Setting high max_overflow causes many temporary connections
