: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(api): scope the hourly read budget to /query and inline endpoint runs (#98712)
Andy Zhao97dfe8a9768b
diff --git a/posthog/api/query.py b/posthog/api/query.pyindex d1cd731d0022..decbe3d48e0a 100644--- a/posthog/api/query.py+++ b/posthog/api/query.py@@ -314,12 +314,13 @@ class QueryViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)limit_context = Nonereset_request_query_cost()+ is_query_service = get_query_tag_value("access_method") == "personal_api_key"+ if is_query_service:+ tag_queries(api_queries_budgeted=True)with tracer.start_as_current_span("posthog.query.process_query_model") as process_span:process_span.set_attribute("team_id", self.team.pk)process_span.set_attribute("query.kind", getattr(query, "kind", "Other"))- process_span.set_attribute(- "query.is_query_service", get_query_tag_value("access_method") == "personal_api_key"- )+ process_span.set_attribute("query.is_query_service", is_query_service)if limit_context is not None:process_span.set_attribute("query.limit_context", limit_context.value)result = process_query_model(@@ -328,7 +329,7 @@ class QueryViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)execution_mode=execution_mode,query_id=client_query_id,user=request.user, # type: ignore[arg-type]- is_query_service=(get_query_tag_value("access_method") == "personal_api_key"),+ is_query_service=is_query_service,limit_context=limit_context,analytics_props=analytics_props,)diff --git a/posthog/api_queries_budget.py b/posthog/api_queries_budget.pyindex 43cf8bf7f0f7..089e2329c839 100644--- a/posthog/api_queries_budget.py+++ b/posthog/api_queries_budget.py@@ -3,7 +3,7 @@Each team has a token bucket in Redis measured in bytes read. The rate comes from the team'sorganization, since the subscription belongs to the organization: teams of a paying organizationrefill API_QUERIES_BUDGET_PAID_MULTIPLIER times faster. The ClickHouse client debits what every-chargeable query read after it runs (posthog/clickhouse/client/execute.py) and the query runner+budgeted query read after it runs (posthog/clickhouse/client/execute.py) and the query runnerreads the balance before admitting one. Refill is lazy: the balance is only brought up to datewhen it is read, so a debit never needs to know the team's rate. The balance floors at minus onehour of refill, so the query that crosses the line can never lock a team out for longer than andiff --git a/posthog/clickhouse/client/execute.py b/posthog/clickhouse/client/execute.pyindex 0084dc875ed3..e84561f6e8b9 100644--- a/posthog/clickhouse/client/execute.py+++ b/posthog/clickhouse/client/execute.py@@ -219,7 +219,7 @@ def resolve_kill_switch_level(team_id: Optional[int]) -> KillSwitchLevel:return level-def _meter_chargeable_query(team_id: str, query_info: Any) -> None:+def _meter_budgeted_query(team_id: str, query_info: Any) -> None:# Runs after the pooled connection is released, and must never raise: a metering failure# is an error counter, not a failed query.try:@@ -231,7 +231,7 @@ def _meter_chargeable_query(team_id: str, query_info: Any) -> None:capture_exception(e)-def _chargeable_query_info(client: Any, query_info_before: Any) -> Optional[Any]:+def _query_info_to_meter(client: Any, query_info_before: Any) -> Optional[Any]:"""The query info to meter for the query that just ran on `client`, or None.The driver only creates a new query info once the connection is established, so the identity@@ -575,7 +575,7 @@ def sync_execute(else:settings["use_hedged_requests"] = "1" if get_hedged_app_queries_enabled() else "0"start_time = perf_counter()- chargeable_query_info: Optional[Any] = None+ budgeted_query_info: Optional[Any] = Nonetry:QUERY_STARTED_COUNTER.labels(@@ -604,8 +604,8 @@ def sync_execute(# A query killed mid-scan (timeout, memory limit) has already cost the read, so# keep the progress the server reported before it died. The Redis write happens# in the outer finally, once the connection is back in the pool.- if tags.chargeable and tags.team_id:- chargeable_query_info = _chargeable_query_info(client, query_info_before)+ if tags.api_queries_budgeted and tags.team_id:+ budgeted_query_info = _query_info_to_meter(client, query_info_before)_record_query_stats(client, query_info_before, execute_start_time)if ("INSERT INTO" in prepared_sql@@ -629,8 +629,8 @@ def sync_execute(raise err from efinally:execution_time = perf_counter() - start_time- if chargeable_query_info is not None:- _meter_chargeable_query(str(tags.team_id), chargeable_query_info)+ if budgeted_query_info is not None:+ _meter_budgeted_query(str(tags.team_id), budgeted_query_info)QUERY_FINISHED_COUNTER.labels(team_id=str(team_id or ""),diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex a83f71f60d84..65a94eee9c44 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -422,6 +422,7 @@ class QueryTags(BaseModel):exported_asset_id: Optional[int] = Noneexport_format: Optional[str] = Nonechargeable: Optional[int] = None+ api_queries_budgeted: Optional[bool] = None # server-set only; request tags cannot reach itrequest_name: Optional[str] = Nonename: Optional[str] = Noneendpoint_version: Optional[int] = None # Endpoints, the productdiff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex 62dc343271f6..f60dc163029b 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -2139,6 +2139,9 @@ class QueryRunner(ABC, Generic[Q, R, CR]):if self.is_query_service:tag_queries(chargeable=1)+ # Only the /query view and the inline endpoint run set api_queries_budgeted; the product+ # tag is caller-supplied via query.tags.productKey, so it cannot opt a query in or out.+ if get_query_tag_value("api_queries_budgeted"):self._enforce_api_queries_budget()with (diff --git a/posthog/hogql_queries/test/test_api_queries_budget.py b/posthog/hogql_queries/test/test_api_queries_budget.pyindex cb4ae1217dbc..5e1c7ee60740 100644--- a/posthog/hogql_queries/test/test_api_queries_budget.py+++ b/posthog/hogql_queries/test/test_api_queries_budget.py@@ -121,20 +121,37 @@ class TestApiQueriesBudgetEnforcement(BaseTest):):self._runner()._enforce_api_queries_budget()- @parameterized.expand([("api_key_query_refused", True), ("app_query_admitted", False)])- def test_call_with_rate_limits_enforces_the_budget_for_api_key_queries_only(self, _name, is_query_service):+ @parameterized.expand([("api_key_query_unbudgeted", True), ("app_query", False)])+ def test_call_with_rate_limits_admits_unbudgeted_queries(self, _name, is_query_service):self._drain()runner = self._runner(is_query_service=is_query_service)with (patch("posthog.hogql_queries.query_runner._api_queries_budget_enforcement_enabled", return_value=True),patch.object(runner, "calculate", return_value="stub result"),):- if is_query_service:- with pytest.raises(APIQueriesBudgetExceeded):- runner._call_with_rate_limits(dashboard_id=None)- else:- result, _duration_ms = runner._call_with_rate_limits(dashboard_id=None)- assert result == "stub result"+ result, _duration_ms = runner._call_with_rate_limits(dashboard_id=None)+ assert result == "stub result"++ @parameterized.expand(+ [+ ("budgeted", {}),+ ("caller_supplied_endpoints_product_tag", {"product": Product.ENDPOINTS}),+ ("caller_supplied_data_catalog_product_tag", {"product": Product.DATA_CATALOG}),+ ]+ )+ def test_call_with_rate_limits_enforces_the_budget_for_budgeted_queries(self, _name, tags):+ self._drain()+ runner = self._runner(is_query_service=True)+ tag_queries(api_queries_budgeted=True, **tags)+ try:+ with (+ patch("posthog.hogql_queries.query_runner._api_queries_budget_enforcement_enabled", return_value=True),+ patch.object(runner, "calculate", return_value="stub result"),+ pytest.raises(APIQueriesBudgetExceeded),+ ):+ runner._call_with_rate_limits(dashboard_id=None)+ finally:+ reset_query_tags()def test_concurrency_limit_ignores_billing_quota_limited_teams(self):# get_api_queries_concurrency_limit reads the plain `posthog.settings` modulediff --git a/posthog/test/test_api_queries_budget.py b/posthog/test/test_api_queries_budget.pyindex 66480b9d2880..c219a14e7ea4 100644--- a/posthog/test/test_api_queries_budget.py+++ b/posthog/test/test_api_queries_budget.py@@ -24,7 +24,7 @@ from posthog.api_queries_budget import (seconds_until_positive,)from posthog.clickhouse.client import sync_execute-from posthog.clickhouse.query_tagging import reset_query_tags, tag_queries+from posthog.clickhouse.query_tagging import Product, reset_query_tags, tag_queriesfrom posthog.redis import get_clientSPEC = BudgetSpec(bytes_per_hour=3600.0, capacity_bytes=7200.0)@@ -118,7 +118,7 @@ class TestRequestQueryCost(SimpleTestCase):assert get_request_query_cost() is None-class TestChargeableQueryMetering(ClickhouseTestMixin, BaseTest):+class TestBudgetedQueryMetering(ClickhouseTestMixin, BaseTest):# LIMIT applies to the aggregate's single output row, not to system.numbers itself,# so bound the scan inside a subquery or the read never terminates.BOUNDED_QUERY = "SELECT sum(number) FROM (SELECT number FROM system.numbers LIMIT 10000)"@@ -127,10 +127,10 @@ class TestChargeableQueryMetering(ClickhouseTestMixin, BaseTest):super().setUp()reset_request_query_cost()- def test_chargeable_query_debits_the_team_budget(self):+ def test_budgeted_query_debits_the_team_budget(self):spec = budget_spec_for(self.organization)refill_and_read(str(self.team.pk), spec)- tag_queries(chargeable=1, team_id=self.team.pk)+ tag_queries(api_queries_budgeted=True, team_id=self.team.pk)try:sync_execute(self.BOUNDED_QUERY)finally:@@ -143,6 +143,29 @@ class TestChargeableQueryMetering(ClickhouseTestMixin, BaseTest):sync_execute(self.BOUNDED_QUERY)assert get_request_query_cost() is None+ def test_chargeable_but_unbudgeted_query_is_not_metered(self):+ tag_queries(chargeable=1, team_id=self.team.pk)+ try:+ sync_execute(self.BOUNDED_QUERY)+ finally:+ reset_query_tags()+ assert get_request_query_cost() is None++ @parameterized.expand(+ [+ ("caller_supplied_endpoints_product_tag", {"product": Product.ENDPOINTS}),+ ("caller_supplied_data_catalog_product_tag", {"product": Product.DATA_CATALOG}),+ ]+ )+ def test_caller_supplied_tags_do_not_change_metering(self, _name, tags):+ tag_queries(api_queries_budgeted=True, team_id=self.team.pk, **tags)+ try:+ sync_execute(self.BOUNDED_QUERY)+ finally:+ reset_query_tags()+ cost = get_request_query_cost()+ assert cost is not None and cost.bytes_read > 0+class QueryDied(Exception):pass@@ -156,7 +179,7 @@ class TestFailedQueryMetering(BaseTest):fake_client.execute.side_effect = QueryDied("network down before connecting")pool = MagicMock()pool.__enter__.return_value = fake_client- tag_queries(chargeable=1, team_id=self.team.pk)+ tag_queries(api_queries_budgeted=True, team_id=self.team.pk)try:with patch("posthog.clickhouse.client.execute.get_client_from_pool", return_value=pool):with pytest.raises(QueryDied):diff --git a/products/endpoints/backend/logic/execution.py b/products/endpoints/backend/logic/execution.pyindex fd625299b743..2d2ec61fa072 100644--- a/products/endpoints/backend/logic/execution.py+++ b/products/endpoints/backend/logic/execution.py@@ -944,6 +944,8 @@ class EndpointExecutionService(PydanticModelMixin):offset: int | None = None,) -> Response:"""Execute query directly against ClickHouse."""+ if is_api_key_access_method(get_query_tag_value("access_method")):+ tag_queries(api_queries_budgeted=True)strategy: EndpointQueryStrategy | None = Nonetry:strategy = strategy_for(endpoint, version, self.team)diff --git a/products/product_analytics/backend/tests/test_facade.py b/products/product_analytics/backend/tests/test_facade.pyindex e353381ac8c6..8735b3231407 100644--- a/products/product_analytics/backend/tests/test_facade.py+++ b/products/product_analytics/backend/tests/test_facade.py@@ -167,7 +167,7 @@ class TestRunCachedTrendsQuery(BaseTest):api_key_org_kwargs = org_limiter.return_value.run.call_args.kwargsassert api_key_team_kwargs["is_api"] is Trueassert api_key_org_kwargs["is_api"] is True- enforce_budget.assert_called_once()+ enforce_budget.assert_not_called()reset_query_tags()run_cached_trends_query(