Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(usage-report): trim oversize org payloads before capture (#60462)

Abhischek779336fb0882
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index 8496a8e55a32..1ed37cc95f2a 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -27,6 +27,7 @@ from django.utils.timezone import now
import structlog
from dateutil.relativedelta import relativedelta
from dateutil.tz import tzutc
+from parameterized import parameterized
from posthog.schema import EventsQuery
@@ -1712,6 +1713,83 @@ class TestCaptureReportGroupProperties(ClickhouseDestroyTablesMixin, TestCase, C
)
+class TestTrimOversizeUsageReportPayload(TestCase):
+ @parameterized.expand(
+ [
+ ("under_limit", 2, False),
+ ("over_limit", 600, True),
+ ]
+ )
+ def test_trims_teams_only_when_over_limit(self, _name: str, team_count: int, expect_trimmed: bool) -> None:
+ from posthog.tasks.usage_report import MAX_USAGE_REPORT_PAYLOAD_BYTES, _trim_oversize_usage_report_payload
+
+ # `team_count` drives the serialized size across the threshold; the org-level totals stay realistic.
+ per_team_counters = {f"counter_{i}": 12345 for i in range(80)}
+ teams = {str(team_id): per_team_counters for team_id in range(team_count)}
+ report = {
+ "team_count": team_count,
+ "event_count_in_period": 7_777,
+ "organization_name": "Big Customer",
+ "teams": teams,
+ }
+ assert (len(json.dumps(report, default=str)) > MAX_USAGE_REPORT_PAYLOAD_BYTES) is expect_trimmed
+
+ result = _trim_oversize_usage_report_payload(report)
+
+ if not expect_trimmed:
+ assert result is report
+ return
+
+ assert result is not report # Original kept intact for the SQS path.
+ assert report["teams"] == teams
+ assert result["teams"] == {}
+ assert result["teams_omitted_due_to_size"] is True
+ assert result["team_count"] == team_count
+ assert result["event_count_in_period"] == 7_777
+ assert result["organization_name"] == "Big Customer"
+ assert len(json.dumps(result, default=str)) <= MAX_USAGE_REPORT_PAYLOAD_BYTES
+
+
+@freeze_time("2022-01-10T00:01:00Z")
+class TestCaptureReportTrimsOversizePayload(TestCase):
+ @patch("posthog.tasks.usage_report.get_ph_client")
+ def test_capture_report_drops_teams_when_payload_too_large(self, mock_client: MagicMock) -> None:
+ from posthog.tasks.usage_report import MAX_USAGE_REPORT_PAYLOAD_BYTES, capture_report
+
+ mock_posthog = MagicMock()
+ mock_client.return_value = mock_posthog
+
+ org = Organization.objects.create(name="Big Customer")
+
+ per_team_counters = {f"counter_{i}": 12345 for i in range(80)}
+ teams = {str(team_id): per_team_counters for team_id in range(600)}
+ full_report_dict = {
+ "team_count": len(teams),
+ "event_count_in_period": 7_777,
+ "organization_user_count": 1,
+ "dashboard_count": 0,
+ "ff_count": 0,
+ "survey_count": 0,
+ "teams": teams,
+ }
+ assert len(json.dumps(full_report_dict, default=str)) > MAX_USAGE_REPORT_PAYLOAD_BYTES
+
+ capture_report(organization_id=str(org.id), full_report_dict=full_report_dict)
+
+ capture_calls = [
+ call
+ for call in mock_posthog.capture.call_args_list
+ if call.kwargs.get("event") == "organization usage report"
+ ]
+ assert len(capture_calls) == 1
+ captured_properties = capture_calls[0].kwargs["properties"]
+ assert captured_properties["teams"] == {}
+ assert captured_properties["teams_omitted_due_to_size"] is True
+ assert captured_properties["team_count"] == len(teams)
+ assert captured_properties["event_count_in_period"] == 7_777
+ assert len(json.dumps(captured_properties, default=str)) <= MAX_USAGE_REPORT_PAYLOAD_BYTES
+
+
@freeze_time("2022-01-10T00:01:00Z")
class TestExternalDataSyncUsageReport(ClickhouseDestroyTablesMixin, TestCase, ClickhouseTestMixin):
def setUp(self) -> None:
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index 235ea81e98f2..a1450c953795 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -86,6 +86,11 @@ QUERY_RETRIES = 3
QUERY_RETRY_DELAY = 1
QUERY_RETRY_BACKOFF = 2
+# Kafka's default `message.max.bytes` is ~1 MiB. For orgs with several hundred
+# teams the per-team breakdown under `teams` makes the report payload exceed
+# that limit, and the event is dropped at the broker — silently.
+MAX_USAGE_REPORT_PAYLOAD_BYTES = 900_000
+
USAGE_REPORT_TASK_KWARGS = {
"queue": CeleryQueue.USAGE_REPORTS.value,
"ignore_result": True,
@@ -1797,6 +1802,19 @@ def get_teams_with_sdk_logs_records_in_period(
return by_sdk
+def _trim_oversize_usage_report_payload(full_report_dict: dict[str, Any]) -> dict[str, Any]:
+ """Drop the per-team breakdown when the serialized report would exceed Kafka's
+ message size limit, so the org-level roll-up still makes it through ingestion.
+
+ Returns the original dict when no trimming is needed. The trimmed copy keeps
+ `team_count` and every org-level counter intact and sets
+ `teams_omitted_due_to_size=True` so downstream consumers can detect the drop.
+ """
+ if len(json.dumps(full_report_dict, default=str)) <= MAX_USAGE_REPORT_PAYLOAD_BYTES:
+ return full_report_dict
+ return {**full_report_dict, "teams": {}, "teams_omitted_due_to_size": True}
+
+
@shared_task(**USAGE_REPORT_TASK_KWARGS, max_retries=3)
@skip_team_scope_audit
def capture_report(
@@ -1815,7 +1833,7 @@ def capture_report(
pha_client=pha_client,
name="organization usage report",
organization_id=organization_id,
- properties=full_report_dict,
+ properties=_trim_oversize_usage_report_payload(full_report_dict),
timestamp=at_date,
)
except Exception as err: