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(flags): tell an empty flag-definitions cache tier from a broken Redis (#97080)

Phil Haack7f21e6ce0f34
diff --git a/docs/internal/feature-flags/hypercache-system.md b/docs/internal/feature-flags/hypercache-system.md
index 8582f5b8a572..d528181ae629 100644
--- a/docs/internal/feature-flags/hypercache-system.md
+++ b/docs/internal/feature-flags/hypercache-system.md
@@ -305,9 +305,16 @@ Operational controls:
| `posthog_hypercache_sync_duration_seconds` | `result`, `namespace`, `value` | Cache sync timing |
| `posthog_remote_config_via_cache` | `result` | Remote config cache performance |
| `posthog_hypercache_read_repair` | `result`, `namespace`, `value` | Rust reader repair outcomes |
+| `flags_flag_definitions_etag_total` | `result` | Rust reader ETag read outcomes |
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)
+
+`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.
+
+`hit`, `miss`, and `none` partition every request. The two failure labels sit on top of that partition, and do not slice it. A failed ETag read increments `redis_missing` or `redis_error`, then falls through and increments `none` or `miss` as well. So read a failure label as a ratio over `hit + miss + none`, and never as a share of a stacked total. Stacked, the total exceeds the request rate, and `none` climbs in step with `redis_missing` for the same underlying cause.
+
Read repair result labels: `success`, `skipped` (key already existed, repair deferred to it), `error`
`skipped` also covers replica lag: reads go to the replica and repairs to the primary, so a key written to the primary but not yet replicated reads as cold and its repair is correctly refused.
@@ -329,6 +336,64 @@ redis-cli get "team_token:{api_token}"
When `FLAGS_REDIS_URL` is set, the local-evaluation flags key is written to the dedicated instance and mirrored to the shared cache, so `redis-cli` returns whichever copy the cluster you point it at holds. The two can disagree. Read the flag-definitions notes under "Dedicated flags Redis" before you act on either copy.
+### Elevated S3 read rate on `/flags/definitions`
+
+`HyperCacheElevatedS3ReadRate` and `HyperCacheCriticalS3ReadRate` fire when the reader
+serves `flags_with_cohorts.json` from S3 for too large a share of reads. Redis and the
+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`
+means Redis answered and the endpoint that served the read held no ETag key. That points at
+the tier rather than at the cluster, but the label does not prove the entry is gone: reads
+go to the replica, so replication lag reads as absence too. Confirm it in step 2 before you
+rebuild 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.
+
+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.
+
+```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"
+
+# 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"
+
+# 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"
+```
+
+Absent on the shared replica and present on the shared primary is replication lag, not a lost entry.
+Rebuilding fixes nothing.
+Check replication lag on the shared 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 the
+mirror rather than to the writer. Absent everywhere means the entry was never built or has
+aged out; rebuild it with `update_flag_caches` and look at step 3.
+
+A shared copy that is absent while the dedicated copy is present does not come back on its
+own. Read repair is disabled for ETag-enabled namespaces, the hourly verifier reads only the
+primary, and the refresh task selects teams by an expiry score stamped from the primary, so a
+team whose dedicated entry is fresh is never revisited. The team keeps reading from S3 until
+its next flag change, or until the primary entry nears its TTL. `update_flag_caches` writes
+both tiers and ends it sooner.
+
+**3. Confirm the writer runs.** Check the success and duration signals for the
+flag-definitions refresh and verification tasks. Tasks that run at their normal cadence and
+duration while entries stay missing point back at the mirror, not at a stalled writer.
+
+Mirror failures increment `posthog_hypercache_mirror_failure` and log `HyperCache secondary
+cache op failed`. Neither firing while the shared copy is absent means the mirror is not
+attempting the write at all, rather than attempting it and failing.
+
### Check cache source in responses
Local evaluation responses include cache source information via Prometheus metrics. Check the `posthog_hypercache_get_from_cache` metric with the appropriate labels.
@@ -345,12 +410,12 @@ update_flag_caches(team)
## Common issues
-| Symptom | Likely cause | Solution |
-| ---------------------------- | ------------------------------------ | ------------------------------------- |
-| Stale data after flag change | Signal not firing | Check transaction.on_commit is used |
-| Cache misses in production | Redis connection issues | Check Redis connectivity and metrics |
-| S3 fallback errors | Object storage misconfigured | Verify OBJECT_STORAGE_ENABLED setting |
-| ETag mismatches | Non-deterministic JSON serialization | HyperCache uses `sort_keys=True` |
+| Symptom | Likely cause | Solution |
+| ---------------------------- | --------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
+| Stale data after flag change | Signal not firing | Check transaction.on_commit is used |
+| Cache misses in production | Redis unreachable, or the tier holds no entry | Split the two with `flags_flag_definitions_etag_total`: `redis_error` is the cluster, `redis_missing` is the tier |
+| S3 fallback errors | Object storage misconfigured | Verify OBJECT_STORAGE_ENABLED setting |
+| ETag mismatches | Non-deterministic JSON serialization | HyperCache uses `sort_keys=True` |
## Dedicated flags Redis
diff --git a/rust/feature-flags/src/api/flag_definitions.rs b/rust/feature-flags/src/api/flag_definitions.rs
index d2ee42337972..4fdc6fcac8ff 100644
--- a/rust/feature-flags/src/api/flag_definitions.rs
+++ b/rust/feature-flags/src/api/flag_definitions.rs
@@ -23,6 +23,7 @@ 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};
@@ -30,7 +31,7 @@ use serde_json::Value;
use sqlx::PgPool;
use std::collections::HashSet;
use std::time::{SystemTime, UNIX_EPOCH};
-use tracing::{info, warn};
+use tracing::{debug, info, warn};
const ALLOWLIST_TTL_SECS: u64 = 60;
@@ -323,14 +324,23 @@ async fn get_etag_from_redis(state: &AppState, team_key: &KeyType) -> Option<Str
}
},
Err(e) => {
- warn!(
- etag_key = %etag_key,
- error = %e,
- "Failed to read ETag from Redis"
- );
+ // 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(), "redis_error".to_string())],
+ &[(
+ "result".to_string(),
+ etag_read_failure_label(&e).to_string(),
+ )],
1,
);
None
@@ -338,6 +348,23 @@ async fn get_etag_from_redis(state: &AppState, team_key: &KeyType) -> Option<Str
}
}
+/// 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 {
@@ -632,6 +659,23 @@ 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");