Add retry loop to database pool initialization (handles startup race conditions)

This commit is contained in:
Reditus committed 2026-05-12 04:37:55 +01:00
1 parent 51cf375823
commit 2b215f8920
1 file changed
+18 -10
+18 -10
View File
@@ -1,6 +1,7 @@
"""Database service - connection pool and query helpers""" """Database service - connection pool and query helpers"""
import logging import logging
import time
import psycopg2 import psycopg2
import psycopg2.extras import psycopg2.extras
import psycopg2.pool import psycopg2.pool
@@ -17,16 +18,23 @@ class DatabaseService:
def init_pool(self): def init_pool(self):
if self.pool is None: if self.pool is None:
try: # Retry up to 10 times with 2s delays (20s total) to handle startup race conditions
self.pool = psycopg2.pool.ThreadedConnectionPool( for attempt in range(10):
minconn=self.min_conn, try:
maxconn=self.max_conn, self.pool = psycopg2.pool.ThreadedConnectionPool(
**self.db_config minconn=self.min_conn,
) maxconn=self.max_conn,
logger.info("Database connection pool initialized") **self.db_config
except Exception as e: )
logger.error(f"Failed to initialize database pool: {e}") logger.info("Database connection pool initialized")
self.pool = None return self.pool
except Exception as e:
if attempt < 9:
logger.warning(f"DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
time.sleep(2)
else:
logger.error(f"Failed to initialize database pool after 10 attempts: {e}")
self.pool = None
return self.pool return self.pool
def get_connection(self): def get_connection(self):