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.

feat(api): scale the hourly read budget with each team's events in the last year (#102570)

Andy Zhao79d69c1f937e
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.py
index fcb3c71a31ad..695e1b076907 100644
--- a/.github/scripts/check-idor-model-coverage.py
+++ b/.github/scripts/check-idor-model-coverage.py
@@ -209,6 +209,7 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
"TeamFeatureFlagPolicyConfig",
# OneToOne extension keyed on the authorized Team; no independently addressable config ID.
"TeamHeatmapConfig",
+ "TeamEventVolume",
"TeamTasksConfig",
"TeamLogsConfig",
"TeamMarketingAnalyticsConfig",
diff --git a/posthog/api_queries_budget.py b/posthog/api_queries_budget.py
index 42fb0ce6e241..20b30803e659 100644
--- a/posthog/api_queries_budget.py
+++ b/posthog/api_queries_budget.py
@@ -1,8 +1,10 @@
"""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
+Each team has a token bucket in Redis measured in bytes read. The rate starts 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
+refill API_QUERIES_BUDGET_PAID_MULTIPLIER times faster. It then grows with the events the team
+ingested in the last year (TeamEventVolume, refreshed nightly), up to
+API_QUERIES_BUDGET_MAX_BYTES_PER_HOUR. The ClickHouse client debits what every
budgeted 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
@@ -73,13 +75,14 @@ def _free_spec() -> BudgetSpec:
return _spec(float(settings.API_QUERIES_BUDGET_FREE_BYTES_PER_HOUR))
-def budget_spec_for(organization: Any) -> BudgetSpec:
+def budget_spec_for(organization: Any, events_last_year: Optional[int] = None) -> 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)
+ scaled = (events_last_year or 0) * float(settings.API_QUERIES_BUDGET_BYTES_PER_EVENT_PER_HOUR)
+ return _spec(min(max(bytes_per_hour, scaled), float(settings.API_QUERIES_BUDGET_MAX_BYTES_PER_HOUR)))
def _bucket_key(team_id: str) -> str:
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index 4d8392e6f3f2..003b9061da6c 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -129,6 +129,7 @@ class Feature(StrEnum):
EVENTS_VALUES_API = "events_values_api"
SESSIONS_VALUES_API = "sessions_values_api"
USAGE_REPORT = "usage_report"
+ API_QUERIES_BUDGET = "api_queries_budget"
DATA_FRESHNESS = "data_freshness" # "when did this project last receive data" probes
BILLING_ETL = "billing_etl"
QUOTA_LIMITING = "quota_limiting"
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index c1487313a828..fbbafef04bf0 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -188,6 +188,7 @@ from posthog.models import Team, User
from posthog.models.instance_setting import get_instance_setting
from posthog.models.team import WeekStartDay
from posthog.models.team.event_retention import events_retention_months_for_team
+from posthog.models.team.team_event_volume import events_last_year_for
from posthog.query_cache import QueryCache, count_query_cache_hit, retention_ttl
from posthog.query_cache.failures import (
BUDGET_EXTENDED,
@@ -539,7 +540,7 @@ def get_api_queries_budget_status(team: Team) -> Optional[BudgetStatus]:
if not budget_enabled():
return None
try:
- spec = budget_spec_for(team.organization)
+ spec = budget_spec_for(team.organization, events_last_year_for(team.pk))
remaining = refill_and_read(str(team.pk), spec)
if remaining is None:
return None
diff --git a/posthog/hogql_queries/test/test_api_queries_budget.py b/posthog/hogql_queries/test/test_api_queries_budget.py
index 5e1c7ee60740..0eed53e5c4a9 100644
--- a/posthog/hogql_queries/test/test_api_queries_budget.py
+++ b/posthog/hogql_queries/test/test_api_queries_budget.py
@@ -5,6 +5,7 @@ from posthog.test.base import BaseTest
from unittest.mock import patch
from django.test import override_settings
+from django.utils import timezone
from parameterized import parameterized
@@ -19,6 +20,7 @@ from posthog.hogql_queries.query_runner import (
API_QUERIES_BUDGET_LIMITED_COUNTER,
get_api_queries_budget_status,
)
+from posthog.models.team.team_event_volume import TeamEventVolume
@override_settings(API_QUERIES_BUDGET_FREE_BYTES_PER_HOUR=3600, API_QUERIES_BUDGET_CAPACITY_HOURS=1)
@@ -52,6 +54,13 @@ class TestApiQueriesBudgetEnforcement(BaseTest):
with patch("posthog.hogql_queries.query_runner.refill_and_read", return_value=None):
assert get_api_queries_budget_status(self.team) is None
+ @override_settings(API_QUERIES_BUDGET_BYTES_PER_EVENT_PER_HOUR=10)
+ def test_status_rate_scales_with_the_teams_event_volume(self):
+ TeamEventVolume.objects.unscoped().create(team=self.team, events_last_year=10_000, computed_at=timezone.now())
+ status = get_api_queries_budget_status(self.team)
+ assert status is not None
+ assert status.spec.bytes_per_hour == 100_000
+
@parameterized.expand([("observed", False), ("enforced", True)])
def test_over_budget_is_counted_and_only_refused_when_enforced(self, outcome, enforced):
self._drain()
diff --git a/posthog/migrations/1389_teameventvolume.py b/posthog/migrations/1389_teameventvolume.py
new file mode 100644
index 000000000000..dbc255de4bc3
--- /dev/null
+++ b/posthog/migrations/1389_teameventvolume.py
@@ -0,0 +1,30 @@
+# Generated by Django 5.2.17 on 2026-09-17 19:27
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1388_activitylog_credential"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="TeamEventVolume",
+ fields=[
+ (
+ "team",
+ models.OneToOneField(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ primary_key=True,
+ serialize=False,
+ to="posthog.team",
+ ),
+ ),
+ ("events_last_year", models.BigIntegerField()),
+ ("computed_at", models.DateTimeField()),
+ ],
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 4628db640b0d..f4cfd85f8bee 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1388_activitylog_credential
+1389_teameventvolume
diff --git a/posthog/models/team/__init__.py b/posthog/models/team/__init__.py
index 9f007cbc3e7d..017e2e6d7d71 100644
--- a/posthog/models/team/__init__.py
+++ b/posthog/models/team/__init__.py
@@ -2,6 +2,7 @@ from .extensions import get_or_create_team_extension, register_team_extension_si
from .js_snippet_config import TeamJsSnippetConfig # noqa: F401
from .team import * # noqa: F403 # legacy: team.py has a large surface (Team, Manager, constants, signals); TODO enumerate explicit re-exports
from .team_caching import get_team_in_cache, set_team_in_cache # noqa: F401
+from .team_event_volume import TeamEventVolume # noqa: F401
from .team_heatmap_config import TeamHeatmapConfig # noqa: F401
from .team_marketing_analytics_config import TeamMarketingAnalyticsConfig # noqa: F401
from .team_provisioning_config import TeamProvisioningConfig # noqa: F401
diff --git a/posthog/models/team/team_event_volume.py b/posthog/models/team/team_event_volume.py
new file mode 100644
index 000000000000..6aac7858ea87
--- /dev/null
+++ b/posthog/models/team/team_event_volume.py
@@ -0,0 +1,20 @@
+from typing import Optional
+
+from django.db import models
+
+from posthog.models.scoping.manager import EnvironmentScopedManager
+from posthog.models.team import Team
+
+
+class TeamEventVolume(models.Model):
+ # Rows come from posthog.tasks.team_event_volume, not from team creation, so this is not
+ # registered as a team extension signal.
+ team = models.OneToOneField(Team, on_delete=models.CASCADE, primary_key=True, db_constraint=False)
+ events_last_year = models.BigIntegerField()
+ computed_at = models.DateTimeField()
+
+ objects = EnvironmentScopedManager()
+
+
+def events_last_year_for(team_id: int) -> Optional[int]:
+ return TeamEventVolume.objects.for_team(team_id).values_list("events_last_year", flat=True).first()
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index d64031ee2ea8..f7fe35c638ec 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -1004,6 +1004,12 @@ API_QUERIES_BUDGET_FREE_BYTES_PER_HOUR: int = get_from_env(
)
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_QUERIES_BUDGET_BYTES_PER_EVENT_PER_HOUR: float = get_from_env(
+ "API_QUERIES_BUDGET_BYTES_PER_EVENT_PER_HOUR", 82_000.0, type_cast=float
+)
+API_QUERIES_BUDGET_MAX_BYTES_PER_HOUR: float = get_from_env(
+ "API_QUERIES_BUDGET_MAX_BYTES_PER_HOUR", 5_000_000_000_000.0, type_cast=float
+)
####
# /api/environments deprecation
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 58e811d0f9f1..3562642229ba 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -68,6 +68,7 @@ from posthog.tasks.tasks import (
update_survey_adaptive_sampling,
update_survey_iteration,
)
+from posthog.tasks.team_event_volume import update_team_event_volumes
from posthog.tasks.team_llm_gateway_policy import refresh_expiring_llm_gateway_policy_cache_entries
from posthog.tasks.team_metadata import cleanup_stale_expiry_tracking_task, refresh_expiring_team_metadata_cache_entries
from posthog.tasks.uploaded_media import sweep_abandoned_media_uploads_task
@@ -320,6 +321,14 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="team metadata expiry tracking cleanup",
)
+ add_periodic_task_with_expiry(
+ sender,
+ crontab(hour="4", minute="0"),
+ update_team_event_volumes.s(),
+ name="team event volume update",
+ expires_seconds=12 * 3600,
+ )
+
# SES tenant reputation reconciliation - daily at 6:30 AM UTC. EventBridge events are the
# real-time path; this sweep catches missed deliveries. Sequential SES API calls per team
# with an SES email integration, so kept daily to stay well inside SES API rate limits.
diff --git a/posthog/tasks/team_event_volume.py b/posthog/tasks/team_event_volume.py
new file mode 100644
index 000000000000..4541935c4363
--- /dev/null
+++ b/posthog/tasks/team_event_volume.py
@@ -0,0 +1,67 @@
+from time import perf_counter
+
+from django.utils import timezone
+
+import structlog
+from celery import shared_task
+
+from posthog.api_queries_budget import budget_enabled
+from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.client.connection import Workload
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.errors import CH_TRANSIENT_ERRORS
+from posthog.models.event.new_events_schema import events_read_table, use_new_events_schema
+from posthog.models.team import Team
+from posthog.models.team.team_event_volume import TeamEventVolume
+from posthog.scoping_audit import skip_team_scope_audit
+
+logger = structlog.get_logger(__name__)
+
+EVENT_VOLUME_DAYS = 365
+
+
+@shared_task(
+ ignore_result=True, autoretry_for=CH_TRANSIENT_ERRORS, retry_backoff=60, retry_backoff_max=600, max_retries=3
+)
+@skip_team_scope_audit
+def update_team_event_volumes() -> None:
+ if not budget_enabled():
+ return
+ started = perf_counter()
+ computed_at = timezone.now()
+ tag_queries(product=Product.INTERNAL, feature=Feature.API_QUERIES_BUDGET)
+ # Timestamps are client-supplied, so a future-dated event would raise the budget until its
+ # timestamp passed. now64() rather than now(), which truncates the sub-second timestamp.
+ rows = sync_execute(
+ f"""
+ SELECT team_id, count() AS events
+ FROM {events_read_table(use_new_events_schema())}
+ WHERE timestamp >= now() - INTERVAL %(days)s DAY AND timestamp <= now64()
+ GROUP BY team_id
+ """,
+ {"days": EVENT_VOLUME_DAYS},
+ workload=Workload.OFFLINE,
+ )
+ team_ids = set(Team.objects.values_list("id", flat=True))
+ volumes = [
+ TeamEventVolume(team_id=team_id, events_last_year=events, computed_at=computed_at)
+ for team_id, events in rows
+ if team_id in team_ids
+ ]
+ TeamEventVolume.objects.unscoped().bulk_create(
+ volumes,
+ update_conflicts=True,
+ update_fields=["events_last_year", "computed_at"],
+ unique_fields=["team"],
+ batch_size=1000,
+ )
+ # A team with no events in the window is absent from the result, so its row is the only one
+ # this run did not stamp.
+ reset = (
+ TeamEventVolume.objects.unscoped()
+ .filter(computed_at__lt=computed_at)
+ .update(events_last_year=0, computed_at=computed_at)
+ )
+ logger.info(
+ "team_event_volumes_updated", teams=len(volumes), reset=reset, seconds=round(perf_counter() - started, 1)
+ )
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index 608628734e79..f28cbec45dda 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -151,6 +151,7 @@
'posthog.tasks.tasks.update_survey_iteration',
'posthog.tasks.team_access_cache_tasks.invalidate_token_cache_task',
'posthog.tasks.team_access_cache_tasks.invalidate_user_tokens_task',
+ 'posthog.tasks.team_event_volume.update_team_event_volumes',
'posthog.tasks.team_llm_gateway_policy.refresh_expiring_llm_gateway_policy_cache_entries',
'posthog.tasks.team_llm_gateway_policy.update_team_llm_gateway_policy_cache_task',
'posthog.tasks.team_metadata.cleanup_stale_expiry_tracking_task',
diff --git a/posthog/tasks/test/test_team_event_volume.py b/posthog/tasks/test/test_team_event_volume.py
new file mode 100644
index 000000000000..f7a3f10679b7
--- /dev/null
+++ b/posthog/tasks/test/test_team_event_volume.py
@@ -0,0 +1,27 @@
+from datetime import timedelta
+
+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+
+from django.utils import timezone
+
+from posthog.models import Team
+from posthog.models.team.team_event_volume import TeamEventVolume
+from posthog.tasks.team_event_volume import update_team_event_volumes
+
+
+class TestUpdateTeamEventVolumes(ClickhouseTestMixin, BaseTest):
+ def test_counts_only_the_last_year_per_team_and_zeroes_teams_that_went_quiet(self) -> None:
+ quiet = Team.objects.create(organization=self.organization, name="quiet")
+ TeamEventVolume.objects.unscoped().create(
+ team=quiet, events_last_year=5, computed_at=timezone.now() - timedelta(days=1)
+ )
+ _create_event(team=self.team, event="e", distinct_id="a", timestamp=timezone.now() - timedelta(days=1))
+ _create_event(team=self.team, event="e", distinct_id="a", timestamp=timezone.now() - timedelta(days=200))
+ _create_event(team=self.team, event="e", distinct_id="a", timestamp=timezone.now() - timedelta(days=400))
+ _create_event(team=self.team, event="e", distinct_id="a", timestamp=timezone.now() + timedelta(days=30))
+ flush_persons_and_events()
+
+ update_team_event_volumes()
+
+ assert TeamEventVolume.objects.for_team(self.team.id).get().events_last_year == 2
+ assert TeamEventVolume.objects.for_team(quiet.id).get().events_last_year == 0
diff --git a/posthog/test/test_api_queries_budget.py b/posthog/test/test_api_queries_budget.py
index 5dfacef06dac..a31c92bcc219 100644
--- a/posthog/test/test_api_queries_budget.py
+++ b/posthog/test/test_api_queries_budget.py
@@ -35,6 +35,8 @@ SPEC = BudgetSpec(bytes_per_hour=3600.0, capacity_bytes=7200.0)
API_QUERIES_BUDGET_FREE_BYTES_PER_HOUR=70_000_000_000,
API_QUERIES_BUDGET_PAID_MULTIPLIER=10,
API_QUERIES_BUDGET_CAPACITY_HOURS=24,
+ API_QUERIES_BUDGET_BYTES_PER_EVENT_PER_HOUR=1_000,
+ API_QUERIES_BUDGET_MAX_BYTES_PER_HOUR=5_000e9,
)
class TestBudgetSpecFor(SimpleTestCase):
@parameterized.expand(
@@ -48,6 +50,19 @@ class TestBudgetSpecFor(SimpleTestCase):
organization = SimpleNamespace(has_active_subscription=has_active_subscription)
assert budget_spec_for(organization) == BudgetSpec(bytes_per_hour=per_hour, capacity_bytes=capacity)
+ @parameterized.expand(
+ [
+ ("unknown_volume_keeps_floor", True, None, 700e9),
+ ("small_volume_keeps_floor", True, 1_000, 700e9),
+ ("volume_scales_above_floor", True, 1_000_000_000, 1_000e9),
+ ("volume_is_capped", True, 100_000_000_000, 5_000e9),
+ ("free_scales_from_its_own_floor", False, 100_000_000, 100e9),
+ ]
+ )
+ def test_spec_scales_with_events_last_year(self, _name, has_active_subscription, events_last_year, per_hour):
+ organization = SimpleNamespace(has_active_subscription=has_active_subscription)
+ assert budget_spec_for(organization, events_last_year).bytes_per_hour == per_hour
+
@override_settings(API_QUERIES_BUDGET_FREE_BYTES_PER_HOUR=70, API_QUERIES_BUDGET_CAPACITY_HOURS=24)
class TestTokenBucket(BaseTest):