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(datadog): split log batches proactively under intake payload limits (#32860)
yucheng-berri60d557c930ea
diff --git a/litellm/integrations/datadog/datadog.py b/litellm/integrations/datadog/datadog.pyindex bd62d1e303a..20239d831cc 100644--- a/litellm/integrations/datadog/datadog.py+++ b/litellm/integrations/datadog/datadog.py@@ -19,7 +19,7 @@ import osimport timeimport tracebackfrom datetime import datetime as datetimeObj-from typing import Any, Dict, List, Optional, Union+from typing import Any, Dict, List, Optional, Sequence, Unionimport httpxfrom httpx import Response@@ -50,6 +50,7 @@ from litellm.types.integrations.base_health_check import IntegrationHealthCheckSfrom litellm.types.integrations.datadog import (DD_ERRORS,DD_MAX_BATCH_SIZE,+ DD_MAX_PAYLOAD_SIZE_BYTES,DataDogStatus,DatadogInitParams,DatadogPayload,@@ -384,8 +385,10 @@ class DataDogLogger(async def _send_with_413_split(self, batch: List) -> List:"""- Send a batch, halving any sub-batch that 413s (payload too large) and retrying the- halves, since Datadog enforces a 5MB uncompressed limit per request.+ Send a batch, halving any sub-batch that exceeds Datadog's intake limits before+ sending, and halving again on a 413 (payload too large) response, since Datadog+ enforces a 5MB uncompressed limit per request. The proactive split avoids paying+ a serialize + gzip + round trip for a payload the intake is guaranteed to reject.A 413 surfaces as a raised MaskedHTTPStatusError (httpx raise_for_status), not areturned response, so both paths are handled. A lone event that still 413s is@@ -398,6 +401,11 @@ class DataDogLogger(chunk = pending.pop()if not chunk:continue+ if len(chunk) > 1 and self._exceeds_intake_limits(chunk):+ mid = len(chunk) // 2+ pending.append(chunk[mid:])+ pending.append(chunk[:mid])+ continuetry:response = await self.async_send_compressed_data(chunk)except Exception as e:@@ -436,6 +444,21 @@ class DataDogLogger(def _undelivered(chunk: List, pending: List[List]) -> List:return chunk + [event for remaining in reversed(pending) for event in remaining]+ @staticmethod+ def _exceeds_intake_limits(chunk: Sequence[DatadogPayload]) -> bool:+ """+ True when a chunk would breach Datadog's log intake limits: more than+ DD_MAX_BATCH_SIZE events per payload, or a serialized size above+ DD_MAX_PAYLOAD_SIZE_BYTES (held under Datadog's 5MB uncompressed cap so+ the batch is split before the intake rejects it with a 413).+ """+ from litellm.litellm_core_utils.safe_json_dumps import safe_dumps++ if len(chunk) > DD_MAX_BATCH_SIZE:+ return True+ payload_size_bytes = len(safe_dumps(chunk).encode("utf-8"))+ return payload_size_bytes > DD_MAX_PAYLOAD_SIZE_BYTES+async def flush_queue(self):if self.flush_lock is None:returndiff --git a/litellm/types/integrations/datadog.py b/litellm/types/integrations/datadog.pyindex 89faac27830..e0f43519b3d 100644--- a/litellm/types/integrations/datadog.py+++ b/litellm/types/integrations/datadog.py@@ -6,6 +6,7 @@ from typing_extensions import NotRequired, TypedDictfrom litellm.types.integrations.custom_logger import StandardCustomLoggerInitParamsDD_MAX_BATCH_SIZE = 1000+DD_MAX_PAYLOAD_SIZE_BYTES = 4_000_000class DataDogStatus(str, Enum):diff --git a/tests/test_litellm/integrations/datadog/test_datadog_logger_batching.py b/tests/test_litellm/integrations/datadog/test_datadog_logger_batching.pyindex d1c7a4032fb..f645379a4f4 100644--- a/tests/test_litellm/integrations/datadog/test_datadog_logger_batching.py+++ b/tests/test_litellm/integrations/datadog/test_datadog_logger_batching.py@@ -1,3 +1,4 @@+import asynciofrom unittest.mock import AsyncMock, Mock, patchimport httpx@@ -6,16 +7,20 @@ from httpx import Request, Responsefrom litellm.integrations.datadog.datadog import DataDogLoggerfrom litellm.llms.custom_httpx.http_handler import MaskedHTTPStatusError-from litellm.types.integrations.datadog import DD_MAX_BATCH_SIZE, DatadogPayload+from litellm.types.integrations.datadog import (+ DD_MAX_BATCH_SIZE,+ DD_MAX_PAYLOAD_SIZE_BYTES,+ DatadogPayload,+)-def _payloads(n):+def _payloads(n, message=None):return [DatadogPayload(ddsource="litellm",ddtags="env:test",hostname="host",- message=f'{{"event": {i}}}',+ message=f"{message}{i}" if message else f'{{"event": {i}}}',service="svc",status="info",)@@ -177,6 +182,87 @@ async def test_413_returned_response_also_splits(datadog_env):assert logger.log_queue == []+def _make_recording_send(sent_batches, delivered):+ async def _send(data):+ sent_batches.append(list(data))+ delivered.extend(data)+ return Response(+ 202, request=Request("POST", "https://example.com"), text="Accepted"+ )++ return _send+++async def test_oversized_payload_splits_before_any_send(datadog_env):+ """Regression for LIT-4325: a batch above Datadog's uncompressed payload limit is+ split proactively, so the intake never has to reject it with a 413."""+ from litellm.litellm_core_utils.safe_json_dumps import safe_dumps++ with patch("asyncio.create_task"):+ logger = DataDogLogger()++ events = _payloads(3, message="x" * 3_000_000)+ logger.log_queue = list(events)+ sent_batches: list = []+ delivered: list = []+ logger.async_send_compressed_data = AsyncMock(+ side_effect=_make_recording_send(sent_batches, delivered)+ )++ await logger.async_send_batch()++ assert delivered == events+ assert len(sent_batches) == 3+ assert all(+ len(safe_dumps(batch).encode("utf-8")) <= DD_MAX_PAYLOAD_SIZE_BYTES+ for batch in sent_batches+ )+ assert logger.log_queue == []+++async def test_batch_over_max_event_count_splits_before_any_send(datadog_env):+ """Datadog caps a payload at 1000 events; a queue that grew past that (e.g. after+ re-queues) must be sent in count-compliant chunks."""+ with patch("asyncio.create_task"):+ logger = DataDogLogger()++ events = _payloads(DD_MAX_BATCH_SIZE + 1)+ logger.log_queue = list(events)+ sent_batches: list = []+ delivered: list = []+ logger.async_send_compressed_data = AsyncMock(+ side_effect=_make_recording_send(sent_batches, delivered)+ )++ await logger.async_send_batch()++ assert delivered == events+ assert all(len(batch) <= DD_MAX_BATCH_SIZE for batch in sent_batches)+ assert logger.log_queue == []+++async def test_single_event_above_payload_cap_is_still_sent(datadog_env):+ """A lone event over the byte cap cannot be split further; it must be sent once+ (Datadog decides), never looped on."""+ with patch("asyncio.create_task"):+ logger = DataDogLogger()++ logger.log_queue = _payloads(1, message="x" * (DD_MAX_PAYLOAD_SIZE_BYTES + 1))+ sent_batches: list = []+ delivered: list = []+ send = AsyncMock(side_effect=_make_recording_send(sent_batches, delivered))+ logger.async_send_compressed_data = send++ await asyncio.wait_for(logger.async_send_batch(), timeout=10)++ assert send.await_count == 1+ assert len(delivered) == 1+ assert logger.log_queue == []++@pytest.mark.asyncioasync def test_partial_delivery_then_transient_error_requeues_only_undelivered(datadog_env,