: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
fix(flags): stop per-flag queries in bulk delete and org flag lookup (#126408)
Paul D'Ambra24317e4d45e7
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex ef5510680767..807c80d6f125 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -5334,8 +5334,8 @@ class FeatureFlagViewSet(# Apply access control - filter to only editable flagsif self.user_access_control:- # Fetch just IDs for access control check (lightweight query)- flags_for_access_check = list(queryset.only("id"))+ # The access check reads created_by_id, so a deferred column costs a query per flag+ flags_for_access_check = list(queryset.only("id", "created_by_id"))self.user_access_control.preload_object_access_controls(cast(list, flags_for_access_check))editable_ids = []@@ -5350,7 +5350,7 @@ class FeatureFlagViewSet(queryset = queryset.filter(id__in=editable_ids)# Prefetch related data for validation (only for flags we'll actually process)- queryset = queryset.prefetch_related("features", "experiment_set")+ queryset = queryset.select_related("team").prefetch_related("features", "experiment_set")flags_list = list(queryset)# Batch query for dependent flagsdiff --git a/products/feature_flags/backend/api/organization_feature_flag.py b/products/feature_flags/backend/api/organization_feature_flag.pyindex 5735c137c662..b2259edf890d 100644--- a/products/feature_flags/backend/api/organization_feature_flag.py+++ b/products/feature_flags/backend/api/organization_feature_flag.py@@ -282,7 +282,7 @@ class OrganizationFeatureFlagView(team_id__in=team_ids,)flags_qs = self._filter_flags_by_rbac(flags_qs, team_ids)- flags = list(flags_qs)+ flags = list(flags_qs.select_related("created_by"))for flag in flags:self._redact_encrypted_payloads(request, flag)diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambrindex 950bef4953d7..63530e46a99f 100644--- a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr@@ -1548,34 +1548,8 @@"posthog_featureflag"."has_encrypted_payloads","posthog_featureflag"."evaluation_runtime","posthog_featureflag"."bucketing_identifier",- "posthog_featureflag"."last_called_at"- FROM "posthog_featureflag"- WHERE (NOT ("posthog_featureflag"."deleted")- AND "posthog_featureflag"."key" = 'key-1'- AND "posthog_featureflag"."team_id" IN (1,- 2,- 3,- 4,- 5 /* ... */)- AND "posthog_featureflag"."id" IN (1,- 2,- 3,- 4,- 5 /* ... */))- '''-# ----# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.15- '''- SELECT "feature_flags_organizationfeatureflagsconfig"."flag_evaluations_mode" AS "flag_evaluations_mode"- FROM "feature_flags_organizationfeatureflagsconfig"- WHERE "feature_flags_organizationfeatureflagsconfig"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid- ORDER BY "feature_flags_organizationfeatureflagsconfig"."organization_id" ASC- LIMIT 1- '''-# ----# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.16- '''- SELECT "posthog_user"."id",+ "posthog_featureflag"."last_called_at",+ "posthog_user"."id","posthog_user"."password","posthog_user"."last_login","posthog_user"."first_name",@@ -1615,56 +1589,29 @@"posthog_user"."onboarding_delegation_accepted_at","posthog_user"."events_column_config","posthog_user"."email_opt_in"- FROM "posthog_user"- WHERE "posthog_user"."id" = 99999- LIMIT 21+ FROM "posthog_featureflag"+ LEFT OUTER JOIN "posthog_user" ON ("posthog_featureflag"."created_by_id" = "posthog_user"."id")+ WHERE (NOT ("posthog_featureflag"."deleted")+ AND "posthog_featureflag"."key" = 'key-1'+ AND "posthog_featureflag"."team_id" IN (1,+ 2,+ 3,+ 4,+ 5 /* ... */)+ AND "posthog_featureflag"."id" IN (1,+ 2,+ 3,+ 4,+ 5 /* ... */))'''# ----# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.17+# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.15'''- SELECT "posthog_user"."id",- "posthog_user"."password",- "posthog_user"."last_login",- "posthog_user"."first_name",- "posthog_user"."last_name",- "posthog_user"."is_staff",- "posthog_user"."date_joined",- "posthog_user"."uuid",- "posthog_user"."current_organization_id",- "posthog_user"."current_team_id",- "posthog_user"."email",- "posthog_user"."pending_email",- "posthog_user"."distinct_id",- "posthog_user"."is_email_verified",- "posthog_user"."credentials_reviewed_at",- "posthog_user"."requested_password_reset_at",- "posthog_user"."requested_2fa_reset_at",- "posthog_user"."has_seen_product_intro_for",- "posthog_user"."strapi_id",- "posthog_user"."is_active",- "posthog_user"."role_at_organization",- "posthog_user"."theme_mode",- "posthog_user"."partial_notification_settings",- "posthog_user"."anonymize_data",- "posthog_user"."allow_impersonation",- "posthog_user"."toolbar_mode",- "posthog_user"."hedgehog_config",- "posthog_user"."allow_sidebar_suggestions",- "posthog_user"."shortcut_position",- "posthog_user"."passkeys_enabled_for_2fa",- "posthog_user"."hide_mcp_hints",- "posthog_user"."ui_configuration",- "posthog_user"."onboarding_skipped_at",- "posthog_user"."onboarding_skipped_reason",- "posthog_user"."onboarding_skipped_organization_id",- "posthog_user"."onboarding_delegated_to_invite_id",- "posthog_user"."onboarding_delegated_to_organization_id",- "posthog_user"."onboarding_delegation_accepted_at",- "posthog_user"."events_column_config",- "posthog_user"."email_opt_in"- FROM "posthog_user"- WHERE "posthog_user"."id" = 99999- LIMIT 21+ SELECT "feature_flags_organizationfeatureflagsconfig"."flag_evaluations_mode" AS "flag_evaluations_mode"+ FROM "feature_flags_organizationfeatureflagsconfig"+ WHERE "feature_flags_organizationfeatureflagsconfig"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid+ ORDER BY "feature_flags_organizationfeatureflagsconfig"."organization_id" ASC+ LIMIT 1'''# ---# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.2diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 358d72df868b..f309488e8dd7 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -16,8 +16,9 @@ from posthog.test.base import (from unittest.mock import ANY, MagicMock, patchfrom django.core.cache import cache-from django.db import IntegrityError+from django.db import IntegrityError, connectionfrom django.test import SimpleTestCase, override_settings+from django.test.utils import CaptureQueriesContextfrom django.utils.timezone import nowimport grpc@@ -13598,6 +13599,32 @@ class TestFeatureFlagBulkDelete(APIBaseTest):assert len(data["deleted"]) == 150assert len(data["errors"]) == 0+ def _bulk_delete_query_count(self, flag_count: int) -> int:+ flags = [+ FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key=f"query_count_flag_{flag_count}_{i}",+ filters={"groups": [{"rollout_percentage": 50, "properties": []}]},+ )+ for i in range(flag_count)+ ]+ with CaptureQueriesContext(connection) as ctx:+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/bulk_delete/",+ {"ids": [f.id for f in flags]},+ )+ assert response.status_code == 200+ assert len(response.json()["deleted"]) == flag_count+ return len(ctx.captured_queries)++ def test_bulk_delete_query_count_does_not_grow_with_flag_count(self):+ self._bulk_delete_query_count(1)+ few = self._bulk_delete_query_count(2)+ many = self._bulk_delete_query_count(6)++ assert few == many, f"deleting 6 flags cost {many} queries vs {few} for 2, so something N+1s"+def test_bulk_delete_validates_running_experiments(self):"""Test that flags linked to running experiments are rejected."""flag = FeatureFlag.objects.create(