: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): clarify Kafka routing is exclusive, not dual-write (#68058)
Phil Haack711c70630bf4
diff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.pyindex 955ec0c9de33..b1fb07db0b15 100644--- a/products/feature_flags/backend/flags_cache.py+++ b/products/feature_flags/backend/flags_cache.py@@ -922,24 +922,26 @@ def get_cache_stats() -> dict[str, Any]:# Signal handlers for automatic cache invalidation-# DUAL-WRITE TRANSITIONAL CODE — remove at cutover.+# KAFKA-CUTOVER TRANSITIONAL CODE — remove at cutover.# Stages: producer (this block) at 0% → Rust consumer ships → ramp gate to 100%# → Kafka becomes primary, this block is deleted and the signal handlers call# the Kafka path directly. The Celery task `update_team_service_flags_cache`# outlives cutover — `cohort_changed_flags_cache` still calls it directly until# cohort invalidation gets its own topic. Throwaway code by design; don't polish.#-# Transitional surface: DUAL_WRITE_FLAG, _kafka_dual_write_enabled,+# Transitional surface: KAFKA_ROUTING_FLAG, _route_to_kafka,# _produce_invalidation, _enqueue_invalidation, and the Kafka branch inside it.# The signal handlers themselves stay; their tails simplify at cutover.-# Per-team gate for the Kafka producer side of dual-write. Celery remains the-# authoritative path until cutover; the Kafka produce is fire-and-forget.-DUAL_WRITE_FLAG = "flags-cache-kafka-dual-write"+# Per-team gate that routes invalidation to Kafka instead of Celery — see+# _enqueue_invalidation for why the two paths are mutually exclusive. The key+# string is kept as "dual-write" (not renamed to match KAFKA_ROUTING_FLAG) since+# it's the live PostHog flag key — renaming it would repoint the rollout.+KAFKA_ROUTING_FLAG = "flags-cache-kafka-dual-write"-def _kafka_dual_write_enabled(team_id: int) -> bool:- """Return True if this team should also produce a Kafka invalidation message.+def _route_to_kafka(team_id: int) -> bool:+ """Return True if this team's invalidation should route to Kafka instead of Celery.A `None` return from `feature_enabled` means the local-eval cache hasn'tloaded the flag definition yet. Treated as disabled, but ticks@@ -952,7 +954,7 @@ def _kafka_dual_write_enabled(team_id: int) -> bool:# None when local evaluation can't resolve the flag. Widen the type so# the None branch below survives type checking.result: bool | None = posthoganalytics.feature_enabled(- DUAL_WRITE_FLAG,+ KAFKA_ROUTING_FLAG,f"team-{team_id}",groups={"project": str(team_id)},group_properties={"project": {"id": str(team_id)}},@@ -963,9 +965,11 @@ def _kafka_dual_write_enabled(team_id: int) -> bool:# If the flag client misbehaves, default to Celery-only — never block the signal handler.# Log so a silent disable across the fleet during rollout is visible in Sentry.logger.warning(+ # Event name kept as "dual_write" (not renamed to match KAFKA_ROUTING_FLAG) so it+ # keeps matching existing Sentry searches set up during the dual-write phase."flags_cache_kafka_dual_write_flag_evaluation_failed",team_id=team_id,- flag=DUAL_WRITE_FLAG,+ flag=KAFKA_ROUTING_FLAG,exc_info=True,)return False@@ -973,6 +977,8 @@ def _kafka_dual_write_enabled(team_id: int) -> bool:if result is None:TOMBSTONE_COUNTER.labels(namespace="flags",+ # Label kept as "dual_write" for continuity with the existing Grafana dashboards+ # referenced above.operation="dual_write_gate_cache_cold",component="flags_cache",).inc()@@ -984,8 +990,9 @@ def _kafka_dual_write_enabled(team_id: int) -> bool:def _produce_invalidation(team_id: int) -> None:"""Produce a single invalidation message; swallow Kafka errors.- Celery is the source of truth during dual-write — a Kafka produce failure- here must not break flag editing. Per-message delivery success/failure is+ A produce failure here must not raise out of a signal handler — see+ `_enqueue_invalidation` for why that means the invalidation is dropped+ rather than retried via Celery. Per-message delivery success/failure isalso counted in KAFKA_PRODUCER_MESSAGES_COUNTER (wired in `_KafkaProducer.produce`).`data` must be a dict (not pre-encoded bytes): `_KafkaProducer.produce`@@ -1011,24 +1018,29 @@ def _produce_invalidation(team_id: int) -> None:def _enqueue_invalidation(team_id: int) -> None:- """Run from `transaction.on_commit`: dual-write to Kafka if enabled, then fire Celery.+ """Run from `transaction.on_commit`: route to Kafka if enabled, otherwise Celery.Deferring until commit avoids race conditions where the Celery worker reads- pre-commit state. Shared by all three signal handlers wired to the+ pre-commit state. Shared by all four signal handlers wired to theflag-invalidation topic. Cohort invalidation is intentionally not routedhere — cohort changes flow through their own topic.- Kafka runs first so a Celery-broker outage (Redis down) does not suppress- the rollout-observability signal we're trying to gather. The Kafka path- swallows its own errors, so it cannot block Celery. Celery's `.delay()`- is allowed to raise — it's the authoritative path during dual-write and- operators want broker failures loud.+ The two paths are mutually exclusive so the rollout proves the Kafka path+ actually works end to end: Celery is not a fallback when the flag is on,+ so a stuck Kafka producer shows up as a stale cache for that team instead+ of being masked by Celery quietly picking up the slack. `_produce_invalidation`+ still swallows its own errors — a produce failure must not raise out of a+ signal handler — but for a flagged team that failure means the invalidation+ is dropped, not retried via Celery. Watch `flags_cache_invalidation_produce_failed`+ logs during rollout. Celery's `.delay()` is allowed to raise when the flag+ is off — it's the sole path in that case and operators want broker failures loud."""from products.feature_flags.backend.tasks import update_team_service_flags_cache- if _kafka_dual_write_enabled(team_id):+ if _route_to_kafka(team_id):_produce_invalidation(team_id)- update_team_service_flags_cache.delay(team_id)+ else:+ update_team_service_flags_cache.delay(team_id)@receiver(post_save, sender=FeatureFlag)diff --git a/products/feature_flags/backend/test/test_flags_cache.py b/products/feature_flags/backend/test/test_flags_cache.pyindex 068e6e11dc55..b8150c97d720 100644--- a/products/feature_flags/backend/test/test_flags_cache.py+++ b/products/feature_flags/backend/test/test_flags_cache.py@@ -743,23 +743,23 @@ class TestServiceFlagsSignals(BaseTest):@override_settings(FLAGS_REDIS_URL="redis://test")-class TestServiceFlagsKafkaDualWrite(BaseTest):- """Kafka dual-write side of the signal handlers. Celery enqueue stays- unchanged; the Kafka produce sits behind a per-team feature flag and- never breaks the signal handler if Kafka is unhappy."""+class TestServiceFlagsKafkaRouting(BaseTest):+ """Kafka/Celery routing side of the signal handlers. The per-team feature+ flag exclusively routes each invalidation to Kafka or Celery — never both —+ and a Kafka produce failure must not break the signal handler."""def setUp(self):super().setUp()clear_flags_cache(self.team, kinds=["redis", "s3"])@patch("products.feature_flags.backend.flags_cache._produce_invalidation")- @patch("products.feature_flags.backend.flags_cache._kafka_dual_write_enabled", return_value=False)+ @patch("products.feature_flags.backend.flags_cache._route_to_kafka", return_value=False)@patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")@patch("django.db.transaction.on_commit", lambda fn: fn())- def test_dual_write_off_skips_kafka_produce(self, mock_task, mock_gate, mock_produce):+ def test_flag_off_routes_to_celery_only(self, mock_task, mock_gate, mock_produce):FeatureFlag.objects.create(team=self.team,- key="dual-write-off",+ key="flag-off",created_by=self.user,filters={"groups": [{"properties": [], "rollout_percentage": 100}]},)@@ -767,21 +767,21 @@ class TestServiceFlagsKafkaDualWrite(BaseTest):mock_produce.assert_not_called()@patch("products.feature_flags.backend.flags_cache.producer_scope")- @patch("products.feature_flags.backend.flags_cache._kafka_dual_write_enabled", return_value=True)+ @patch("products.feature_flags.backend.flags_cache._route_to_kafka", return_value=True)@patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")@patch("django.db.transaction.on_commit", lambda fn: fn())- def test_dual_write_on_produces_to_kafka(self, mock_task, mock_gate, mock_producer_scope):+ def test_flag_on_routes_to_kafka_only(self, mock_task, mock_gate, mock_producer_scope):mock_producer = MagicMock()mock_producer_scope.return_value.__enter__.return_value = mock_producerFeatureFlag.objects.create(team=self.team,- key="dual-write-on",+ key="flag-on",created_by=self.user,filters={"groups": [{"properties": [], "rollout_percentage": 100}]},)- mock_task.delay.assert_called_once_with(self.team.id)+ mock_task.delay.assert_not_called()mock_producer_scope.assert_called_once()scope_kwargs = mock_producer_scope.call_args.kwargsassert scope_kwargs["topic"] == KAFKA_FLAGS_CACHE_INVALIDATION@@ -803,60 +803,46 @@ class TestServiceFlagsKafkaDualWrite(BaseTest):assert envelope.operation == "invalidate"@patch("products.feature_flags.backend.flags_cache.producer_scope")- @patch("products.feature_flags.backend.flags_cache._kafka_dual_write_enabled", return_value=True)+ @patch("products.feature_flags.backend.flags_cache._route_to_kafka", return_value=True)@patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")@patch("django.db.transaction.on_commit", lambda fn: fn())- def test_dual_write_swallows_produce_errors(self, mock_task, mock_gate, mock_producer_scope):+ def test_flag_on_kafka_failure_does_not_raise_or_fall_back_to_celery(+ self, mock_task, mock_gate, mock_producer_scope+ ):mock_producer_scope.side_effect = RuntimeError("kafka cluster unreachable")- # Should not raise — Kafka outage must not break flag editing.+ # Should not raise — Kafka outage must not break flag editing. Celery+ # is not a fallback when the flag is on, so it must stay untouched.FeatureFlag.objects.create(team=self.team,- key="dual-write-error",+ key="flag-on-kafka-error",created_by=self.user,filters={"groups": [{"properties": [], "rollout_percentage": 100}]},)- mock_task.delay.assert_called_once_with(self.team.id)+ mock_task.delay.assert_not_called()mock_gate.assert_called_once_with(self.team.id)mock_producer_scope.assert_called_once()@patch("products.feature_flags.backend.flags_cache._produce_invalidation")- @patch("products.feature_flags.backend.flags_cache._kafka_dual_write_enabled", return_value=True)- @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")- @patch("django.db.transaction.on_commit", lambda fn: fn())- def test_kafka_produces_before_celery_enqueue(self, mock_task, mock_gate, mock_produce):- parent = MagicMock()- parent.attach_mock(mock_produce, "produce")- parent.attach_mock(mock_task.delay, "celery")-- FeatureFlag.objects.create(- team=self.team,- key="dual-write-order",- created_by=self.user,- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},- )-- call_names = [c[0] for c in parent.mock_calls]- assert call_names == ["produce", "celery"], f"expected produce before celery, got {call_names}"-- @patch("products.feature_flags.backend.flags_cache._produce_invalidation")- @patch("products.feature_flags.backend.flags_cache._kafka_dual_write_enabled", return_value=True)+ @patch("products.feature_flags.backend.flags_cache._route_to_kafka", return_value=False)@patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")@patch("django.db.transaction.on_commit", lambda fn: fn())- def test_kafka_produces_even_when_celery_broker_raises(self, mock_task, mock_gate, mock_produce):+ def test_flag_off_celery_broker_failure_propagates(self, mock_task, mock_gate, mock_produce):mock_task.delay.side_effect = RuntimeError("celery broker unreachable")+ # Celery is the sole path when the flag is off, so a broker failure+ # must be loud rather than swallowed.with pytest.raises(RuntimeError, match="celery broker unreachable"):FeatureFlag.objects.create(team=self.team,- key="dual-write-celery-down",+ key="flag-off-celery-down",created_by=self.user,filters={"groups": [{"properties": [], "rollout_percentage": 100}]},)mock_gate.assert_called_once_with(self.team.id)- mock_produce.assert_called_once_with(self.team.id)+ mock_produce.assert_not_called()@patch("products.feature_flags.backend.flags_cache._produce_invalidation")@patch(@@ -902,22 +888,22 @@ class TestServiceFlagsKafkaDualWrite(BaseTest):mock_tombstone.labels.return_value.inc.assert_called_once()@patch("products.feature_flags.backend.flags_cache._produce_invalidation")- @patch("products.feature_flags.backend.flags_cache._kafka_dual_write_enabled", return_value=True)+ @patch("products.feature_flags.backend.flags_cache._route_to_kafka", return_value=True)@patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")@patch("django.db.transaction.on_commit", lambda fn: fn())- def test_team_create_dual_writes(self, mock_task, mock_gate, mock_produce):- new_team = Team.objects.create(organization=self.organization, name="Dual-Write Team")- mock_task.delay.assert_called_with(new_team.id)+ def test_team_create_routes_to_kafka_when_flag_on(self, mock_task, mock_gate, mock_produce):+ new_team = Team.objects.create(organization=self.organization, name="Kafka Routing Team")+ mock_task.delay.assert_not_called()mock_produce.assert_called_with(new_team.id)@patch("products.feature_flags.backend.flags_cache._produce_invalidation")- @patch("products.feature_flags.backend.flags_cache._kafka_dual_write_enabled", return_value=True)+ @patch("products.feature_flags.backend.flags_cache._route_to_kafka", return_value=True)@patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")@patch("django.db.transaction.on_commit", lambda fn: fn())- def test_evaluation_context_save_dual_writes(self, mock_task, mock_gate, mock_produce):+ def test_evaluation_context_save_routes_to_kafka_when_flag_on(self, mock_task, mock_gate, mock_produce):flag = FeatureFlag.objects.create(team=self.team,- key="dual-write-ctx-save",+ key="flag-on-ctx-save",created_by=self.user,filters={"groups": [{"properties": [], "rollout_percentage": 100}]},)@@ -925,17 +911,17 @@ class TestServiceFlagsKafkaDualWrite(BaseTest):mock_task.reset_mock()mock_produce.reset_mock()- ctx = EvaluationContext.objects.create(team=self.team, name="ctx-dual-write")+ ctx = EvaluationContext.objects.create(team=self.team, name="ctx-kafka-routing")FeatureFlagEvaluationContext.objects.create(feature_flag=flag, evaluation_context=ctx)- mock_task.delay.assert_called_with(self.team.id)+ mock_task.delay.assert_not_called()mock_produce.assert_called_with(self.team.id)@patch("products.feature_flags.backend.flags_cache._produce_invalidation")- @patch("products.feature_flags.backend.flags_cache._kafka_dual_write_enabled", return_value=True)+ @patch("products.feature_flags.backend.flags_cache._route_to_kafka", return_value=True)@patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")@patch("django.db.transaction.on_commit", lambda fn: fn())- def test_cohort_change_does_not_dual_write(self, mock_task, mock_gate, mock_produce):+ def test_cohort_change_does_not_route_through_gate(self, mock_task, mock_gate, mock_produce):"""Cohort changes flow through their own topic — must bypass _enqueue_invalidation."""Cohort.objects.create(team=self.team,