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(api): narrow the team plus organization reads on api key paths (#102907)

posthog[bot]29bb275923ba
diff --git a/posthog/api/personal_api_key.py b/posthog/api/personal_api_key.py
index aadd33fc7c24..d11022c25524 100644
--- a/posthog/api/personal_api_key.py
+++ b/posthog/api/personal_api_key.py
@@ -242,8 +242,12 @@ class PersonalAPIKeySerializer(serializers.ModelSerializer):
if personal_api_key.scoped_organizations:
org_ids = personal_api_key.scoped_organizations
elif personal_api_key.scoped_teams:
- teams = Team.objects.filter(pk__in=personal_api_key.scoped_teams).select_related("organization")
- org_ids = list({team.organization_id for team in teams})
+ # `organization_id` is a column on the team row, so no organization join is needed.
+ org_ids = list(
+ Team.objects.filter(pk__in=personal_api_key.scoped_teams)
+ .values_list("organization_id", flat=True)
+ .distinct()
+ )
else:
user_permissions = UserPermissions(personal_api_key.user)
org_ids = list(user_permissions.organization_memberships.keys())
diff --git a/posthog/models/activity_logging/personal_api_key_utils.py b/posthog/models/activity_logging/personal_api_key_utils.py
index 7f876a724782..01af1e376c14 100644
--- a/posthog/models/activity_logging/personal_api_key_utils.py
+++ b/posthog/models/activity_logging/personal_api_key_utils.py
@@ -31,8 +31,9 @@ class PersonalAPIKeyContext(ActivityContextBase):
def get_personal_api_key_access_locations(api_key: PersonalAPIKey) -> set[LogScope]:
"""Calculate where activity logs should be created for a PersonalAPIKey based on its scope."""
if api_key.scoped_teams:
- teams = Team.objects.filter(pk__in=api_key.scoped_teams).select_related("organization")
- return {LogScope(str(team.organization_id), team.id) for team in teams}
+ # `organization_id` is a column on the team row, so no organization join is needed.
+ teams = Team.objects.filter(pk__in=api_key.scoped_teams).values_list("organization_id", "id")
+ return {LogScope(str(organization_id), team_id) for organization_id, team_id in teams}
elif api_key.scoped_organizations:
return {LogScope(str(org_id), None) for org_id in api_key.scoped_organizations}
else:
diff --git a/posthog/models/activity_logging/project_secret_api_key_utils.py b/posthog/models/activity_logging/project_secret_api_key_utils.py
index 0b1ac8cff6be..fdb5d20b6110 100644
--- a/posthog/models/activity_logging/project_secret_api_key_utils.py
+++ b/posthog/models/activity_logging/project_secret_api_key_utils.py
@@ -36,7 +36,14 @@ def _get_team(api_key: ProjectSecretAPIKey) -> Optional[Team]:
if team_id is None:
return None
- return Team.objects.select_related("organization").filter(id=team_id).first()
+ # The log entry reads only the team name, the organization id and the organization name,
+ # so skip the rest of both wide rows.
+ return (
+ Team.objects.select_related("organization")
+ .only("id", "name", "organization_id", "organization__id", "organization__name")
+ .filter(id=team_id)
+ .first()
+ )
def _get_access_location(api_key: ProjectSecretAPIKey) -> tuple[LogScope, Optional[Team]]:
diff --git a/posthog/models/activity_logging/retention.py b/posthog/models/activity_logging/retention.py
index 7e6e193a6c7e..e9b17894f0ad 100644
--- a/posthog/models/activity_logging/retention.py
+++ b/posthog/models/activity_logging/retention.py
@@ -81,7 +81,13 @@ def activity_log_retention_start_for_team(team: Optional["Team"], team_id: Optio
if team is None:
if team_id is None:
return None
- team = Team.objects.filter(id=team_id).select_related("organization").first()
+ team = (
+ Team.objects.filter(id=team_id)
+ .select_related("organization")
+ # `_lookback_window` reads the entitlement array and the id, so skip the rest of both rows.
+ .only("id", "organization_id", "organization__id", "organization__available_product_features")
+ .first()
+ )
if team is None:
return None
diff --git a/posthog/test/activity_logging/test_personal_api_key_activity_logging.py b/posthog/test/activity_logging/test_personal_api_key_activity_logging.py
index 79596091b9c5..ccf7c8c9f86e 100644
--- a/posthog/test/activity_logging/test_personal_api_key_activity_logging.py
+++ b/posthog/test/activity_logging/test_personal_api_key_activity_logging.py
@@ -353,6 +353,7 @@ class TestPersonalAPIKeyScopeChanges(ActivityLogTestHelper):
filtered_teams = [teams_dict[team_id] for team_id in kwargs["pk__in"] if team_id in teams_dict]
mock_result = MagicMock()
mock_result.select_related.return_value = filtered_teams
+ mock_result.values_list.return_value = [(team.organization_id, team.id) for team in filtered_teams]
return mock_result
elif "organization_id__in" in kwargs:
org_ids = kwargs["organization_id__in"]
@@ -387,6 +388,7 @@ class TestPersonalAPIKeyScopeChanges(ActivityLogTestHelper):
else:
mock_result = MagicMock()
mock_result.select_related.return_value = []
+ mock_result.values_list.return_value = []
return mock_result
return filter_teams