: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): move the self-heal rebuild queue to the dedicated redis (#96648)
James Gilla183c565df2a
diff --git a/docs/internal/feature-flags/hypercache-system.md b/docs/internal/feature-flags/hypercache-system.mdindex 30b4677d0faf..8582f5b8a572 100644--- a/docs/internal/feature-flags/hypercache-system.md+++ b/docs/internal/feature-flags/hypercache-system.md@@ -367,6 +367,8 @@ Four HyperCache instances bind that alias. For flags (`products/feature_flags/baThe SDK-facing flag-definitions cache (`local_evaluation.py`) is part-way through the same move, so its write side and read side currently point at different clusters. Django writes it to the dedicated instance and mirrors each write to the shared default cache, covering the payload, the ETag, and the cache-miss sentinel. Deletes mirror as well. The Rust `/flags/definitions` reader still reads the shared cache, so the shared copy is the one serving SDK traffic. A later change moves that reader to the dedicated instance, and the mirror is removed after it.+The flag-definitions self-heal queue follows the write side, not the read side. The Rust endpoint enqueues a rebuild request on the dedicated instance (`State::flags_namespace_redis_client`), and the Celery drain reads the queue from `flag_definitions_hypercache.redis_url` (`products/feature_flags/backend/rebuild_queue.py`). Both resolve from `FLAGS_REDIS_URL`, so the producer and the consumer move together on configuration. They can still split on connection state: a Rust process that cannot reach the dedicated cluster at startup falls back to the shared one and enqueues there for its whole life, while Celery keeps draining the dedicated one. Those teams wait for the hourly verifier. `server.rs` logs that startup failure at error level, and the same failure already sends the flags.json, team-metadata, and remote-config readers to the shared cluster, where Django writes nothing. Django and the Rust fleet deploy independently, so a deploy of one before the other leaves requests on the cluster the other side is not reading. Clean up on the **shared** cluster only, and never on the dedicated one, which holds the live queue once both sides are up. A Rust-first rollout puts the window's requests on the dedicated cluster, where the drain collects them as soon as Django deploys, so they need no cleanup. A Django-first rollout puts them on the shared cluster, where nothing reads them again. Either order also leaves the pre-move queue members and the open circuits on the shared cluster. Run `DEL flag_definitions:rebuild_requests flag_definitions:rebuild_circuit` there after both sides are deployed. The circuit-breaker set is included because only the drain prunes it and the key carries no TTL. The cooldown and failure-streak keys expire on their own.+The Rust service only operates when `FLAGS_REDIS_URL` is configured. All cache update functions check this setting and skip operations if not set.## Scheduled tasksdiff --git a/products/feature_flags/backend/rebuild_queue.py b/products/feature_flags/backend/rebuild_queue.pyindex e59b39da91c7..6fdeddb0ac20 100644--- a/products/feature_flags/backend/rebuild_queue.py+++ b/products/feature_flags/backend/rebuild_queue.py@@ -78,6 +78,14 @@ REBUILD_DEAD_LETTER = Gauge("posthog_flag_definitions_rebuild_dead_letter_teams","Teams whose rebuild circuit is open (repeatedly failing)",)+# Every other gauge here reads the cluster the drain resolved, so a producer and consumer+# split reads as zero on all of them while the enqueue counter still reports ok: a dead+# queue looks healthy. This reads the cluster the drain does not use, which is non-zero+# only while the two ends disagree. Remove it when the dedicated-Redis move is complete.+REBUILD_UNREAD_CLUSTER_DEPTH = Gauge(+ "posthog_flag_definitions_rebuild_unread_cluster_depth",+ "Teams queued on the Redis cluster the drain does not read (0 when both ends agree)",+)def _parse_team_id(raw: bytes | str) -> int | None:@@ -89,10 +97,13 @@ def _parse_team_id(raw: bytes | str) -> int | None:def _redis() -> redis_lib.Redis:- # Pinned to the shared Redis, matching the Rust producer. The hypercache's- # redis_url follows cache_alias, which binds the dedicated cluster, so the- # producer and consumer must move together or not at all.- return get_client(settings.REDIS_URL)+ # Derived from the hypercache, so the consumer follows the same cluster as the+ # writer: dedicated when FLAGS_REDIS_URL registers the alias, shared otherwise.+ # The Rust producer resolves the same setting (`State::flags_namespace_redis_client`),+ # but falls back to the shared cluster when it cannot reach the dedicated one at+ # startup. Such a process enqueues where nothing drains, and its teams wait for the+ # hourly verifier.+ return get_client(flag_definitions_hypercache.redis_url)def drain_rebuild_requests(batch_size: int = DRAIN_BATCH_SIZE) -> dict[str, int]:@@ -153,8 +164,24 @@ def drain_rebuild_requests(batch_size: int = DRAIN_BATCH_SIZE) -> dict[str, int]return stats+def _emit_unread_cluster_gauge() -> None:+ """Publish the queue depth on the cluster the drain does not read, so the deploy window+ and the cleanup step afterwards are both observable. Failures here must not fail a drain,+ because this gauge is diagnostic."""+ if flag_definitions_hypercache.redis_url == settings.REDIS_URL:+ REBUILD_UNREAD_CLUSTER_DEPTH.set(0)+ return+ try:+ depth = get_client(settings.REDIS_URL).zcard(REBUILD_REQUESTS_ZSET)+ except Exception:+ logger.exception("flag definitions self-heal unread cluster gauge failed")+ return+ REBUILD_UNREAD_CLUSTER_DEPTH.set(depth)++def _emit_queue_gauges(redis: redis_lib.Redis, now: float) -> None:REBUILD_QUEUE_DEPTH.set(redis.zcard(REBUILD_REQUESTS_ZSET))+ _emit_unread_cluster_gauge()oldest = redis.zrange(REBUILD_REQUESTS_ZSET, 0, 0, withscores=True)if oldest:# score is the most-recent enqueue time in epoch millis. Rust re-enqueues withdiff --git a/products/feature_flags/backend/test/test_rebuild_queue.py b/products/feature_flags/backend/test/test_rebuild_queue.pyindex 0105b2791f95..f2d6b5bf6a07 100644--- a/products/feature_flags/backend/test/test_rebuild_queue.py+++ b/products/feature_flags/backend/test/test_rebuild_queue.py@@ -1,4 +1,5 @@import time+from collections.abc import Iteratorfrom contextlib import contextmanagerfrom types import SimpleNamespace@@ -6,12 +7,16 @@ import pytestfrom unittest.mock import patchfrom django.conf import settings+from django.test import override_settingsimport fakeredisfrom celery.exceptions import SoftTimeLimitExceededfrom prometheus_client import REGISTRY+from posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIAS+from products.feature_flags.backend import rebuild_queue+from products.feature_flags.backend.local_evaluation import _build_flag_definitions_hypercachefrom products.feature_flags.backend.rebuild_queue import (CIRCUIT_OPEN_THRESHOLD,CIRCUIT_ZSET,@@ -55,6 +60,26 @@ def _enqueue(client, team_id, score=0):client.zadd(REBUILD_REQUESTS_ZSET, {str(team_id): score})+DEDICATED_REDIS_URL = "redis://flags-dedicated:6379/"+++@contextmanager+def _dedicated_cache(registered: bool) -> Iterator[None]:+ """Force the dedicated flags cache alias on or off, then rebuild the hypercache so the+ real cache_alias derivation runs rather than a patched URL. Both cases are pinned+ because FLAGS_REDIS_URL decides this and a developer's environment may set it while CI+ does not. Without the alias the hypercache URL collapses onto settings.REDIS_URL, which+ makes a split between the producer's cluster and the consumer's unrepresentable."""+ caches = {alias: cache for alias, cache in settings.CACHES.items() if alias != FLAGS_DEDICATED_CACHE_ALIAS}+ if registered:+ caches[FLAGS_DEDICATED_CACHE_ALIAS] = {**settings.CACHES["default"], "LOCATION": DEDICATED_REDIS_URL}+ with (+ override_settings(CACHES=caches),+ patch.object(rebuild_queue, "flag_definitions_hypercache", _build_flag_definitions_hypercache()),+ ):+ yield++def test_drain_rebuilds_queued_team_and_clears_it(fake_redis):_enqueue(fake_redis, 140414)with _rebuilds():@@ -200,14 +225,63 @@ def test_request_zset_key_matches_rust_contract():assert REBUILD_REQUESTS_ZSET == "flag_definitions:rebuild_requests"-def test_redis_client_pinned_to_the_shared_cluster():- # The Rust producer enqueues on the shared Redis. Deriving the consumer's client- # from the hypercache (whose cache_alias binds the dedicated cluster) splits the- # queue: the drain reads an empty set while misses pile up unseen on the shared one.- # The hypercache URL is forced to differ because in test settings it equals- # settings.REDIS_URL, and equal URLs cannot detect a revert of the pin.+def test_drain_reads_the_dedicated_cluster_and_ignores_the_shared_one():+ # Rust enqueues on the dedicated cluster whenever FLAGS_REDIS_URL is configured+ # (State::flags_namespace_redis_client), so a drain that reads the shared one finds an+ # empty set while misses pile up unseen.+ dedicated, shared = fakeredis.FakeRedis(), fakeredis.FakeRedis()+ clients = {DEDICATED_REDIS_URL: dedicated, settings.REDIS_URL: shared}++ with _dedicated_cache(registered=True):+ _enqueue(dedicated, 140414)+ _enqueue(shared, 999999)+ with (+ patch.object(rebuild_queue, "get_client", side_effect=lambda url: clients[url]),+ _rebuilds() as set_cache,+ ):+ stats = drain_rebuild_requests()++ assert stats["success"] == 1+ assert [call.args[0].id for call in set_cache.call_args_list] == [140414]+ assert dedicated.zcard(REBUILD_REQUESTS_ZSET) == 0+ assert shared.zrange(REBUILD_REQUESTS_ZSET, 0, -1) == [b"999999"]+++def test_unread_cluster_gauge_reports_the_other_cluster_depth():+ # Every other gauge follows the cluster the drain resolved, so a producer and consumer+ # split reads zero on all of them. This one is the signal that the split happened, and+ # the one that shows the post-deploy cleanup worked.+ dedicated, shared = fakeredis.FakeRedis(), fakeredis.FakeRedis()+ clients = {DEDICATED_REDIS_URL: dedicated, settings.REDIS_URL: shared}++ with _dedicated_cache(registered=True):+ _enqueue(shared, 999999)+ _enqueue(shared, 999998)+ with (+ patch.object(rebuild_queue, "get_client", side_effect=lambda url: clients[url]),+ _rebuilds(),+ ):+ drain_rebuild_requests()++ assert REGISTRY.get_sample_value("posthog_flag_definitions_rebuild_unread_cluster_depth") == 2.0+++def test_unread_cluster_gauge_is_zero_when_both_ends_agree():+ # Self-hosted resolves both ends to one cluster, where "the other cluster" does not+ # exist. The gauge must read 0 rather than repeat the live queue depth.+ with _dedicated_cache(registered=False):+ with patch.object(rebuild_queue, "get_client", return_value=fakeredis.FakeRedis()), _rebuilds():+ drain_rebuild_requests()++ assert REGISTRY.get_sample_value("posthog_flag_definitions_rebuild_unread_cluster_depth") == 0.0+++def test_drain_falls_back_to_the_shared_cluster_without_the_alias():+ # Self-hosted installs leave FLAGS_REDIS_URL unset, so the alias never registers and+ # both ends stay on the shared cluster. A derivation that hardcodes the dedicated URL+ # points every self-hosted drain at a cluster that does not exist.with (- patch.object(rebuild_queue.flag_definitions_hypercache, "redis_url", "redis://dedicated:6379/"),+ _dedicated_cache(registered=False),patch.object(rebuild_queue, "get_client") as get_client_mock,):rebuild_queue._redis()diff --git a/rust/feature-flags/src/api/flag_definitions.rs b/rust/feature-flags/src/api/flag_definitions.rsindex bb9d19546fab..d2ee42337972 100644--- a/rust/feature-flags/src/api/flag_definitions.rs+++ b/rust/feature-flags/src/api/flag_definitions.rs@@ -39,7 +39,7 @@ const ALLOWLIST_TTL_SECS: u64 = 60;/// time in epoch millis). Must stay in sync with `REBUILD_REQUESTS_ZSET` in/// `products/feature_flags/backend/rebuild_queue.py` (pinned by the Python test/// `test_request_zset_key_matches_rust_contract`).-const FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET: &str = "flag_definitions:rebuild_requests";+pub(crate) const FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET: &str = "flag_definitions:rebuild_requests";static CONSTANCE_KEY: Lazy<String> = Lazy::new(|| constance_key("RATE_LIMITING_ALLOW_LIST_TEAMS"));/// Refresh the rate limit allowlist from the database if stale, then update the limiter.@@ -471,14 +471,29 @@ async fn get_from_cache(/// Fire-and-forget enqueue of a flag-definitions rebuild request on cache miss.///-/// Writes to a Redis sorted set on `state.redis_client` — the same shared client-/// the flags-with-cohorts HyperCacheReader is built from (see `server.rs`), so the-/// queue can never point at a different Redis than the one the cache lives in.+/// Writes to a Redis sorted set on the flags-namespace client, because that is where the+/// Django writer lives. The Celery drain derives its Redis from+/// `flag_definitions_hypercache.redis_url` (`rebuild_queue.py`), which resolves from the same+/// `FLAGS_REDIS_URL`. A request written to any other cluster is never drained and the team+/// never gets rebuilt.+///+/// The two ends agree on configuration, not on connection state. A process that cannot reach+/// the dedicated cluster at startup falls back to the shared one and enqueues there for its+/// whole life, while Celery keeps draining the dedicated one. Those teams wait for the hourly+/// verifier instead. The same startup failure already sends the flags.json, team-metadata, and+/// remote-config readers to the shared cluster, where Django writes nothing, so it degrades+/// more than this queue.+///+/// This is deliberately not the client the payload and the ETag are read from. During the+/// migration the flags-with-cohorts reader stays pinned to the shared cluster (`server.rs`),+/// which Django mirrors the cache to. Unifying the queue with the reader severs the queue+/// from the drain.+////// Re-enqueuing a team only updates its score, so a client polling a missing team/// every ~30s occupies a single slot. Spawned so it never adds latency to (or/// changes) the failing response.fn enqueue_flag_definitions_rebuild(state: &AppState, team_id: i32) {- let redis = state.redis_client.clone();+ let redis = state.flags_namespace_redis_client();tokio::spawn(async move {let score = SystemTime::now().duration_since(UNIX_EPOCH)diff --git a/rust/feature-flags/src/router.rs b/rust/feature-flags/src/router.rsindex 70e81480d2a6..1fa9472af607 100644--- a/rust/feature-flags/src/router.rs+++ b/rust/feature-flags/src/router.rs@@ -136,6 +136,22 @@ pub struct State {}impl State {+ /// The Redis cluster the flags namespace lives in: the dedicated flags cluster when its+ /// client exists, and the shared cluster when it does not. `server.rs` repeats this+ /// derivation inline for the flags.json, team_metadata, and remote-config readers and for+ /// the auth token cache, because those are built before `State` exists.+ ///+ /// The client is absent for two different reasons. `FLAGS_REDIS_URL` can be unset, and the+ /// dedicated cluster can be unreachable at process start (`create_dedicated_readwrite_client`+ /// in `server.rs`, which logs that failure at error level). Only the first reason keeps this+ /// process and Django on one cluster. The second sends every caller here to the shared+ /// cluster for the life of the process, while Django keeps using the dedicated one.+ pub(crate) fn flags_namespace_redis_client(&self) -> Arc<dyn RedisClient + Send + Sync> {+ self.dedicated_redis_client+ .clone()+ .unwrap_or_else(|| self.redis_client.clone())+ }+/// Builds a `FlagService` from shared state. Centralized so every endpoint gets the/// same caching/fallback config instead of copying the constructor per handler.pub(crate) fn flag_service(&self) -> FlagService {diff --git a/rust/feature-flags/src/utils/test_utils.rs b/rust/feature-flags/src/utils/test_utils.rsindex 5f9a8b83b114..cbcf33212463 100644--- a/rust/feature-flags/src/utils/test_utils.rs+++ b/rust/feature-flags/src/utils/test_utils.rs@@ -1,4 +1,5 @@use crate::{+ api::flag_definitions::FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET,cohorts::cohort_models::{Cohort, CohortId, CohortType},config::{Config, DEFAULT_TEST_CONFIG},flags::{@@ -211,7 +212,7 @@ pub async fn read_flag_definitions_rebuild_requests(redis_url: &str) -> Vec<Strilet redis = setup_redis_client(Some(redis_url.to_string())).await;redis.zrangebyscore(- "flag_definitions:rebuild_requests".to_string(),+ FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET.to_string(),"-inf".to_string(),"+inf".to_string(),)@@ -219,6 +220,17 @@ pub async fn read_flag_definitions_rebuild_requests(redis_url: &str) -> Vec<Stri.unwrap_or_default()}+/// Clear the flag-definitions self-heal rebuild-requests sorted set. Nothing flushes the+/// test redis between runs, and team ids restart when the test database is recreated, so a+/// stale member with a reused id would satisfy a poll on its first read.+pub async fn clear_flag_definitions_rebuild_requests(redis_url: &str) {+ let redis = setup_redis_client(Some(redis_url.to_string())).await;+ redis+ .del(FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET.to_string())+ .await+ .unwrap();+}+/// An S3 client that reports every key as NotFound. Lets integration tests force a/// genuine HyperCache `CacheMiss` (redis miss + S3 NotFound) without a real object/// store, so a `/flags/definitions` miss classifies as `cache_miss` rather thandiff --git a/rust/feature-flags/tests/test_flag_definitions.rs b/rust/feature-flags/tests/test_flag_definitions.rsindex eb38a055d564..dd13fa37ca64 100644--- a/rust/feature-flags/tests/test_flag_definitions.rs+++ b/rust/feature-flags/tests/test_flag_definitions.rs@@ -2752,6 +2752,68 @@ async fn test_cache_miss_enqueues_rebuild_when_self_heal_enabled() {);}+#[tokio::test]+async fn test_cache_miss_enqueues_rebuild_on_dedicated_redis() {+ use feature_flags::{+ config::{Config, FlexBool},+ utils::test_utils::{+ clear_flag_definitions_rebuild_requests, dummy_s3_client,+ read_flag_definitions_rebuild_requests, TestContext,+ },+ };+ use reqwest;++ // The Celery drain reads the queue from the dedicated cluster, so the enqueue has to+ // follow the writer even while the flags-with-cohorts reader is hardcoded to the+ // shared one (`server.rs`).+ let mut config = Config::default_test_config();+ config.flags_redis_url = "redis://localhost:6379/1".to_string();+ config.flag_definitions_self_heal_enabled = FlexBool(true);+ let context = TestContext::new(Some(&config)).await;++ let (team, secret_token, _) = context+ .create_team_with_secret_token(None, None, None)+ .await+ .unwrap();+ // Only the dedicated db is cleared: the shared one is polled concurrently by the+ // sibling self-heal tests in this binary, so the shared assertion below compares+ // membership before and after instead of requiring an empty set.+ clear_flag_definitions_rebuild_requests(&config.flags_redis_url).await;+ let shared_before = read_flag_definitions_rebuild_requests(&config.redis_url).await;++ // Leave both caches unseeded and inject a NotFound S3 so the read is a genuine+ // cache_miss rather than an s3_error.+ let server =+ common::ServerHandle::for_config_with_s3(config.clone(), Some(dummy_s3_client())).await;+ let response = reqwest::Client::new()+ .get(format!(+ "http://{}/flags/definitions?token={}",+ server.addr, team.api_token+ ))+ .header("Authorization", format!("Bearer {secret_token}"))+ .send()+ .await+ .unwrap();++ assert_eq!(response.status(), 503, "expected a cache-miss 503");+ assert!(+ poll_for_rebuild_enqueue(&config.flags_redis_url, team.id).await,+ "team {} should be enqueued on the dedicated redis, where the drain reads",+ team.id+ );++ let shared_after = read_flag_definitions_rebuild_requests(&config.redis_url).await;+ let added: Vec<&String> = shared_after+ .iter()+ .filter(|member| !shared_before.contains(member))+ .collect();+ assert!(+ !added.contains(&&team.id.to_string()),+ "team {} must not be enqueued on the shared redis, where nothing drains",+ team.id+ );+}+#[tokio::test]async fn test_cache_miss_does_not_enqueue_rebuild_when_self_heal_disabled() {use feature_flags::{