Skip to content
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
e6f894d
fix(proxy): add prisma reconnect primitive and db watchdog
ishaan-jaff Feb 20, 2026
d1b2805
fix(proxy): start and stop prisma watchdog in lifecycle
ishaan-jaff Feb 20, 2026
ffe8637
fix(auth): retry key lookup once after prisma reconnect
ishaan-jaff Feb 20, 2026
4dee7dc
test(proxy): add prisma self-heal watchdog coverage
ishaan-jaff Feb 20, 2026
b560164
test(auth): cover reconnect-once behavior for key lookup
ishaan-jaff Feb 20, 2026
cb19ec1
refactor(auth): extract db reconnect helper and remove inline import
ishaan-jaff Feb 20, 2026
e89c5b7
fix(proxy): apply reconnect cooldown after attempt and add auth timeo…
ishaan-jaff Feb 20, 2026
14f529a
fix(auth): bound reconnect latency on key lookup path
ishaan-jaff Feb 20, 2026
5e0fbf0
test(auth): assert reconnect timeout argument in key lookup
ishaan-jaff Feb 20, 2026
67809b8
test(proxy): verify reconnect cooldown timestamp set after attempt
ishaan-jaff Feb 20, 2026
edcb6bd
fix(proxy): harden prisma reconnect cycle semantics
ishaan-jaff Feb 21, 2026
1144b7f
test(proxy): cover watchdog reconnect + timeout budget
ishaan-jaff Feb 21, 2026
1921bad
fix(proxy): bound watchdog probe and reconnect paths
ishaan-jaff Feb 21, 2026
2083f39
test(proxy): cover watchdog timeout and probe behavior
ishaan-jaff Feb 21, 2026
2c02d1e
fix(proxy): narrow prisma db connection error classification
ishaan-jaff Feb 21, 2026
c0a395a
fix(proxy): add auth reconnect lock timeout budget
ishaan-jaff Feb 21, 2026
4844f76
fix(auth): pass lock timeout for db reconnect retries
ishaan-jaff Feb 21, 2026
3bb2423
test(proxy): cover narrow prisma connection error detection
ishaan-jaff Feb 21, 2026
f288319
test(proxy): add reconnect lock-timeout behavior coverage
ishaan-jaff Feb 21, 2026
b53c342
test(auth): assert reconnect lock timeout argument
ishaan-jaff Feb 21, 2026
aa71695
fix(proxy): avoid lock leak race in reconnect lock timeout path
ishaan-jaff Feb 21, 2026
8b8c58a
test(proxy): cover reconnect lock-timeout race cleanup
ishaan-jaff Feb 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 54 additions & 6 deletions litellm/proxy/auth/auth_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,11 @@
LiteLLM_ObjectPermissionTable,
LiteLLM_OrganizationMembershipTable,
LiteLLM_OrganizationTable,
LiteLLM_ProjectTableCachedObj,
LiteLLM_TagTable,
LiteLLM_TeamMembership,
LiteLLM_TeamTable,
LiteLLM_TeamTableCachedObj,
LiteLLM_ProjectTableCachedObj,
LiteLLM_UserTable,
LiteLLMRoutes,
LitellmUserRoles,
Expand All @@ -57,6 +57,7 @@
UserAPIKeyAuth,
)
from litellm.proxy.auth.route_checks import RouteChecks
from litellm.proxy.db.exception_handler import PrismaDBExceptionHandler
from litellm.proxy.route_llm_request import route_request
from litellm.proxy.utils import PrismaClient, ProxyLogging, log_db_metrics
from litellm.router import Router
Expand Down Expand Up @@ -1982,6 +1983,51 @@ def get_key_object_from_ui_hash_key(
)


async def _fetch_key_object_from_db_with_reconnect(
hashed_token: str,
prisma_client: PrismaClient,
parent_otel_span: Optional[Span],
proxy_logging_obj: Optional[ProxyLogging],
) -> Optional[BaseModel]:
"""
Fetch key object from DB and retry once if a DB connection error can be healed.
"""
try:
return await prisma_client.get_data(
token=hashed_token,
table_name="combined_view",
parent_otel_span=parent_otel_span,
proxy_logging_obj=proxy_logging_obj,
)
except Exception as e:
if PrismaDBExceptionHandler.is_database_connection_error(e):
did_reconnect = False
if hasattr(prisma_client, "attempt_db_reconnect"):
auth_reconnect_timeout = getattr(
prisma_client, "_db_auth_reconnect_timeout_seconds", 2.0
)
if not isinstance(auth_reconnect_timeout, (int, float)):
auth_reconnect_timeout = 2.0
auth_reconnect_lock_timeout = getattr(
prisma_client, "_db_auth_reconnect_lock_timeout_seconds", 0.1
)
if not isinstance(auth_reconnect_lock_timeout, (int, float)):
auth_reconnect_lock_timeout = 0.1
did_reconnect = await prisma_client.attempt_db_reconnect(
reason="auth_get_key_object_lookup_failure",
timeout_seconds=auth_reconnect_timeout,
lock_timeout_seconds=auth_reconnect_lock_timeout,
)
if did_reconnect:
return await prisma_client.get_data(
token=hashed_token,
table_name="combined_view",
parent_otel_span=parent_otel_span,
proxy_logging_obj=proxy_logging_obj,
)
raise


