: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(flags): read flag definitions from the dedicated redis behind a toggle (#97168)
James Gill46fa692e1d2a
diff --git a/docker-compose.base.yml b/docker-compose.base.ymlindex 74e500bc67d8..281dbc86f9d9 100644--- a/docker-compose.base.yml+++ b/docker-compose.base.yml@@ -356,7 +356,6 @@ services:KAFKA_HOSTS: 'kafka'DEPLOYMENT: hobbyCDP_API_URL: 'http://plugins:6738'- FLAGS_REDIS_ENABLED: false# Off-ORM persons_db util (posthog/persons_db.py). Hobby keeps persons in# the main posthog DB, so both point there.PERSONS_DB_WRITER_URL: 'postgres://posthog:posthog@db:5432/posthog'diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex e932d902516f..f6e693e79087 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -686,9 +686,9 @@ services:db:condition: service_healthyenvironment:- # Mode 2: Dual-write warming phase for developersFLAGS_REDIS_URL: 'redis://redis7:6379/1'- FLAGS_REDIS_ENABLED: 'false' # Warming but not reading yet+ # The /flags/definitions reader stays on shared Redis unless+ # FLAG_DEFINITIONS_DEDICATED_REDIS_ENABLED is set.REDIS_COMPRESSION_ENABLED: 'true'INTERNAL_REQUEST_TOKEN: 'dev-internal-token'diff --git a/docs/internal/feature-flags/hypercache-system.md b/docs/internal/feature-flags/hypercache-system.mdindex d528181ae629..15a43ed5fd60 100644--- a/docs/internal/feature-flags/hypercache-system.md+++ b/docs/internal/feature-flags/hypercache-system.md@@ -309,7 +309,7 @@ Operational controls:Result labels: `hit_redis`, `hit_s3`, `hit_db`, `missing`, `batch_miss`-ETag result labels: `hit` (client ETag matched, 304), `miss` (client sent a stale ETag), `none` (client sent none), `redis_missing` (the endpoint that answered held no ETag key), `redis_error` (the read itself failed)+ETag result labels: `hit` (client ETag matched, 304), `miss` (client sent a stale ETag), `none` (client sent none), `redis_missing` (the endpoint that answered held no ETag key), `redis_error` (the read failed, or the stored value did not decode)`redis_missing` and `redis_error` are the pair that separates a cache-tier problem from an unreachable cluster. Keep them apart on dashboards and alerts. `redis_missing` reports the read, not the cause: reads go to the replica, so a key Django wrote to the primary counts here until it replicates. A sustained rise is a tier that holds nothing, and a short burst that clears on its own is lag.@@ -344,36 +344,73 @@ cache tier both produce that symptom, so establish which one first.**1. Separate a cluster fault from an empty tier.** Split `flags_flag_definitions_etag_total`by `result`. A rise in `redis_error` points at the cluster; check managed-cache CPU,-evictions, command latency, and memory before going further. A rise in `redis_missing`+evictions, command latency, and memory before going further. `redis_error` also covers a+stored ETag that did not decode, so a flat count of one or two teams is corrupt data rather+than a cluster fault. A rise in `redis_missing`means Redis answered and the endpoint that served the read held no ETag key. That points atthe tier rather than at the cluster, but the label does not prove the entry is gone: readsgo to the replica, so replication lag reads as absence too. Confirm it in step 2 before yourebuild anything.-**2. Compare the endpoints for one affected team.** Django writes the dedicated instance-and mirrors to the shared one, and the reader serves from the shared copy, so the two can-disagree. Take a team id from a reader `Cache hit for flag definitions` record with-`source="s3"`. It logs at info, carries `team_id`, and names a team the alert is counting.-The absent-ETag record carries the key but logs at debug, so production does not keep it.+**2. Compare the endpoints for one affected team.** Django writes the dedicated instance and+mirrors to the shared one, so the two can disagree. Which copy the reader served depends on+`FLAG_DEFINITIONS_DEDICATED_REDIS_ENABLED`, so read+`flags_flag_definitions_reads_dedicated_redis` first and start from the cluster it names.+Reading the wrong endpoint makes a healthy mirror look broken.-Query the shared replica first.-That endpoint answered the read the metric counted, and the shared primary can hold a key the replica does not.-`REDIS_READER_URL` can be unset, in which case reads go to `REDIS_URL` and the first two commands return the same answer.+Take a team id from a reader `Cache hit for flag definitions` record with `source="s3"`. It+logs at info, carries `team_id`, and names a team the alert is counting. An absent ETag+writes no log record at all, so the `redis_missing` counter is the only signal that it+happened.++Query the replica of the cluster the gauge named.+That endpoint answered the read the metric counted, and that cluster's primary can hold a key the replica does not.+Either reader URL can be unset, in which case reads go to the matching writer URL.+The replica commands fall back the same way, so that cluster's two commands then return the same answer.++Check the payload key and its ETag key on each endpoint.+Redis evicts per key, so the pair can diverge although the writer sets both with one TTL.+The payload is the key the alert counts, and the ETag key explains the counters from step 1.```bash-# Shared replica, the endpoint the reader served from-redis-cli -u "$REDIS_READER_URL" exists "posthog:1:cache/teams/{team_id}/feature_flags/flags_with_cohorts.json:etag"+KEY="posthog:1:cache/teams/{team_id}/feature_flags/flags_with_cohorts.json"++# Shared replica, served to pods reporting reason="disabled" or reason="no_dedicated_client"+redis-cli -u "${REDIS_READER_URL:-$REDIS_URL}" exists "$KEY"+redis-cli -u "${REDIS_READER_URL:-$REDIS_URL}" exists "$KEY:etag"# Shared primary, which the mirror writes-redis-cli -u "$REDIS_URL" exists "posthog:1:cache/teams/{team_id}/feature_flags/flags_with_cohorts.json:etag"+redis-cli -u "$REDIS_URL" exists "$KEY"+redis-cli -u "$REDIS_URL" exists "$KEY:etag"++# Dedicated replica, served to pods reporting reason="dedicated"+redis-cli -u "${FLAGS_REDIS_READER_URL:-$FLAGS_REDIS_URL}" exists "$KEY"+redis-cli -u "${FLAGS_REDIS_READER_URL:-$FLAGS_REDIS_URL}" exists "$KEY:etag"-# Dedicated cluster, which Django writes first-redis-cli -u "$FLAGS_REDIS_URL" exists "posthog:1:cache/teams/{team_id}/feature_flags/flags_with_cohorts.json:etag"+# Dedicated primary, which Django writes first+redis-cli -u "$FLAGS_REDIS_URL" exists "$KEY"+redis-cli -u "$FLAGS_REDIS_URL" exists "$KEY:etag"```-Absent on the shared replica and present on the shared primary is replication lag, not a lost entry.+Read the branches below per key.++An absent payload beside a present ETag on the endpoint the reader served is the reading that+every ETag-only check calls healthy. The handler reads the ETag key on every request and answers+304 before it fetches the payload, so a team whose SDKs poll with a matching `If-None-Match`+keeps the ETag key recent while the payload ages toward eviction. Read repair is disabled for+this namespace, so the S3 hit does not rewarm the payload. Rebuild it with `update_flag_caches`.++An absent ETag beside a present payload serves a 200 with the full payload on every poll, so+it writes no `source="s3"` record and raises no alert. `redis_missing` climbing with no matching+rise in S3 reads is that state. It does not repair itself: `verify_team_flag_definitions`+compares the payload only, so the hourly verifier reads the team as clean and the ETag stays+missing until the team's next flag change or its TTL refresh. The counter carries no `team_id`,+so set `TEAM_IDS_TO_TRACK` to name a suspected team, or rebuild with `update_flag_caches`.++Absent on the replica of the cluster the reader served, and present on that cluster's primary,+is replication lag rather than a lost entry.Rebuilding fixes nothing.-Check replication lag on the shared cluster instead, and expect the alert to clear on its own.+Check replication lag on that cluster instead, and expect the alert to clear on its own.Present on the dedicated cluster and absent on both shared endpoints isolates the fault to themirror rather than to the writer. Absent everywhere means the entry was never built or has@@ -424,13 +461,26 @@ The feature-flags Rust service can use a separate Redis instance for caching, is### Enabling dedicated Redis```bash-FLAGS_REDIS_URL=redis://flags-redis:6379 # Separate instance for flags+FLAGS_REDIS_URL=redis://flags-redis:6379 # Separate instance for flags+FLAG_DEFINITIONS_DEDICATED_REDIS_ENABLED=false # Cluster the /flags/definitions reader uses```When `FLAGS_REDIS_URL` is set, Django registers it as the `flags_dedicated` cache alias (`FLAGS_DEDICATED_CACHE_ALIAS` in `posthog/caching/flags_redis_cache.py`, wired up in `posthog/settings/data_stores.py`).Four HyperCache instances bind that alias. For flags (`products/feature_flags/backend/flags_cache.py`), remote config, and team metadata, Django writes to the dedicated instance and the Rust service reads them from it.-The 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 SDK-facing flag-definitions cache (`local_evaluation.py`) is part-way through the same move, and its read side is switchable. 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.++`FLAG_DEFINITIONS_DEDICATED_REDIS_ENABLED` decides which cluster the Rust `/flags/definitions` reader uses. It defaults to false, which keeps the reader on the shared cache. Set it per fleet to move the reader to the dedicated instance.++Remove the mirror only after that move has baked. The mirror is what makes the switch reversible. With the mirror gone, a reader sent back to the shared cache reads a cluster nothing writes to. This endpoint has no database fallback on a miss.++The payload and the ETag always share one client. They therefore cannot disagree about which cluster holds the current definitions. `HyperCacheReader::get_etag` reads the same `redis_client` as the payload and derives its key from the same config. Both are set once in the constructor, from the client `server.rs` resolves.++Do not give the ETag a gate of its own. A stale ETag on one cluster can match a client `If-None-Match` while the other cluster holds a newer payload. The endpoint then answers 304 and pins the SDK to stale definitions. No metric records an error.++`flags_flag_definitions_reads_dedicated_redis` reports which cluster each pod resolved. Its `reason` label separates two cases. `disabled` is a pod nobody has switched. `no_dedicated_client` is a pod that was switched but could not build a dedicated client, so it reads the shared cache for the life of the process.++Reads on the dedicated instance go to its `-ro` reader endpoint. `NotFound` is unrecoverable, so `ReadWriteClient` does not consult the primary. A key the writer just wrote reads as absent until it replicates. That window serves a 200 with the full payload instead of a 304.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.diff --git a/docs/internal/feature-flags/rust-service-overview.md b/docs/internal/feature-flags/rust-service-overview.mdindex ec5aa19fec96..40c0cc0d422f 100644--- a/docs/internal/feature-flags/rust-service-overview.md+++ b/docs/internal/feature-flags/rust-service-overview.md@@ -274,15 +274,16 @@ Cache and query health are observable via the `flags_cohort_membership_cache_*`### Redis-| Variable | Default | Purpose |-| ----------------------------- | --------------------------- | ---------------------------------------- |-| `REDIS_URL` | `redis://localhost:6379/` | Shared Redis primary |-| `REDIS_READER_URL` | (falls back to `REDIS_URL`) | Shared Redis replica |-| `FLAGS_REDIS_URL` | (empty) | Dedicated flags Redis primary |-| `FLAGS_REDIS_READER_URL` | (empty) | Dedicated flags Redis replica |-| `FLAGS_REDIS_ENABLED` | `false` | Read from dedicated flags Redis |-| `REDIS_RESPONSE_TIMEOUT_MS` | `100` | Redis response timeout (capped at 30s) |-| `REDIS_CONNECTION_TIMEOUT_MS` | `5000` | Redis connection timeout (capped at 60s) |+| Variable | Default | Purpose |+| ------------------------------------------ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `REDIS_URL` | `redis://localhost:6379/` | Shared Redis primary |+| `REDIS_READER_URL` | (falls back to `REDIS_URL`) | Shared Redis replica |+| `FLAGS_REDIS_URL` | (empty) | Dedicated flags Redis primary |+| `FLAGS_REDIS_READER_URL` | (empty) | Dedicated flags Redis replica |+| `FLAGS_REDIS_ENABLED` | `false` | Inert. Nothing reads it, so setting it moves no read path |+| `FLAG_DEFINITIONS_DEDICATED_REDIS_ENABLED` | `false` | Serve the `/flags/definitions` payload and its ETag from the dedicated flags Redis instead of the shared one. See [dedicated flags Redis](hypercache-system.md#dedicated-flags-redis) |+| `REDIS_RESPONSE_TIMEOUT_MS` | `100` | Redis response timeout (capped at 30s) |+| `REDIS_CONNECTION_TIMEOUT_MS` | `5000` | Redis connection timeout (capped at 60s) |### S3 / HyperCachediff --git a/rust/feature-flags/src/api/flag_definitions.rs b/rust/feature-flags/src/api/flag_definitions.rsindex 4fdc6fcac8ff..3b70d84dc504 100644--- a/rust/feature-flags/src/api/flag_definitions.rs+++ b/rust/feature-flags/src/api/flag_definitions.rs@@ -23,7 +23,6 @@ use axum::{};use common_hypercache::{HyperCacheError, KeyType};use common_metrics::inc;-use common_redis::CustomRedisError;use common_types::TeamId;use once_cell::sync::Lazy;use serde::{Deserialize, Serialize};@@ -31,7 +30,7 @@ use serde_json::Value;use sqlx::PgPool;use std::collections::HashSet;use std::time::{SystemTime, UNIX_EPOCH};-use tracing::{debug, info, warn};+use tracing::{info, warn};const ALLOWLIST_TTL_SECS: u64 = 60;@@ -196,7 +195,37 @@ pub async fn flags_definitions(let client_etag = extract_etag_from_header(headers.get("if-none-match"));let team_key = KeyType::team(team.clone());- let current_etag = get_etag_from_redis(&state, &team_key).await;+ let current_etag = match state+ .flags_with_cohorts_hypercache_reader+ .get_etag(&team_key)+ .await+ {+ Ok(Some(etag)) => Some(etag),+ Ok(None) => {+ // Redis answered and held no ETag key for this team. Counted apart from a+ // cluster fault because the two need opposite responses: rebuild the cache+ // tier, or treat Redis as the fault.+ inc(+ FLAG_DEFINITIONS_ETAG_COUNTER,+ &[("result".to_string(), "redis_missing".to_string())],+ 1,+ );+ None+ }+ Err(e) => {+ warn!(+ team_id = team.id,+ error = %e,+ "Failed to read flag definitions ETag"+ );+ inc(+ FLAG_DEFINITIONS_ETAG_COUNTER,+ &[("result".to_string(), "redis_error".to_string())],+ 1,+ );+ None+ }+ };// If client sent a matching ETag, short-circuit with 304 (skip full data fetch)if let (Some(ref client_val), Some(ref current_val)) = (&client_etag, ¤t_etag) {@@ -299,72 +328,6 @@ pub(crate) fn extract_etag_from_header(header: Option<&axum::http::HeaderValue>)}}-/// Read the ETag for a team's flag definitions from Redis.-///-/// Django stores ETags as separate Redis keys with an `:etag` suffix,-/// pickle-serialized via Django's cache framework. Returns `None` if the-/// ETag is unavailable (cache miss, Redis error, deserialization error)-/// — this gracefully degrades to always returning 200 with full data.-async fn get_etag_from_redis(state: &AppState, team_key: &KeyType) -> Option<String> {- let config = state.flags_with_cohorts_hypercache_reader.config();- let cache_key = config.get_redis_cache_key(team_key);- let etag_key = format!("{}:etag", cache_key);-- match state.redis_client.get_raw_bytes(etag_key.clone()).await {- Ok(raw_bytes) => match serde_pickle::from_slice::<String>(&raw_bytes, Default::default()) {- Ok(etag) if !etag.is_empty() => Some(etag),- Ok(_) => None,- Err(e) => {- warn!(- etag_key = %etag_key,- error = %e,- "Failed to deserialize ETag from Redis"- );- None- }- },- Err(e) => {- // Absence is routine while a team's entry fills, and at warn level one cold- // entry writes a line per request. An unreachable cluster is not routine.- if matches!(e, CustomRedisError::NotFound) {- debug!(etag_key = %etag_key, "ETag absent from Redis");- } else {- warn!(- etag_key = %etag_key,- error = %e,- "Failed to read ETag from Redis"- );- }- inc(- FLAG_DEFINITIONS_ETAG_COUNTER,- &[(- "result".to_string(),- etag_read_failure_label(&e).to_string(),- )],- 1,- );- None- }- }-}--/// Metric label for a failed ETag read.-///-/// An absent key and an unreachable Redis need opposite responses: the first says the-/// Redis endpoint that answered holds no ETag key for this team, the second says the-/// cluster is down. One label for both hides that difference from the on-call, who has to-/// pick between rebuilding the cache and treating Redis as the fault.-///-/// `redis_missing` names what the read saw, not the cause. Reads go to a replica, and-/// `NotFound` is unrecoverable, so `ReadWriteClient` does not consult the primary. A key-/// that Django wrote to the primary therefore reads as absent until it replicates.-fn etag_read_failure_label(err: &CustomRedisError) -> &'static str {- match err {- CustomRedisError::NotFound => "redis_missing",- _ => "redis_error",- }-}-/// Handles non-GET HTTP methods (HEAD, OPTIONS, and unsupported methods)pub(crate) fn handle_non_get_method(method: &Method) -> Response {match *method {@@ -511,10 +474,11 @@ async fn get_from_cache(/// 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.+/// This is deliberately not the client the payload and the ETag are read from. The reader has its+/// own cluster switch (`FLAG_DEFINITIONS_DEDICATED_REDIS_ENABLED`, resolved in `server.rs`), so+/// during the cutover it can sit on either cluster while the queue must stay on the one Celery+/// drains. Unifying the queue with the reader severs the queue from the drain whenever the two+/// clusters differ.////// 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@@ -659,23 +623,6 @@ mod tests {assert_eq!(extract_etag_from_header(Some(&val)), None);}- #[test]- fn test_etag_read_failure_label_separates_absence_from_failure() {- // The on-call reads this label to choose between rebuilding the cache tier and- // treating Redis as the fault, so an absent key must not report as an error.- assert_eq!(- etag_read_failure_label(&CustomRedisError::NotFound),- "redis_missing"- );- for err in [- CustomRedisError::Timeout,- CustomRedisError::ParseError("bad pickle".to_string()),- CustomRedisError::InvalidConfiguration("no url".to_string()),- ] {- assert_eq!(etag_read_failure_label(&err), "redis_error");- }- }-#[test]fn test_extract_etag_from_header_bare_value() {let val = axum::http::HeaderValue::from_static("a1b2c3d4e5f6g7h8");diff --git a/rust/feature-flags/src/config.rs b/rust/feature-flags/src/config.rsindex b99391e3a55a..b40f5ba1abc0 100644--- a/rust/feature-flags/src/config.rs+++ b/rust/feature-flags/src/config.rs@@ -476,9 +476,7 @@ pub struct Config {#[envconfig(default = "")]pub flags_redis_reader_url: String,- // Controls whether to read from dedicated Redis cache- // false = Mode 2: dual-write to both caches, read from shared (warming phase)- // true = Mode 3: read and write dedicated Redis only (cutover complete)+ // Nothing reads this. Flipping it moves no read path and emits no warning.#[envconfig(default = "false")]pub flags_redis_enabled: FlexBool,@@ -489,6 +487,15 @@ pub struct Config {#[envconfig(from = "FLAG_DEFINITIONS_SELF_HEAL_ENABLED", default = "true")]pub flag_definitions_self_heal_enabled: FlexBool,+ // Cluster switch for the /flags/definitions reader. When enabled, the flags-with-cohorts+ // payload and its ETag both come from the dedicated flags Redis instead of the shared one.+ //+ // Deliberately a new variable rather than FLAGS_REDIS_ENABLED, which deployed environments+ // already set. Reusing it would tie the cutover to a deploy instead of a config change, and+ // remove the ability to flip the read path back without a rollout.+ #[envconfig(from = "FLAG_DEFINITIONS_DEDICATED_REDIS_ENABLED", default = "false")]+ pub flag_definitions_dedicated_redis_enabled: FlexBool,+// S3 configuration for HyperCache fallback#[envconfig(default = "posthog")]pub object_storage_bucket: String,@@ -1068,6 +1075,7 @@ impl Config {flags_redis_reader_url: "".to_string(),flags_redis_enabled: FlexBool(false),flag_definitions_self_heal_enabled: FlexBool(false),+ flag_definitions_dedicated_redis_enabled: FlexBool(false),redis_response_timeout_ms: 100,redis_connection_timeout_ms: 5000,write_database_url: "postgres://posthog:posthog@localhost:5432/test_posthog"diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rsindex 71bcd58bd0b8..831a52c42967 100644--- a/rust/feature-flags/src/metrics/consts.rs+++ b/rust/feature-flags/src/metrics/consts.rs@@ -377,9 +377,18 @@ pub const FLAG_DEFINITIONS_CACHE_HIT_COUNTER: &str = "flags_flag_definitions_cacpub const FLAG_DEFINITIONS_CACHE_MISS_COUNTER: &str = "flags_flag_definitions_cache_miss_total";// Flag definitions ETag metrics-// Labels: result (hit = 304, miss = 200 with stale etag, none = 200 without etag, redis_error = etag read failed)+// Labels: result (hit = 304, miss = 200 with stale etag, none = 200 without etag,+// redis_missing = Redis answered and held no etag key,+// redis_error = the etag read failed or the stored value did not decode)pub const FLAG_DEFINITIONS_ETAG_COUNTER: &str = "flags_flag_definitions_etag_total";+// Per-pod resolved cluster for the /flags/definitions reader: 1 on the dedicated flags Redis,+// 0 on the shared one. Every emission carries a `reason` label, so+// `{reason="no_dedicated_client"}` separates a pod that wanted the dedicated cluster and could+// not get one from a pod nobody has flipped yet.+pub const FLAG_DEFINITIONS_READS_DEDICATED_REDIS_GAUGE: &str =+ "flags_flag_definitions_reads_dedicated_redis";+// Flag definitions self-heal: a cache miss enqueued a rebuild request for a Celery// worker to drain. Labels: result (ok = enqueued, error = redis zadd failed).pub const FLAG_DEFINITIONS_REBUILD_REQUESTED_COUNTER: &str =diff --git a/rust/feature-flags/src/server.rs b/rust/feature-flags/src/server.rsindex f894ce6d53e0..23f728da272f 100644--- a/rust/feature-flags/src/server.rs+++ b/rust/feature-flags/src/server.rs@@ -13,6 +13,7 @@ use crate::database_pools::DatabasePools;use crate::db_monitor::DatabasePoolMonitor;use crate::flags::flag_definitions_cache::FlagDefinitionsCache;use crate::flags::flag_group_type_mapping::GroupTypeCacheManager;+use crate::metrics::consts::FLAG_DEFINITIONS_READS_DEDICATED_REDIS_GAUGE;use crate::rayon_dispatcher::RayonDispatcher;use crate::router;use crate::tokio_monitor::TokioRuntimeMonitor;@@ -20,6 +21,7 @@ use common_cache::NegativeCache;use common_cookieless::CookielessManager;use common_geoip::GeoIpClient;use common_hypercache::{HyperCacheConfig, HyperCacheReader, S3Client};+use common_metrics::gauge;use common_redis::{Client, CompressionConfig, ReadWriteClient, ReadWriteClientConfig, RedisClient,};@@ -170,18 +172,26 @@ pub async fn serve_with_rate_limiter_clock<C>(let dedicated_redis_client =create_dedicated_readwrite_client(&config, compression_config.clone()).await;- // Log the cache migration mode based on configuration- let cache_mode = match (- dedicated_redis_client.is_some(),- *config.flags_redis_enabled,- ) {- (false, _) => "Mode 1 (Shared-only): All caches use shared Redis",- (true, false) => {- "Mode 2 (Dual-write): Reading from shared Redis, warming dedicated Redis in background"- }- (true, true) => "Mode 3 (Dedicated-only): All flags caches use dedicated Redis",+ // The flags-with-cohorts reader is the one flags cache with its own cluster switch.+ let (flags_with_cohorts_redis_client, flag_definitions_cluster) =+ resolve_flag_definitions_redis_client(+ dedicated_redis_client.as_ref(),+ &redis_client,+ *config.flag_definitions_dedicated_redis_enabled,+ );++ // Per cache, not one mode string: flags_with_cohorts no longer agrees with the rest.+ let other_flags_caches = if dedicated_redis_client.is_some() {+ "dedicated"+ } else {+ "shared"};- tracing::info!("Feature flags cache migration mode: {}", cache_mode);+ tracing::info!(+ other_flags_caches,+ flags_with_cohorts = flag_definitions_cluster.cluster(),+ flags_with_cohorts_reason = flag_definitions_cluster.reason(),+ "Feature flags Redis cluster per cache"+ );// Create database pools with persons routing supportlet database_pools = match DatabasePools::from_config(&config).await {@@ -395,9 +405,6 @@ pub async fn serve_with_rate_limiter_clock<C>(};// Create HyperCacheReader for flags with cohorts (used by /flags/definitions endpoint)- // Uses the shared cache (redis_client) - same cache Django writes to via HyperCache- let flags_with_cohorts_redis_client = redis_client.clone();-let mut flags_with_cohorts_config = HyperCacheConfig::new("feature_flags".to_string(),"flags_with_cohorts.json".to_string(),@@ -608,6 +615,21 @@ pub async fn serve_with_rate_limiter_clock<C>(rate_limiter_clock,);+ // Emitted here, not where the cluster is resolved: `router_with_rate_limiter_clock` installs+ // the Prometheus recorder, and a gauge set before that goes to the no-op recorder.+ gauge(+ FLAG_DEFINITIONS_READS_DEDICATED_REDIS_GAUGE,+ &[(+ "reason".to_string(),+ flag_definitions_cluster.reason().to_string(),+ )],+ if flag_definitions_cluster.reads_dedicated() {+ 1.0+ } else {+ 0.0+ },+ );+tracing::info!(service_mode = ?service_mode,"listening on {:?}",@@ -724,6 +746,68 @@ async fn create_readwrite_client(}}+/// Which cluster the `/flags/definitions` reader resolved to. `NoDedicatedClient` is kept+/// distinct from `Disabled` because both read shared, but only one of them is a fault.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum FlagDefinitionsCluster {+ Disabled,+ Dedicated,+ NoDedicatedClient,+}++impl FlagDefinitionsCluster {+ /// The cluster the reader serves from. Two of the three outcomes read shared, so this+ /// answers "which cluster" where `reason` answers "why".+ fn cluster(self) -> &'static str {+ match self {+ Self::Dedicated => "dedicated",+ Self::Disabled | Self::NoDedicatedClient => "shared",+ }+ }++ fn reason(self) -> &'static str {+ match self {+ Self::Disabled => "disabled",+ Self::Dedicated => "dedicated",+ Self::NoDedicatedClient => "no_dedicated_client",+ }+ }++ fn reads_dedicated(self) -> bool {+ matches!(self, Self::Dedicated)+ }+}++/// Pick the Redis cluster the `/flags/definitions` readers use.+///+/// Do not give the ETag a gate of its own. Both the payload and the ETag come from this one+/// client, so a stale-but-present ETag on one cluster can never match a client's `If-None-Match`+/// while the other cluster holds a newer payload. That pairing answers 304 and pins the SDK to+/// stale definitions with no error on any metric.+fn resolve_flag_definitions_redis_client(+ dedicated_redis_client: Option<&Arc<dyn Client + Send + Sync>>,+ shared_redis_client: &Arc<dyn Client + Send + Sync>,+ dedicated_enabled: bool,+) -> (Arc<dyn Client + Send + Sync>, FlagDefinitionsCluster) {+ match (dedicated_enabled, dedicated_redis_client) {+ (true, Some(dedicated)) => (dedicated.clone(), FlagDefinitionsCluster::Dedicated),+ (true, None) => {+ tracing::warn!(+ "FLAG_DEFINITIONS_DEDICATED_REDIS_ENABLED is set but no dedicated flags Redis \+ client exists. /flags/definitions keeps reading from shared Redis."+ );+ (+ shared_redis_client.clone(),+ FlagDefinitionsCluster::NoDedicatedClient,+ )+ }+ (false, _) => (+ shared_redis_client.clone(),+ FlagDefinitionsCluster::Disabled,+ ),+ }+}+/// Create dedicated ReadWriteClient for flags cache with graceful fallback////// Implements fallback strategy:@@ -876,7 +960,9 @@ pub async fn create_redis_client(#[cfg(test)]mod tests {use super::*;+ use common_redis::MockRedisClient;use lifecycle::LifecycleError;+ use rstest::rstest;/// Locks in the contract that drives the early-return paths in `serve()`:/// `fail_init` must surface a `ComponentFailure { tag: "http-server", reason }` —@@ -909,6 +995,59 @@ mod tests {);}+ /// An inverted toggle here moves a production read path with no other signal.+ #[rstest]+ #[case::off_with_dedicated(false, true, FlagDefinitionsCluster::Disabled, "disabled", "shared")]+ #[case::off_without_dedicated(+ false,+ false,+ FlagDefinitionsCluster::Disabled,+ "disabled",+ "shared"+ )]+ #[case::on_with_dedicated(+ true,+ true,+ FlagDefinitionsCluster::Dedicated,+ "dedicated",+ "dedicated"+ )]+ #[case::on_without_dedicated(+ true,+ false,+ FlagDefinitionsCluster::NoDedicatedClient,+ "no_dedicated_client",+ "shared"+ )]+ fn test_resolve_flag_definitions_redis_client(+ #[case] dedicated_enabled: bool,+ #[case] dedicated_present: bool,+ #[case] expected_cluster: FlagDefinitionsCluster,+ #[case] expected_reason: &str,+ #[case] expected_redis: &str,+ ) {+ let shared: Arc<dyn Client + Send + Sync> = Arc::new(MockRedisClient::new());+ let dedicated: Arc<dyn Client + Send + Sync> = Arc::new(MockRedisClient::new());++ let (resolved, cluster) = resolve_flag_definitions_redis_client(+ dedicated_present.then_some(&dedicated),+ &shared,+ dedicated_enabled,+ );++ let expected = if expected_cluster.reads_dedicated() {+ &dedicated+ } else {+ &shared+ };+ assert!(Arc::ptr_eq(&resolved, expected));+ assert_eq!(cluster, expected_cluster);+ // Runbook step 2 dispatches the on-call on these two strings, so a rename here+ // sends them to the wrong Redis endpoint during the cutover.+ assert_eq!(cluster.reason(), expected_reason);+ assert_eq!(cluster.cluster(), expected_redis);+ }+#[tokio::test]async fn test_create_dedicated_readwrite_client_no_config() {// When FLAGS_REDIS_URL is not set, should return Nonediff --git a/rust/feature-flags/src/utils/test_utils.rs b/rust/feature-flags/src/utils/test_utils.rsindex a43682058103..00fad8a67fef 100644--- a/rust/feature-flags/src/utils/test_utils.rs+++ b/rust/feature-flags/src/utils/test_utils.rs@@ -1826,15 +1826,27 @@ impl TestContext {.await}- /// Populate cache for a team and store an ETag alongside it.- /// The ETag is stored at `{cache_key}:etag` using pickle serialization,- /// matching Django's HyperCache behavior.+ /// Populate cache for a team and store an ETag alongside it, on the shared Redis.+ /// See `populate_cache_for_team_with_etag_on`.pub async fn populate_cache_for_team_with_etag(&self,team_id: i32,etag: &str,) -> Result<(), Error> {let redis_client = setup_redis_client(Some(self.config.redis_url.clone())).await;+ self.populate_cache_for_team_with_etag_on(redis_client, team_id, etag)+ .await+ }++ /// Populate cache for a team and store an ETag alongside it, on the given Redis.+ /// The ETag is stored at `{cache_key}:etag` using pickle serialization,+ /// matching Django's HyperCache behavior.+ pub async fn populate_cache_for_team_with_etag_on(+ &self,+ redis_client: Arc<dyn RedisClientTrait + Send + Sync>,+ team_id: i32,+ etag: &str,+ ) -> Result<(), Error> {self.populate_flag_definitions_cache(redis_client.clone(), team_id).await?;diff --git a/rust/feature-flags/tests/test_flag_definitions.rs b/rust/feature-flags/tests/test_flag_definitions.rsindex dd13fa37ca64..1ea686756457 100644--- a/rust/feature-flags/tests/test_flag_definitions.rs+++ b/rust/feature-flags/tests/test_flag_definitions.rs@@ -1601,7 +1601,29 @@ async fn test_flag_definitions_rate_limit_metrics_incremented() {let redis_client =feature_flags::utils::test_utils::setup_redis_client(Some(config.redis_url.clone())).await;context- .populate_flag_definitions_cache(redis_client, team.id)+ .populate_flag_definitions_cache(redis_client.clone(), team.id)+ .await+ .unwrap();++ // A second team whose `:etag` value cannot be decoded. Deleting `etag_read_failure_label`+ // left `redis_error` with no coverage, and this is the only test that can scrape /metrics.+ let (corrupt_team, corrupt_secret_token, _) = context+ .create_team_with_secret_token(None, None, None)+ .await+ .unwrap();+ context+ .populate_flag_definitions_cache(redis_client.clone(), corrupt_team.id)+ .await+ .unwrap();+ redis_client+ .set_bytes(+ format!(+ "posthog:1:cache/teams/{}/feature_flags/flags_with_cohorts.json:etag",+ corrupt_team.id+ ),+ b"not-a-pickle".to_vec(),+ None,+ ).await.unwrap();@@ -1634,6 +1656,19 @@ async fn test_flag_definitions_rate_limit_metrics_incremented() {assert_eq!(response.status(), 429);+ // The corrupt team is not rate limited, so this request reaches the ETag read.+ let corrupt_response = client+ .get(format!(+ "http://{}/flags/definitions?token={}",+ server.addr, corrupt_team.api_token+ ))+ .header("Authorization", format!("Bearer {corrupt_secret_token}"))+ .send()+ .await+ .unwrap();++ assert_eq!(corrupt_response.status(), 200);+// Fetch metrics from /metrics endpointlet metrics_response = client.get(format!("http://{}/metrics", server.addr))@@ -1653,6 +1688,42 @@ async fn test_flag_definitions_rate_limit_metrics_incremented() {"Metrics should include rate limited counter");+ // Runbook step 2 picks which cluster to query from this gauge, so assert the series and+ // its value and not just the metric name. This config leaves the toggle off.+ let gauge_value = metrics_text+ .lines()+ .find(|line| {+ line.starts_with("flags_flag_definitions_reads_dedicated_redis{")+ && line.contains(r#"reason="disabled""#)+ })+ .and_then(|line| line.rsplit(' ').next())+ .and_then(|value| value.parse::<f64>().ok());+ assert_eq!(+ gauge_value,+ Some(0.0),+ "A reader left on shared Redis should report the gauge at 0 with reason=\"disabled\". Metrics: {metrics_text}"+ );++ // An absent ETag writes no log record, so this counter is the only trace that it+ // happened. populate_flag_definitions_cache writes no `:etag` key, so the first+ // request above took that path.+ assert!(+ metrics_text.lines().any(|line| line+ .starts_with("flags_flag_definitions_etag_total{")+ && line.contains(r#"result="redis_missing""#)),+ "An absent ETag should count as redis_missing rather than redis_error. Metrics: {metrics_text}"+ );++ // Routing a decode failure back to Ok(None) would revert this to redis_missing, which sends+ // the on-call to rebuild a cache tier when the fault is corrupt data.+ assert!(+ metrics_text.lines().any(+ |line| line.starts_with("flags_flag_definitions_etag_total{")+ && line.contains(r#"result="redis_error""#)+ ),+ "An undecodable ETag should count as redis_error. Metrics: {metrics_text}"+ );+// Verify key label is present in metrics (key is the generic label for team_id)let key_label = format!("key=\"{}\"", team.id);assert!(@@ -1887,6 +1958,144 @@ async fn test_etag_graceful_degradation_without_stored_etag() {);}+/// Stands in for the dedicated cluster. The shared cache is database 0, so keys cannot collide.+const DEDICATED_REDIS_URL: &str = "redis://localhost:6379/1";++/// Setup both dedicated-cluster tests need: the reader pointed at the dedicated database with+/// the toggle on, plus a team to request.+async fn dedicated_context_and_team() -> (+ feature_flags::config::Config,+ feature_flags::utils::test_utils::TestContext,+ feature_flags::team::team_models::Team,+ String,+) {+ use feature_flags::config::{Config, FlexBool};+ use feature_flags::utils::test_utils::TestContext;++ let config = Config {+ flags_redis_url: DEDICATED_REDIS_URL.to_string(),+ flag_definitions_dedicated_redis_enabled: FlexBool(true),+ ..Config::default_test_config()+ };+ let context = TestContext::new(Some(&config)).await;+ let (team, secret_token, _) = context+ .create_team_with_secret_token(None, None, None)+ .await+ .unwrap();++ (config, context, team, secret_token)+}++/// Seeds only the dedicated database: a reader left on shared 503s, and a payload that moved+/// without its ETag loses the header.+#[tokio::test]+async fn test_dedicated_redis_serves_payload_and_etag() {+ use feature_flags::utils::test_utils::setup_redis_client;++ let (config, context, team, secret_token) = dedicated_context_and_team().await;++ let etag_value = "dedicated_etag_01";+ let dedicated = setup_redis_client(Some(DEDICATED_REDIS_URL.to_string())).await;+ context+ .populate_cache_for_team_with_etag_on(dedicated, team.id, etag_value)+ .await+ .unwrap();++ let server = common::ServerHandle::for_config(config.clone()).await;+ let client = reqwest::Client::new();++ let response = client+ .get(format!(+ "http://{}/flags/definitions?token={}",+ server.addr, team.api_token+ ))+ .header("Authorization", format!("Bearer {secret_token}"))+ .send()+ .await+ .unwrap();++ let status = response.status();+ let etag_header = response+ .headers()+ .get("etag")+ .map(|v| v.to_str().unwrap().to_string());+ let body_text = response.text().await.unwrap();++ assert_eq!(+ status, 200,+ "Should read the payload from the dedicated Redis. Body: {body_text}"+ );+ let body: serde_json::Value = serde_json::from_str(&body_text).unwrap();+ assert!(+ body.get("flags").is_some(),+ "Body should carry the dedicated payload. Body: {body_text}"+ );+ assert_eq!(+ etag_header.as_deref(),+ Some(format!("W/\"{etag_value}\"").as_str()),+ "Should serve the dedicated ETag"+ );+}++/// The split-brain 304, which is silent in production: a shared ETag matching while the+/// dedicated cluster holds a newer payload pins the SDK to stale definitions.+#[tokio::test]+async fn test_dedicated_redis_ignores_shared_etag() {+ use feature_flags::utils::test_utils::setup_redis_client;++ let (config, context, team, secret_token) = dedicated_context_and_team().await;++ let shared_etag = "shared_etag_0001";+ let dedicated_etag = "dedicated_etag_1";+ let shared = setup_redis_client(Some(config.redis_url.clone())).await;+ let dedicated = setup_redis_client(Some(DEDICATED_REDIS_URL.to_string())).await;+ context+ .populate_cache_for_team_with_etag_on(shared, team.id, shared_etag)+ .await+ .unwrap();+ context+ .populate_cache_for_team_with_etag_on(dedicated, team.id, dedicated_etag)+ .await+ .unwrap();++ let server = common::ServerHandle::for_config(config.clone()).await;+ let client = reqwest::Client::new();++ let response = client+ .get(format!(+ "http://{}/flags/definitions?token={}",+ server.addr, team.api_token+ ))+ .header("Authorization", format!("Bearer {secret_token}"))+ .send()+ .await+ .unwrap();++ assert_eq!(response.status(), 200);+ assert_eq!(+ response.headers().get("etag").unwrap().to_str().unwrap(),+ format!("W/\"{dedicated_etag}\""),+ "Should serve the dedicated ETag, not the shared one"+ );++ let response = client+ .get(format!(+ "http://{}/flags/definitions?token={}",+ server.addr, team.api_token+ ))+ .header("Authorization", format!("Bearer {secret_token}"))+ .header("If-None-Match", format!("W/\"{shared_etag}\""))+ .send()+ .await+ .unwrap();++ assert_eq!(+ response.status(),+ 200,+ "The shared cluster's ETag must not produce a 304 once reads are dedicated"+ );+}+#[tokio::test]async fn test_flag_definitions_billing_limited_returns_402() {use feature_flags::{config::Config, utils::test_utils::TestContext};@@ -2763,11 +2972,11 @@ async fn test_cache_miss_enqueues_rebuild_on_dedicated_redis() {};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`).+ // The Celery drain reads the queue from the dedicated cluster, so the enqueue has to follow+ // the writer regardless of which cluster the reader is on. This case leaves+ // FLAG_DEFINITIONS_DEDICATED_REDIS_ENABLED off, so the reader is still on shared.let mut config = Config::default_test_config();- config.flags_redis_url = "redis://localhost:6379/1".to_string();+ config.flags_redis_url = DEDICATED_REDIS_URL.to_string();config.flag_definitions_self_heal_enabled = FlexBool(true);let context = TestContext::new(Some(&config)).await;