Fix: Thread-safe DB connection manager with pooling (#212)
Summary
This PR implements thread-safe database connection management with connection pooling and proper resource cleanup.
Changes
- Added
backend/app/database/core.py(async SQLAlchemy engine + session manager) - Added
tests/test_db_pool.pyto verify concurrency and rollback behavior - Added
docs/DATABASE_CONNECTION.mddocumentation - Updated
backend/app/core/config/settings.pyfor database configuration - Updated
pyproject.tomlandbackend/requirements.txtto include new dependencies
Verification
Run the following tests:
pytest tests/test_db_pool.py
<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit
* **New Features**
* Added optional environment-configurable database URL and asynchronous database connectivity with pooled connections for improved performance and reliability.
* **Documentation**
* Added a guide covering database connection setup, pooling behavior, and best practices.
* **Tests**
* Added tests for connection pool sizing, concurrent session handling, and rollback/cleanup on errors.
* **Chores**
* Added async DB runtime and test dependencies.
<sub>βοΈ Tip: You can customize this high-level summary in your review settings.</sub>
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Adds async database support via SQLAlchemy/asyncpg: new optional π― 3 (Moderate) | β±οΈ ~22 minutes π I nibble bytes and hop through queues, Connections pooled, a cozy fuse. βοΈ Tip: You can configure your own custom pre-merge checks in the settings.π Walkthrough
Walkthrough
database_url setting, an async engine/session module with pooling and a get_db() generator, updated dependencies, documentation, and tests for pool behavior and session lifecycle.Changes
Cohort / File(s)
Summary
Configuration
backend/app/core/config/settings.pyAdded optional
database_url: Optional[str] = None to Settings.
Async DB core
backend/app/database/core.pyNew async engine (
create_async_engine) and async_session_maker created from DATABASE_URL; engine may be None with a warning; added async def get_db() -> AsyncGenerator[AsyncSession, None] that raises if engine uninitialized, yields sessions, and handles rollback/closure on errors.
Project deps
pyproject.toml, backend/requirements.txtAdded
sqlalchemy and asyncpg to project dependencies; added asyncpg==0.29.0 and pytest-asyncio==0.23.5 to backend requirements.
Documentation
docs/DATABASE_CONNECTION.mdNew doc describing AsyncIO SQLAlchemy setup, pool parameters, DATABASE_URL usage, get_db DI pattern, and testing considerations.
Tests
tests/test_db_pool.pyNew async tests mocking engine/session: asserts pool size/timeout, simulates 50 concurrent session acquisitions, and verifies rollback+close on error.
Sequence Diagram(s)
sequenceDiagram
participant Client as FastAPI Route
participant GetDb as get_db()
participant Maker as async_session_maker
participant Pool as Connection Pool
participant Session as AsyncSession
Client->>GetDb: request session
alt Engine initialized
GetDb->>Maker: create session
Maker->>Pool: acquire connection
Pool-->>Maker: provide connection
Maker-->>Session: return AsyncSession
GetDb-->>Client: yield session
Client->>Session: execute queries
alt Success
Client->>GetDb: return normally
GetDb->>Session: close session
Session->>Pool: release connection
else Exception
Client->>GetDb: exception raised
GetDb->>Session: rollback
GetDb->>Session: close session
Session->>Pool: release connection
end
else Engine not initialized
GetDb-->>Client: raise RuntimeError
end
Estimated code review effort
Poem
Sessions yield and roll back light,
Async fields gleam in rabbit sight.
Hooray β the DB sleeps snug at night!π₯ Pre-merge checks | β
3
β
Passed checks (3 passed)
Check name
Status
Explanation
Description Check
β
Passed
Check skipped - CodeRabbitβs high-level summary is enabled.
Title check
β
Passed
The title 'Fix: Thread-safe DB connection manager with pooling (
#212)' directly and accurately describes the main change: implementing a thread-safe database connection manager with connection pooling, which is the primary objective of the PR across all modified files.
Docstring Coverage
β
Passed
Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%.
β¨ Finishing touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands and usage tips.
Fixes #212
Addressed CodeRabbit feedback:
- Removed redundant session.close()
- Switched to logger.exception for better tracing
- Refactored tests to use importlib.reload with fixture
- Fixed async mock aexit using AsyncMock