Consider a FastAPI app using a database connection pool. What is the main effect of using connection pooling on the app's performance under high load?
Think about how opening a new connection each time affects speed.
Connection pooling keeps a set of open connections ready to use. This avoids the overhead of opening and closing connections repeatedly, which reduces latency and improves performance under load.
Which code snippet correctly creates an async connection pool for a PostgreSQL database using SQLAlchemy in FastAPI?
Check the parameter names and types for connection pool configuration.
Option A correctly uses pool_size and max_overflow to configure the connection pool size. Option A uses poolclass but QueuePool is default and requires import. Option A disables pooling. Option A uses a string instead of an integer for pool_size, causing an error.
Given this FastAPI code snippet, why might the app run out of database connections under heavy load?
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
engine = create_async_engine('postgresql+asyncpg://user:pass@localhost/db', pool_size=5)
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
async def get_db():
session = async_session()
yield session
@app.get('/items')
async def read_items(db: AsyncSession = Depends(get_db)):
result = await db.execute('SELECT * FROM items')
return result.fetchall()Look at how sessions are managed and closed.
The get_db() dependency creates sessions but does not close them properly (no async with or explicit await session.close() in a finally block). This causes connections to leak and exhaust the pool under heavy load.
Given this connection pool configuration in FastAPI using SQLAlchemy, what is the maximum number of simultaneous database connections that can be open?
engine = create_async_engine(
'postgresql+asyncpg://user:pass@localhost/db',
pool_size=3,
max_overflow=2
)Remember that max_overflow adds extra connections beyond the pool size.
The pool_size sets the number of persistent connections (3). The max_overflow allows up to 2 additional temporary connections beyond the pool size. So total max connections = 3 + 2 = 5.
In a FastAPI app using async endpoints, why is it better to use an async connection pool rather than a synchronous one?
Think about how async code handles waiting for I/O.
Async connection pools use non-blocking calls, allowing the app to handle many requests concurrently without waiting for database responses. Sync pools block the event loop, reducing concurrency and performance in async apps.