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.

perf(weekly-digest): stop scanning every organization per digest batch (#100730)

posthog[bot]ad2c28fe31ca
diff --git a/posthog/temporal/tests/weekly_digest/test_queries.py b/posthog/temporal/tests/weekly_digest/test_queries.py
index 874f01ca534e..bcb55c549c5c 100644
--- a/posthog/temporal/tests/weekly_digest/test_queries.py
+++ b/posthog/temporal/tests/weekly_digest/test_queries.py
@@ -5,7 +5,10 @@ import pytest
from posthog.schema import ErrorTrackingIssueStatus
-from posthog.temporal.weekly_digest.queries import query_new_error_issues
+from posthog.constants import AvailableFeature
+from posthog.models.organization import Organization
+from posthog.models.team import Team
+from posthog.temporal.weekly_digest.queries import query_new_error_issues, query_teams_for_digest
from products.error_tracking.backend.facade.testing import create_issue
@@ -40,3 +43,25 @@ def test_query_new_error_issues_window_boundaries_and_status(team):
# Only active issues created within the window, newest first
assert [r["id"] for r in results] == [at_period_end, in_window]
assert all(r["team_id"] == team.id for r in results)
+
+
[email protected]("with_organization", [False, True])
+def test_query_teams_for_digest_loads_the_used_fields_in_one_query(
+ organization, with_organization, django_assert_num_queries
+):
+ internal_organization = Organization.objects.create(name="internal metrics", for_internal_metrics=True)
+ Team.objects.create(organization=internal_organization, name="internal metrics team")
+ Team.objects.create(organization=organization, name="demo team", is_demo=True)
+ digest_teams = [Team.objects.create(organization=organization, name=f"digest team {i}") for i in range(3)]
+
+ paged_ids = []
+ with django_assert_num_queries(1):
+ for team in query_teams_for_digest(with_organization=with_organization):
+ # Every team field the digest activities read. One left out of the query would load
+ # lazily here instead, costing an extra query per team.
+ _ = team.project_id, team.organization_id
+ if with_organization:
+ team.organization.is_feature_available(AvailableFeature.ACCESS_CONTROL)
+ paged_ids.append(team.id)
+
+ assert paged_ids == [team.id for team in digest_teams]
diff --git a/posthog/temporal/weekly_digest/activities.py b/posthog/temporal/weekly_digest/activities.py
index cf17f8f31bfd..ae6f72bc1fa8 100644
--- a/posthog/temporal/weekly_digest/activities.py
+++ b/posthog/temporal/weekly_digest/activities.py
@@ -106,10 +106,12 @@ async def _load_playlist_counts_from_django_cache(r: redis.Redis, filters: Filte
LOGGER = get_write_only_logger()
-def _teams_in_range(input: GenerateDigestDataBatchInput) -> QuerySet:
+def _teams_in_range(input: GenerateDigestDataBatchInput, *, with_organization: bool = False) -> QuerySet:
# An id predicate lets Postgres seek to the first row of the batch on the primary key.
# LIMIT/OFFSET made it build and discard every row before the batch instead.
- return query_teams_for_digest().filter(id__gte=input.team_id_range.start, id__lt=input.team_id_range.end)
+ return query_teams_for_digest(with_organization=with_organization).filter(
+ id__gte=input.team_id_range.start, id__lt=input.team_id_range.end
+ )
async def generate_digest_data_lookup(
@@ -502,7 +504,7 @@ async def generate_user_notification_lookup(input: GenerateDigestDataBatchInput)
user_count = 0
async with redis.from_url(_redis_url(input.common)) as r:
- async for team in _teams_in_range(input):
+ async for team in _teams_in_range(input, with_organization=True):
try:
async for user in await database_sync_to_async(team.all_users_with_access)():
if should_send_notification(user, NotificationSetting.WEEKLY_PROJECT_DIGEST.value, team.id):
@@ -548,7 +550,7 @@ async def generate_product_suggestion_lookup(input: GenerateDigestDataBatchInput
campaigns_by_org: dict[str, list[dict]] = {}
async with redis.from_url(_redis_url(input.common)) as r:
- async for team in _teams_in_range(input):
+ async for team in _teams_in_range(input, with_organization=True):
try:
organization_id = str(team.organization_id)
if organization_id not in campaigns_by_org:
diff --git a/posthog/temporal/weekly_digest/queries.py b/posthog/temporal/weekly_digest/queries.py
index 3f15a6e6e9bf..bc0355de90e5 100644
--- a/posthog/temporal/weekly_digest/queries.py
+++ b/posthog/temporal/weekly_digest/queries.py
@@ -19,22 +19,32 @@ from products.surveys.backend.models import Survey
from products.warehouse_sources.backend.facade.models import ExternalDataSource
-def query_teams_for_digest() -> QuerySet:
- return (
- Team.objects.select_related("organization")
- .exclude(Q(organization__for_internal_metrics=True) | Q(is_demo=True))
- .only(
+def query_teams_for_digest(*, with_organization: bool = False) -> QuerySet:
+ """Teams eligible for a digest, ordered by id.
+
+ Pass `with_organization` only when the caller reads `Team.organization`.
+ """
+ # Excluding through the organization join makes Postgres read every organization row on
+ # every call, to build a hash it then discards. A subquery hits the partial index on
+ # for_internal_metrics, so the cost follows the team batch instead of the organization count.
+ queryset = (
+ Team.objects.exclude(is_demo=True)
+ .exclude(organization_id__in=Organization.objects.filter(for_internal_metrics=True).values("id"))
+ .order_by("id")
+ )
+
+ if with_organization:
+ # all_users_with_access reads organization.available_product_features, a large JSON
+ # column, so only the callers that ask for the organization pay to load it.
+ return queryset.select_related("organization").only(
"id",
- "name",
"project_id",
"organization_id",
"organization__id",
- "organization__name",
- "organization__created_at",
"organization__available_product_features",
)
- .order_by("id")
- )
+
+ return queryset.only("id", "project_id", "organization_id")
def query_team_ids_for_digest() -> QuerySet: