: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
feat(db): add fail-fast circuit breaker for product databases (#62443)
Julian Bez0e5df838e199
diff --git a/posthog/db_backends/failopen/base.py b/posthog/db_backends/failopen/base.pynew file mode 100644index 000000000000..39c976071389--- /dev/null+++ b/posthog/db_backends/failopen/base.py@@ -0,0 +1,44 @@+from __future__ import annotations++from django.db import InterfaceError, OperationalError+from django.db.backends.postgresql.base import DatabaseWrapper as PostgresDatabaseWrapper++from posthog.db_circuit_breaker import get_circuit_breaker+++class CircuitOpenError(OperationalError):+ """Raised instead of attempting a connection when the breaker is open.++ Subclasses ``OperationalError`` so callers and the ORM treat it like any+ other database connection failure, but it is raised in microseconds rather+ than after the per-database ``connect_timeout``.+ """+++class DatabaseWrapper(PostgresDatabaseWrapper):+ """Postgres backend with a fail-fast circuit breaker on the connection path.++ When the breaker for this alias is open, ``ensure_connection`` raises+ immediately instead of waiting on a dead host — freeing the worker to serve+ other requests and stopping a single product-database outage from exhausting+ the shared worker pool. Connection failures feed the breaker so it opens+ after a few failures and probes for recovery on a cooldown.+ """++ def ensure_connection(self) -> None:+ if self.connection is not None:+ return++ breaker = get_circuit_breaker()+ decision = breaker.before_connect(self.alias)+ if not decision.allowed:+ raise CircuitOpenError(f"circuit breaker open for database '{self.alias}'")++ try:+ super().ensure_connection()+ except Exception as exc:+ if isinstance(exc, OperationalError | InterfaceError):+ breaker.record_failure(self.alias, was_probe=decision.is_probe)+ raise+ else:+ breaker.record_success(self.alias, was_probe=decision.is_probe)diff --git a/posthog/db_circuit_breaker.py b/posthog/db_circuit_breaker.pynew file mode 100644index 000000000000..6eaee4669192--- /dev/null+++ b/posthog/db_circuit_breaker.py@@ -0,0 +1,282 @@+from __future__ import annotations++import time+import logging+from dataclasses import dataclass+from functools import lru_cache++from django.conf import settings++import redis+from statshog.defaults.django import statsd++from posthog.redis import get_client++logger = logging.getLogger(__name__)+++def _now() -> float:+ return time.time()+++# Bumping the version invalidates breaker state from any prior version with+# different key semantics, so a rolling deploy can't mix incompatible writes.+_KEY_PREFIX = "posthog:dbcb:v1"++# Hard cap on how long a single breaker Redis call may block. Redis sits in the+# hot path of every product-DB connection, so it must never be the thing that+# stalls the request it is supposed to be protecting.+_REDIS_OP_TIMEOUT_SECONDS = 0.1++# Floor for how long the open marker is remembered in Redis (decoupled from the+# cooldown) so low-traffic products stay protected across idle gaps while down.+_OPEN_MARKER_MIN_TTL_SECONDS = 300++# Decide whether the breaker should let a connection attempt through. Returns+# {allowed, is_probe, open_until}. While open and within cooldown the request is+# denied without touching the database, and the real Redis deadline is returned+# so each worker can cache it accurately. Once cooldown expires the breaker is+# half-open: a single worker wins the probe lease and is allowed through to test+# recovery; everyone else keeps failing fast (open_until=0, so they don't cache+# and keep re-checking Redis to pick up recovery promptly).+_ALLOW_SCRIPT = """+local open_until = redis.call('GET', KEYS[1])+if not open_until then+ return {1, 0, 0}+end+if tonumber(ARGV[1]) < tonumber(open_until) then+ return {0, 0, tonumber(open_until)}+end+local got = redis.call('SET', KEYS[2], '1', 'NX', 'EX', ARGV[2])+if got then+ return {1, 1, 0}+end+return {0, 0, 0}+"""++# Record a failed connection. A failing probe re-opens the breaker immediately+# and releases the lease. Otherwise the failure counter is incremented within a+# fixed window (TTL set only when the counter is created); crossing the threshold+# opens the breaker. The open marker (KEYS[2]) holds the cooldown deadline as its+# value but is kept for ARGV[6] seconds — far longer than the cooldown — so a+# low-traffic product whose DB stays down through an idle gap still has the open+# marker present when traffic resumes, forcing a single half-open probe instead+# of letting every worker burn the connect timeout. Returns 1 when the breaker is+# open after this failure, else 0.+_FAILURE_SCRIPT = """+local now = tonumber(ARGV[1])+local threshold = tonumber(ARGV[2])+local cooldown = tonumber(ARGV[3])+local window = tonumber(ARGV[4])+local is_probe = ARGV[5]+local open_for = tonumber(ARGV[6])++if is_probe == '1' then+ redis.call('SET', KEYS[2], tostring(now + cooldown), 'EX', open_for)+ redis.call('DEL', KEYS[3])+ redis.call('DEL', KEYS[1])+ return 1+end++local n = redis.call('INCR', KEYS[1])+if n == 1 then+ redis.call('EXPIRE', KEYS[1], window)+end+if n >= threshold then+ redis.call('SET', KEYS[2], tostring(now + cooldown), 'EX', open_for)+ return 1+end+return 0+"""+++@dataclass(frozen=True)+class BreakerDecision:+ allowed: bool+ is_probe: bool+++_CLOSED = BreakerDecision(allowed=True, is_probe=False)+_DENIED = BreakerDecision(allowed=False, is_probe=False)+++@dataclass(frozen=True)+class _BreakerConfig:+ enabled: bool+ failure_threshold: int+ cooldown_seconds: int+ probe_timeout_seconds: int+ window_seconds: int+++def _load_config() -> _BreakerConfig:+ return _BreakerConfig(+ enabled=bool(getattr(settings, "PRODUCT_DB_CIRCUIT_BREAKER_ENABLED", False)),+ failure_threshold=int(getattr(settings, "PRODUCT_DB_CIRCUIT_BREAKER_FAILURE_THRESHOLD", 3)),+ cooldown_seconds=int(getattr(settings, "PRODUCT_DB_CIRCUIT_BREAKER_COOLDOWN_SECONDS", 30)),+ probe_timeout_seconds=int(getattr(settings, "PRODUCT_DB_CIRCUIT_BREAKER_PROBE_TIMEOUT_SECONDS", 5)),+ window_seconds=int(getattr(settings, "PRODUCT_DB_CIRCUIT_BREAKER_WINDOW_SECONDS", 30)),+ )+++@lru_cache(maxsize=1)+def _get_redis() -> redis.Redis | None:+ """Dedicated, tightly-timed Redis client for the breaker.++ Uses fakeredis in tests. In prod, builds a client with short socket timeouts+ so Redis itself can never block the connection path for more than ~100ms.+ """+ if settings.TEST:+ return get_client()++ redis_url = settings.REDIS_URL+ if not redis_url:+ return None++ return redis.from_url(+ redis_url,+ db=0,+ socket_timeout=_REDIS_OP_TIMEOUT_SECONDS,+ socket_connect_timeout=_REDIS_OP_TIMEOUT_SECONDS,+ )+++class ProductDBCircuitBreaker:+ """Per-alias fail-fast circuit breaker for product databases.++ State lives in Redis so one worker tripping the breaker is seen by all 50-200+ pods immediately, rather than each independently burning the connect timeout+ discovering the database is down. Every Redis call is wrapped to fail safe:+ if Redis is slow or unavailable the breaker stays closed and the normal+ connection attempt (with its own ``connect_timeout``) proceeds — the breaker+ must never be what takes a healthy database offline.++ A small in-process cache of the open deadline lets workers skip Redis+ entirely while the breaker is open, so an outage doesn't generate one Redis+ round-trip per request per worker.+ """++ def __init__(self) -> None:+ # Registered lazily off the first client; redis-py's Script handles the+ # EVALSHA-then-load-on-NOSCRIPT dance for us.+ self._allow_script: redis.commands.core.Script | None = None+ self._failure_script: redis.commands.core.Script | None = None+ # alias -> local monotonic-ish deadline (time.time) we believe it's open until+ self._local_open_until: dict[str, float] = {}++ def _keys(self, alias: str) -> tuple[str, str, str]:+ base = f"{_KEY_PREFIX}:{alias}"+ return f"{base}:fails", f"{base}:open_until", f"{base}:probe"++ def before_connect(self, alias: str) -> BreakerDecision:+ config = _load_config()+ if not config.enabled:+ return _CLOSED++ # Local fast-path: if we recently learned the breaker is open, don't even+ # talk to Redis until the cooldown we cached has elapsed.+ cached_until = self._local_open_until.get(alias)+ now = _now()+ if cached_until is not None and now < cached_until:+ return _DENIED++ client = _get_redis()+ if client is None:+ return _CLOSED++ _, open_until_key, probe_key = self._keys(alias)+ if self._allow_script is None:+ self._allow_script = client.register_script(_ALLOW_SCRIPT)+ try:+ result = self._allow_script(+ keys=[open_until_key, probe_key], args=[now, config.probe_timeout_seconds], client=client+ )+ except Exception:+ logger.exception("product_db_circuit_breaker_allow_failed", extra={"alias": alias})+ return _CLOSED++ allowed = bool(result[0])+ is_probe = bool(result[1])+ if allowed:+ self._local_open_until.pop(alias, None)+ return BreakerDecision(allowed=True, is_probe=is_probe)++ # Denied: cache the real Redis deadline so we skip Redis while genuinely+ # open. open_until=0 means the cooldown has elapsed and another worker+ # holds the probe lease — don't cache that, so we keep re-checking Redis+ # and pick up recovery as soon as the probe resolves.+ open_until = float(result[2])+ if open_until > now:+ self._local_open_until[alias] = open_until+ else:+ self._local_open_until.pop(alias, None)+ return _DENIED++ def record_failure(self, alias: str, *, was_probe: bool) -> None:+ config = _load_config()+ if not config.enabled:+ return+ client = _get_redis()+ if client is None:+ return++ fails_key, open_until_key, probe_key = self._keys(alias)+ if self._failure_script is None:+ self._failure_script = client.register_script(_FAILURE_SCRIPT)+ # Capture once so the local deadline matches the open_until Redis computes.+ now = _now()+ # Keep the open marker well past the cooldown so an idle, still-down product+ # forces a single probe (not a connect-timeout stampede) when traffic resumes.+ open_marker_ttl = max(config.cooldown_seconds * 10, _OPEN_MARKER_MIN_TTL_SECONDS)+ try:+ opened = self._failure_script(+ keys=[fails_key, open_until_key, probe_key],+ args=[+ now,+ config.failure_threshold,+ config.cooldown_seconds,+ config.window_seconds,+ int(was_probe),+ open_marker_ttl,+ ],+ client=client,+ )+ except Exception:+ logger.exception("product_db_circuit_breaker_record_failure_failed", extra={"alias": alias})+ return++ if opened:+ self._local_open_until[alias] = now + config.cooldown_seconds+ statsd.incr("product_db_circuit_breaker_opened", tags={"alias": alias})+ logger.warning(+ "product_db_circuit_breaker_opened",+ extra={"alias": alias, "was_probe": was_probe, "cooldown_seconds": config.cooldown_seconds},+ )++ def record_success(self, alias: str, *, was_probe: bool) -> None:+ # Only a successful probe needs to mutate state — it closes the breaker.+ # Successes in the normal closed state are the common case and stay+ # work-free so the healthy hot path costs a single Redis call (the allow).+ if not was_probe:+ return+ if not _load_config().enabled:+ return+ client = _get_redis()+ if client is None:+ return++ fails_key, open_until_key, probe_key = self._keys(alias)+ try:+ client.delete(fails_key, open_until_key, probe_key)+ except Exception:+ logger.exception("product_db_circuit_breaker_record_success_failed", extra={"alias": alias})+ return++ self._local_open_until.pop(alias, None)+ statsd.incr("product_db_circuit_breaker_closed", tags={"alias": alias})+ logger.warning("product_db_circuit_breaker_closed", extra={"alias": alias})+++@lru_cache(maxsize=1)+def get_circuit_breaker() -> ProductDBCircuitBreaker:+ return ProductDBCircuitBreaker()diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.pyindex 020133e5bf96..d8b9b446892d 100644--- a/posthog/settings/data_stores.py+++ b/posthog/settings/data_stores.py@@ -190,6 +190,27 @@ product_routes = load_product_db_routes(Path(__file__).resolve().parents[2])configured_product_databases: set[str] = set()PRODUCT_DB_WRITER_URLS: dict[str, str] = {}+# Fail-fast circuit breaker for product databases. When a product DB is+# unreachable, the custom backend raises immediately on connect instead of+# blocking the worker on `connect_timeout`, so one product's outage can't+# exhaust the shared worker pool. See posthog/db_circuit_breaker.py.+PRODUCT_DB_FAIL_OPEN_ENGINE = "posthog.db_backends.failopen"+PRODUCT_DB_CIRCUIT_BREAKER_ENABLED: bool = get_from_env(+ "PRODUCT_DB_CIRCUIT_BREAKER_ENABLED", not TEST, type_cast=str_to_bool+)+PRODUCT_DB_CIRCUIT_BREAKER_FAILURE_THRESHOLD: int = get_from_env(+ "PRODUCT_DB_CIRCUIT_BREAKER_FAILURE_THRESHOLD", 3, type_cast=int+)+PRODUCT_DB_CIRCUIT_BREAKER_COOLDOWN_SECONDS: int = get_from_env(+ "PRODUCT_DB_CIRCUIT_BREAKER_COOLDOWN_SECONDS", 30, type_cast=int+)+PRODUCT_DB_CIRCUIT_BREAKER_PROBE_TIMEOUT_SECONDS: int = get_from_env(+ "PRODUCT_DB_CIRCUIT_BREAKER_PROBE_TIMEOUT_SECONDS", 5, type_cast=int+)+PRODUCT_DB_CIRCUIT_BREAKER_WINDOW_SECONDS: int = get_from_env(+ "PRODUCT_DB_CIRCUIT_BREAKER_WINDOW_SECONDS", 30, type_cast=int+)+for route in product_routes:if route.database in configured_product_databases:continue@@ -212,10 +233,12 @@ for route in product_routes:PRODUCT_DB_WRITER_URLS[db] = writer_urlDATABASES[writer_alias] = dict(dj_database_url.parse(writer_url, conn_max_age=0))DATABASES[writer_alias].setdefault("OPTIONS", {})["connect_timeout"] = 3+ DATABASES[writer_alias]["ENGINE"] = PRODUCT_DB_FAIL_OPEN_ENGINEreader_url = os.getenv(reader_env, writer_url)DATABASES[reader_alias] = dict(dj_database_url.parse(reader_url, conn_max_age=0))DATABASES[reader_alias].setdefault("OPTIONS", {})["connect_timeout"] = 3+ DATABASES[reader_alias]["ENGINE"] = PRODUCT_DB_FAIL_OPEN_ENGINEif TEST:# Skip the global migration-graph walk during test DB setup. Withoutdiff --git a/posthog/test/test_db_circuit_breaker.py b/posthog/test/test_db_circuit_breaker.pynew file mode 100644index 000000000000..52a44eeb2dad--- /dev/null+++ b/posthog/test/test_db_circuit_breaker.py@@ -0,0 +1,139 @@+from unittest import mock++from django.test import SimpleTestCase, override_settings++from posthog.db_circuit_breaker import ProductDBCircuitBreaker, _get_redis+from posthog.redis import get_client++ALIAS = "visual_review_db_reader"++BREAKER_SETTINGS = {+ "PRODUCT_DB_CIRCUIT_BREAKER_ENABLED": True,+ "PRODUCT_DB_CIRCUIT_BREAKER_FAILURE_THRESHOLD": 3,+ "PRODUCT_DB_CIRCUIT_BREAKER_COOLDOWN_SECONDS": 30,+ "PRODUCT_DB_CIRCUIT_BREAKER_PROBE_TIMEOUT_SECONDS": 5,+ "PRODUCT_DB_CIRCUIT_BREAKER_WINDOW_SECONDS": 30,+}+++@override_settings(**BREAKER_SETTINGS)+class TestProductDBCircuitBreaker(SimpleTestCase):+ def setUp(self) -> None:+ super().setUp()+ _get_redis.cache_clear()+ get_client().flushdb()+ self.clock = {"now": 1000.0}+ self.now_patch = mock.patch("posthog.db_circuit_breaker._now", side_effect=lambda: self.clock["now"])+ self.now_patch.start()+ self.addCleanup(self.now_patch.stop)+ self.addCleanup(_get_redis.cache_clear)++ def _open_breaker(self, breaker: ProductDBCircuitBreaker) -> None:+ for _ in range(BREAKER_SETTINGS["PRODUCT_DB_CIRCUIT_BREAKER_FAILURE_THRESHOLD"]):+ breaker.record_failure(ALIAS, was_probe=False)++ def test_closed_breaker_allows_without_probe(self) -> None:+ decision = ProductDBCircuitBreaker().before_connect(ALIAS)+ self.assertTrue(decision.allowed)+ self.assertFalse(decision.is_probe)++ def test_failures_below_threshold_stay_closed(self) -> None:+ breaker = ProductDBCircuitBreaker()+ breaker.record_failure(ALIAS, was_probe=False)+ breaker.record_failure(ALIAS, was_probe=False)++ self.assertTrue(ProductDBCircuitBreaker().before_connect(ALIAS).allowed)++ def test_opens_after_threshold_failures(self) -> None:+ breaker = ProductDBCircuitBreaker()+ self._open_breaker(breaker)++ # A fresh breaker (other worker) sees the open state via shared Redis.+ self.assertFalse(ProductDBCircuitBreaker().before_connect(ALIAS).allowed)++ def test_denied_worker_caches_real_redis_deadline(self) -> None:+ # Breaker opens at now=1000, so Redis holds open_until=1030.+ self._open_breaker(ProductDBCircuitBreaker())+ self.clock["now"] += 25 # 1025, still within cooldown++ other_worker = ProductDBCircuitBreaker()+ self.assertFalse(other_worker.before_connect(ALIAS).allowed)+ # Caches the real Redis deadline (1030), not a fresh now+cooldown (1055).+ self.assertEqual(other_worker._local_open_until[ALIAS], 1030.0)++ def test_open_marker_outlives_cooldown(self) -> None:+ # The open marker must persist far longer than the cooldown so an idle,+ # still-down product forces a probe (not a connect stampede) when traffic+ # resumes. TTL uses fakeredis wall-clock, so assert right after opening.+ self._open_breaker(ProductDBCircuitBreaker())++ _, open_until_key, _ = ProductDBCircuitBreaker()._keys(ALIAS)+ ttl = get_client().ttl(open_until_key)+ self.assertGreater(ttl, BREAKER_SETTINGS["PRODUCT_DB_CIRCUIT_BREAKER_COOLDOWN_SECONDS"])++ def test_other_apps_unaffected_by_open_breaker(self) -> None:+ self._open_breaker(ProductDBCircuitBreaker())++ self.assertTrue(ProductDBCircuitBreaker().before_connect("warehouse_sources_queue_db_reader").allowed)++ def test_half_open_grants_single_probe(self) -> None:+ self._open_breaker(ProductDBCircuitBreaker())+ self.clock["now"] += 31 # cooldown elapsed++ first = ProductDBCircuitBreaker().before_connect(ALIAS)+ second = ProductDBCircuitBreaker().before_connect(ALIAS)++ self.assertTrue(first.allowed)+ self.assertTrue(first.is_probe)+ # Lease is held by the first probe — concurrent workers keep failing fast.+ self.assertFalse(second.allowed)++ def test_successful_probe_closes_breaker(self) -> None:+ self._open_breaker(ProductDBCircuitBreaker())+ self.clock["now"] += 31++ prober = ProductDBCircuitBreaker()+ probe = prober.before_connect(ALIAS)+ self.assertTrue(probe.is_probe)+ prober.record_success(ALIAS, was_probe=True)++ self.assertTrue(ProductDBCircuitBreaker().before_connect(ALIAS).allowed)++ def test_failed_probe_reopens_breaker(self) -> None:+ self._open_breaker(ProductDBCircuitBreaker())+ self.clock["now"] += 31++ prober = ProductDBCircuitBreaker()+ probe = prober.before_connect(ALIAS)+ self.assertTrue(probe.is_probe)+ prober.record_failure(ALIAS, was_probe=True)++ # Still open right after the failed probe; cooldown restarts.+ self.assertFalse(ProductDBCircuitBreaker().before_connect(ALIAS).allowed)+ self.clock["now"] += 31+ self.assertTrue(ProductDBCircuitBreaker().before_connect(ALIAS).is_probe)++ def test_local_cache_short_circuits_redis_while_open(self) -> None:+ breaker = ProductDBCircuitBreaker()+ self._open_breaker(breaker)++ # The breaker that tripped caches the open deadline and never hits Redis again.+ with mock.patch("posthog.db_circuit_breaker._get_redis") as redis_mock:+ self.assertFalse(breaker.before_connect(ALIAS).allowed)+ redis_mock.assert_not_called()++ @override_settings(PRODUCT_DB_CIRCUIT_BREAKER_ENABLED=False)+ def test_disabled_breaker_always_allows(self) -> None:+ breaker = ProductDBCircuitBreaker()+ self._open_breaker(breaker)++ self.assertTrue(breaker.before_connect(ALIAS).allowed)++ def test_fails_safe_open_when_redis_unavailable(self) -> None:+ with mock.patch("posthog.db_circuit_breaker._get_redis", return_value=None):+ self.assertTrue(ProductDBCircuitBreaker().before_connect(ALIAS).allowed)++ def test_redis_error_fails_safe_to_closed(self) -> None:+ breaker = ProductDBCircuitBreaker()+ breaker._allow_script = mock.Mock(side_effect=Exception("redis down"))+ self.assertTrue(breaker.before_connect(ALIAS).allowed)diff --git a/posthog/test/test_failopen_backend.py b/posthog/test/test_failopen_backend.pynew file mode 100644index 000000000000..e0df53385e1b--- /dev/null+++ b/posthog/test/test_failopen_backend.py@@ -0,0 +1,73 @@+from unittest import mock++from django.db import OperationalError, ProgrammingError+from django.test import SimpleTestCase++from posthog.db_backends.failopen.base import CircuitOpenError, DatabaseWrapper+from posthog.db_circuit_breaker import BreakerDecision++ALIAS = "visual_review_db_reader"+++class TestFailOpenBackend(SimpleTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.wrapper = DatabaseWrapper.__new__(DatabaseWrapper)+ self.wrapper.connection = None+ self.wrapper.alias = ALIAS++ self.breaker = mock.Mock()+ breaker_patch = mock.patch("posthog.db_backends.failopen.base.get_circuit_breaker", return_value=self.breaker)+ breaker_patch.start()+ self.addCleanup(breaker_patch.stop)++ self.super_patch = mock.patch("posthog.db_backends.failopen.base.PostgresDatabaseWrapper.ensure_connection")+ self.super_ensure = self.super_patch.start()+ self.addCleanup(self.super_patch.stop)++ def test_open_breaker_raises_without_connecting(self) -> None:+ self.breaker.before_connect.return_value = BreakerDecision(allowed=False, is_probe=False)++ with self.assertRaises(CircuitOpenError):+ self.wrapper.ensure_connection()++ self.super_ensure.assert_not_called()+ self.breaker.record_failure.assert_not_called()+ self.breaker.record_success.assert_not_called()++ def test_successful_connection_records_success(self) -> None:+ self.breaker.before_connect.return_value = BreakerDecision(allowed=True, is_probe=True)++ self.wrapper.ensure_connection()++ self.super_ensure.assert_called_once()+ self.breaker.record_success.assert_called_once_with(ALIAS, was_probe=True)+ self.breaker.record_failure.assert_not_called()++ def test_connection_failure_records_failure_and_reraises(self) -> None:+ self.breaker.before_connect.return_value = BreakerDecision(allowed=True, is_probe=False)+ self.super_ensure.side_effect = OperationalError("connection refused")++ with self.assertRaises(OperationalError):+ self.wrapper.ensure_connection()++ self.breaker.record_failure.assert_called_once_with(ALIAS, was_probe=False)+ self.breaker.record_success.assert_not_called()++ def test_query_error_is_not_counted_as_connection_failure(self) -> None:+ self.breaker.before_connect.return_value = BreakerDecision(allowed=True, is_probe=False)+ self.super_ensure.side_effect = ProgrammingError("relation does not exist")++ with self.assertRaises(ProgrammingError):+ self.wrapper.ensure_connection()++ self.breaker.record_failure.assert_not_called()+ self.breaker.record_success.assert_not_called()++ def test_existing_connection_skips_breaker(self) -> None:+ self.wrapper.connection = object()++ self.wrapper.ensure_connection()++ self.breaker.before_connect.assert_not_called()+ self.super_ensure.assert_not_called()diff --git a/products/README.md b/products/README.mdindex fea1a43ce790..b96c21c71803 100644--- a/products/README.md+++ b/products/README.md@@ -247,6 +247,17 @@ This aligns with the facade pattern: if your product needs data from Team or Use- No `ON DELETE CASCADE` from the main DB — handle cleanup in application code or via background tasks- No `transaction.atomic()` spanning both databases — design for eventual consistency across boundaries+### Resilience: the circuit breaker++Separate databases only isolate failures if your product's outage can't drag the rest of the app down with it. Two layers provide that:++1. **`connect_timeout=3`** on every product alias — a connection to an unreachable host fails in 3s instead of blocking on the OS TCP default (60-120s).+2. **A fail-fast circuit breaker** (`posthog/db_circuit_breaker.py`) on a custom database backend (`posthog.db_backends.failopen`). When a product DB is unreachable, the breaker opens after a few connection failures and then raises immediately on connect — in microseconds, instead of waiting on the timeout. This frees the worker to serve other requests, so one product database going down can't exhaust the shared worker pool and take the whole app offline.++Breaker state lives in Redis, so one worker tripping the breaker is seen by all pods at once. The breaker is **per product alias**: while it's open, only that product's endpoints fail (fast, with an `OperationalError`); everything else is unaffected. After a cooldown, a single probe request tests recovery and closes the breaker on success. If Redis itself is unavailable the breaker fails safe (stays closed) so it can never be what takes a healthy database offline.++There is **no fail-open redirect to `default`** — product tables don't exist there, so a redirect would only produce a different error. The isolation win is _fast, contained failure_, not silent degradation. Tune via `PRODUCT_DB_CIRCUIT_BREAKER_*` env vars; disabled in tests by default.+## Running tests with TurboProducts use Turborepo for selective testing. Only tests affected by your changes run.