Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

perf(spend): move cost-callback payload deepcopy off the request event loop (#31579)

Yassin Kortam6ab3742fa673
diff --git a/litellm/proxy/db/db_spend_update_writer.py b/litellm/proxy/db/db_spend_update_writer.py
index cf4c3e98f00..ca6875ca800 100644
--- a/litellm/proxy/db/db_spend_update_writer.py
+++ b/litellm/proxy/db/db_spend_update_writer.py
@@ -175,16 +175,9 @@ class DBSpendUpdateWriter:
if team_id is not None and team_id != "":
payload["team_id"] = team_id
- # One deepcopy shared by all 6 daily spend helpers (was 5, fixes agent bug)
- payload_copy = copy.deepcopy(payload)
-
- # Deepcopy request_tags for _update_tag_db
- request_tags = copy.deepcopy(payload.get("request_tags"))
-
- # Keep _insert_spend_log_to_db awaited inline (not a task, preserve current behavior)
if disable_spend_logs is False:
await self._insert_spend_log_to_db(
- payload=copy.deepcopy(payload),
+ payload=payload,
prisma_client=prisma_client,
)
else:
@@ -204,8 +197,7 @@ class DBSpendUpdateWriter:
prisma_client=prisma_client,
user_api_key_cache=user_api_key_cache,
litellm_proxy_budget_name=litellm_proxy_budget_name,
- payload_copy=payload_copy,
- request_tags=request_tags,
+ payload=payload,
)
)
@@ -336,14 +328,18 @@ class DBSpendUpdateWriter:
prisma_client: Optional[PrismaClient],
user_api_key_cache: DualCache,
litellm_proxy_budget_name: Optional[str],
- payload_copy: SpendLogsPayload,
- request_tags: Optional[Any],
+ payload: SpendLogsPayload,
):
"""
Runs all 11 spend-update helpers sequentially inside a single asyncio task.
Each helper is wrapped in try/except so one failure doesn't prevent the others.
+
+ The deepcopy runs here, off the awaited request path, so the daily spend
+ helpers get a payload isolated from the spend-log queue entry and the caller.
"""
+ payload_copy = copy.deepcopy(payload)
+ request_tags = payload_copy.get("request_tags")
try:
await self._update_user_db(
response_cost=response_cost,
diff --git a/tests/test_litellm/proxy/db/test_db_spend_update_writer.py b/tests/test_litellm/proxy/db/test_db_spend_update_writer.py
index 04c93f48ca9..c29cdaf4171 100644
--- a/tests/test_litellm/proxy/db/test_db_spend_update_writer.py
+++ b/tests/test_litellm/proxy/db/test_db_spend_update_writer.py
@@ -1,4 +1,5 @@
import asyncio
+import copy
import json
import os
import sys
@@ -1419,8 +1420,7 @@ async def test_batch_database_updates_isolation_on_failure():
prisma_client=MagicMock(),
user_api_key_cache=MagicMock(),
litellm_proxy_budget_name="budget",
- payload_copy={"key": "value"},
- request_tags=None,
+ payload={"key": "value"},
)
# _update_key_db raised, but all others should still have been called
@@ -1704,3 +1704,117 @@ async def test_commit_spend_updates_iterates_in_sorted_order(
)
assert captured_where_values == expected_order
+
+
+async def test_update_database_does_not_deepcopy_on_request_path():
+ """
+ Regression for LIT-4088: copy.deepcopy must not run while the caller awaits
+ update_database(). The deepcopy used to isolate the daily-spend helpers is
+ relocated into the _batch_database_updates background task, and the spend-log
+ insert receives the payload directly (all consumers are read-only).
+
+ Asserts:
+ - zero copy.deepcopy calls happen on the awaited request path
+ - the batch background task still hands the daily helpers an isolated copy
+ (mutating the original after the task ran does not bleed into it)
+ - the spend-log insert receives the payload on the request path with the
+ correct content
+ """
+ db_writer = DBSpendUpdateWriter()
+
+ captured_batch_payloads = []
+ captured_spend_log = {}
+
+ async def capture_batch_payload(**kwargs):
+ captured_batch_payloads.append(kwargs.get("payload"))
+
+ async def capture_spend_log(**kwargs):
+ payload = kwargs.get("payload")
+ captured_spend_log["ref"] = payload
+ captured_spend_log["model_at_call"] = payload["model"]
+
+ db_writer._insert_spend_log_to_db = AsyncMock(side_effect=capture_spend_log)
+ db_writer._update_user_db = AsyncMock()
+ db_writer._update_key_db = AsyncMock()
+ db_writer._update_team_db = AsyncMock()
+ db_writer._update_org_db = AsyncMock()
+ db_writer._update_tag_db = AsyncMock()
+ db_writer._update_agent_db = AsyncMock()
+ db_writer.add_spend_log_transaction_to_daily_user_transaction = AsyncMock(
+ side_effect=capture_batch_payload
+ )
+ db_writer.add_spend_log_transaction_to_daily_end_user_transaction = AsyncMock()
+ db_writer.add_spend_log_transaction_to_daily_agent_transaction = AsyncMock()
+ db_writer.add_spend_log_transaction_to_daily_team_transaction = AsyncMock()
+ db_writer.add_spend_log_transaction_to_daily_org_transaction = AsyncMock()
+ db_writer.add_spend_log_transaction_to_daily_tag_transaction = AsyncMock()
+
+ fake_payload = {
+ "startTime": "2024-01-01T00:00:00",
+ "endTime": "2024-01-01T00:01:00",
+ "model": "gpt-4",
+ "custom_llm_provider": "openai",
+ "request_tags": '["prod-tag"]',
+ "spend": 0.0,
+ "nested": {"a": 1},
+ }
+
+ deepcopy_calls = []
+ real_deepcopy = copy.deepcopy
+
+ def counting_deepcopy(obj, *args, **kwargs):
+ deepcopy_calls.append(obj)
+ return real_deepcopy(obj, *args, **kwargs)
+
+ with (
+ patch("litellm.proxy.proxy_server.disable_spend_logs", False),
+ patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),
+ patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
+ patch("litellm.proxy.proxy_server.litellm_proxy_budget_name", "test-budget"),
+ patch(
+ "litellm.proxy.spend_tracking.spend_tracking_utils.get_logging_payload",
+ return_value=fake_payload,
+ ),
+ patch(
+ "litellm.proxy.db.db_spend_update_writer.copy.deepcopy",
+ counting_deepcopy,
+ ),
+ ):
+ await db_writer.update_database(
+ token="test-token",
+ user_id="test-user",
+ end_user_id="test-end-user",
+ team_id="test-team",
+ org_id="test-org",
+ kwargs={"model": "gpt-4", "custom_llm_provider": "openai"},
+ completion_response=MagicMock(),
+ start_time=datetime.now(),
+ end_time=datetime.now(),
+ response_cost=0.1,
+ )
+
+ # Request path is clean: nothing was deepcopied while the caller awaited.
+ assert len(deepcopy_calls) == 0
+
+ # The spend-log insert ran inline on the request path with the real payload.
+ assert captured_spend_log["ref"] is fake_payload
+ assert captured_spend_log["model_at_call"] == "gpt-4"
+ assert fake_payload["spend"] == 0.1
+
+ # Now let the batch background task run; the deepcopy happens here.
+ await asyncio.sleep(0)
+
+ assert len(deepcopy_calls) >= 1
+ assert len(captured_batch_payloads) == 1
+ batch_payload = captured_batch_payloads[0]
+ assert batch_payload is not fake_payload
+ assert batch_payload["model"] == "gpt-4"
+ assert batch_payload["spend"] == 0.1
+
+ # Mutating the original after the batch task captured its snapshot must not
+ # leak into the daily helper's isolated copy.
+ fake_payload["model"] = "MUTATED"
+ fake_payload["nested"]["a"] = 999
+ assert batch_payload["model"] == "gpt-4"
+ assert batch_payload["nested"]["a"] == 1