Files
romm/backend/handler/database/base_handler.py
Georges-Antoine Assi 6b2ca96397 fix(db): recycle pooled connections before the server drops them
The engine sets `pool_pre_ping` but no `pool_recycle`, so a connection
the database closed for being idle is still handed out, and the ping on
that half-closed socket blocks the worker until TCP gives up: tens of
seconds to minutes of an unresponsive API for every request that draws
it, while a fresh connection to the same server answers instantly.

Default to 300s, under the lowest `wait_timeout` MariaDB is commonly
configured with, and make it settable.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 20:25:36 -04:00

44 lines
1.5 KiB
Python

import logging
import time
from sqlalchemy import create_engine, event
from sqlalchemy.orm import sessionmaker
from config import DB_POOL_RECYCLE_SECONDS, DEV_SQL_ECHO
from config.config_manager import ConfigManager
# `pool_pre_ping` alone still hands out a connection the server closed while it
# sat idle, and the ping on a half-closed socket blocks the worker until TCP
# gives up. Recycling retires it first.
sync_engine = create_engine(
ConfigManager.get_db_engine(),
pool_pre_ping=True,
pool_recycle=DB_POOL_RECYCLE_SECONDS if DB_POOL_RECYCLE_SECONDS > 0 else -1,
echo=False,
)
sync_session = sessionmaker(bind=sync_engine, expire_on_commit=False)
# Disable SQLAlchemy logging as echo will print the queries
logging.getLogger("sqlalchemy.engine.Engine").handlers = [logging.NullHandler()]
if DEV_SQL_ECHO:
@event.listens_for(sync_engine, "before_cursor_execute")
def before_cursor_execute(
conn, cursor, statement, parameters, context, executemany
):
context._query_start_time = time.time()
print("--------START--------")
print(f"SQL: {statement}")
print(f"Parameters: {parameters}")
@event.listens_for(sync_engine, "after_cursor_execute")
def after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
total_time = time.time() - context._query_start_time
print(f"Execution time: {total_time:.4f} seconds")
print("--------END--------")
class DBBaseHandler: ...