From 093fccde2ec0846886de22cfeefe7e8bfda2847b Mon Sep 17 00:00:00 2001 From: Alexsander Hamir Date: Thu, 29 Jan 2026 16:08:51 -0800 Subject: [PATCH] Use direct LiteLLM_SpendLogs query for global spend to reduce DB CPU and impact on other APIs --- litellm/proxy/auth/user_api_key_auth.py | 3 ++- litellm/proxy/spend_tracking/spend_management_endpoints.py | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/litellm/proxy/auth/user_api_key_auth.py b/litellm/proxy/auth/user_api_key_auth.py index 40ad2488ed2..e14ea637b85 100644 --- a/litellm/proxy/auth/user_api_key_auth.py +++ b/litellm/proxy/auth/user_api_key_auth.py @@ -227,7 +227,8 @@ async def _fetch_global_spend_with_event_coordination( """ async def _load_global_spend() -> Optional[float]: - sql_query = """SELECT SUM(spend) AS total_spend FROM "MonthlyGlobalSpend";""" + # Single aggregation on base table (same result, less CPU than SUM over MonthlyGlobalSpend view) + sql_query = """SELECT SUM("spend") AS total_spend FROM "LiteLLM_SpendLogs" WHERE "startTime" >= (CURRENT_DATE - INTERVAL '30 days')""" response = await prisma_client.db.query_raw(query=sql_query) val = response[0]["total_spend"] return float(val) if val is not None else None diff --git a/litellm/proxy/spend_tracking/spend_management_endpoints.py b/litellm/proxy/spend_tracking/spend_management_endpoints.py index dcdc17ef318..8d42a80af3f 100644 --- a/litellm/proxy/spend_tracking/spend_management_endpoints.py +++ b/litellm/proxy/spend_tracking/spend_management_endpoints.py @@ -2423,7 +2423,8 @@ async def global_spend(): if prisma_client is None: raise HTTPException(status_code=500, detail={"error": "No db connected"}) - sql_query = """SELECT SUM(spend) as total_spend FROM "MonthlyGlobalSpend";""" + # Single aggregation on base table (same result, less CPU than SUM over MonthlyGlobalSpend view) + sql_query = """SELECT SUM("spend") AS total_spend FROM "LiteLLM_SpendLogs" WHERE "startTime" >= (CURRENT_DATE - INTERVAL '30 days')""" response = await prisma_client.db.query_raw(query=sql_query) if response is not None: if isinstance(response, list) and len(response) > 0: