|
| 1 | +# Database Configuration |
| 2 | + |
| 3 | +This guide covers SQLAlchemy setup and connection pooling best practices for production use. |
| 4 | + |
| 5 | +## Installation |
| 6 | + |
| 7 | +Install the SQLAlchemy extra: |
| 8 | + |
| 9 | +```bash |
| 10 | +pip install fastapi-api-key[sqlalchemy] |
| 11 | +``` |
| 12 | + |
| 13 | +## Basic Setup |
| 14 | + |
| 15 | +The `SqlAlchemyApiKeyRepository` requires an `AsyncSession`: |
| 16 | + |
| 17 | +```python |
| 18 | +from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker |
| 19 | +from fastapi_api_key.repositories.sql import SqlAlchemyApiKeyRepository |
| 20 | + |
| 21 | +# Create async engine |
| 22 | +engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/db") |
| 23 | + |
| 24 | +# Create session factory |
| 25 | +async_session = async_sessionmaker(engine, expire_on_commit=False) |
| 26 | + |
| 27 | +# Use in your application |
| 28 | +async with async_session() as session: |
| 29 | + repo = SqlAlchemyApiKeyRepository(session) |
| 30 | + # ... use repository |
| 31 | + await session.commit() |
| 32 | +``` |
| 33 | + |
| 34 | +## Connection Pooling |
| 35 | + |
| 36 | +SQLAlchemy uses connection pooling by default. For production, configure the pool explicitly. |
| 37 | + |
| 38 | +### PostgreSQL (asyncpg) |
| 39 | + |
| 40 | +```python |
| 41 | +from sqlalchemy.ext.asyncio import create_async_engine |
| 42 | + |
| 43 | +engine = create_async_engine( |
| 44 | + "postgresql+asyncpg://user:pass@localhost/db", |
| 45 | + pool_size=5, # Number of persistent connections |
| 46 | + max_overflow=10, # Additional connections when pool is exhausted |
| 47 | + pool_timeout=30, # Seconds to wait for a connection |
| 48 | + pool_recycle=1800, # Recycle connections after 30 minutes |
| 49 | + pool_pre_ping=True, # Verify connections before use |
| 50 | +) |
| 51 | +``` |
| 52 | + |
| 53 | +### SQLite (aiosqlite) |
| 54 | + |
| 55 | +SQLite doesn't benefit from connection pooling. Use `NullPool` for async SQLite: |
| 56 | + |
| 57 | +```python |
| 58 | +from sqlalchemy.ext.asyncio import create_async_engine |
| 59 | +from sqlalchemy.pool import NullPool |
| 60 | + |
| 61 | +engine = create_async_engine( |
| 62 | + "sqlite+aiosqlite:///./api_keys.db", |
| 63 | + poolclass=NullPool, |
| 64 | +) |
| 65 | +``` |
| 66 | + |
| 67 | +### MySQL (aiomysql) |
| 68 | + |
| 69 | +```python |
| 70 | +from sqlalchemy.ext.asyncio import create_async_engine |
| 71 | + |
| 72 | +engine = create_async_engine( |
| 73 | + "mysql+aiomysql://user:pass@localhost/db", |
| 74 | + pool_size=5, |
| 75 | + max_overflow=10, |
| 76 | + pool_timeout=30, |
| 77 | + pool_recycle=3600, # MySQL default wait_timeout is 8 hours |
| 78 | + pool_pre_ping=True, |
| 79 | +) |
| 80 | +``` |
| 81 | + |
| 82 | +## Pool Size Guidelines |
| 83 | + |
| 84 | +| Scenario | pool_size | max_overflow | |
| 85 | +|----------|-----------|--------------| |
| 86 | +| Development | 2 | 5 | |
| 87 | +| Small app (<100 req/s) | 5 | 10 | |
| 88 | +| Medium app (100-1000 req/s) | 10 | 20 | |
| 89 | +| Large app (>1000 req/s) | 20+ | 40+ | |
| 90 | + |
| 91 | +!!! tip "Rule of Thumb" |
| 92 | + A good starting point is `pool_size = (2 * CPU cores) + effective_spindle_count`. |
| 93 | + For cloud databases, start with 5-10 and monitor. |
| 94 | + |
| 95 | +## FastAPI Integration |
| 96 | + |
| 97 | +Use a dependency to manage sessions per request: |
| 98 | + |
| 99 | +```python |
| 100 | +from contextlib import asynccontextmanager |
| 101 | +from fastapi import FastAPI, Depends |
| 102 | +from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession |
| 103 | + |
| 104 | +from fastapi_api_key import ApiKeyService |
| 105 | +from fastapi_api_key.repositories.sql import SqlAlchemyApiKeyRepository |
| 106 | + |
| 107 | +# Engine with connection pooling |
| 108 | +engine = create_async_engine( |
| 109 | + "postgresql+asyncpg://user:pass@localhost/db", |
| 110 | + pool_size=5, |
| 111 | + max_overflow=10, |
| 112 | + pool_pre_ping=True, |
| 113 | +) |
| 114 | + |
| 115 | +async_session = async_sessionmaker(engine, expire_on_commit=False) |
| 116 | + |
| 117 | + |
| 118 | +@asynccontextmanager |
| 119 | +async def lifespan(app: FastAPI): |
| 120 | + # Startup: optionally create tables |
| 121 | + async with engine.begin() as conn: |
| 122 | + # await conn.run_sync(Base.metadata.create_all) |
| 123 | + pass |
| 124 | + yield |
| 125 | + # Shutdown: dispose of the connection pool |
| 126 | + await engine.dispose() |
| 127 | + |
| 128 | + |
| 129 | +app = FastAPI(lifespan=lifespan) |
| 130 | + |
| 131 | + |
| 132 | +async def get_session(): |
| 133 | + async with async_session() as session: |
| 134 | + yield session |
| 135 | + |
| 136 | + |
| 137 | +async def get_api_key_service(session: AsyncSession = Depends(get_session)): |
| 138 | + repo = SqlAlchemyApiKeyRepository(session) |
| 139 | + return ApiKeyService(repo=repo) |
| 140 | +``` |
| 141 | + |
| 142 | +## Connection Health |
| 143 | + |
| 144 | +### Pre-ping |
| 145 | + |
| 146 | +Enable `pool_pre_ping=True` to test connections before use. This handles: |
| 147 | + |
| 148 | +- Database restarts |
| 149 | +- Network interruptions |
| 150 | +- Idle connection timeouts |
| 151 | + |
| 152 | +### Pool Recycling |
| 153 | + |
| 154 | +Set `pool_recycle` to a value less than your database's connection timeout: |
| 155 | + |
| 156 | +| Database | Default Timeout | Recommended `pool_recycle` | |
| 157 | +|----------|-----------------|---------------------------| |
| 158 | +| PostgreSQL | No limit | 1800 (30 min) | |
| 159 | +| MySQL | 8 hours | 3600 (1 hour) | |
| 160 | +| MariaDB | 8 hours | 3600 (1 hour) | |
| 161 | + |
| 162 | +## Monitoring |
| 163 | + |
| 164 | +Log pool statistics for debugging: |
| 165 | + |
| 166 | +```python |
| 167 | +import logging |
| 168 | + |
| 169 | +logging.getLogger("sqlalchemy.pool").setLevel(logging.DEBUG) |
| 170 | +``` |
| 171 | + |
| 172 | +Check pool status programmatically: |
| 173 | + |
| 174 | +```python |
| 175 | +pool = engine.pool |
| 176 | +print(f"Pool size: {pool.size()}") |
| 177 | +print(f"Checked out: {pool.checkedout()}") |
| 178 | +print(f"Overflow: {pool.overflow()}") |
| 179 | +print(f"Checked in: {pool.checkedin()}") |
| 180 | +``` |
| 181 | + |
| 182 | +## Common Issues |
| 183 | + |
| 184 | +### "QueuePool limit reached" |
| 185 | + |
| 186 | +The pool is exhausted. Solutions: |
| 187 | + |
| 188 | +1. Increase `pool_size` and `max_overflow` |
| 189 | +2. Ensure sessions are properly closed (use context managers) |
| 190 | +3. Reduce query execution time |
| 191 | + |
| 192 | +### "Connection reset by peer" |
| 193 | + |
| 194 | +The database closed an idle connection. Solutions: |
| 195 | + |
| 196 | +1. Enable `pool_pre_ping=True` |
| 197 | +2. Set `pool_recycle` to a lower value |
| 198 | +3. Check database idle timeout settings |
| 199 | + |
| 200 | +### High latency on first request |
| 201 | + |
| 202 | +The pool creates connections lazily. Pre-warm the pool: |
| 203 | + |
| 204 | +```python |
| 205 | +async def warm_pool(): |
| 206 | + """Pre-create connections to avoid cold start latency.""" |
| 207 | + async with engine.connect() as conn: |
| 208 | + await conn.execute(text("SELECT 1")) |
| 209 | +``` |
0 commit comments