Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix: batch the events retention sync so it can finish (#75083)

Andy Zhaoba0f798f5182
diff --git a/posthog/temporal/sync_events_retention/activities.py b/posthog/temporal/sync_events_retention/activities.py
index 054500b986bb..2a71fc09731a 100644
--- a/posthog/temporal/sync_events_retention/activities.py
+++ b/posthog/temporal/sync_events_retention/activities.py
@@ -3,7 +3,6 @@ from temporalio import activity
from posthog.constants import AvailableFeature
from posthog.models.team import Team
from posthog.models.team.event_retention import parse_events_feature_to_months
-from posthog.sync import database_sync_to_async
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.logger import get_write_only_logger
from posthog.temporal.sync_events_retention.types import SyncEventsRetentionInput
@@ -20,40 +19,44 @@ async def sync_events_retention(input: SyncEventsRetentionInput) -> None:
"""
async with Heartbeater():
logger = LOGGER.bind()
- teams_to_update = []
- query_counter = 0
-
logger.info("Syncing events retention for all teams...")
- async for team in Team.objects.select_related("organization").only(
- "id", "name", "organization", "event_retention_months"
- ):
- organization = team.organization
- retention_feature = await database_sync_to_async(organization.get_available_feature)(
- AvailableFeature.PRODUCT_ANALYTICS_DATA_RETENTION
- )
- target_months = parse_events_feature_to_months(retention_feature)
-
- if team.event_retention_months != target_months:
- logger.info(
- "Events retention period synced",
- team_id=team.id,
- team_name=team.name,
- organization_id=organization.id,
- retention_months_before=team.event_retention_months,
- retention_months_after=target_months,
+
+ last_pk = 0
+ total_processed = 0
+ total_updated = 0
+
+ while True:
+ # Bounded keyset batches: pgbouncer disables server-side cursors, so iterating the full queryset
+ # would materialize every team (with its joined organization row) in memory at once.
+ teams = [
+ team
+ async for team in Team.objects.filter(pk__gt=last_pk)
+ .order_by("pk")
+ .select_related("organization")
+ .only("id", "event_retention_months", "organization__available_product_features")[: input.batch_size]
+ ]
+ if not teams:
+ break
+ last_pk = teams[-1].pk
+
+ teams_to_update: list[Team] = []
+ for team in teams:
+ retention_feature = team.organization.get_available_feature(
+ AvailableFeature.PRODUCT_ANALYTICS_DATA_RETENTION
)
- team.event_retention_months = target_months
- teams_to_update.append(team)
-
- query_counter += 1
- if query_counter >= input.batch_size:
- query_counter = 0
- logger.info(f"Processed {input.batch_size} teams...")
-
- if not input.dry_run:
- logger.info(f"Updating {len(teams_to_update)} teams...")
- await database_sync_to_async(Team.objects.bulk_update)(
- teams_to_update, ["event_retention_months"], batch_size=input.batch_size
- )
+ target_months = parse_events_feature_to_months(retention_feature)
+ if team.event_retention_months != target_months:
+ team.event_retention_months = target_months
+ teams_to_update.append(team)
+
+ if teams_to_update and not input.dry_run:
+ await Team.objects.abulk_update(teams_to_update, ["event_retention_months"])
+
+ total_processed += len(teams)
+ total_updated += len(teams_to_update)
+ logger.info(f"Processed {total_processed} teams, {total_updated} updated so far...")
+
+ if input.dry_run:
+ logger.info(f"DRY RUN: Would have updated {total_updated} of {total_processed} teams")
else:
- logger.info(f"DRY RUN: Would have updated {len(teams_to_update)} teams...")
+ logger.info(f"Updated {total_updated} of {total_processed} teams")
diff --git a/posthog/temporal/tests/sync_events_retention/test_activities.py b/posthog/temporal/tests/sync_events_retention/test_activities.py
index 05656f9ca3ae..29a2bd96e754 100644
--- a/posthog/temporal/tests/sync_events_retention/test_activities.py
+++ b/posthog/temporal/tests/sync_events_retention/test_activities.py
@@ -46,6 +46,19 @@ async def test_syncs_event_retention_months_from_billing(features: list[dict], e
assert team.event_retention_months == expected_months
[email protected]_db(transaction=True)
+async def test_syncs_all_teams_across_batches():
+ features = [{"key": "product_analytics_data_retention", "limit": 1, "unit": "year"}]
+ teams = [await _team_with_features(features, current_months=999) for _ in range(3)]
+
+ await ActivityEnvironment().run(sync_events_retention, SyncEventsRetentionInput(dry_run=False, batch_size=1))
+
+ for team in teams:
+ await sync_to_async(team.refresh_from_db)()
+ assert team.event_retention_months == 12
+
+
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
async def test_dry_run_computes_but_does_not_persist():