Skip to content

[BUG] DB session leak in /health endpoint — generator cleanup never called #740

Description

@vipul674

Description of the Bug

In backend/app/main.py, the inline /health endpoint acquires a DB session using next(get_db()):

db = next(get_db())

The get_db() function is a context manager generator:

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

Using next(get_db()) only executes the setup code (creating the session). The generator's finally block (which closes the DB session) never executes because close() or generator cleanup is never called on the generator object.

This means every hit to the /health endpoint leaks one DB connection. Under repeated health checks (e.g., from Docker's healthcheck which runs every 30 seconds, or from a load balancer), this will exhaust the database connection pool over time.

Note: The get_db_session dependency function (used in route handlers) correctly uses contextmanager and cleanup. The issue is specific to the inline /health endpoint which uses next(get_db()) directly.

Steps to Reproduce

  1. Start the application with PostgreSQL (connection pool has a fixed size)
  2. Hit the /api/health endpoint repeatedly
  3. Monitor the number of active database connections
  4. Observe that connections increase with each health check hit and are never released

Expected Behavior

The health endpoint should properly close the DB session after use, either by using get_db_session() as a context manager or by explicitly calling db.close().

Affected File

backend/app/main.py (lines ~124-138)

Suggested Fix

Replace next(get_db()) with a proper context manager usage:

from backend.app.database import get_db_session

# Inside the health check:
with get_db_session() as db:
    # use db
    pass

Or manually close the generator:

gen = get_db()
db = next(gen)
try:
    # use db
finally:
    gen.close()

GSSoC '26

  • Yes, I am participating in GirlScript Summer of Code and would like to fix this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    gssocGirlScript Summer of Code 2026 issue/PR

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions