diff --git a/backend/jobs.py b/backend/jobs.py index 3d2fe93..ac88276 100644 --- a/backend/jobs.py +++ b/backend/jobs.py @@ -1,5 +1,6 @@ """Job definitions and enqueueing utilities using pgqueuer.""" +import asyncio import json import asyncpg @@ -12,14 +13,21 @@ JOB_RANDOM_NUMBER = "random_number" # Connection pool for job enqueueing (lazy initialized) _pool: asyncpg.Pool | None = None +_pool_lock = asyncio.Lock() async def get_job_pool() -> asyncpg.Pool: """Get or create the connection pool for job enqueueing.""" global _pool - if _pool is None: - _pool = await asyncpg.create_pool(ASYNCPG_DATABASE_URL, min_size=1, max_size=5) - return _pool + if _pool is not None: + return _pool + async with _pool_lock: + # Double-check after acquiring lock + if _pool is None: + _pool = await asyncpg.create_pool( + ASYNCPG_DATABASE_URL, min_size=1, max_size=5 + ) + return _pool async def close_job_pool() -> None: