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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(proxy): requeue Redis spend buffer transactions when DB commit fails
Devin AIbde00952b6aa
diff --git a/litellm/proxy/db/db_spend_update_writer.py b/litellm/proxy/db/db_spend_update_writer.pyindex 54a4c2dad91..cc266019ff7 100644--- a/litellm/proxy/db/db_spend_update_writer.py+++ b/litellm/proxy/db/db_spend_update_writer.py@@ -797,6 +797,12 @@ class DBSpendUpdateWriter:):verbose_proxy_logger.debug("acquired lock for spend updates")+ # Track everything popped from Redis. Each category is removed once it+ # has been committed to the DB, so whatever is left after a failure can+ # be re-queued for the next tick instead of being lost. Committed+ # categories are never re-queued, so their spend is not double-counted.+ uncommitted: dict[str, Any] = {} # mutable-ok: drives which popped categories still need re-queuing+try:(db_spend_update_transactions,@@ -807,6 +813,15 @@ class DBSpendUpdateWriter:daily_agent_spend_update_transactions,) = await self.redis_update_buffer.get_all_transactions_from_redis_buffer_pipeline()+ uncommitted = { # mutable-ok: drives which popped categories still need re-queuing+ "db_spend_update_transactions": db_spend_update_transactions,+ "daily_spend_update_transactions": daily_spend_update_transactions,+ "daily_team_spend_update_transactions": daily_team_spend_update_transactions,+ "daily_org_spend_update_transactions": daily_org_spend_update_transactions,+ "daily_end_user_spend_update_transactions": daily_end_user_spend_update_transactions,+ "daily_agent_spend_update_transactions": daily_agent_spend_update_transactions,+ }+if db_spend_update_transactions is not None:verbose_proxy_logger.info("Spend tracking - committing spend updates from Redis to DB: "@@ -826,6 +841,7 @@ class DBSpendUpdateWriter:proxy_logging_obj=proxy_logging_obj,db_spend_update_transactions=db_spend_update_transactions,)+ uncommitted.pop("db_spend_update_transactions", None)if daily_spend_update_transactions is not None:await DBSpendUpdateWriter.update_daily_user_spend(@@ -834,6 +850,8 @@ class DBSpendUpdateWriter:proxy_logging_obj=proxy_logging_obj,daily_spend_transactions=daily_spend_update_transactions,)+ uncommitted.pop("daily_spend_update_transactions", None)+if daily_team_spend_update_transactions is not None:await DBSpendUpdateWriter.update_daily_team_spend(n_retry_times=n_retry_times,@@ -841,6 +859,7 @@ class DBSpendUpdateWriter:proxy_logging_obj=proxy_logging_obj,daily_spend_transactions=daily_team_spend_update_transactions,)+ uncommitted.pop("daily_team_spend_update_transactions", None)if daily_org_spend_update_transactions is not None:await DBSpendUpdateWriter.update_daily_org_spend(@@ -849,6 +868,7 @@ class DBSpendUpdateWriter:proxy_logging_obj=proxy_logging_obj,daily_spend_transactions=daily_org_spend_update_transactions,)+ uncommitted.pop("daily_org_spend_update_transactions", None)if daily_end_user_spend_update_transactions is not None:await DBSpendUpdateWriter.update_daily_end_user_spend(@@ -857,6 +877,8 @@ class DBSpendUpdateWriter:proxy_logging_obj=proxy_logging_obj,daily_spend_transactions=daily_end_user_spend_update_transactions,)+ uncommitted.pop("daily_end_user_spend_update_transactions", None)+if daily_agent_spend_update_transactions is not None:await DBSpendUpdateWriter.update_daily_agent_spend(n_retry_times=n_retry_times,@@ -864,14 +886,20 @@ class DBSpendUpdateWriter:proxy_logging_obj=proxy_logging_obj,daily_spend_transactions=daily_agent_spend_update_transactions,)+ uncommitted.pop("daily_agent_spend_update_transactions", None)except Exception as e:spend_log_error("Spend tracking - failed to commit spend updates from Redis to DB. "- "Data already popped from Redis may be lost. Error: %s",+ "Re-queuing uncommitted transactions to Redis for retry on next tick. Error: %s",str(e),exc=e,)finally:+ to_restore = { # mutable-ok: transient kwargs payload consumed immediately below+ name: txns for name, txns in uncommitted.items() if txns is not None+ }+ if to_restore:+ await self.redis_update_buffer.restore_transactions_to_redis(**to_restore)await self.pod_lock_manager.release_lock(cronjob_id=DB_SPEND_UPDATE_JOB_NAME,)@@ -1020,11 +1048,11 @@ class DBSpendUpdateWriter:cronjob_id=DB_DAILY_TAG_SPEND_UPDATE_JOB_NAME,):verbose_proxy_logger.debug("acquired lock for daily tag spend updates")+ daily_tag_spend_update_transactions = (+ await self.redis_update_buffer.get_all_daily_tag_spend_update_transactions_from_redis_buffer()+ )+ committed = Falsetry:- daily_tag_spend_update_transactions = (- await self.redis_update_buffer.get_all_daily_tag_spend_update_transactions_from_redis_buffer()- )-if daily_tag_spend_update_transactions:await DBSpendUpdateWriter.update_daily_tag_spend(n_retry_times=n_retry_times,@@ -1032,14 +1060,19 @@ class DBSpendUpdateWriter:proxy_logging_obj=proxy_logging_obj,daily_spend_transactions=daily_tag_spend_update_transactions,)+ committed = Trueexcept Exception as e:spend_log_error("Spend tracking - failed to commit daily tag spend updates from Redis to DB. "- "Data already popped from Redis may be lost. Error: %s",+ "Re-queuing to Redis for retry on next tick. Error: %s",str(e),exc=e,)finally:+ if not committed and daily_tag_spend_update_transactions:+ await self.redis_update_buffer.restore_transactions_to_redis(+ daily_tag_spend_update_transactions=daily_tag_spend_update_transactions,+ )await self.pod_lock_manager.release_lock(cronjob_id=DB_DAILY_TAG_SPEND_UPDATE_JOB_NAME,)diff --git a/litellm/proxy/db/db_transaction_queue/redis_update_buffer.py b/litellm/proxy/db/db_transaction_queue/redis_update_buffer.pyindex c924448669d..b30fadd86ab 100644--- a/litellm/proxy/db/db_transaction_queue/redis_update_buffer.py+++ b/litellm/proxy/db/db_transaction_queue/redis_update_buffer.py@@ -8,6 +8,8 @@ import asyncioimport jsonfrom typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, cast+from redis.exceptions import RedisError+from litellm._logging import verbose_proxy_loggerfrom litellm.caching import RedisCachefrom litellm.constants import (@@ -374,6 +376,59 @@ class RedisUpdateBuffer:if daily_txns:await daily_queue.update_queue.put(daily_txns)+ async def restore_transactions_to_redis(+ self,+ db_spend_update_transactions: DBSpendUpdateTransactions | None = None,+ daily_spend_update_transactions: dict[str, BaseDailySpendTransaction] | None = None,+ daily_team_spend_update_transactions: dict[str, BaseDailySpendTransaction] | None = None,+ daily_org_spend_update_transactions: dict[str, BaseDailySpendTransaction] | None = None,+ daily_end_user_spend_update_transactions: dict[str, BaseDailySpendTransaction] | None = None,+ daily_agent_spend_update_transactions: dict[str, BaseDailySpendTransaction] | None = None,+ daily_tag_spend_update_transactions: dict[str, BaseDailySpendTransaction] | None = None,+ ) -> None:+ """+ Re-push transactions that were popped from Redis but not committed to the DB.++ The leader drains the buffers with a destructive ``lpop`` before committing to+ the database. When a commit fails after its retries are exhausted, the popped+ transactions must be pushed back so a later scheduler tick can retry them;+ otherwise the aggregated spend is lost permanently. The re-pushed payloads use+ the same JSON encoding as the store path, so the next drain parses them normally.+ """+ if self.redis_cache is None:+ return++ _configs = (+ (db_spend_update_transactions, REDIS_UPDATE_BUFFER_KEY),+ (daily_spend_update_transactions, REDIS_DAILY_SPEND_UPDATE_BUFFER_KEY),+ (daily_team_spend_update_transactions, REDIS_DAILY_TEAM_SPEND_UPDATE_BUFFER_KEY),+ (daily_org_spend_update_transactions, REDIS_DAILY_ORG_SPEND_UPDATE_BUFFER_KEY),+ (daily_end_user_spend_update_transactions, REDIS_DAILY_END_USER_SPEND_UPDATE_BUFFER_KEY),+ (daily_agent_spend_update_transactions, REDIS_DAILY_AGENT_SPEND_UPDATE_BUFFER_KEY),+ (daily_tag_spend_update_transactions, REDIS_DAILY_TAG_SPEND_UPDATE_BUFFER_KEY),+ )++ rpush_list: list[RedisPipelineRpushOperation] = [ # mutable-ok: async_rpush_pipeline requires a list arg+ RedisPipelineRpushOperation(key=redis_key, values=[safe_dumps(transactions)])+ for transactions, redis_key in _configs+ if transactions+ ]+ if len(rpush_list) == 0:+ return++ try:+ await self.redis_cache.async_rpush_pipeline(rpush_list=rpush_list)+ verbose_proxy_logger.info(+ "Spend tracking - restored %d uncommitted transaction set(s) to Redis for retry on next tick.",+ len(rpush_list),+ )+ except RedisError as e:+ verbose_proxy_logger.error(+ "Spend tracking - failed to restore uncommitted transactions to Redis. "+ "These spend updates are lost. Error: %s",+ str(e),+ )+@staticmethoddef _number_of_transactions_to_store_in_redis(db_spend_update_transactions: DBSpendUpdateTransactions,diff --git a/tests/test_litellm/proxy/db/db_transaction_queue/test_redis_update_buffer.py b/tests/test_litellm/proxy/db/db_transaction_queue/test_redis_update_buffer.pyindex 33372e7794a..79909561683 100644--- a/tests/test_litellm/proxy/db/db_transaction_queue/test_redis_update_buffer.py+++ b/tests/test_litellm/proxy/db/db_transaction_queue/test_redis_update_buffer.py@@ -270,6 +270,52 @@ async def test_get_all_transactions_from_redis_buffer_pipeline_no_redis():assert result == (None, None, None, None, None, None)+async def test_restore_transactions_to_redis_pushes_only_provided(+ redis_update_buffer, mock_redis_cache+):+ """+ restore_transactions_to_redis re-pushes only the transaction sets it was+ given, to their matching buffer keys, so uncommitted spend can be retried.+ """+ from litellm.constants import (+ REDIS_DAILY_SPEND_UPDATE_BUFFER_KEY,+ REDIS_UPDATE_BUFFER_KEY,+ )++ mock_redis_cache.async_rpush_pipeline = AsyncMock(return_value=[1, 1])++ db_spend = {"key_list_transactions": {"key1": 1.0}}+ daily_user = {"user_key1": {"spend": 1.0}}++ await redis_update_buffer.restore_transactions_to_redis(+ db_spend_update_transactions=db_spend,+ daily_spend_update_transactions=daily_user,+ )++ mock_redis_cache.async_rpush_pipeline.assert_called_once()+ rpush_list = mock_redis_cache.async_rpush_pipeline.call_args.kwargs["rpush_list"]+ pushed_keys = {op["key"] for op in rpush_list}+ assert pushed_keys == {+ REDIS_UPDATE_BUFFER_KEY,+ REDIS_DAILY_SPEND_UPDATE_BUFFER_KEY,+ }+ # Payloads round-trip through the same JSON encoding used on the store path+ payloads = {op["key"]: json.loads(op["values"][0]) for op in rpush_list}+ assert payloads[REDIS_UPDATE_BUFFER_KEY] == db_spend+ assert payloads[REDIS_DAILY_SPEND_UPDATE_BUFFER_KEY] == daily_user+++async def test_restore_transactions_to_redis_noop_when_empty(+ redis_update_buffer, mock_redis_cache+):+ """Nothing to restore -> no Redis call."""+ mock_redis_cache.async_rpush_pipeline = AsyncMock()+ await redis_update_buffer.restore_transactions_to_redis()+ mock_redis_cache.async_rpush_pipeline.assert_not_called()++def test_validate_redis_transaction_buffer_raises_without_redis():"""When use_redis_transaction_buffer=true but no Redis cache is configured,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.pyindex 4c17c5d3482..10544e82453 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@@ -1532,9 +1532,9 @@ async def test_commit_spend_updates_uses_pipeline():mock_redis_update_buffer = AsyncMock()mock_redis_update_buffer.store_in_memory_spend_updates_in_redis = AsyncMock()- # Return all-None tuple (no data to commit)+ # Return all-None tuple (no data to commit); the pipeline yields 6 slotsmock_redis_update_buffer.get_all_transactions_from_redis_buffer_pipeline = (- AsyncMock(return_value=(None, None, None, None, None, None, None))+ AsyncMock(return_value=(None, None, None, None, None, None)))db_writer.redis_update_buffer = mock_redis_update_buffer@@ -1565,6 +1565,153 @@ async def test_commit_spend_updates_uses_pipeline():mock_redis_update_buffer.get_all_daily_tag_spend_update_transactions_from_redis_buffer.assert_not_called()+async def test_commit_with_redis_requeues_all_on_db_failure():+ """+ Regression for #33872: if the DB commit fails after the leader has already+ popped transactions from Redis, the popped transactions must be re-queued to+ Redis so a later tick can retry them, instead of being silently lost.+ """+ db_writer = DBSpendUpdateWriter()++ db_spend = {+ "user_list_transactions": {"user1": 1.5},+ "end_user_list_transactions": {},+ "key_list_transactions": {"key1": 1.5},+ "team_list_transactions": {},+ "team_member_list_transactions": {},+ "org_list_transactions": {},+ "tag_list_transactions": {},+ "agent_list_transactions": {},+ }+ daily_user = {"user_key1": {"spend": 1.5, "api_requests": 1}}++ mock_redis_update_buffer = AsyncMock()+ mock_redis_update_buffer.get_all_transactions_from_redis_buffer_pipeline = AsyncMock(+ return_value=(db_spend, daily_user, None, None, None, None)+ )+ mock_redis_update_buffer.restore_transactions_to_redis = AsyncMock()+ db_writer.redis_update_buffer = mock_redis_update_buffer++ mock_pod_lock_manager = AsyncMock()+ mock_pod_lock_manager.acquire_lock = AsyncMock(return_value=True)+ mock_pod_lock_manager.release_lock = AsyncMock()+ db_writer.pod_lock_manager = mock_pod_lock_manager++ # Every DB write raises -> simulates a full database outage+ db_writer._commit_spend_updates_to_db = AsyncMock(side_effect=Exception("db down"))++ with patch.object(+ DBSpendUpdateWriter,+ "update_daily_user_spend",+ new=AsyncMock(side_effect=Exception("db down")),+ ):+ await db_writer._commit_spend_updates_to_db_with_redis(+ prisma_client=MagicMock(),+ n_retry_times=0,+ proxy_logging_obj=MagicMock(),+ )++ # Both failed categories must be re-queued to Redis, nothing lost+ mock_redis_update_buffer.restore_transactions_to_redis.assert_awaited_once()+ _, kwargs = mock_redis_update_buffer.restore_transactions_to_redis.call_args+ assert kwargs["db_spend_update_transactions"] == db_spend+ assert kwargs["daily_spend_update_transactions"] == daily_user+ # The lock must still be released+ mock_pod_lock_manager.release_lock.assert_awaited_once()+++async def test_commit_with_redis_only_requeues_failed_category():+ """+ A partial DB failure must not re-queue categories that already committed,+ otherwise their spend would be double-counted on the next tick.+ """+ db_writer = DBSpendUpdateWriter()++ db_spend = {+ "user_list_transactions": {"user1": 1.5},+ "end_user_list_transactions": {},+ "key_list_transactions": {},+ "team_list_transactions": {},+ "team_member_list_transactions": {},+ "org_list_transactions": {},+ "tag_list_transactions": {},+ "agent_list_transactions": {},+ }+ daily_user = {"user_key1": {"spend": 1.5, "api_requests": 1}}++ mock_redis_update_buffer = AsyncMock()+ mock_redis_update_buffer.get_all_transactions_from_redis_buffer_pipeline = AsyncMock(+ return_value=(db_spend, daily_user, None, None, None, None)+ )+ mock_redis_update_buffer.restore_transactions_to_redis = AsyncMock()+ db_writer.redis_update_buffer = mock_redis_update_buffer++ mock_pod_lock_manager = AsyncMock()+ mock_pod_lock_manager.acquire_lock = AsyncMock(return_value=True)+ mock_pod_lock_manager.release_lock = AsyncMock()+ db_writer.pod_lock_manager = mock_pod_lock_manager++ # db_spend commits fine; only the daily user commit fails+ db_writer._commit_spend_updates_to_db = AsyncMock()++ with patch.object(+ DBSpendUpdateWriter,+ "update_daily_user_spend",+ new=AsyncMock(side_effect=Exception("db down")),+ ):+ await db_writer._commit_spend_updates_to_db_with_redis(+ prisma_client=MagicMock(),+ n_retry_times=0,+ proxy_logging_obj=MagicMock(),+ )++ mock_redis_update_buffer.restore_transactions_to_redis.assert_awaited_once()+ _, kwargs = mock_redis_update_buffer.restore_transactions_to_redis.call_args+ # Only the failed daily category is requeued; the committed db_spend is not+ assert kwargs == {"daily_spend_update_transactions": daily_user}+++async def test_commit_with_redis_no_requeue_on_success():+ """When all commits succeed, nothing should be re-queued to Redis."""+ db_writer = DBSpendUpdateWriter()++ db_spend = {+ "user_list_transactions": {"user1": 1.5},+ "end_user_list_transactions": {},+ "key_list_transactions": {},+ "team_list_transactions": {},+ "team_member_list_transactions": {},+ "org_list_transactions": {},+ "tag_list_transactions": {},+ "agent_list_transactions": {},+ }++ mock_redis_update_buffer = AsyncMock()+ mock_redis_update_buffer.get_all_transactions_from_redis_buffer_pipeline = AsyncMock(+ return_value=(db_spend, None, None, None, None, None)+ )+ mock_redis_update_buffer.restore_transactions_to_redis = AsyncMock()+ db_writer.redis_update_buffer = mock_redis_update_buffer++ mock_pod_lock_manager = AsyncMock()+ mock_pod_lock_manager.acquire_lock = AsyncMock(return_value=True)+ mock_pod_lock_manager.release_lock = AsyncMock()+ db_writer.pod_lock_manager = mock_pod_lock_manager++ db_writer._commit_spend_updates_to_db = AsyncMock()++ await db_writer._commit_spend_updates_to_db_with_redis(+ prisma_client=MagicMock(),+ n_retry_times=0,+ proxy_logging_obj=MagicMock(),+ )++ mock_redis_update_buffer.restore_transactions_to_redis.assert_not_awaited()++@pytest.mark.parametrize("bucket_name,input_dict,table_attr,method_name,where_key,expected_order",[