Date: July 14, 2025 Status: Accepted Deciders: Claude Code (Architecture Assistant), Development Team
Architectural survey reveals 5 distinct async session management patterns across the codebase, creating maintenance complexity, resource leaks, and inconsistent behavior:
'another operation is in progress' in testssession.commit() vs async with session.begin()Standardize on Context Manager Session Pattern with automatic resource management and consistent transaction handling.
1. Single Session Factory
class AsyncSessionFactory:
@staticmethod
async def create_session() -> AsyncSession:
"""Create new session with proper configuration"""
return await db.get_session()
@staticmethod
@asynccontextmanager
async def session_scope():
"""Context manager for automatic session lifecycle"""
session = await AsyncSessionFactory.create_session()
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()
2. Repository Pattern Standardization
# All repositories use AsyncSession constructor
class ExampleRepository(BaseRepository):
def __init__(self, session: AsyncSession):
super().__init__(session)
async def example_operation(self, data):
# Use transaction context for all operations
async with self.session.begin():
entity = self.model(**data)
self.session.add(entity)
# Automatic commit/rollback
3. Service Layer Pattern
# Services use context manager for automatic cleanup
async def example_service_method():
async with AsyncSessionFactory.session_scope() as session:
repo = ExampleRepository(session)
return await repo.example_operation(data)
# Automatic cleanup
Phase 1: Infrastructure (Immediate)
AsyncSessionFactory with context manager supportAsyncSession onlyasync with session.begin()Phase 2: Service Layer (Medium-term)
Phase 3: Cleanup (Long-term)
DatabasePool.get_pool() pattern entirelydb.get_session() usage outside infrastructure1. Create AsyncSessionFactory
# services/database/session_factory.py
from contextlib import asynccontextmanager
from sqlalchemy.ext.asyncio import AsyncSession
from .connection import db
class AsyncSessionFactory:
@staticmethod
async def create_session() -> AsyncSession:
return await db.get_session()
@staticmethod
@asynccontextmanager
async def session_scope():
session = await AsyncSessionFactory.create_session()
try:
yield session
except Exception:
await session.rollback()
raise
finally:
await session.close()
2. Update BaseRepository Pattern
# services/database/repositories.py
class BaseRepository:
def __init__(self, session: AsyncSession):
self.session = session
async def create(self, **kwargs):
async with self.session.begin():
entity = self.model(**kwargs)
self.session.add(entity)
# Automatic commit via context manager
3. Replace RepositoryFactory
# Deprecated: RepositoryFactory.get_repositories()
# New pattern: Use AsyncSessionFactory.session_scope()
async def example_usage():
async with AsyncSessionFactory.session_scope() as session:
repo = ExampleRepository(session)
return await repo.operation()
High-Priority Components:
Medium-Priority Components:
1. Unify Test and Production Patterns
# conftest.py - align with production pattern
@pytest.fixture
async def db_session():
async with AsyncSessionFactory.session_scope() as session:
yield session
2. Remove Legacy Test Patterns
db_session_factory in favor of unified patternRequirements:
.to_domain()services/database/)async with session.begin() for all operationssession.commit() callsRequirements:
AsyncSessionFactory.session_scope() context managerMigration Risk: Introduce patterns gradually alongside existing ones
Performance Risk: Context manager overhead
Complexity Risk: Developers must learn new pattern
Phase 1 Success Criteria:
Phase 2 Success Criteria:
Phase 3 Success Criteria:
After 12.5 hours of debugging, AsyncSessionFactory proved to be the correct pattern:
Successfully migrated:
What appeared as test failures were often system improvements. The infrastructure is sound - focus on business logic accuracy rather than chasing cosmetic warnings.
Implementation Date: July 14, 2025 Migration Timeline: 3 phases over 2-4 weeks Risk Level: Medium (careful migration required) Business Impact: None (transparent to users)