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(billing): send today's usage for limit updates (#89222)

Pawel Cebulaa5f49afdc2ac
diff --git a/ee/api/billing.py b/ee/api/billing.py
index 3e6e04a06c21..82fe6e7936c0 100644
--- a/ee/api/billing.py
+++ b/ee/api/billing.py
@@ -1,6 +1,6 @@
import json
from collections.abc import Callable, Sequence
-from typing import Any, Optional
+from typing import Any, Optional, cast
from zoneinfo import ZoneInfo
from django.http import HttpResponse
@@ -43,6 +43,8 @@ logger = structlog.get_logger(__name__)
BILLING_SERVICE_JWT_AUD = "posthog:license-key"
OWNER_ONLY_BILLING_FLAG = "owner-only-billing"
MEMBER_BILLING_USAGE_SPEND_READ_ACCESS_FLAG = "member-billing-usage-spend-read-access"
+BILLING_LIMIT_TODAYS_USAGE_FLAG = "billing-limit-todays-usage"
+BILLING_LIMIT_TODAYS_USAGE_KEYS = ("posthog_code_credits",)
def _owner_only_billing_enabled(user: User, organization: Organization) -> Optional[bool]:
@@ -93,6 +95,53 @@ def _member_billing_usage_spend_read_access_enabled(user: User, organization: Or
return False
+def _billing_limit_todays_usage_enabled(user: User, organization: Organization) -> bool:
+ if not user.distinct_id:
+ return False
+
+ try:
+ return (
+ posthog_feature_flag_enabled(
+ BILLING_LIMIT_TODAYS_USAGE_FLAG,
+ str(user.distinct_id),
+ organization_id=organization.id,
+ )
+ is True
+ )
+ except Exception as e:
+ capture_exception(e, {"organization_id": organization.id, "flag": BILLING_LIMIT_TODAYS_USAGE_FLAG})
+ return False
+
+
+def _todays_usage_value(usage_key: str, usage: dict[str, Any]) -> int:
+ value = usage.get("todays_usage")
+ if value is None:
+ return 0
+ if isinstance(value, bool) or not isinstance(value, int):
+ raise ValidationError(f"Invalid today's usage value for {usage_key}.")
+ if value < 0:
+ raise ValidationError(f"Invalid today's usage value for {usage_key}.")
+ return value
+
+
+def _todays_usage_by_usage_key(organization: Organization) -> dict[str, int]:
+ usage_summary = organization.usage or {}
+ todays_usage_by_usage_key: dict[str, int] = {}
+
+ for usage_key in BILLING_LIMIT_TODAYS_USAGE_KEYS:
+ usage = usage_summary.get(usage_key)
+ if usage is None:
+ continue
+ if not isinstance(usage, dict):
+ raise ValidationError(f"Invalid current usage summary for {usage_key}.")
+
+ todays_usage = _todays_usage_value(usage_key, usage)
+ if todays_usage:
+ todays_usage_by_usage_key[usage_key] = todays_usage
+
+ return todays_usage_by_usage_key
+
+
def user_has_billing_usage_spend_read_access(user: User, organization: Organization) -> bool:
membership = OrganizationMembership.objects.filter(user=user, organization=organization).only("level").first()
if not membership:
@@ -444,6 +493,10 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
body = {}
if custom_limits_usd:
body["custom_limits_usd"] = custom_limits_usd
+ if _billing_limit_todays_usage_enabled(cast(User, self.request.user), org):
+ todays_usage = _todays_usage_by_usage_key(org)
+ if todays_usage:
+ body["todays_usage_by_usage_key"] = todays_usage
if reset_limit_next_period:
body["reset_limit_next_period"] = reset_limit_next_period
diff --git a/ee/api/test/test_billing.py b/ee/api/test/test_billing.py
index dfd6708fa881..a412f64b273a 100644
--- a/ee/api/test/test_billing.py
+++ b/ee/api/test/test_billing.py
@@ -29,6 +29,7 @@ from posthog.models.utils import generate_random_token_personal, hash_key_value
from products.access_control.backend.models.access_control import AccessControl
from ee.api.billing import (
+ BILLING_LIMIT_TODAYS_USAGE_FLAG,
MEMBER_BILLING_USAGE_SPEND_READ_ACCESS_FLAG,
OWNER_ONLY_BILLING_FLAG,
BillingUsageRequestSerializer,
@@ -900,6 +901,63 @@ class TestBillingAPI(APILicensedTest):
assert len(billing_calls) == 1
assert billing_calls[0].kwargs["params"] == {"include_forecasting": "true"}
+ @patch("ee.billing.billing_manager.BillingManager.get_billing")
+ @patch("ee.billing.billing_manager.BillingManager.update_billing")
+ @patch("ee.api.billing.posthog_feature_flag_enabled")
+ def test_patch_sends_todays_usage_when_enabled(self, mock_feature_enabled, mock_update_billing, mock_get_billing):
+ mock_feature_enabled.side_effect = lambda key, *_args, **_kwargs: key == BILLING_LIMIT_TODAYS_USAGE_FLAG
+ self.organization_membership.level = OrganizationMembership.Level.OWNER
+ self.organization_membership.save()
+ self.organization.usage = create_usage_summary(
+ events={"usage": 100, "todays_usage": 20, "limit": None},
+ posthog_code_credits={"usage": 1200, "todays_usage": 3400, "limit": 5000},
+ posthog_code_token_credits={"usage": 999, "todays_usage": 1, "limit": None},
+ )
+ self.organization.save()
+ mock_get_billing.return_value = create_billing_response(customer=create_billing_customer())
+
+ response = self.client.patch(
+ "/api/billing//",
+ data={"custom_limits_usd": {"posthog_code_usage": 50}},
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ mock_update_billing.assert_called_once()
+ assert mock_update_billing.call_args.args[1] == {
+ "custom_limits_usd": {"posthog_code_usage": 50},
+ "todays_usage_by_usage_key": {"posthog_code_credits": 3400},
+ }
+ mock_feature_enabled.assert_any_call(
+ BILLING_LIMIT_TODAYS_USAGE_FLAG,
+ str(self.user.distinct_id),
+ organization_id=self.organization.id,
+ )
+
+ @patch("ee.billing.billing_manager.BillingManager.get_billing")
+ @patch("ee.billing.billing_manager.BillingManager.update_billing")
+ @patch("ee.api.billing.posthog_feature_flag_enabled", return_value=False)
+ def test_patch_does_not_send_todays_usage_when_disabled(
+ self, _mock_feature_enabled, mock_update_billing, mock_get_billing
+ ):
+ self.organization_membership.level = OrganizationMembership.Level.OWNER
+ self.organization_membership.save()
+ self.organization.usage = create_usage_summary(
+ posthog_code_credits={"usage": 1200, "todays_usage": 3400, "limit": 5000}
+ )
+ self.organization.save()
+ mock_get_billing.return_value = create_billing_response(customer=create_billing_customer())
+
+ response = self.client.patch(
+ "/api/billing//",
+ data={"custom_limits_usd": {"posthog_code_usage": 50}},
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ mock_update_billing.assert_called_once()
+ assert mock_update_billing.call_args.args[1] == {"custom_limits_usd": {"posthog_code_usage": 50}}
+
class TestPortalBillingAPI(APILicensedTest):
def setUp(self):