@log_db_metrics
async def get_key_object(
hashed_token: str,
Expand Down Expand Up @@ -2020,11 +2066,13 @@ async def get_key_object(
)

# else, check db
_valid_token: Optional[BaseModel] = await prisma_client.get_data(
token=hashed_token,
table_name="combined_view",
parent_otel_span=parent_otel_span,
proxy_logging_obj=proxy_logging_obj,
_valid_token: Optional[BaseModel] = (
await _fetch_key_object_from_db_with_reconnect(
hashed_token=hashed_token,
prisma_client=prisma_client,
parent_otel_span=parent_otel_span,
proxy_logging_obj=proxy_logging_obj,
)
)

if _valid_token is None:
Expand Down
24 changes: 23 additions & 1 deletion litellm/proxy/db/exception_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,30 @@ def is_database_connection_error(e: Exception) -> bool:

if isinstance(e, DB_CONNECTION_ERROR_TYPES):
return True
if isinstance(e, prisma.errors.PrismaError):
if isinstance(
e, (prisma.errors.ClientNotConnectedError, prisma.errors.HTTPClientClosedError)
):
return True
if isinstance(e, prisma.errors.PrismaError):
error_message = str(e).lower()
# Treat generic PrismaError as connection error only when its text
# clearly indicates transport/connectivity failure.
connection_keywords = (
"can't reach database server",
"cannot reach database server",
"can't connect",
"cannot connect",
"connection error",
"connection closed",
"timed out",
"timeout",
"connection refused",
"network is unreachable",
"no route to host",
"broken pipe",
)
if any(keyword in error_message for keyword in connection_keywords):
return True
if isinstance(e, ProxyException) and e.type == ProxyErrorTypes.no_db_connection:
return True
return False
Expand Down
14 changes: 13 additions & 1 deletion litellm/proxy/proxy_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -388,10 +388,10 @@ def generate_feedback_box():
from litellm.proxy.management_endpoints.organization_endpoints import (
router as organization_router,
)
from litellm.proxy.management_endpoints.policy_endpoints import router as policy_router
from litellm.proxy.management_endpoints.project_endpoints import (
router as project_router,
)
from litellm.proxy.management_endpoints.policy_endpoints import router as policy_router
from litellm.proxy.management_endpoints.router_settings_endpoints import (
router as router_settings_router,
)
Expand Down Expand Up @@ -902,6 +902,15 @@ async def proxy_startup_event(app: FastAPI): # noqa: PLR0915
except Exception as e:
verbose_proxy_logger.error(f"Error stopping token refresh task: {e}")

# Shutdown event - stop Prisma DB health watchdog task
if prisma_client is not None and hasattr(
prisma_client, "stop_db_health_watchdog_task"
):
try:
await prisma_client.stop_db_health_watchdog_task()
except Exception as e:
verbose_proxy_logger.error(f"Error stopping DB health watchdog task: {e}")

await proxy_shutdown_event() # type: ignore[reportGeneralTypeIssues]


Expand Down Expand Up @@ -5829,6 +5838,9 @@ async def _setup_prisma_client(
is not True
):
await prisma_client.health_check()

if hasattr(prisma_client, "start_db_health_watchdog_task"):
await prisma_client.start_db_health_watchdog_task()
return prisma_client
except Exception as e:
PrismaDBExceptionHandler.handle_db_exception(e)
Expand Down
195 changes: 195 additions & 0 deletions litellm/proxy/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@
should_create_missing_views,
)
from litellm.proxy.db.db_spend_update_writer import DBSpendUpdateWriter
from litellm.proxy.db.exception_handler import PrismaDBExceptionHandler
from litellm.proxy.db.log_db_metrics import log_db_metrics
from litellm.proxy.db.prisma_client import PrismaWrapper
from litellm.proxy.guardrails.guardrail_hooks.unified_guardrail.unified_guardrail import (
Expand Down Expand Up @@ -2266,6 +2267,32 @@ def __init__(
else False
),
) # Client to connect to Prisma db
self._db_reconnect_lock = asyncio.Lock()
self._db_health_watchdog_task: Optional[asyncio.Task] = None
self._db_last_reconnect_attempt_ts: float = 0.0
self._db_reconnect_cooldown_seconds: int = max(
1, int(os.getenv("PRISMA_RECONNECT_COOLDOWN_SECONDS", "15"))
)
self._db_health_watchdog_interval_seconds: int = max(
5, int(os.getenv("PRISMA_HEALTH_WATCHDOG_INTERVAL_SECONDS", "30"))
)
self._db_health_watchdog_enabled: bool = (
str_to_bool(os.getenv("PRISMA_HEALTH_WATCHDOG_ENABLED", "true")) is True
)
self._db_health_watchdog_probe_timeout_seconds: float = max(
0.5,
float(os.getenv("PRISMA_HEALTH_WATCHDOG_PROBE_TIMEOUT_SECONDS", "5.0")),
)
self._db_watchdog_reconnect_timeout_seconds: float = max(
1.0, float(os.getenv("PRISMA_WATCHDOG_RECONNECT_TIMEOUT_SECONDS", "30.0"))
)
self._db_auth_reconnect_timeout_seconds: float = max(
0.5, float(os.getenv("PRISMA_AUTH_RECONNECT_TIMEOUT_SECONDS", "2.0"))
)
self._db_auth_reconnect_lock_timeout_seconds: float = max(
0.0,
float(os.getenv("PRISMA_AUTH_RECONNECT_LOCK_TIMEOUT_SECONDS", "0.1")),
)
verbose_proxy_logger.debug("Success - Created Prisma Client")

def get_request_status(
Expand Down Expand Up @@ -3533,6 +3560,174 @@ async def disconnect(self):
)
raise e

async def _run_reconnect_cycle(
self, timeout_seconds: Optional[float] = None
) -> None:
"""
Run a reconnect cycle with direct db operations and a single overall timeout
budget to avoid long retries on hot paths (e.g. auth).
"""
async def _do_direct_reconnect() -> None:
try:
await self.db.disconnect()
except Exception as disconnect_err:
verbose_proxy_logger.debug(
"Prisma DB disconnect before reconnect failed (ignored): %s",
disconnect_err,
)

await self.db.connect()
await self.db.query_raw("SELECT 1")

effective_timeout = (
timeout_seconds
if timeout_seconds is not None
else self._db_watchdog_reconnect_timeout_seconds
)
await asyncio.wait_for(_do_direct_reconnect(), timeout=effective_timeout)

async def attempt_db_reconnect(
self,
reason: str,
force: bool = False,
timeout_seconds: Optional[float] = None,
lock_timeout_seconds: Optional[float] = None,
) -> bool:
"""
Attempt to reconnect the Prisma client in a singleflight manner.

Returns:
bool: True if reconnection succeeded, else False.
"""
now = time.time()
if (
force is False
and now - self._db_last_reconnect_attempt_ts
< self._db_reconnect_cooldown_seconds
):
verbose_proxy_logger.debug(
"Skipping DB reconnect attempt due to cooldown. reason=%s",
reason,
)
return False

async def _attempt_reconnect_inside_lock() -> bool:
now = time.time()
if (
force is False
and now - self._db_last_reconnect_attempt_ts
< self._db_reconnect_cooldown_seconds
):
verbose_proxy_logger.debug(
"Skipping DB reconnect attempt inside lock due to cooldown. reason=%s",
reason,
)
return False

verbose_proxy_logger.warning(
"Attempting Prisma DB reconnect. reason=%s", reason
)

reconnect_succeeded = False
try:
await self._run_reconnect_cycle(timeout_seconds=timeout_seconds)
reconnect_succeeded = True
verbose_proxy_logger.info(
"Prisma DB reconnect succeeded. reason=%s", reason
)
except Exception as reconnect_err:
verbose_proxy_logger.error(
"Prisma DB reconnect failed. reason=%s error=%s",
reason,
reconnect_err,
)
finally:
# Start cooldown after reconnect attempt has completed.
self._db_last_reconnect_attempt_ts = time.time()

return reconnect_succeeded

if lock_timeout_seconds is None:
async with self._db_reconnect_lock:
return await _attempt_reconnect_inside_lock()

try:
await asyncio.wait_for(
self._db_reconnect_lock.acquire(),
timeout=lock_timeout_seconds,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wait_for(lock.acquire()) can leak the lock on timeout

On Python 3.9–3.11, asyncio.wait_for(lock.acquire(), timeout=...) has a known race condition: if the lock becomes available at the exact moment the timeout fires, the lock is acquired but TimeoutError is still raised. Since the lock is never released, all subsequent callers will deadlock on it permanently.

This was fixed in CPython 3.12 (bpo-98048), but since litellm supports Python ≥3.9, this path is vulnerable.

A safer pattern is to use asyncio.wait_for with a wrapper that releases on cancellation, or use a manual approach:

Suggested change
try:
await asyncio.wait_for(
self._db_reconnect_lock.acquire(),
timeout=lock_timeout_seconds,
)
result = asyncio.get_event_loop().create_future()
async def _acquire_with_timeout():
await self._db_reconnect_lock.acquire()
if not result.done():
result.set_result(True)
task = asyncio.ensure_future(_acquire_with_timeout())
try:
await asyncio.wait_for(asyncio.shield(task), timeout=lock_timeout_seconds)
except asyncio.TimeoutError:
task.cancel()
# If the lock was acquired between timeout and cancel, release it
if self._db_reconnect_lock.locked():
try:
self._db_reconnect_lock.release()
except RuntimeError:
pass

Alternatively, a simpler approach: use a asyncio.wait_for only on Python 3.12+ and fall back to a manual timer on older versions, or just use asyncio.timeout() (3.11+).

Context Used: Rule from dashboard - What: Avoid creating new database requests or Router objects in the critical request path.

Why: Cre... (source)

except asyncio.TimeoutError:
verbose_proxy_logger.debug(
"Skipping DB reconnect attempt due to lock acquisition timeout. reason=%s timeout=%ss",
reason,
lock_timeout_seconds,
)
return False

try:
return await _attempt_reconnect_inside_lock()
finally:
self._db_reconnect_lock.release()

async def start_db_health_watchdog_task(self) -> None:
"""
Start a background task that probes DB health and attempts reconnect on failure.
"""
if self._db_health_watchdog_enabled is not True:
verbose_proxy_logger.debug(
"Prisma DB health watchdog disabled via PRISMA_HEALTH_WATCHDOG_ENABLED"
)
return
if self._db_health_watchdog_task is not None:
return
self._db_health_watchdog_task = asyncio.create_task(
self._db_health_watchdog_loop()
)
verbose_proxy_logger.info(
"Started Prisma DB health watchdog (interval=%ss, reconnect_cooldown=%ss, probe_timeout=%ss, reconnect_timeout=%ss)",
self._db_health_watchdog_interval_seconds,
self._db_reconnect_cooldown_seconds,
self._db_health_watchdog_probe_timeout_seconds,
self._db_watchdog_reconnect_timeout_seconds,
)

async def stop_db_health_watchdog_task(self) -> None:
"""
Stop DB health watchdog task gracefully.
"""
if self._db_health_watchdog_task is None:
return
self._db_health_watchdog_task.cancel()
try:
await self._db_health_watchdog_task
except asyncio.CancelledError:
pass
self._db_health_watchdog_task = None
verbose_proxy_logger.info("Stopped Prisma DB health watchdog")

async def _db_health_watchdog_loop(self) -> None:
while True:
try:
await asyncio.sleep(self._db_health_watchdog_interval_seconds)
await asyncio.wait_for(
self.db.query_raw("SELECT 1"),
timeout=self._db_health_watchdog_probe_timeout_seconds,
)
except asyncio.CancelledError:
break
except Exception as e:
if isinstance(
e, asyncio.TimeoutError
) or PrismaDBExceptionHandler.is_database_connection_error(e):
await self.attempt_db_reconnect(
reason="db_health_watchdog_connection_error",
timeout_seconds=self._db_watchdog_reconnect_timeout_seconds,
)
else:
verbose_proxy_logger.debug(
"Prisma DB health watchdog observed non-DB error: %s", e
)
Comment on lines +3741 to +3762

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Watchdog health_check uses backoff retries before reaching reconnect

health_check() is decorated with @backoff.on_exception(max_tries=3, max_time=10), so each watchdog iteration will retry the health check with exponential backoff for up to 10 seconds before the exception propagates here. Combined with the unbounded attempt_db_reconnect call, a single watchdog cycle when the DB is down could take 10s (health_check retries) + unbounded time (reconnect with no timeout) before the loop can sleep and try again.

Consider calling self.db.query_raw("SELECT 1") directly instead of self.health_check() to avoid the backoff retries in the watchdog loop, since the watchdog already has its own retry-via-sleep cadence.


@backoff.on_exception(
backoff.expo,
Exception,
Expand Down
Loading
Loading