Skip to content

Potential Performance Issue with Session Management in Repository Methods #40

Description

I noticed that in the current implementation of the UserSQLAlchemyRepo, each repository method creates a new session using the session_factory() context manager. It can lead to potential performance issues when multiple repository methods are called sequentially within the same service layer function.

_async_session_factory = async_sessionmaker(
class_=AsyncSession,
sync_session_class=RoutingSession,
expire_on_commit=False,
)
session = async_scoped_session(
session_factory=_async_session_factory,
scopefunc=get_session_context,
)
class Base(DeclarativeBase):
...
@asynccontextmanager
async def session_factory() -> AsyncGenerator[AsyncSession, None]:
_session = async_sessionmaker(
class_=AsyncSession,
sync_session_class=RoutingSession,
expire_on_commit=False,
)()
try:
yield _session
finally:
await _session.close()

async def get_user_by_email_or_nickname(
self,
*,
email: str,
nickname: str,
) -> User | None:
async with session_factory() as read_session:
stmt = await read_session.execute(
select(User).where(or_(User.email == email, User.nickname == nickname)),
)
return stmt.scalars().first()

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions