: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
feat(api): hourly read budget per team replaces the monthly api queries quota (#95375)
Andy Zhao8a67a1ebf7ca
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex da9cbaf19157..8d74ca7cc36d 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -49407,6 +49407,12 @@"QueryStatus": {"additionalProperties": false,"properties": {+ "budget_remaining_bytes": {+ "$ref": "#/definitions/integer"+ },+ "bytes_read": {+ "$ref": "#/definitions/integer"+ },"complete": {"default": false,"description": "Whether the query is still running. Will be true if the query is complete, even if it errored. Either result or error will be set.",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 1bed7c8f3958..12efe0511bbc 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -2774,6 +2774,8 @@ export type QueryStatus = {task_id?: stringquery_progress?: ClickhouseQueryProgresslabels?: string[]+ bytes_read?: integer+ budget_remaining_bytes?: integer}export interface LifecycleQueryResponse extends AnalyticsQueryResponseBase {diff --git a/posthog/api/query.py b/posthog/api/query.pyindex ee364811c3d8..8487d78be43f 100644--- a/posthog/api/query.py+++ b/posthog/api/query.py@@ -46,13 +46,13 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.services.query import process_query_modelfrom posthog.api.streaming import sse_streaming_responsefrom posthog.api.utils import action, is_async_query, is_insight_actors_options_query, is_insight_actors_query+from posthog.api_queries_budget import get_request_query_cost, reset_request_query_costfrom posthog.clickhouse.client.execute_async import QueryNotFoundError, cancel_query, get_query_statusfrom posthog.clickhouse.client.limit import ConcurrencyLimitExceededfrom posthog.clickhouse.query_tagging import get_query_tag_value, get_query_tags, tag_queriesfrom posthog.constants import AvailableFeaturefrom posthog.errors import ExposedCHQueryError, InternalCHQueryErrorfrom posthog.event_usage import EventSource, get_request_analytics_properties, report_user_or_team_action-from posthog.exceptions import QuotaLimitExceededfrom posthog.exceptions_capture import capture_exceptionfrom posthog.hogql_queries.apply_dashboard_filters import apply_dashboard_filters, apply_dashboard_variablesfrom posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner@@ -98,6 +98,12 @@ QUERY_VALIDATION_ERROR_TOTAL = Counter()+def _add_query_cost_headers(response: HttpResponseBase, bytes_read: int, remaining_bytes: int | None) -> None:+ response["X-PostHog-Query-Bytes-Read"] = str(bytes_read)+ if remaining_bytes is not None:+ response["X-PostHog-Query-Budget-Remaining-Bytes"] = str(remaining_bytes)++def _extract_validation_code(error: ValidationError) -> str:validation_codes = error.get_codes()if isinstance(validation_codes, list):@@ -297,6 +303,7 @@ class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMielse:limit_context = None+ reset_request_query_cost()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"))@@ -354,7 +361,15 @@ class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMiif formatted is not None:result["formatted_results"] = formatted- return Response(result, status=response_status)+ response = Response(result, status=response_status)+ cost = get_request_query_cost()+ if cost is not None and get_query_tag_value("access_method") == "personal_api_key":+ _add_query_cost_headers(+ response,+ cost.bytes_read,+ int(cost.remaining_bytes) if cost.remaining_bytes is not None else None,+ )+ return responseexcept (ExposedHogQLError, ExposedCHQueryError, HogVMException) as e:detail = str(e)extra: dict | None = None@@ -382,8 +397,9 @@ class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMiraiseexcept ConcurrencyLimitExceeded as c:self._raise_concurrency_throttled(c)- except QuotaLimitExceeded:- # Expected while an org is over quota - a 402 the caller can act on, not error noise.+ except Throttled:+ # Expected while a team is over its hourly query budget: a 429 with Retry-After is the+ # caller's signal, not error noise.raiseexcept Exception as e:# Breaker replays were already captured when the original failure happened.@@ -435,7 +451,10 @@ class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMielif query_status.complete:http_code = status.HTTP_200_OK- return JsonResponse(query_status_response.model_dump(), safe=False, status=http_code)+ response = JsonResponse(query_status_response.model_dump(), safe=False, status=http_code)+ if query_status.bytes_read is not None:+ _add_query_cost_headers(response, query_status.bytes_read, query_status.budget_remaining_bytes)+ return response@extend_schema(responses={200: OpenApiTypes.OBJECT})@action(methods=["POST"], detail=False)@@ -510,8 +529,9 @@ class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMireturn Response(result.model_dump(), status=200)except ConcurrencyLimitExceeded as c:self._raise_concurrency_throttled(c)- except QuotaLimitExceeded:- # Expected while an org is over quota - a 402 the caller can act on, not error noise.+ except Throttled:+ # Expected while a team is over its hourly query budget: a 429 with Retry-After is the+ # caller's signal, not error noise.raiseexcept Exception as e:# Breaker replays were already captured when the original failure happened.diff --git a/posthog/api/test/test_query.py b/posthog/api/test/test_query.pyindex e41aba72fdd0..543927b8bf67 100644--- a/posthog/api/test/test_query.py+++ b/posthog/api/test/test_query.py@@ -29,6 +29,7 @@ from posthog.schema import (HogQLQuery,PersonPropertyFilter,PropertyOperator,+ QueryStatus,)from posthog.hogql.constants import LimitContext@@ -43,9 +44,10 @@ from posthog.clickhouse.client import sync_executefrom posthog.clickhouse.client.limit import ConcurrencyLimitExceededfrom posthog.clickhouse.query_tagging import Product, QueryTagsfrom posthog.event_usage import EventSource-from posthog.exceptions import ClickHouseQueryTimeOut+from posthog.exceptions import APIQueriesBudgetExceeded, ClickHouseQueryTimeOutfrom posthog.llm.completions import OpenAICompletion-from posthog.models.utils import UUIDT+from posthog.models import PersonalAPIKey+from posthog.models.utils import UUIDT, generate_random_token_personal, hash_key_valuefrom products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyTypefrom products.managed_warehouse.backend.facade.query_labels import MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIX@@ -1001,6 +1003,8 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):"error": False,"error_message": None,"error_code": None,+ "bytes_read": None,+ "budget_remaining_bytes": None,"expiration_time": mock.ANY,"id": mock.ANY,"query_async": True,@@ -1533,3 +1537,51 @@ class TestMcpProductTaggingEndToEnd(ClickhouseTestMixin, APIBaseTest):comment = self._get_log_comment_for_team()self.assertNotEqual(comment.get("source"), "mcp")self.assertNotEqual(comment.get("product"), Product.MCP.value)+++class TestQueryCostHeaders(ClickhouseTestMixin, APIBaseTest):+ def _personal_key_headers(self) -> dict[str, str]:+ value = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="cost headers", user=self.user, secure_value=hash_key_value(value), scopes=["query:read"]+ )+ return {"Authorization": f"Bearer {value}"}++ @parameterized.expand([("api_key", True), ("session", False)])+ def test_only_api_key_query_responses_carry_cost_headers(self, _name, api_key):+ response = self.client.post(+ f"/api/projects/{self.team.id}/query/",+ {"query": {"kind": "HogQLQuery", "query": "SELECT 1"}},+ format="json",+ headers=self._personal_key_headers() if api_key else {},+ )+ assert response.status_code == 200, response.content+ assert ("X-PostHog-Query-Bytes-Read" in response) is api_key+ if api_key:+ assert int(response["X-PostHog-Query-Bytes-Read"]) >= 0+ assert int(response["X-PostHog-Query-Budget-Remaining-Bytes"]) > 0++ def test_async_query_status_carries_the_cost_once_complete(self):+ query_status = QueryStatus(+ id="q1", team_id=self.team.id, complete=True, bytes_read=1234, budget_remaining_bytes=99+ )+ with patch("posthog.api.query.get_query_status", return_value=query_status):+ response = self.client.get(f"/api/projects/{self.team.id}/query/q1/", headers=self._personal_key_headers())+ assert response.status_code == 200+ assert response["X-PostHog-Query-Bytes-Read"] == "1234"+ assert response["X-PostHog-Query-Budget-Remaining-Bytes"] == "99"++ def test_budget_429_is_not_captured_as_an_error(self):+ with (+ patch("posthog.api.query.process_query_model", side_effect=APIQueriesBudgetExceeded(wait=5)),+ patch("posthog.api.query.capture_exception") as mock_capture,+ ):+ response = self.client.post(+ f"/api/projects/{self.team.id}/query/",+ {"query": {"kind": "HogQLQuery", "query": "SELECT 1"}},+ format="json",+ headers=self._personal_key_headers(),+ )+ assert response.status_code == 429+ assert response["Retry-After"] == "5"+ assert not mock_capture.calleddiff --git a/posthog/api_queries_budget.py b/posthog/api_queries_budget.pynew file mode 100644index 000000000000..505201ef8015--- /dev/null+++ b/posthog/api_queries_budget.py@@ -0,0 +1,187 @@+"""Hourly read budget for API key queries.++Each team has a token bucket in Redis measured in bytes read. The rate comes from the team's+organization, since the subscription belongs to the organization: teams of a paying organization+refill 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+reads the balance before admitting one. Refill is lazy: the balance is only brought up to date+when it is read, so a debit never needs to know the team's rate. The balance floors at minus one+hour of refill, so the query that crosses the line can never lock a team out for longer than an+hour. Everything fails open.++Exports:+* BudgetSpec, budget_spec_for, budget_enabled+* refill_and_read, debit, seconds_until_positive+* QueryCost, reset_request_query_cost, record_request_query_cost, get_request_query_cost+"""++import math+import time+from contextvars import ContextVar+from typing import Any, Optional++from django.conf import settings++from prometheus_client import Counter++from posthog.dataclasses import frozen+from posthog.exceptions_capture import capture_exception+from posthog.redis import get_client++BUDGET_KEY_PREFIX = "@posthog/api-queries-budget/"+# A bucket nobody touches for a week is rebuilt full on the next read, so the key can expire.+BUDGET_TTL_SECONDS = 7 * 24 * 3600++API_QUERIES_BUDGET_ERRORS_COUNTER = Counter(+ "posthog_api_queries_budget_errors_total",+ "Errors swallowed by the fail-open api queries budget paths.",+ labelnames=["op"],+)+++@frozen+class BudgetSpec:+ bytes_per_hour: float+ capacity_bytes: float+++@frozen+class QueryCost:+ bytes_read: int+ remaining_bytes: Optional[float]+++_request_query_cost: ContextVar[Optional[QueryCost]] = ContextVar("api_queries_request_cost", default=None)+++def budget_enabled() -> bool:+ return float(settings.API_QUERIES_BUDGET_FREE_BYTES_PER_HOUR) > 0+++def _spec(bytes_per_hour: float) -> BudgetSpec:+ return BudgetSpec(+ bytes_per_hour=bytes_per_hour,+ capacity_bytes=bytes_per_hour * float(settings.API_QUERIES_BUDGET_CAPACITY_HOURS),+ )+++def _free_spec() -> BudgetSpec:+ return _spec(float(settings.API_QUERIES_BUDGET_FREE_BYTES_PER_HOUR))+++def budget_spec_for(organization: Any) -> BudgetSpec:+ bytes_per_hour = float(settings.API_QUERIES_BUDGET_FREE_BYTES_PER_HOUR)+ # NULL means the subscription state was never synced, and an organization is not refused+ # on a number we do not have.+ if organization.has_active_subscription is not False:+ bytes_per_hour *= float(settings.API_QUERIES_BUDGET_PAID_MULTIPLIER)+ return _spec(bytes_per_hour)+++def _bucket_key(team_id: str) -> str:+ return f"{BUDGET_KEY_PREFIX}team/{team_id}"+++# KEYS[1] bucket, ARGV[1] now in seconds, ARGV[2] bytes per hour, ARGV[3] capacity, ARGV[4] ttl.+# A missing bucket starts full. The floor is one hour of refill. Capacity and floor are stored so+# a debit that arrives before any read (a chargeable query that did not go through the query+# runner) can use them.+_REFILL_AND_READ = """+local tokens = tonumber(redis.call('HGET', KEYS[1], 'tokens'))+local refilled_at = tonumber(redis.call('HGET', KEYS[1], 'refilled_at'))+local now = tonumber(ARGV[1])+local floor = tonumber(ARGV[2])+local capacity = tonumber(ARGV[3])+if tokens == nil then tokens = capacity end+if refilled_at == nil then refilled_at = now end+tokens = math.min(capacity, tokens + math.max(0, now - refilled_at) / 3600 * floor)+tokens = math.max(tokens, -floor)+redis.call('HSET', KEYS[1], 'tokens', tokens, 'refilled_at', now, 'capacity', capacity, 'floor', floor)+redis.call('EXPIRE', KEYS[1], ARGV[4])+return tostring(tokens)+"""++# KEYS[1] bucket, ARGV[1] bytes, ARGV[2] fallback capacity, ARGV[3] fallback floor, ARGV[4] ttl.+_DEBIT = """+local tokens = tonumber(redis.call('HGET', KEYS[1], 'tokens'))+local capacity = tonumber(redis.call('HGET', KEYS[1], 'capacity'))+local floor = tonumber(redis.call('HGET', KEYS[1], 'floor'))+if capacity == nil then capacity = tonumber(ARGV[2]) end+if floor == nil then floor = tonumber(ARGV[3]) end+if tokens == nil then tokens = capacity end+tokens = math.max(tokens - tonumber(ARGV[1]), -floor)+redis.call('HSET', KEYS[1], 'tokens', tokens, 'capacity', capacity, 'floor', floor)+redis.call('EXPIRE', KEYS[1], ARGV[4])+return tostring(tokens)+"""+++def refill_and_read(team_id: str, spec: BudgetSpec, now: Optional[float] = None) -> Optional[float]:+ try:+ result = get_client().eval(+ _REFILL_AND_READ,+ 1,+ _bucket_key(team_id),+ now if now is not None else time.time(),+ spec.bytes_per_hour,+ spec.capacity_bytes,+ BUDGET_TTL_SECONDS,+ )+ return float(result)+ except Exception as e:+ API_QUERIES_BUDGET_ERRORS_COUNTER.labels(op="read").inc()+ capture_exception(e)+ return None+++def debit(team_id: str, bytes_read: int) -> Optional[float]:+ """Take the bytes off the team's bucket. Returns the remaining balance, or None when the budget+ is disabled or Redis failed."""+ if not budget_enabled() or bytes_read <= 0:+ return None+ free = _free_spec()+ try:+ result = get_client().eval(+ _DEBIT,+ 1,+ _bucket_key(team_id),+ int(bytes_read),+ free.capacity_bytes,+ free.bytes_per_hour,+ BUDGET_TTL_SECONDS,+ )+ return float(result)+ except Exception as e:+ API_QUERIES_BUDGET_ERRORS_COUNTER.labels(op="debit").inc()+ capture_exception(e)+ return None+++def seconds_until_positive(remaining: float, spec: BudgetSpec) -> int:+ if remaining > 0:+ return 0+ if spec.bytes_per_hour <= 0:+ return 1+ # A zero balance is still exhausted, and DRF only sends Retry-After for a positive wait.+ return max(1, math.ceil(-remaining / (spec.bytes_per_hour / 3600.0)))+++def reset_request_query_cost() -> None:+ _request_query_cost.set(None)+++def record_request_query_cost(cost: QueryCost) -> None:+ previous = _request_query_cost.get()+ if previous is None:+ _request_query_cost.set(cost)+ return+ _request_query_cost.set(+ QueryCost(+ bytes_read=previous.bytes_read + cost.bytes_read,+ remaining_bytes=cost.remaining_bytes if cost.remaining_bytes is not None else previous.remaining_bytes,+ )+ )+++def get_request_query_cost() -> Optional[QueryCost]:+ return _request_query_cost.get()diff --git a/posthog/api_queries_quota.py b/posthog/api_queries_quota.pydeleted file mode 100644index a7b32370f80c..000000000000--- a/posthog/api_queries_quota.py+++ /dev/null@@ -1,57 +0,0 @@-"""Per-organization monthly counter of chargeable API query bytes read.--The product-owned metering for the free-tier API queries quota: incremented from the-ClickHouse client for chargeable queries, read by the query runner's quota check. Kept-dependency-light (Redis only) so both layers can import it without cycles.-"""--from datetime import UTC, datetime--from dateutil.relativedelta import relativedelta-from prometheus_client import Counter--from posthog.exceptions_capture import capture_exception-from posthog.redis import get_client--COUNTER_KEY_PREFIX = "@posthog/api-queries-bytes/"-# Keys are month-scoped; TTL only has to outlive the month it closes over.-COUNTER_TTL_SECONDS = 63 * 24 * 3600--API_QUERIES_QUOTA_ERRORS_COUNTER = Counter(- "posthog_api_queries_quota_errors_total",- "Errors swallowed by the fail-open api queries quota paths.",- labelnames=["op"],-)---def _counter_key(org_id: str, now: datetime) -> str:- return f"{COUNTER_KEY_PREFIX}{org_id}/{now.strftime('%Y%m')}"---def increment_api_queries_bytes(org_id: str, bytes_read: int) -> None:- if not bytes_read:- return- try:- key = _counter_key(org_id, datetime.now(UTC))- pipe = get_client().pipeline(transaction=False)- pipe.incrby(key, bytes_read)- pipe.expire(key, COUNTER_TTL_SECONDS)- pipe.execute()- except Exception as e:- API_QUERIES_QUOTA_ERRORS_COUNTER.labels(op="increment").inc()- capture_exception(e)---def get_api_queries_bytes(org_id: str) -> int:- try:- value = get_client().get(_counter_key(org_id, datetime.now(UTC)))- return int(value) if value else 0- except Exception as e:- API_QUERIES_QUOTA_ERRORS_COUNTER.labels(op="read").inc()- capture_exception(e)- return 0---def next_counter_reset(now: datetime) -> datetime:- """First instant of the next UTC month, when the counter key rolls over."""- return datetime(now.year, now.month, 1, tzinfo=UTC) + relativedelta(months=1)diff --git a/posthog/clickhouse/client/execute.py b/posthog/clickhouse/client/execute.pyindex 45928e4b3b67..cc6c1c998cb0 100644--- a/posthog/clickhouse/client/execute.py+++ b/posthog/clickhouse/client/execute.py@@ -19,7 +19,7 @@ from clickhouse_driver import Client as SyncClientfrom opentelemetry import tracefrom prometheus_client import Counter-from posthog.api_queries_quota import increment_api_queries_bytes+from posthog.api_queries_budget import API_QUERIES_BUDGET_ERRORS_COUNTER, QueryCost, debit, record_request_query_costfrom posthog.clickhouse.client.connection import (ClickHouseUser,Workload,@@ -41,6 +41,7 @@ from posthog.clickhouse.query_tagging import ()from posthog.dataclasses import frozenfrom posthog.errors import clickhouse_error_type, wrap_clickhouse_query_error+from posthog.exceptions_capture import capture_exceptionfrom posthog.settings import CLICKHOUSE_PER_TEAM_QUERY_SETTINGS, DEBUG, TESTfrom posthog.utils import generate_short_id, patchable@@ -215,6 +216,32 @@ def resolve_kill_switch_level(team_id: Optional[int]) -> KillSwitchLevel:return level+def _meter_chargeable_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:+ bytes_read = int(query_info.progress.bytes or 0)+ remaining = debit(team_id, bytes_read)+ record_request_query_cost(QueryCost(bytes_read=bytes_read, remaining_bytes=remaining))+ except Exception as e:+ API_QUERIES_BUDGET_ERRORS_COUNTER.labels(op="meter").inc()+ capture_exception(e)+++def _chargeable_query_info(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+ check keeps a pooled client's previous query from being re-metered when connecting fails.+ The driver also clears `last_query` when it disconnects after a server-side error, so a query+ the server killed is not metered.+ """+ query_info = getattr(client, "last_query", None)+ if query_info is None or query_info is query_info_before or not query_info.progress:+ return None+ return query_info++def kill_switch_overrides(team_id: Optional[int], ch_user: ClickHouseUser = ClickHouseUser.DEFAULT) -> dict[str, int]:"""The ClickHouse setting ceilings the kill switch imposes right now, empty when it is off.@@ -507,6 +534,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] = Nonetry:QUERY_STARTED_COUNTER.labels(@@ -530,18 +558,10 @@ def sync_execute()finally:# A query killed mid-scan (timeout, memory limit) has already cost the read, so- # meter the progress the server reported before it died. The driver only resets- # `last_query` once the connection is established; the identity check keeps a- # pooled client's previous query from being re-metered when connecting fails.- query_info = getattr(client, "last_query", None)- if (- tags.chargeable- and tags.org_id- and query_info is not None- and query_info is not query_info_before- and query_info.progress- ):- increment_api_queries_bytes(str(tags.org_id), query_info.progress.bytes)+ # 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 ("INSERT INTO" in prepared_sqland hasattr(client, "last_query")@@ -560,6 +580,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)QUERY_FINISHED_COUNTER.labels(team_id=str(team_id or ""),diff --git a/posthog/clickhouse/client/execute_async.py b/posthog/clickhouse/client/execute_async.pyindex 069b3742b4b3..9db6d5dd05ea 100644--- a/posthog/clickhouse/client/execute_async.py+++ b/posthog/clickhouse/client/execute_async.py@@ -15,6 +15,7 @@ from posthog.hogql.constants import LimitContextfrom posthog.hogql.errors import ExposedHogQLErrorfrom posthog import celery, redis+from posthog.api_queries_budget import get_request_query_cost, reset_request_query_costfrom posthog.clickhouse.client.async_task_chain import add_task_to_on_commitfrom posthog.clickhouse.client.limit import ConcurrencyLimitExceededfrom posthog.clickhouse.query_tagging import get_query_tags, tag_queries@@ -261,6 +262,7 @@ def execute_process_query(wait_duration = (query_status.pickup_time - query_status.start_time) / datetime.timedelta(seconds=1)QUERY_WAIT_TIME.labels(team=team_id, mode=trigger).observe(wait_duration)+ reset_request_query_cost()try:results = process_query_dict(team=team,@@ -316,6 +318,12 @@ def execute_process_query(# Do not raise here, the task itself did its job and we cannot recoverfinally:query_status.end_time = datetime.datetime.now(datetime.UTC)+ cost = get_request_query_cost()+ if cost is not None:+ query_status.bytes_read = cost.bytes_read+ query_status.budget_remaining_bytes = (+ int(cost.remaining_bytes) if cost.remaining_bytes is not None else None+ )manager.store_query_status(query_status)cache_key = Nonetry:diff --git a/posthog/clickhouse/client/test/test_execute_async.py b/posthog/clickhouse/client/test/test_execute_async.pyindex 3154779c8521..2f5dc07bd058 100644--- a/posthog/clickhouse/client/test/test_execute_async.py+++ b/posthog/clickhouse/client/test/test_execute_async.py@@ -16,6 +16,7 @@ from posthog.schema import ClickhouseQueryProgress, QueryStatusfrom posthog.hogql.constants import DEFAULT_POSTHOG_AI_RETURNED_ROWSfrom posthog.hogql.errors import ExposedHogQLError+from posthog.api_queries_budget import QueryCost, record_request_query_costfrom posthog.clickhouse.client import (execute_async as client,sync_execute,@@ -218,6 +219,28 @@ class TestExecuteProcessQuery(TestCase):args_loaded = json.loads(args[1])self.assertEqual(args_loaded["results"], [None, None, None, 1.0, "👍"])+ @patch("posthog.clickhouse.client.execute_async.redis.get_client")+ @patch("posthog.api.services.query.process_query_dict")+ def test_execute_process_query_stores_the_query_cost(self, mock_process_query_dict, mock_redis_client):+ mock_redis = MagicMock()+ mock_redis.get.return_value = json.dumps(+ {"id": self.query_id, "team_id": self.team.id, "complete": False, "error": False}+ ).encode()+ mock_redis_client.return_value = mock_redis++ def run_and_meter(**kwargs):+ record_request_query_cost(QueryCost(bytes_read=1234, remaining_bytes=99.9))+ return {"results": []}++ mock_process_query_dict.side_effect = run_and_meter++ execute_process_query(self.team.id, self.user.id, self.query_id, self.query_json, self.limit_context)++ args, _kwargs = mock_redis.set.call_args+ stored = json.loads(args[1])+ assert stored["bytes_read"] == 1234+ assert stored["budget_remaining_bytes"] == 99+@parameterized.expand([("user_safe_ch_error", ExposedCHQueryError("NOT_AN_AGGREGATE"), False),diff --git a/posthog/exceptions.py b/posthog/exceptions.pyindex eaf60c855d78..4e486e00251c 100644--- a/posthog/exceptions.py+++ b/posthog/exceptions.py@@ -5,7 +5,7 @@ from django.http.response import JsonResponseimport structlogfrom rest_framework import status-from rest_framework.exceptions import APIException, ValidationError+from rest_framework.exceptions import APIException, Throttled, ValidationErrorfrom rest_framework.response import Responsefrom posthog.clickhouse.query_tagging import get_query_tags@@ -29,12 +29,16 @@ class QuotaLimitExceeded(APIException):default_detail = "Your organization reached its billing limit for this resource. Increase the limits in Billing settings, or ask an org admin to do so."-class APIQueriesQuotaExceeded(QuotaLimitExceeded):- default_code = "api_queries_quota_exceeded"+class APIQueriesBudgetExceeded(Throttled):+ # DRF sets this in Throttled.__init__ and its handler turns it into Retry-After; the stubs omit it.+ wait: Optional[float]++ default_code = "api_queries_budget_exceeded"+ # DRF appends "Expected available in N seconds." to this, so the wait is not repeated here.default_detail = (- "Your organization has read more query data over the API than its free allowance for this month. "- "API queries will be available again when the allowance resets. "- "Upgrade your plan in Billing settings to restore access sooner, or ask an org admin to do so."+ "This project used its hourly budget of data read by API queries. "+ "To stay under it, read less data per query or run queries less often. "+ "See https://posthog.com/docs/sql/optimizing-queries for ways to read less.")diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex 52dbb9747e87..2cd324df8471 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -7,9 +7,7 @@ from functools import cache, cached_propertyfrom time import perf_counterfrom types import UnionTypefrom typing import Any, Generic, NamedTuple, Optional, Protocol, TypeGuard, TypeVar, Union, cast, get_args, get_origin-from zoneinfo import ZoneInfo-from django.conf import settings as django_settingsfrom django.db import OperationalErrorimport orjson@@ -112,7 +110,14 @@ from posthog.hogql.timings import HogQLTimingsfrom posthog.hogql.warehouse_warnings import accumulator_scopefrom posthog import settings-from posthog.api_queries_quota import API_QUERIES_QUOTA_ERRORS_COUNTER, get_api_queries_bytes, next_counter_reset+from posthog.api_queries_budget import (+ API_QUERIES_BUDGET_ERRORS_COUNTER,+ BudgetSpec,+ budget_enabled,+ budget_spec_for,+ refill_and_read,+ seconds_until_positive,+)from posthog.caching.utils import ThresholdMode, cache_target_age, is_stale, last_refresh_from_cached_resultfrom posthog.clickhouse.client.connection import ClickHouseUser, Workloadfrom posthog.clickhouse.client.execute_async import QueryNotFoundError, enqueue_process_query_task, get_query_status@@ -125,9 +130,10 @@ from posthog.clickhouse.client.limit import ()from posthog.clickhouse.query_tagging import get_query_tag_value, is_api_key_access_method, tag_queriesfrom posthog.constants import AvailableFeature+from posthog.dataclasses import frozenfrom posthog.errors import QueryErrorCategory, classify_query_error, clickhouse_error_typefrom posthog.event_usage import AnalyticsProps, groups, report_user_or_team_action-from posthog.exceptions import APIQueriesQuotaExceeded+from posthog.exceptions import APIQueriesBudgetExceededfrom posthog.exceptions_capture import capture_exceptionfrom posthog.hogql_queries.access_controlled_resources import queried_access_controlled_resourcesfrom posthog.hogql_queries.query_failure_handling import (@@ -200,12 +206,18 @@ SURVEY_QUERY_EXECUTION_DURATION = Histogram(buckets=[0.05, 0.1, 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 5.0, 7.5, 10.0, 15.0, 20.0, 30.0, 60.0, 120.0],)-API_QUERIES_QUOTA_ENFORCEMENT_FLAG = "api-queries-quota-enforcement"+API_QUERIES_BUDGET_ENFORCEMENT_FLAG = "api-queries-budget-enforcement"++API_QUERIES_BUDGET_LIMITED_COUNTER = Counter(+ "posthog_api_queries_budget_limited_total",+ "Query executions for teams whose hourly api queries read budget is exhausted.",+ labelnames=["outcome"], # observed | enforced+)-API_QUERIES_QUOTA_LIMITED_COUNTER = Counter(- "posthog_api_queries_quota_limited_total",- "Query executions for teams whose organization is over its api_queries_read_bytes quota.",- labelnames=["surface", "outcome"], # surface: api; outcome: observed | enforced+API_QUERIES_BUDGET_BALANCE_HISTOGRAM = Histogram(+ "posthog_api_queries_budget_balance_bytes",+ "Balance of the team's hourly api queries read budget at each admission check. Negative is debt.",+ buckets=[-1e11, -1e10, -1e9, -1e8, 0, 1e8, 1e9, 1e10, 1e11, 1e12],)@@ -328,6 +340,9 @@ def _classify_error_for_slo(exc: Exception) -> tuple[QueryErrorCategory, SloOutc"""if isinstance(exc, UserAccessControlError):return QueryErrorCategory.USER_ERROR, SloOutcome.SUCCESS+ if isinstance(exc, APIQueriesBudgetExceeded):+ # A team over its budget is refused on purpose, not a platform failure.+ return QueryErrorCategory.RATE_LIMITED, SloOutcome.SUCCESScategory = classify_query_error(exc)if category in (QueryErrorCategory.USER_ERROR, QueryErrorCategory.RATE_LIMITED, QueryErrorCategory.CANCELLED):return category, SloOutcome.SUCCESS@@ -365,27 +380,12 @@ def shared_insights_execution_mode(execution_mode: ExecutionMode) -> SharedExecu)-def get_api_queries_quota_limited_until(team: Team) -> Optional[datetime]:- if not django_settings.API_QUERIES_FREE_TIER_READ_BYTES_LIMIT:- return None- try:- if team.organization.has_active_subscription is not False:- return None- if get_api_queries_bytes(str(team.organization_id)) <= django_settings.API_QUERIES_FREE_TIER_READ_BYTES_LIMIT:- return None- return next_counter_reset(datetime.now(UTC))- except Exception as e:- API_QUERIES_QUOTA_ERRORS_COUNTER.labels(op="check").inc()- capture_exception(e)- return None---def _api_queries_enforcement_enabled(team: Team) -> bool:+def _api_queries_budget_enforcement_enabled(team: Team) -> bool:org_id = str(team.organization_id)try:return bool(posthoganalytics.feature_enabled(- API_QUERIES_QUOTA_ENFORCEMENT_FLAG,+ API_QUERIES_BUDGET_ENFORCEMENT_FLAG,org_id,groups={"organization": org_id},group_properties={"organization": {"id": org_id}},@@ -397,32 +397,28 @@ def _api_queries_enforcement_enabled(team: Team) -> bool:return False-def _format_data_size(bytes_count: int) -> str:- # Decimal units, to match how the allowance is defined (50 TB = 50e12 bytes).- for unit, size in (("TB", 1_000_000_000_000), ("GB", 1_000_000_000), ("MB", 1_000_000)):- if bytes_count >= size:- value = f"{bytes_count / size:.1f}".removesuffix(".0")- return f"{value} {unit}"- return f"{bytes_count:,} bytes"+@frozen+class BudgetStatus:+ remaining_bytes: float+ spec: BudgetSpec+ retry_after_seconds: int-def _api_queries_quota_detail(*, used: int, limit: int, limited_until: datetime, project_timezone: str) -> str:+def get_api_queries_budget_status(team: Team) -> Optional[BudgetStatus]:+ if not budget_enabled():+ return Nonetry:- local = limited_until.astimezone(ZoneInfo(project_timezone))- except Exception:- local = limited_until- reset = f"{local:%B} {local.day}, {local.year}"- # The reset is midnight UTC, so in most project timezones it lands mid-day; show the- # time whenever it isn't local midnight.- if local.hour or local.minute:- reset += f" at {local:%H:%M}"- reset += f" ({local.tzinfo})"- return (- f"Your organization used {_format_data_size(used)} of its {_format_data_size(limit)} "- "monthly free allowance for API queries. "- f"The allowance resets on {reset}. "- "Upgrade your plan in Billing settings to restore access sooner, or ask an org admin to do so."- )+ spec = budget_spec_for(team.organization)+ remaining = refill_and_read(str(team.pk), spec)+ if remaining is None:+ return None+ return BudgetStatus(+ remaining_bytes=remaining, spec=spec, retry_after_seconds=seconds_until_positive(remaining, spec)+ )+ except Exception as e:+ API_QUERIES_BUDGET_ERRORS_COUNTER.labels(op="check").inc()+ capture_exception(e)+ return NoneRunnableQueryNode = Union[@@ -2077,7 +2073,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):if self.is_query_service:tag_queries(chargeable=1)- self._enforce_api_queries_quota()+ self._enforce_api_queries_budget()with (get_materialized_endpoints_rate_limiter().run(@@ -2542,35 +2538,30 @@ class QueryRunner(ABC, Generic[Q, R, CR]):feature = self.team.organization.get_available_feature(AvailableFeature.API_QUERIES_CONCURRENCY)return feature.get("limit") if feature else None- def _enforce_api_queries_quota(self) -> None:- """402 chargeable API queries for orgs over quota, when enforcement is flagged on.-- Observe-only (counter, no block) when the flag is off. Never blocks unless the- live counter confirms over-quota.- """- limited_until = get_api_queries_quota_limited_until(self.team)- if limited_until is None:+ def _enforce_api_queries_budget(self) -> None:+ """Hourly read budget for api key queries. Observe-only until the org is flagged in;+ then an exhausted budget is a 429. The query that crosses the line still runs in full,+ since the budget is debited after the query and the next request is the one refused."""+ status = get_api_queries_budget_status(self.team)+ if status is None:+ return+ API_QUERIES_BUDGET_BALANCE_HISTOGRAM.observe(status.remaining_bytes)+ if status.remaining_bytes > 0:return- used = get_api_queries_bytes(str(self.team.organization_id))- limit = django_settings.API_QUERIES_FREE_TIER_READ_BYTES_LIMIT- outcome = "enforced" if _api_queries_enforcement_enabled(self.team) else "observed"- API_QUERIES_QUOTA_LIMITED_COUNTER.labels(surface="api", outcome=outcome).inc()+ enforced = _api_queries_budget_enforcement_enabled(self.team)+ outcome = "enforced" if enforced else "observed"+ API_QUERIES_BUDGET_LIMITED_COUNTER.labels(outcome=outcome).inc()logger.info(- "api_queries_quota_limited",+ "api_queries_budget_limited",organization_id=str(self.team.organization_id),team_id=self.team.pk,- usage_bytes=used,- limit_bytes=limit,- limited_until=limited_until.isoformat(),+ remaining_bytes=status.remaining_bytes,+ bytes_per_hour=status.spec.bytes_per_hour,+ retry_after_seconds=status.retry_after_seconds,outcome=outcome,)- if outcome == "observed":- return- raise APIQueriesQuotaExceeded(- detail=_api_queries_quota_detail(- used=used, limit=limit, limited_until=limited_until, project_timezone=self.team.timezone- )- )+ if outcome == "enforced":+ raise APIQueriesBudgetExceeded(wait=status.retry_after_seconds)@abstractmethoddef to_query(self) -> ast.SelectQuery | ast.SelectSetQuery:diff --git a/posthog/hogql_queries/test/test_api_queries_budget.py b/posthog/hogql_queries/test/test_api_queries_budget.pynew file mode 100644index 000000000000..9009e3a759d9--- /dev/null+++ b/posthog/hogql_queries/test/test_api_queries_budget.py@@ -0,0 +1,106 @@+import pytest+from posthog.test.base import BaseTest+from unittest.mock import patch++from django.test import override_settings++from parameterized import parameterized++from posthog.schema import HogQLQuery++from posthog.api_queries_budget import budget_spec_for, debit, refill_and_read+from posthog.exceptions import APIQueriesBudgetExceeded+from posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner+from posthog.hogql_queries.query_runner import (+ API_QUERIES_BUDGET_BALANCE_HISTOGRAM,+ API_QUERIES_BUDGET_LIMITED_COUNTER,+ get_api_queries_budget_status,+)+++@override_settings(API_QUERIES_BUDGET_FREE_BYTES_PER_HOUR=3600, API_QUERIES_BUDGET_CAPACITY_HOURS=1)+class TestApiQueriesBudgetEnforcement(BaseTest):+ def setUp(self):+ super().setUp()+ self.organization.has_active_subscription = False+ self.organization.save()++ def _runner(self, is_query_service: bool = True) -> HogQLQueryRunner:+ runner = HogQLQueryRunner(query=HogQLQuery(query="SELECT 1"), team=self.team)+ runner.is_query_service = is_query_service+ return runner++ def _drain(self) -> None:+ refill_and_read(str(self.team.pk), budget_spec_for(self.organization))+ debit(str(self.team.pk), 10_000)++ def test_status_reports_remaining_and_retry_after(self):+ self._drain()+ status = get_api_queries_budget_status(self.team)+ assert status is not None+ assert status.remaining_bytes < 0+ assert status.retry_after_seconds > 0++ @override_settings(API_QUERIES_BUDGET_FREE_BYTES_PER_HOUR=0)+ def test_disabled_budget_has_no_status(self):+ assert get_api_queries_budget_status(self.team) is None++ def test_redis_error_admits(self):+ with patch("posthog.hogql_queries.query_runner.refill_and_read", return_value=None):+ assert get_api_queries_budget_status(self.team) is None++ @parameterized.expand([("observed", False), ("enforced", True)])+ def test_over_budget_is_counted_and_only_refused_when_enforced(self, outcome, enforced):+ self._drain()+ before = API_QUERIES_BUDGET_LIMITED_COUNTER.labels(outcome=outcome)._value.get()+ with patch("posthog.hogql_queries.query_runner._api_queries_budget_enforcement_enabled", return_value=enforced):+ if enforced:+ with pytest.raises(APIQueriesBudgetExceeded) as excinfo:+ self._runner()._enforce_api_queries_budget()+ assert excinfo.value.status_code == 429+ assert (excinfo.value.wait or 0) > 0+ else:+ self._runner()._enforce_api_queries_budget()+ assert API_QUERIES_BUDGET_LIMITED_COUNTER.labels(outcome=outcome)._value.get() == before + 1++ def test_under_budget_admits_without_touching_the_counter_even_when_enforced(self):+ refill_and_read(str(self.team.pk), budget_spec_for(self.organization))+ before = API_QUERIES_BUDGET_LIMITED_COUNTER.labels(outcome="enforced")._value.get()+ checks_before = sum(bucket.get() for bucket in API_QUERIES_BUDGET_BALANCE_HISTOGRAM._buckets)+ with patch("posthog.hogql_queries.query_runner._api_queries_budget_enforcement_enabled", return_value=True):+ self._runner()._enforce_api_queries_budget()+ assert API_QUERIES_BUDGET_LIMITED_COUNTER.labels(outcome="enforced")._value.get() == before+ assert sum(bucket.get() for bucket in API_QUERIES_BUDGET_BALANCE_HISTOGRAM._buckets) == checks_before + 1++ def test_flag_service_error_fails_open_to_observe(self):+ self._drain()+ with patch(+ "posthog.hogql_queries.query_runner.posthoganalytics.feature_enabled",+ side_effect=Exception("flag service down"),+ ):+ 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):+ 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"++ def test_concurrency_limit_ignores_billing_quota_limited_teams(self):+ # get_api_queries_concurrency_limit reads the plain `posthog.settings` module+ # (not django.conf.settings), so @override_settings on the class doesn't reach it.+ runner = self._runner()+ with (+ patch("posthog.hogql_queries.query_runner.settings.API_QUERIES_ENABLED", True),+ patch("ee.billing.quota_limiting.list_limited_team_attributes", return_value=[self.team.api_token]),+ ):+ assert runner.get_api_queries_concurrency_limit() != 0diff --git a/posthog/hogql_queries/test/test_api_queries_quota.py b/posthog/hogql_queries/test/test_api_queries_quota.pydeleted file mode 100644index a491fc853438..000000000000--- a/posthog/hogql_queries/test/test_api_queries_quota.py+++ /dev/null@@ -1,209 +0,0 @@-from datetime import UTC, datetime--import pytest-from posthog.test.base import BaseTest-from unittest.mock import patch--from django.test import SimpleTestCase, override_settings--from parameterized import parameterized--from posthog.schema import HogQLQuery--from posthog.api_queries_quota import API_QUERIES_QUOTA_ERRORS_COUNTER, increment_api_queries_bytes-from posthog.exceptions import APIQueriesQuotaExceeded-from posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner-from posthog.hogql_queries.query_runner import (- API_QUERIES_QUOTA_LIMITED_COUNTER,- _api_queries_enforcement_enabled,- _api_queries_quota_detail,- _format_data_size,- get_api_queries_quota_limited_until,-)---@override_settings(API_QUERIES_FREE_TIER_READ_BYTES_LIMIT=1000)-class TestGetApiQueriesQuotaLimitedUntil(BaseTest):- def _set(self, has_active_subscription, counter_bytes):- self.organization.has_active_subscription = has_active_subscription- self.organization.save()- if counter_bytes:- increment_api_queries_bytes(str(self.organization.id), counter_bytes)-- @parameterized.expand(- [- # (has_active_subscription, counter_bytes, expect_limited)- ("free_over_limit", False, 2000, True),- ("free_under_limit", False, 500, False),- ("paying_over_limit", True, 2000, False),- ("unknown_subscription_over_limit", None, 2000, False),- ]- )- def test_check_matrix(self, _name, has_active_subscription, counter_bytes, expect_limited):- self._set(has_active_subscription, counter_bytes)- result = get_api_queries_quota_limited_until(self.team)- if expect_limited:- assert result is not None and result.tzinfo is not None- else:- assert result is None-- @override_settings(API_QUERIES_FREE_TIER_READ_BYTES_LIMIT=0)- def test_zero_setting_disables(self):- self._set(False, 2000)- assert get_api_queries_quota_limited_until(self.team) is None-- def test_counter_error_fails_open(self):- self._set(False, 2000)- with patch("posthog.hogql_queries.query_runner.get_api_queries_bytes", side_effect=Exception("redis down")):- assert get_api_queries_quota_limited_until(self.team) is None-- def test_counter_error_increments_error_counter(self):- self._set(False, 2000)- before = API_QUERIES_QUOTA_ERRORS_COUNTER.labels(op="check")._value.get()- with patch("posthog.hogql_queries.query_runner.get_api_queries_bytes", side_effect=Exception("redis down")):- get_api_queries_quota_limited_until(self.team)- after = API_QUERIES_QUOTA_ERRORS_COUNTER.labels(op="check")._value.get()- assert after == before + 1---class TestApiQueriesQuotaDetail(SimpleTestCase):- def test_detail_includes_usage_limit_and_reset(self):- detail = _api_queries_quota_detail(- used=62_500_000_000_000,- limit=50_000_000_000_000,- limited_until=datetime(2026, 9, 1, tzinfo=UTC),- project_timezone="UTC",- )- assert "62.5 TB" in detail- assert "50 TB" in detail- assert "September 1, 2026 (UTC)" in detail- assert "Billing settings" in detail-- def test_detail_renders_reset_in_project_timezone(self):- detail = _api_queries_quota_detail(- used=62_500_000_000_000,- limit=50_000_000_000_000,- limited_until=datetime(2026, 9, 1, tzinfo=UTC),- project_timezone="America/Los_Angeles",- )- assert "August 31, 2026 at 17:00 (America/Los_Angeles)" in detail-- def test_detail_falls_back_to_utc_on_bad_timezone(self):- detail = _api_queries_quota_detail(- used=62_500_000_000_000,- limit=50_000_000_000_000,- limited_until=datetime(2026, 9, 1, tzinfo=UTC),- project_timezone="Not/AZone",- )- assert "September 1, 2026 (UTC)" in detail-- @parameterized.expand(- [- ("terabytes_trimmed", 50_000_000_000_000, "50 TB"),- ("terabytes_fraction", 62_500_000_000_000, "62.5 TB"),- ("gigabytes", 500_000_000_000, "500 GB"),- ("small_values_stay_bytes", 999, "999 bytes"),- ]- )- def test_format_data_size(self, _name, bytes_count, expected):- assert _format_data_size(bytes_count) == expected---class TestApiQueriesEnforcementEnabled(BaseTest):- def test_flag_on_returns_true(self):- with patch("posthog.hogql_queries.query_runner.posthoganalytics.feature_enabled", return_value=True):- assert _api_queries_enforcement_enabled(self.team) is True-- def test_flag_service_error_fails_open_to_false(self):- with patch(- "posthog.hogql_queries.query_runner.posthoganalytics.feature_enabled",- side_effect=Exception("flag service down"),- ):- assert _api_queries_enforcement_enabled(self.team) is False---class TestApiQueriesQuotaEnforcement(BaseTest):- def _runner(self):- runner = HogQLQueryRunner(query=HogQLQuery(query="select 1"), team=self.team)- runner.is_query_service = True- return runner-- def test_not_limited_is_noop(self):- with patch("posthog.hogql_queries.query_runner.get_api_queries_quota_limited_until", return_value=None):- self._runner()._enforce_api_queries_quota() # must not raise-- def test_limited_flag_off_observes_and_runs(self):- before = API_QUERIES_QUOTA_LIMITED_COUNTER.labels(surface="api", outcome="observed")._value.get()- with (- patch(- "posthog.hogql_queries.query_runner.get_api_queries_quota_limited_until",- return_value=datetime(2026, 9, 1, tzinfo=UTC),- ),- patch("posthog.hogql_queries.query_runner._api_queries_enforcement_enabled", return_value=False),- ):- self._runner()._enforce_api_queries_quota() # must not raise- after = API_QUERIES_QUOTA_LIMITED_COUNTER.labels(surface="api", outcome="observed")._value.get()- assert after == before + 1-- def test_limited_flag_on_raises_402(self):- before = API_QUERIES_QUOTA_LIMITED_COUNTER.labels(surface="api", outcome="enforced")._value.get()- with (- patch(- "posthog.hogql_queries.query_runner.get_api_queries_quota_limited_until",- return_value=datetime(2026, 9, 1, tzinfo=UTC),- ),- patch("posthog.hogql_queries.query_runner._api_queries_enforcement_enabled", return_value=True),- ):- with pytest.raises(APIQueriesQuotaExceeded) as exc_info:- self._runner()._enforce_api_queries_quota()- assert exc_info.value.status_code == 402- after = API_QUERIES_QUOTA_LIMITED_COUNTER.labels(surface="api", outcome="enforced")._value.get()- assert after == before + 1-- def test_flag_service_error_fails_open_to_observe(self):- with (- patch(- "posthog.hogql_queries.query_runner.get_api_queries_quota_limited_until",- return_value=datetime(2026, 9, 1, tzinfo=UTC),- ),- patch(- "posthog.hogql_queries.query_runner.posthoganalytics.feature_enabled",- side_effect=Exception("flag service down"),- ),- ):- self._runner()._enforce_api_queries_quota() # must not raise-- def test_call_with_rate_limits_enforces_quota_for_query_service(self):- runner = self._runner()- with (- patch.object(runner, "calculate", return_value="stub result"),- patch(- "posthog.hogql_queries.query_runner.get_api_queries_quota_limited_until",- return_value=datetime(2026, 9, 1, tzinfo=UTC),- ),- patch("posthog.hogql_queries.query_runner._api_queries_enforcement_enabled", return_value=True),- ):- with pytest.raises(APIQueriesQuotaExceeded):- runner._call_with_rate_limits(dashboard_id=None)-- def test_call_with_rate_limits_skips_enforcement_for_non_query_service(self):- runner = HogQLQueryRunner(query=HogQLQuery(query="select 1"), team=self.team)- runner.is_query_service = False- with (- patch.object(runner, "calculate", return_value="stub result"),- patch("posthog.hogql_queries.query_runner.get_api_queries_quota_limited_until") as check,- ):- result, _duration_ms = runner._call_with_rate_limits(dashboard_id=None)- assert result == "stub result"- check.assert_not_called()-- def test_concurrency_limit_no_longer_returns_zero_for_limited_teams(self):- # get_api_queries_concurrency_limit reads the plain `posthog.settings` module- # (not django.conf.settings), so @override_settings on the class doesn't reach it.- runner = self._runner()- with (- patch("posthog.hogql_queries.query_runner.settings.API_QUERIES_ENABLED", True),- patch("ee.billing.quota_limiting.list_limited_team_attributes", return_value=[self.team.api_token]),- ):- # Quota state (list_limited_team_attributes) must not affect the concurrency limit.- assert runner.get_api_queries_concurrency_limit() != 0diff --git a/posthog/schema.py b/posthog/schema.pyindex 149a3b2ac09a..3bd4fee267ef 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -6677,6 +6677,8 @@ class QueryStatus(BaseModel):model_config = ConfigDict(extra="forbid",)+ budget_remaining_bytes: int | None = None+ bytes_read: int | None = Nonecomplete: bool | None = Field(default=False,description=(diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 2b67be8364ce..20853f05f5ff 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -907,11 +907,11 @@ KAFKA_PRODUCE_ACK_TIMEOUT_SECONDS = int(os.getenv("KAFKA_PRODUCE_ACK_TIMEOUT_SEC# if `true` we highly increase the rate limit on /query endpoint and limit the number of concurrent queriesAPI_QUERIES_ENABLED = get_from_env("API_QUERIES_ENABLED", False, type_cast=str_to_bool)-# Monthly read-bytes allowance for organizations without an active subscription,-# enforced from the product-owned counter in posthog/api_queries_quota.py. 0 disables it.-API_QUERIES_FREE_TIER_READ_BYTES_LIMIT: int = get_from_env(- "API_QUERIES_FREE_TIER_READ_BYTES_LIMIT", 50_000_000_000_000, type_cast=int+API_QUERIES_BUDGET_FREE_BYTES_PER_HOUR: int = get_from_env(+ "API_QUERIES_BUDGET_FREE_BYTES_PER_HOUR", 20_000_000_000, type_cast=int)+API_QUERIES_BUDGET_PAID_MULTIPLIER: float = get_from_env("API_QUERIES_BUDGET_PAID_MULTIPLIER", 10.0, type_cast=float)+API_QUERIES_BUDGET_CAPACITY_HOURS: float = get_from_env("API_QUERIES_BUDGET_CAPACITY_HOURS", 24.0, type_cast=float)##### /api/environments deprecationdiff --git a/posthog/test/test_api_queries_budget.py b/posthog/test/test_api_queries_budget.pynew file mode 100644index 000000000000..9d2e537351de--- /dev/null+++ b/posthog/test/test_api_queries_budget.py@@ -0,0 +1,147 @@+from types import SimpleNamespace++import pytest+from posthog.test.base import BaseTest, ClickhouseTestMixin+from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase, override_settings++from parameterized import parameterized++from posthog.api_queries_budget import (+ API_QUERIES_BUDGET_ERRORS_COUNTER,+ BudgetSpec,+ QueryCost,+ budget_spec_for,+ debit,+ get_request_query_cost,+ record_request_query_cost,+ refill_and_read,+ reset_request_query_cost,+ seconds_until_positive,+)+from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.query_tagging import reset_query_tags, tag_queries++SPEC = BudgetSpec(bytes_per_hour=3600.0, capacity_bytes=7200.0)+++@override_settings(+ API_QUERIES_BUDGET_FREE_BYTES_PER_HOUR=70_000_000_000,+ API_QUERIES_BUDGET_PAID_MULTIPLIER=10,+ API_QUERIES_BUDGET_CAPACITY_HOURS=24,+)+class TestBudgetSpecFor(SimpleTestCase):+ @parameterized.expand(+ [+ ("free", False, 70e9, 1680e9),+ ("paying", True, 700e9, 16800e9),+ ("unknown_fails_open_to_paying", None, 700e9, 16800e9),+ ]+ )+ def test_spec_by_subscription(self, _name, has_active_subscription, per_hour, capacity):+ organization = SimpleNamespace(has_active_subscription=has_active_subscription)+ assert budget_spec_for(organization) == BudgetSpec(bytes_per_hour=per_hour, capacity_bytes=capacity)+++@override_settings(API_QUERIES_BUDGET_FREE_BYTES_PER_HOUR=70, API_QUERIES_BUDGET_CAPACITY_HOURS=24)+class TestTokenBucket(BaseTest):+ def test_fresh_bucket_starts_full(self):+ assert refill_and_read("team-a", SPEC, now=1000.0) == 7200.0++ def test_debit_then_refill_at_rate_capped_at_capacity(self):+ refill_and_read("team-a", SPEC, now=1000.0)+ assert debit("team-a", 5000) == 2200.0+ assert refill_and_read("team-a", SPEC, now=1001.0) == 2201.0+ assert refill_and_read("team-a", SPEC, now=99999.0) == 7200.0++ def test_negative_balance_reports_seconds_until_positive(self):+ refill_and_read("team-a", SPEC, now=1000.0)+ remaining = debit("team-a", 9000)+ assert remaining == -1800.0+ assert seconds_until_positive(remaining, SPEC) == 1800+ assert seconds_until_positive(5.0, SPEC) == 0+ assert seconds_until_positive(0.0, SPEC) == 1++ def test_balance_floors_at_minus_one_hour_of_refill(self):+ refill_and_read("team-a", SPEC, now=1000.0)+ assert debit("team-a", 50_000) == -3600.0+ assert seconds_until_positive(-3600.0, SPEC) == 3600+ assert refill_and_read("team-a", SPEC, now=1000.0 + 3600) == 0.0++ def test_debit_before_any_read_uses_the_free_capacity_and_floor(self):+ assert debit("team-new", 100) == 1580.0+ assert debit("team-new", 100) == 1480.0+ assert debit("team-new", 5000) == -70.0++ @override_settings(API_QUERIES_BUDGET_FREE_BYTES_PER_HOUR=0)+ def test_disabled_budget_does_not_debit(self):+ assert debit("team-a", 1000) is None++ def test_redis_errors_fail_open_and_count(self):+ read_before = API_QUERIES_BUDGET_ERRORS_COUNTER.labels(op="read")._value.get()+ debit_before = API_QUERIES_BUDGET_ERRORS_COUNTER.labels(op="debit")._value.get()+ with patch("posthog.api_queries_budget.get_client", side_effect=Exception("redis down")):+ assert refill_and_read("team-a", SPEC) is None+ assert debit("team-a", 1) is None+ assert API_QUERIES_BUDGET_ERRORS_COUNTER.labels(op="read")._value.get() == read_before + 1+ assert API_QUERIES_BUDGET_ERRORS_COUNTER.labels(op="debit")._value.get() == debit_before + 1+++class TestRequestQueryCost(SimpleTestCase):+ def test_costs_accumulate_within_a_request_and_reset_between(self):+ reset_request_query_cost()+ assert get_request_query_cost() is None+ record_request_query_cost(QueryCost(bytes_read=100, remaining_bytes=50.0))+ record_request_query_cost(QueryCost(bytes_read=50, remaining_bytes=None))+ assert get_request_query_cost() == QueryCost(bytes_read=150, remaining_bytes=50.0)+ reset_request_query_cost()+ assert get_request_query_cost() is None+++class TestChargeableQueryMetering(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)"++ def setUp(self):+ super().setUp()+ reset_request_query_cost()++ def test_chargeable_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)+ 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+ assert cost.remaining_bytes is not None and cost.remaining_bytes < spec.capacity_bytes++ def test_untagged_query_is_not_metered(self):+ sync_execute(self.BOUNDED_QUERY)+ assert get_request_query_cost() is None+++class QueryDied(Exception):+ pass+++class TestFailedQueryMetering(BaseTest):+ def test_connection_failure_does_not_remeter_previous_query(self):+ reset_request_query_cost()+ fake_client = MagicMock()+ fake_client.last_query = SimpleNamespace(progress=SimpleNamespace(bytes=9999))+ 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)+ try:+ with patch("posthog.clickhouse.client.execute.get_client_from_pool", return_value=pool):+ with pytest.raises(QueryDied):+ sync_execute("SELECT 1")+ finally:+ reset_query_tags()+ assert get_request_query_cost() is Nonediff --git a/posthog/test/test_api_queries_quota_counter.py b/posthog/test/test_api_queries_quota_counter.pydeleted file mode 100644index 11958456f2f8..000000000000--- a/posthog/test/test_api_queries_quota_counter.py+++ /dev/null@@ -1,105 +0,0 @@-from datetime import UTC, datetime-from types import SimpleNamespace--import pytest-from posthog.test.base import BaseTest, ClickhouseTestMixin-from unittest.mock import MagicMock, patch--from posthog.api_queries_quota import (- API_QUERIES_QUOTA_ERRORS_COUNTER,- get_api_queries_bytes,- increment_api_queries_bytes,- next_counter_reset,-)-from posthog.clickhouse.client import sync_execute-from posthog.clickhouse.query_tagging import reset_query_tags, tag_queries---class TestApiQueriesQuotaCounter(BaseTest):- def test_increment_then_read_round_trips(self):- increment_api_queries_bytes("org-a", 1000)- increment_api_queries_bytes("org-a", 500)- assert get_api_queries_bytes("org-a") == 1500-- def test_missing_key_reads_zero(self):- assert get_api_queries_bytes("org-never-seen") == 0-- def test_zero_bytes_is_noop(self):- increment_api_queries_bytes("org-a", 0)- assert get_api_queries_bytes("org-a") == 0-- def test_redis_errors_fail_open(self):- with patch("posthog.api_queries_quota.get_client", side_effect=Exception("redis down")):- increment_api_queries_bytes("org-a", 1000) # must not raise- assert get_api_queries_bytes("org-a") == 0-- def test_increment_error_increments_error_counter(self):- before = API_QUERIES_QUOTA_ERRORS_COUNTER.labels(op="increment")._value.get()- with patch("posthog.api_queries_quota.get_client", side_effect=Exception("redis down")):- increment_api_queries_bytes("org-a", 1000)- after = API_QUERIES_QUOTA_ERRORS_COUNTER.labels(op="increment")._value.get()- assert after == before + 1-- def test_read_error_increments_error_counter(self):- before = API_QUERIES_QUOTA_ERRORS_COUNTER.labels(op="read")._value.get()- with patch("posthog.api_queries_quota.get_client", side_effect=Exception("redis down")):- get_api_queries_bytes("org-a")- after = API_QUERIES_QUOTA_ERRORS_COUNTER.labels(op="read")._value.get()- assert after == before + 1-- def test_next_counter_reset_rolls_month_and_year(self):- assert next_counter_reset(datetime(2026, 8, 12, tzinfo=UTC)) == datetime(2026, 9, 1, tzinfo=UTC)- assert next_counter_reset(datetime(2026, 12, 31, tzinfo=UTC)) == datetime(2027, 1, 1, tzinfo=UTC)---class TestChargeableByteMetering(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)"-- def test_chargeable_tagged_query_increments_counter(self):- tag_queries(chargeable=1, org_id=self.organization.id)- try:- sync_execute(self.BOUNDED_QUERY)- finally:- reset_query_tags()- assert get_api_queries_bytes(str(self.organization.id)) > 0-- def test_untagged_query_does_not_count(self):- sync_execute(self.BOUNDED_QUERY)- assert get_api_queries_bytes(str(self.organization.id)) == 0---class QueryDied(Exception):- pass---class TestFailedQueryMetering(BaseTest):- def _sync_execute_with_fake_client(self, fake_client):- pool = MagicMock()- pool.__enter__.return_value = fake_client- tag_queries(chargeable=1, org_id=self.organization.id)- try:- with patch("posthog.clickhouse.client.execute.get_client_from_pool", return_value=pool):- with pytest.raises(QueryDied):- sync_execute("SELECT 1")- finally:- reset_query_tags()-- def test_killed_query_meters_progress_reported_before_death(self):- fake_client = MagicMock()-- def die_mid_scan(*args, **kwargs):- fake_client.last_query = SimpleNamespace(progress=SimpleNamespace(bytes=4444))- raise QueryDied("timeout")-- fake_client.execute.side_effect = die_mid_scan- self._sync_execute_with_fake_client(fake_client)- assert get_api_queries_bytes(str(self.organization.id)) == 4444-- def test_connection_failure_does_not_remeter_previous_query(self):- fake_client = MagicMock()- fake_client.last_query = SimpleNamespace(progress=SimpleNamespace(bytes=9999))- fake_client.execute.side_effect = QueryDied("network down before connecting")- self._sync_execute_with_fake_client(fake_client)- assert get_api_queries_bytes(str(self.organization.id)) == 0diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 7fe55b31223a..be2bc6646f0e 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -1383,6 +1383,8 @@ export interface ClickhouseQueryProgressApi {}export interface QueryStatusApi {+ budget_remaining_bytes?: number | null+ bytes_read?: number | null/** Whether the query is still running. Will be true if the query is complete, even if it errored. Either result or error will be set. */complete?: boolean | nulldashboard_id?: number | nulldiff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex ad5240b6ab4e..b5c7400829cb 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -1911,6 +1911,8 @@ export interface ClickhouseQueryProgressApi {}export interface QueryStatusApi {+ budget_remaining_bytes?: number | null+ bytes_read?: number | null/** Whether the query is still running. Will be true if the query is complete, even if it errored. Either result or error will be set. */complete?: boolean | nulldashboard_id?: number | nulldiff --git a/products/endpoints/frontend/generated/api.schemas.ts b/products/endpoints/frontend/generated/api.schemas.tsindex 6867adbcc978..4fa5b28cf78b 100644--- a/products/endpoints/frontend/generated/api.schemas.ts+++ b/products/endpoints/frontend/generated/api.schemas.ts@@ -1013,6 +1013,8 @@ export interface ClickhouseQueryProgressApi {}export interface QueryStatusApi {+ budget_remaining_bytes?: number | null+ bytes_read?: number | null/** Whether the query is still running. Will be true if the query is complete, even if it errored. Either result or error will be set. */complete?: boolean | nulldashboard_id?: number | nulldiff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex b184406a8a96..88366b5d3230 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -949,6 +949,8 @@ export interface ClickhouseQueryProgressApi {}export interface QueryStatusApi {+ budget_remaining_bytes?: number | null+ bytes_read?: number | null/** Whether the query is still running. Will be true if the query is complete, even if it errored. Either result or error will be set. */complete?: boolean | nulldashboard_id?: number | nulldiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ac169e94b017..3f50fe544738 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -1046,6 +1046,8 @@ export namespace Schemas {}export interface QueryStatus {+ budget_remaining_bytes?: number | null;+ bytes_read?: number | null;/** Whether the query is still running. Will be true if the query is complete, even if it errored. Either result or error will be set. */complete?: boolean | null;dashboard_id?: number | null;