: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
perf(warehouse-sources): cache the per-org billing period row sum (#91961)
Daniel RC6ac151dbd143
diff --git a/products/warehouse_sources/backend/temporal/data_imports/row_tracking.py b/products/warehouse_sources/backend/temporal/data_imports/row_tracking.pyindex a2f1daf6954f..181b492c2506 100644--- a/products/warehouse_sources/backend/temporal/data_imports/row_tracking.py+++ b/products/warehouse_sources/backend/temporal/data_imports/row_tracking.py@@ -11,13 +11,16 @@ from django.db.utils import InternalError, OperationalErrorimport requestsimport structlogfrom dateutil import parser-from redis import exceptions as redis_exceptions+from redis import (+ Redis,+ exceptions as redis_exceptions,+)from structlog.types import FilteringBoundLoggerfrom posthog.cloud_utils import get_cached_instance_licensefrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Organization, Team-from posthog.redis import get_async_client+from posthog.redis import get_async_client, get_clientfrom posthog.settings import EE_AVAILABLEfrom posthog.settings.base_variables import TESTfrom posthog.sync import database_sync_to_async_pool@@ -157,6 +160,75 @@ async def get_all_rows_for_team(team_id: int) -> int:dwh_pricing_free_period_start = datetime(2025, 10, 29, 0, 0, 0, tzinfo=UTC)dwh_pricing_free_period_end = datetime(2025, 11, 6, 0, 0, 0, tzinfo=UTC)+# The billing-period sum only moves when a job completes, so serving it from a cache for a+# few minutes costs at most the rows one organization completes inside the window. The hard+# stop behind this check (check_billing_limits_activity, reading the quota-limiting cache)+# already refreshes on a 15 minute cron, so this adds no staleness the gate did not have.+BILLING_PERIOD_ROWS_CACHE_TTL_SECONDS = 5 * 60+++def _billing_period_rows_key(organization_id: uuid.UUID | str, billing_cycle_start: datetime) -> str:+ # The cycle start is part of the key so a new billing period reads a fresh sum instead of+ # waiting out the TTL of the previous period's total.+ return f"posthog:data_warehouse_billing_period_rows:{organization_id}:{billing_cycle_start.isoformat()}"+++def _get_sync_redis() -> Redis | None:+ """Synchronous Redis client for the billing-period cache, or None when it is not configured.++ The cache is read inside the same database thread as the query it replaces, so it uses the+ synchronous client rather than the async one the row-tracking helpers use.+ """+ if not settings.DATA_WAREHOUSE_REDIS_HOST or not settings.DATA_WAREHOUSE_REDIS_PORT:+ return None++ return get_client(f"redis://{settings.DATA_WAREHOUSE_REDIS_HOST}:{settings.DATA_WAREHOUSE_REDIS_PORT}/")+++def _rows_synced_in_billing_period(+ organization_id: uuid.UUID | str, team_ids: list[int], billing_cycle_start: datetime+) -> int:+ key = _billing_period_rows_key(organization_id, billing_cycle_start)+ redis = _get_sync_redis()++ if redis is not None:+ try:+ cached_rows = redis.get(key)+ if cached_rows is not None:+ return int(cached_rows)+ except redis_exceptions.RedisError as e:+ # A cache failure must fall through to the query rather than raise: the caller treats+ # a RedisError as "fail open", which would skip the billing check for this run+ # instead of paying for the query.+ #+ # Drop the client so the write below is skipped too. This runs on a shared database+ # executor thread, and a Redis endpoint that answers slowly can hold one for up to+ # REDIS_SOCKET_TIMEOUT_SECONDS per command, which would delay unrelated activities.+ redis = None+ logger.warning("BillingLimits: could not read the cached row count, querying Postgres", error=str(e))+ except ValueError as e:+ # A value that is not an integer means a corrupt key rather than an unhealthy Redis,+ # so keep the client: the write below replaces the bad value.+ logger.warning("BillingLimits: cached row count is not a number, querying Postgres", error=str(e))++ # Completed rows for every team in the org, excluding each source's first 7 free days.+ result = ExternalDataJob.objects.filter(+ Q(finished_at__gte=F("pipeline__created_at") + timedelta(days=7)),+ team_id__in=team_ids,+ finished_at__gte=billing_cycle_start,+ billable=True,+ status=ExternalDataJob.Status.COMPLETED,+ ).aggregate(total_rows=Sum("rows_synced"))+ rows_synced_in_billing_period = result.get("total_rows") or 0++ if redis is not None:+ try:+ redis.set(key, rows_synced_in_billing_period, ex=BILLING_PERIOD_ROWS_CACHE_TTL_SECONDS)+ except redis_exceptions.RedisError as e:+ logger.warning("BillingLimits: could not cache the row count", error=str(e))++ return rows_synced_in_billing_period+async def will_hit_billing_limit(team_id: int, source: "ExternalDataSource", logger: FilteringBoundLogger) -> bool:if not EE_AVAILABLE:@@ -197,29 +269,20 @@ async def will_hit_billing_limit(team_id: int, source: "ExternalDataSource", logbilling_res = billing_manager.get_billing(organization)- rows_synced_in_billing_period_dict = None- current_billing_cycle_start_dt = None+ rows_synced_in_billing_period = 0current_billing_cycle_start = billing_res.get("billing_period", {}).get("current_period_start")if current_billing_cycle_start is not None:- current_billing_cycle_start_dt = parser.parse(current_billing_cycle_start)-- # Get all completed rows for all teams in org- rows_synced_in_billing_period_dict = ExternalDataJob.objects.filter(- Q(finished_at__gte=F("pipeline__created_at") + timedelta(days=7)),- team_id__in=all_teams_in_org,- finished_at__gte=current_billing_cycle_start_dt,- billable=True,- status=ExternalDataJob.Status.COMPLETED,- ).aggregate(total_rows=Sum("rows_synced"))+ rows_synced_in_billing_period = _rows_synced_in_billing_period(+ organization.id, all_teams_in_org, parser.parse(current_billing_cycle_start)+ )return (organization.id,all_teams_in_org,billing_res,current_billing_cycle_start,- current_billing_cycle_start_dt,- rows_synced_in_billing_period_dict,+ rows_synced_in_billing_period,)(@@ -227,8 +290,7 @@ async def will_hit_billing_limit(team_id: int, source: "ExternalDataSource", logall_teams_in_org,billing_res,current_billing_cycle_start,- current_billing_cycle_start_dt,- rows_synced_in_billing_period_dict,+ rows_synced_in_billing_period,) = await _get_billing_data()await logger.adebug(f"BillingLimits: Organisation_id = {org_id}")@@ -257,8 +319,6 @@ async def will_hit_billing_limit(team_id: int, source: "ExternalDataSource", logawait logger.adebug("BillingLimits: rows_synced_limit is None or not a number, returning False")return False- rows_synced_in_billing_period = rows_synced_in_billing_period_dict.get("total_rows", 0) or 0-await logger.adebug(f"BillingLimits: rows_synced_in_billing_period = {rows_synced_in_billing_period}")rows_per_team = await asyncio.gather(*[get_all_rows_for_team(t_id) for t_id in all_teams_in_org])diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_row_tracking.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_row_tracking.pyindex ed3febaabf7f..085c3e83e9d8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/test_row_tracking.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_row_tracking.py@@ -19,11 +19,13 @@ from redis import exceptions as redis_exceptionsfrom structlog.types import FilteringBoundLoggerfrom posthog.models import Team+from posthog.redis import get_clientfrom posthog.sync import database_sync_to_asyncfrom posthog.tasks.usage_report import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.temporal.data_imports.row_tracking import (+ _get_redis,finish_row_tracking,increment_rows,setup_row_tracking,@@ -31,6 +33,17 @@ from products.warehouse_sources.backend.temporal.data_imports.row_tracking impor)+class _CacheReadFailsClient:+ def __init__(self, inner):+ self._inner = inner++ def __getattr__(self, name):+ return getattr(self._inner, name)++ def get(self, *args, **kwargs):+ raise redis_exceptions.ConnectionError("Error connecting to redis:6379.")++class TestRowTrackingRedisUnavailable(BaseTest):@parameterized.expand([@@ -146,13 +159,30 @@ class TestRowTracking(BaseTest):await finish_row_tracking(t_id, schema_id)- async def _run(self, source: ExternalDataSource, limit: int) -> bool:+ async def _clear_billing_period_rows_cache(self) -> None:+ # The organization is created once per test class and Redis is not rolled back between+ # tests, so a cached sum would otherwise leak into the next test.+ with override_settings(DATA_WAREHOUSE_REDIS_HOST="localhost", DATA_WAREHOUSE_REDIS_PORT="6379"):+ async with _get_redis() as redis:+ if not redis:+ return++ keys = await redis.keys(f"posthog:data_warehouse_billing_period_rows:{self.organization.id}:*")+ if keys:+ await redis.delete(*keys)++ async def _run(self, source: ExternalDataSource, limit: int, clear_cache: bool = True) -> bool:from ee.models.license import License- await sync_to_async(License.objects.create)(+ if clear_cache:+ await self._clear_billing_period_rows_cache()++ await sync_to_async(License.objects.get_or_create)(key="12345::67890",- plan="enterprise",- valid_until=datetime(2038, 1, 19, 3, 14, 7, tzinfo=ZoneInfo("UTC")),+ defaults={+ "plan": "enterprise",+ "valid_until": datetime(2038, 1, 19, 3, 14, 7, tzinfo=ZoneInfo("UTC")),+ },)with (@@ -273,6 +303,44 @@ class TestRowTracking(BaseTest):async with self._setup_redis_rows(20, team_id=another_team.pk):assert await self._run(source, 10) is True+ @pytest.mark.asyncio+ async def test_row_tracking_serves_the_billing_period_sum_from_cache(self):+ source = await self._create_source()++ assert await self._run(source, 10) is False++ await sync_to_async(ExternalDataJob.objects.create)(+ team=self.team,+ rows_synced=11,+ pipeline=source,+ finished_at=datetime.now(),+ billable=True,+ status=ExternalDataJob.Status.COMPLETED,+ )++ assert await self._run(source, 10, clear_cache=False) is False+ assert await self._run(source, 10) is True++ @pytest.mark.asyncio+ async def test_row_tracking_queries_postgres_when_the_cache_read_fails(self):+ # A Redis failure must fall through to the query. The caller treats a RedisError as+ # "fail open", so letting one escape would skip the billing check for this run.+ source = await self._create_source()+ await sync_to_async(ExternalDataJob.objects.create)(+ team=self.team,+ rows_synced=11,+ pipeline=source,+ finished_at=datetime.now(),+ billable=True,+ status=ExternalDataJob.Status.COMPLETED,+ )++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.row_tracking.get_client",+ side_effect=lambda url: _CacheReadFailsClient(get_client(url)),+ ):+ assert await self._run(source, 10) is True+@pytest.mark.asyncioasync def test_row_tracking_fails_open_on_redis_error_without_capturing_exception(self):# A transient Redis connectivity blip while fetching billing data (e.g. a DNS