: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): sync dogfood flag definitions into EU HyperCache from US (#70944)
Phil Haackcb1a32d6f4c3
diff --git a/posthog/settings/feature_flags.py b/posthog/settings/feature_flags.pyindex 783264ae969e..06104344af9b 100644--- a/posthog/settings/feature_flags.py+++ b/posthog/settings/feature_flags.py@@ -107,3 +107,10 @@ MAX_FEATURE_FLAG_FILTER_SIZE_BYTES: int = get_from_env(# Team ID for the local-evaluation canary. Unset disables the canary task.FEATURE_FLAGS_CANARY_TEAM_ID: int | None = get_from_env("FEATURE_FLAGS_CANARY_TEAM_ID", optional=True, type_cast=int)++# Project secret API key (PSAK) scoped to team 2, used only by the EU cross-region+# dogfood flags sync (products/feature_flags/backend/cross_region_flag_sync.py) to+# poll team 2's flag definitions from the US region, since team 2 lives only in the+# US Postgres. Unset disables the sync. Not needed on US, where team 2's HyperCache+# entry is built locally via the normal signal-driven path.+POSTHOG_FLAGS_PROJECT_SECRET_TOKEN: str = get_from_env("POSTHOG_FLAGS_PROJECT_SECRET_TOKEN", "")diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex cb9e6c571cd5..1e358eb6a2ac 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -89,6 +89,7 @@ from products.feature_flags.backend.tasks import (feature_flags_local_eval_canary_task,refresh_expiring_flag_definitions_cache_entries,refresh_expiring_flags_cache_entries,+ sync_cross_region_dogfood_flags_task,)from products.logs.backend.facade.tasks import logs_alert_events_cleanup_taskfrom products.reminders.backend.tasks import process_due_reminders@@ -363,6 +364,21 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:expires_seconds=5 * 60,)+ # Cross-region dogfood flags sync (EU only) - every 30s, matching the SDK's+ # own default poll_interval so EU's local-eval freshness matches what a+ # customer backend gets. Raw interval is safe here (sub-minute; see the+ # warning on add_periodic_task_with_expiry above). Registered only in EU so+ # US beat schedules don't carry a permanently-no-op entry. expires sheds+ # queued ticks older than one interval, so a backed-up queue doesn't replay+ # a burst of stale polls on recovery.+ if get_instance_region() == "EU":+ sender.add_periodic_task(+ 30,+ sync_cross_region_dogfood_flags_task.s(),+ name="cross-region dogfood flags sync",+ expires=30,+ )+add_periodic_task_with_expiry(sender,crontab(minute="*/5"),diff --git a/products/feature_flags/backend/cross_region_flag_sync.py b/products/feature_flags/backend/cross_region_flag_sync.pynew file mode 100644index 000000000000..d4c3089535f2--- /dev/null+++ b/products/feature_flags/backend/cross_region_flag_sync.py@@ -0,0 +1,109 @@+"""+Cross-region sync of the dogfood team's (team 2) flag definitions into EU's+HyperCache.++Every other team's `flag_definitions_hypercache` entry is rebuilt locally by+Django signals reading straight from Postgres (see local_evaluation.py). Team 2+-- PostHog's internal "self" team, used for our own dogfooded local evaluation+-- lives only in the US Postgres, so EU has no rows to build it from. Rather+than have every EU pod poll the US API directly (which HyperCache exists to+avoid), a single periodic task fetches team 2's flag definitions from the US+region's authenticated `/flags/definitions` endpoint and writes the result+straight into EU's HyperCache, so every EU pod still reads from the shared+cache with zero per-pod polling.++No-op on US, where team 2's HyperCache entry is already populated by the+normal signal-driven path.+"""++from django.conf import settings++import requests+import structlog+from posthoganalytics.request import US_INGESTION_ENDPOINT++from posthog.utils import capture_exception_throttled, get_instance_region++from products.feature_flags.backend.local_evaluation import flag_definitions_hypercache++logger = structlog.get_logger(__name__)++# PostHog's own internal "self" team, canonically team 2 (see _build_flag_provider+# in posthog/utils.py). Only its US Postgres rows are authoritative.+DOGFOOD_SELF_TEAM_ID = 2++_FLAGS_DEFINITIONS_PATH = "/flags/definitions"+_REQUEST_TIMEOUT_SECONDS = (3, 10) # (connect, read)++# Throttle window for capturing an unexpected failure (network error, bad JSON) to+# PostHog error tracking, shared across the 30s schedule so a sustained outage+# reports once per window instead of once per tick.+_SYNC_FAILURE_CAPTURE_THROTTLE_KEY = "cross_region_dogfood_flags_sync_capture_throttle"+_SYNC_FAILURE_CAPTURE_THROTTLE_TTL = 300 # seconds+++def sync_cross_region_dogfood_flags() -> None:+ """Refresh team 2's flag-definitions HyperCache entry in EU from the US region.++ No-op outside EU or when the PSAK isn't configured. Uses the endpoint's ETag+ support: sends `If-None-Match` with the locally cached ETag, so an unchanged+ upstream is a 304 with no payload transferred and no local write.+ """+ # Defense in depth: the beat registration in scheduled.py is also EU-gated.+ # This keeps direct invocation (shell, tests) safe outside EU.+ if get_instance_region() != "EU":+ return++ token = settings.POSTHOG_FLAGS_PROJECT_SECRET_TOKEN+ if not token:+ logger.debug("cross_region_dogfood_flags_sync_no_token")+ return++ headers = {"Authorization": f"Bearer {token}"}+ local_etag = flag_definitions_hypercache.get_etag(DOGFOOD_SELF_TEAM_ID)+ if local_etag:+ headers["If-None-Match"] = f'"{local_etag}"'++ try:+ response = requests.get(+ f"{US_INGESTION_ENDPOINT}{_FLAGS_DEFINITIONS_PATH}",+ headers=headers,+ timeout=_REQUEST_TIMEOUT_SECONDS,+ )+ except requests.RequestException as e:+ capture_exception_throttled(_SYNC_FAILURE_CAPTURE_THROTTLE_KEY, e, _SYNC_FAILURE_CAPTURE_THROTTLE_TTL)+ logger.warning("cross_region_dogfood_flags_sync_request_failed", error=str(e))+ return++ if response.status_code == 304:+ return++ if response.status_code != 200:+ logger.warning(+ "cross_region_dogfood_flags_sync_bad_status",+ status_code=response.status_code,+ )+ return++ try:+ payload = response.json()+ except ValueError as e:+ capture_exception_throttled(_SYNC_FAILURE_CAPTURE_THROTTLE_KEY, e, _SYNC_FAILURE_CAPTURE_THROTTLE_TTL)+ logger.warning("cross_region_dogfood_flags_sync_bad_json")+ return++ if not isinstance(payload, dict):+ # A malformed-but-valid-JSON body (e.g. null, a list) would otherwise be cached+ # verbatim and served to every EU pod until the next successful sync.+ logger.warning("cross_region_dogfood_flags_sync_unexpected_shape", payload_type=type(payload).__name__)+ return++ # update_cache (not bare set_cache_value) for parity with the signal-driven write+ # path: it emits the cache-sync metrics dashboards watch, and its info log only+ # fires when flags actually changed, since unchanged upstreams 304 above. The+ # write is unconditional (no skip_if_unchanged): a 200 already means the content+ # changed, and a bare int key isn't tracked in the expiry sorted set (unlike a+ # Team key), so this write is what re-stamps the Redis TTL. On a long run of 304s+ # the entry can still expire; that self-heals within one tick, because the etag+ # expires with it, so the next poll sends no If-None-Match and gets a full 200.+ flag_definitions_hypercache.update_cache(DOGFOOD_SELF_TEAM_ID, data=payload)diff --git a/products/feature_flags/backend/tasks.py b/products/feature_flags/backend/tasks.pyindex 0a5d93024c0d..6d7bcbba75fb 100644--- a/products/feature_flags/backend/tasks.py+++ b/products/feature_flags/backend/tasks.py@@ -15,6 +15,7 @@ from posthog.storage.hypercache_manager import HYPERCACHE_SIGNAL_UPDATE_COUNTERfrom posthog.tasks.utils import CeleryQueue, PushGatewayTaskfrom products.feature_flags.backend.canary import run_local_eval_canary+from products.feature_flags.backend.cross_region_flag_sync import sync_cross_region_dogfood_flagsfrom products.feature_flags.backend.flags_cache import (cleanup_stale_expiry_tracking,clear_flags_cache,@@ -64,6 +65,17 @@ def drain_flag_definitions_rebuild_requests() -> None:drain_rebuild_requests()+@shared_task(ignore_result=True, queue=CeleryQueue.FEATURE_FLAGS_LONG_RUNNING.value)+def sync_cross_region_dogfood_flags_task() -> None:+ """Celery entrypoint for sync_cross_region_dogfood_flags.++ On its own queue (not CeleryQueue.FEATURE_FLAGS) because it makes a blocking+ cross-region HTTP call: a stalled upstream shouldn't be able to delay the+ fast, sub-second signal-driven cache rebuilds sharing that queue.+ """+ sync_cross_region_dogfood_flags()++@shared_task(ignore_result=True, queue=CeleryQueue.FEATURE_FLAGS.value)@skip_team_scope_auditdef update_team_service_flags_cache(team_id: int) -> None:diff --git a/products/feature_flags/backend/test/test_cross_region_flag_sync.py b/products/feature_flags/backend/test/test_cross_region_flag_sync.pynew file mode 100644index 000000000000..ac01d61c4dc1--- /dev/null+++ b/products/feature_flags/backend/test/test_cross_region_flag_sync.py@@ -0,0 +1,106 @@+from posthog.test.base import BaseTest+from unittest.mock import Mock, patch++from django.test import override_settings++import requests+from parameterized import parameterized++from products.feature_flags.backend.cross_region_flag_sync import DOGFOOD_SELF_TEAM_ID, sync_cross_region_dogfood_flags+from products.feature_flags.backend.local_evaluation import clear_flag_definition_caches, flag_definitions_hypercache++_MODULE = "products.feature_flags.backend.cross_region_flag_sync"+++def _mock_response(status_code: int, json_data: dict | list | None = None, json_error: bool = False) -> Mock:+ response = Mock()+ response.status_code = status_code+ if json_error:+ response.json.side_effect = ValueError("bad json")+ else:+ response.json.return_value = json_data+ return response+++@override_settings(CLOUD_DEPLOYMENT="EU", POSTHOG_FLAGS_PROJECT_SECRET_TOKEN="phs_test_token")+class TestSyncCrossRegionDogfoodFlags(BaseTest):+ def setUp(self):+ super().setUp()+ clear_flag_definition_caches(DOGFOOD_SELF_TEAM_ID, kinds=["redis", "s3"])++ @override_settings(CLOUD_DEPLOYMENT="US")+ def test_no_op_outside_eu(self):+ # Every EU pod would otherwise re-poll the US API directly -- exactly the+ # per-pod polling this task exists to replace -- if this guard were dropped.+ with patch(f"{_MODULE}.requests.get") as mock_get:+ sync_cross_region_dogfood_flags()++ mock_get.assert_not_called()++ @override_settings(POSTHOG_FLAGS_PROJECT_SECRET_TOKEN="")+ def test_no_op_without_token(self):+ # Before the charts secret is provisioned, this would otherwise send a+ # request with an empty bearer token every 30s.+ with patch(f"{_MODULE}.requests.get") as mock_get:+ sync_cross_region_dogfood_flags()++ mock_get.assert_not_called()++ def test_sends_stored_etag_and_skips_write_on_304(self):+ payload = {"flags": [{"key": "existing"}], "group_type_mapping": {}, "cohorts": {}}+ flag_definitions_hypercache.set_cache_value(DOGFOOD_SELF_TEAM_ID, payload)+ local_etag = flag_definitions_hypercache.get_etag(DOGFOOD_SELF_TEAM_ID)+ assert local_etag++ with (+ patch(f"{_MODULE}.requests.get", return_value=_mock_response(304)) as mock_get,+ patch.object(flag_definitions_hypercache, "set_cache_value") as mock_set,+ ):+ sync_cross_region_dogfood_flags()++ url, kwargs = mock_get.call_args+ assert url[0] == "https://us.i.posthog.com/flags/definitions"+ assert kwargs["headers"]["Authorization"] == "Bearer phs_test_token"+ assert kwargs["headers"]["If-None-Match"] == f'"{local_etag}"'+ # 304 means unchanged -- a write here would defeat the point of sending the etag.+ mock_set.assert_not_called()++ def test_writes_fetched_payload_on_200(self):+ payload = {"flags": [{"key": "new-flag"}], "group_type_mapping": {}, "cohorts": {}}++ with patch(f"{_MODULE}.requests.get", return_value=_mock_response(200, payload)):+ sync_cross_region_dogfood_flags()++ assert flag_definitions_hypercache.get_from_cache(DOGFOOD_SELF_TEAM_ID) == payload+ # A write that doesn't arm the ETag would make every later tick skip the+ # conditional GET, silently degrading to a full transfer on every poll.+ assert flag_definitions_hypercache.get_etag(DOGFOOD_SELF_TEAM_ID)++ def test_fails_safe_on_request_exception(self):+ # A crash here would take down the Celery task every 30s; the existing+ # cache entry must survive an upstream hiccup instead.+ with (+ patch(f"{_MODULE}.requests.get", side_effect=requests.ConnectionError("boom")),+ patch.object(flag_definitions_hypercache, "set_cache_value") as mock_set,+ ):+ sync_cross_region_dogfood_flags()++ mock_set.assert_not_called()++ @parameterized.expand(+ [+ ("server_error", 500, False, None),+ ("bad_json_body", 200, True, None),+ # A non-dict shape would otherwise be cached verbatim and served to every+ # EU pod until the next successful sync -- must fail safe like the others.+ ("unexpected_shape", 200, False, ["not", "a", "dict"]),+ ]+ )+ def test_fails_safe_on_bad_response(self, _name, status_code, json_error, json_data):+ with (+ patch(f"{_MODULE}.requests.get", return_value=_mock_response(status_code, json_data, json_error)),+ patch.object(flag_definitions_hypercache, "set_cache_value") as mock_set,+ ):+ sync_cross_region_dogfood_flags()++ mock_set.assert_not_called()