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.

fix(preflight): restore kafka connectivity probe (#58743)

posthog[bot]8ba83d48f152
diff --git a/posthog/api/test/test_preflight.py b/posthog/api/test/test_preflight.py
index 8cb2afcd0e41..1a01bc164b12 100644
--- a/posthog/api/test/test_preflight.py
+++ b/posthog/api/test/test_preflight.py
@@ -9,6 +9,7 @@ from unittest.mock import patch
from django.test import override_settings
from django.utils import timezone
+from parameterized import parameterized
from rest_framework import status
from posthog.cloud_utils import TEST_clear_instance_license_cache
@@ -317,6 +318,23 @@ class TestPreflight(APIBaseTest, QueryMatchingTest):
assert response.json()["allow_dev_login"] is True
assert is_dev_login_allowed()
+ @parameterized.expand([(False,), (True,)])
+ def test_preflight_kafka_reflects_probe_on_self_hosted(self, probe_result):
+ # Regression for #54702: the kafka probe was removed, hardcoding the
+ # response to False off-cloud and blocking self-hosted Live-mode setup.
+ # Patch is_kafka_connected at the view's import site so the preflight
+ # wiring is exercised directly; TEST=False also defeats the helper's own
+ # DEBUG/TEST short-circuit as belt-and-braces.
+ self.client.logout()
+ with (
+ self.is_cloud(False),
+ self.settings(TEST=False, OBJECT_STORAGE_ENABLED=False),
+ patch("posthog.views.is_kafka_connected", return_value=probe_result),
+ ):
+ response = self.client.get("/_preflight/")
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["kafka"] is probe_result
+
@override_settings(DEBUG=True, ALLOW_DEV_LOGIN=False)
def test_preflight_omits_allow_dev_login_when_disabled(self):
with self.is_cloud(False):
diff --git a/posthog/health.py b/posthog/health.py
index d8adebe92dea..721a2322daff 100644
--- a/posthog/health.py
+++ b/posthog/health.py
@@ -28,10 +28,13 @@ from django.db import DEFAULT_DB_ALIAS, connections
from django.db.migrations.executor import MigrationExecutor
from django.http import HttpRequest, HttpResponse, JsonResponse
+from confluent_kafka import Producer as ConfluentProducer
from structlog import get_logger
from posthog.celery import app
from posthog.database_healthcheck import DATABASE_FOR_FLAG_MATCHING
+from posthog.kafka_client.profiles import KafkaClusterProfile
+from posthog.kafka_client.routing import get_producer
from posthog.security.outbound_proxy import internal_requests
logger = get_logger(__name__)
@@ -237,6 +240,32 @@ def is_clickhouse_connected() -> bool:
return True
+def is_kafka_connected() -> bool:
+ """
+ Probe Kafka connectivity for the preflight check on self-hosted instances.
+
+ Constructs a producer for the DEFAULT cluster profile (routing-aware) and
+ asks for cluster metadata with a short timeout. If either step fails, the
+ cluster is treated as unreachable.
+ """
+ if settings.DEBUG or settings.TEST:
+ return True
+
+ try:
+ producer = get_producer(profile=KafkaClusterProfile.DEFAULT)
+ # Outside TEST/DEBUG `_KafkaProducer` always wraps a real `ConfluentProducer`
+ # (the test fake has no `list_topics`), but mypy can't see that from the
+ # union type — cast to narrow it.
+ cast(ConfluentProducer, producer.producer).list_topics(timeout=3)
+ except Exception:
+ # Surface at warning, not debug: this probe exists so a self-hosted operator
+ # can see *why* /preflight blocks setup. Debug logs are off by default, which
+ # would leave them with a red light and no reason.
+ logger.warning("kafka_connection_failure", exc_info=True)
+ return False
+ return True
+
+
def is_celery_broker_connected() -> bool:
"""
Check we can connect to the celery broker.
diff --git a/posthog/test/test_health.py b/posthog/test/test_health.py
index 5b176cffe969..7262db3c6243 100644
--- a/posthog/test/test_health.py
+++ b/posthog/test/test_health.py
@@ -24,7 +24,7 @@ import kombu.connection
import kombu.exceptions
import django_redis.exceptions
-from posthog.health import logger
+from posthog.health import is_kafka_connected, logger
@pytest.mark.django_db
@@ -372,6 +372,50 @@ def test_readyz_skips_prestop_check_when_setting_is_empty(client: Client):
assert resp.status_code == 200
[email protected]("debug,test", [(False, True), (True, False)])
+def test_is_kafka_connected_short_circuits_under_debug_or_test(debug, test):
+ # Either DEBUG or TEST avoids the live probe — keeps local dev and the test
+ # suite from needing a real broker.
+ with patch("posthog.health.settings.DEBUG", debug), patch("posthog.health.settings.TEST", test):
+ assert is_kafka_connected() is True
+
+
+ "break_producer",
+ [
+ pytest.param(
+ lambda m: setattr(m, "side_effect", Exception("producer build failed")),
+ id="producer_build_raises",
+ ),
+ pytest.param(
+ lambda m: setattr(m.return_value.producer.list_topics, "side_effect", Exception("broker unreachable")),
+ id="list_topics_raises",
+ ),
+ ],
+)
+def test_is_kafka_connected_returns_false_when_probe_fails(break_producer):
+ # Either step failing — building the producer or the metadata round-trip — is
+ # treated as the broker being unreachable.
+ with (
+ patch("posthog.health.settings.DEBUG", False),
+ patch("posthog.health.settings.TEST", False),
+ patch("posthog.health.get_producer") as get_producer_mock,
+ ):
+ break_producer(get_producer_mock)
+ assert is_kafka_connected() is False
+
+
+def test_is_kafka_connected_returns_true_when_metadata_succeeds():
+ with (
+ patch("posthog.health.settings.DEBUG", False),
+ patch("posthog.health.settings.TEST", False),
+ patch("posthog.health.get_producer") as get_producer_mock,
+ ):
+ get_producer_mock.return_value.producer.list_topics.return_value = mock.Mock()
+ assert is_kafka_connected() is True
+ get_producer_mock.return_value.producer.list_topics.assert_called_once_with(timeout=3)
+
+
@pytest.fixture(autouse=True)
def debug_log_level():
"""
diff --git a/posthog/views.py b/posthog/views.py
index 00bfcb40aedf..26645d77379d 100644
--- a/posthog/views.py
+++ b/posthog/views.py
@@ -29,7 +29,7 @@ from posthog.auth import AUTH_BRAND_COOKIE, apply_auth_brand_cookie, normalize_a
from posthog.cloud_utils import is_cloud
from posthog.email import is_email_available
from posthog.exceptions_capture import capture_exception
-from posthog.health import is_clickhouse_connected
+from posthog.health import is_clickhouse_connected, is_kafka_connected
from posthog.helpers.dev_login import is_dev_login_allowed
from posthog.models import Organization, User
from posthog.models.activity_logging.activity_log import Detail, log_activity
@@ -197,7 +197,7 @@ def preflight_check(request: HttpRequest) -> JsonResponse:
"clickhouse": in_cloud
or _traced("preflight.is_clickhouse_connected", is_clickhouse_connected)
or settings.TEST,
- "kafka": in_cloud or settings.TEST,
+ "kafka": in_cloud or _traced("preflight.is_kafka_connected", is_kafka_connected),
"db": in_cloud or _traced("preflight.is_postgres_alive", is_postgres_alive),
"initiated": in_cloud or _traced("preflight.organization_exists", Organization.objects.exists),
"cloud": in_cloud,