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): repair Redis on hypercache S3 hit (#78070)

Phil Haack052f9e9f4f04
diff --git a/docs/internal/feature-flags/hypercache-system.md b/docs/internal/feature-flags/hypercache-system.md
index 8558500a5d67..58e9e4dc8928 100644
--- a/docs/internal/feature-flags/hypercache-system.md
+++ b/docs/internal/feature-flags/hypercache-system.md
@@ -244,6 +244,28 @@ if team is None:
The cached team is serialized using `CachingTeamSerializer` and reconstructed as a `Team` instance on retrieval.
+## Read repair
+
+Both readers write an S3 hit back into Redis so the next read of the same key is served by Redis instead of paying another S3 read.
+
+The Django reader (`HyperCache.get_from_cache_with_source`) repairs on every S3 hit, synchronously, through the normal write path with the full cache TTL.
+
+The Rust reader (`rust/common/hypercache`) has an opt-in variant, deliberately more conservative than Django's:
+
+- Repairs only on a confirmed Redis miss. A read that fell through to S3 because Redis errored or timed out does not repair, since that tier is degraded and repair writes would add load to it.
+- Writes with `SET NX`, so a repair never overwrites an existing entry and concurrent repairs of one cold key collapse into one write.
+- Uses a short TTL (`HYPERCACHE_READ_REPAIR_TTL_SECONDS`, default 600) and does not register the entry in the expiry sorted set, so the Django refresh job stays the only owner of an entry's real lifetime. The short TTL also bounds how long a resurrected entry lingers in the `HyperCacheWriter::delete` race, where a reader that read S3 just before the delete writes the key back afterwards.
+- Is detached and best-effort: a Redis failure cannot fail a request that already has its value.
+- Refuses etag-enabled namespaces at reader construction (with a startup warning), because the payload and its companion `:etag` key are written atomically by the writer and a payload-only repair would leave the pair inconsistent.
+
+Enabled by default for the readers with no in-process cache in front of them: `array/config.json` in the feature-flags service, and `surveys` and `array/config.json` in hypercache-server. The `feature_flags` readers are excluded: they are etag-paired, and `FlagDefinitionsCache` already absorbs repeat reads of a cold key in process. `team_metadata` is excluded too: a hit there is trusted as proof of a valid token with no Postgres re-check, and team deletion clears Redis before S3, so a repair landing in that gap would resurrect a deleted team in Redis for up to the repair TTL.
+
+Operational controls:
+
+- `HYPERCACHE_READ_REPAIR_TTL_SECONDS=0` disables repair for a service without a code change. The deployment charts pass arbitrary env vars through `.Values.env`, so no chart change is needed.
+- In the feature-flags service, `SKIP_WRITES=true` also disables repair, keeping read-only instances read-only.
+- The `posthog_hypercache_read_repair` counter tracks repair outcomes. A sustained high repair rate means keys are repeatedly going cold (eviction, expiry outpacing the refresh job), which the S3 read rate alone no longer shows because repair suppresses it.
+
## Cache TTL settings
| Cache | Hit TTL | Miss TTL |
@@ -251,6 +273,7 @@ The cached team is serialized using `CachingTeamSerializer` and reconstructed as
| HyperCache (default) | 30 days | 1 day |
| Remote config serving | 1 day | 1 day |
| Team authentication | 5 days | N/A (deleted on miss) |
+| Rust read repair | 600s | N/A (no miss writes) |
## Performance characteristics
@@ -269,9 +292,14 @@ The cached team is serialized using `CachingTeamSerializer` and reconstructed as
| `posthog_hypercache_sync` | `result`, `namespace`, `value` | Cache sync task outcomes |
| `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 |
Result labels: `hit_redis`, `hit_s3`, `hit_db`, `missing`, `batch_miss`
+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.
+
## Debugging
### Check Redis cache
diff --git a/docs/internal/feature-flags/rust-service-overview.md b/docs/internal/feature-flags/rust-service-overview.md
index 1cc725972f43..e9215ba67bf6 100644
--- a/docs/internal/feature-flags/rust-service-overview.md
+++ b/docs/internal/feature-flags/rust-service-overview.md
@@ -267,11 +267,12 @@ Cache and query health are observable via the `flags_cohort_membership_cache_*`
### S3 / HyperCache
-| Variable | Default | Purpose |
-| ------------------------- | ----------- | -------------------------------- |
-| `OBJECT_STORAGE_BUCKET` | `posthog` | S3 bucket name |
-| `OBJECT_STORAGE_REGION` | `us-east-1` | AWS region |
-| `OBJECT_STORAGE_ENDPOINT` | (empty) | Custom S3 endpoint for local dev |
+| Variable | Default | Purpose |
+| ------------------------------------ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `OBJECT_STORAGE_BUCKET` | `posthog` | S3 bucket name |
+| `OBJECT_STORAGE_REGION` | `us-east-1` | AWS region |
+| `OBJECT_STORAGE_ENDPOINT` | (empty) | Custom S3 endpoint for local dev |
+| `HYPERCACHE_READ_REPAIR_TTL_SECONDS` | `600` | TTL for writing an S3 hit back into Redis after a confirmed miss. `0` disables, as does `SKIP_WRITES`. Also read by hypercache-server. See [read repair](hypercache-system.md#read-repair) |
### Team lookup
diff --git a/rust/common/hypercache/Cargo.toml b/rust/common/hypercache/Cargo.toml
index 3fd779ee57ee..95b391078e2d 100644
--- a/rust/common/hypercache/Cargo.toml
+++ b/rust/common/hypercache/Cargo.toml
@@ -26,3 +26,4 @@ tracing = { workspace = true }
[dev-dependencies]
mockall = { workspace = true }
common-hypercache = { path = ".", features = ["mock-client"] }
+tokio = { workspace = true, features = ["test-util"] }
diff --git a/rust/common/hypercache/src/lib.rs b/rust/common/hypercache/src/lib.rs
index b313a256bba8..0d30f6d5e886 100644
--- a/rust/common/hypercache/src/lib.rs
+++ b/rust/common/hypercache/src/lib.rs
@@ -50,7 +50,7 @@ use std::sync::Arc;
use std::time::{Duration, Instant};
use thiserror::Error;
use tokio::time::timeout;
-use tracing::debug;
+use tracing::{debug, warn};
/// Metric name for tracking hypercache operations in Prometheus (same one used in Django's HyperCache)
pub const HYPERCACHE_COUNTER_NAME: &str = "posthog_hypercache_get_from_cache";
@@ -58,6 +58,11 @@ pub const HYPERCACHE_COUNTER_NAME: &str = "posthog_hypercache_get_from_cache";
/// Metric name for tracking Redis failure reasons (timeout, get_error, pickle_error, json_error)
const HYPERCACHE_REDIS_MISS_REASON_COUNTER_NAME: &str = "posthog_hypercache_redis_miss_reason";
+/// Metric name for tracking read-repair writes back into Redis after an S3 hit.
+/// Labels: `namespace`, `value`, `result` (success | skipped | error), where `skipped`
+/// means the key already existed and the repair deferred to it.
+const HYPERCACHE_READ_REPAIR_COUNTER_NAME: &str = "posthog_hypercache_read_repair";
+
/// Per-tier latency histogram for the Redis read inside `get_typed_with_source`.
/// Labels: `namespace`, `value`, `outcome` (hit | miss | timeout | error).
pub const HYPERCACHE_REDIS_OP_MS: &str = "posthog_hypercache_redis_op_ms";
@@ -203,6 +208,19 @@ pub struct HyperCacheConfig {
/// sorted set with an expiry-timestamp score, mirroring Python's
/// `HyperCache._track_expiry`. `None` disables expiry tracking.
pub expiry_sorted_set_key: Option<String>,
+ /// When set, an S3 hit that followed a Redis miss writes the payload back into Redis
+ /// with this TTL, so the next reader for the same key is served by Redis. `None`
+ /// (the default) leaves the reader read-only. Not supported on etag-enabled
+ /// namespaces: `HyperCacheReader` construction warns and disables it there. A value
+ /// above `HyperCacheReader::MAX_READ_REPAIR_TTL_SECONDS` is capped there too.
+ ///
+ /// Keep this short. It is a stampede damper for cold keys, not a substitute for the
+ /// writer: repaired entries are deliberately not registered in `expiry_sorted_set_key`,
+ /// so Django's refresh job stays the only thing that owns an entry's real lifetime.
+ /// Whether a repair can resurrect a key deleted by `HyperCacheWriter::delete` is fixed
+ /// at read time by whether the S3 read preceded the delete; the TTL doesn't affect that.
+ /// What the TTL bounds is how long a resurrected entry lingers before it expires.
+ pub read_repair_ttl_seconds: Option<u64>,
}
impl HyperCacheConfig {
@@ -225,6 +243,7 @@ impl HyperCacheConfig {
enable_etag: false,
django_cache_version: "1".to_string(),
expiry_sorted_set_key: None,
+ read_repair_ttl_seconds: None,
}
}
@@ -248,6 +267,7 @@ impl HyperCacheConfig {
enable_etag: false,
django_cache_version,
expiry_sorted_set_key: None,
+ read_repair_ttl_seconds: None,
}
}
@@ -303,6 +323,12 @@ pub struct HyperCacheReader {
}
impl HyperCacheReader {
+ /// Read repair is a stampede damper, not a writer. A TTL beyond this would outlive the
+ /// refresh cycle and widen how long a `HyperCacheWriter::delete` race can resurrect a
+ /// deleted key for. Caps a misconfigured env var (e.g. seconds vs. milliseconds) instead
+ /// of letting it silently disable the short-TTL invariant.
+ const MAX_READ_REPAIR_TTL_SECONDS: u64 = 3_600; // 1 hour
+
pub async fn new(
redis_client: Arc<dyn RedisClient + Send + Sync>,
config: HyperCacheConfig,
@@ -324,19 +350,42 @@ impl HyperCacheReader {
let aws_s3_client = AwsS3SdkClient::from_conf(s3_config_builder.build());
let s3_client = Arc::new(S3Impl::new(aws_s3_client)) as Arc<dyn S3Client + Send + Sync>;
- Ok(Self {
- redis_client,
- s3_client,
- config,
- })
+ Ok(Self::new_with_s3_client(redis_client, s3_client, config))
}
/// Create a new HyperCacheReader with a custom S3 client (useful for testing)
pub fn new_with_s3_client(
redis_client: Arc<dyn RedisClient + Send + Sync>,
s3_client: Arc<dyn S3Client + Send + Sync>,
- config: HyperCacheConfig,
+ mut config: HyperCacheConfig,
) -> Self {
+ // Read repair writes only the payload, but an etag-enabled namespace needs the
+ // payload and its companion etag written atomically (see
+ // `HyperCacheWriter::set_with_etag`). Repairing only the payload would leave the
+ // pair inconsistent, so those namespaces are left to the writer. The refusal is
+ // announced at construction rather than silently skipping every repair.
+ if config.enable_etag && config.read_repair_ttl_seconds.is_some() {
+ warn!(
+ namespace = %config.namespace,
+ value = %config.object_name,
+ "read repair is not supported for etag-enabled namespaces; disabling it for this reader"
+ );
+ config.read_repair_ttl_seconds = None;
+ }
+
+ if let Some(ttl) = config.read_repair_ttl_seconds {
+ if ttl > Self::MAX_READ_REPAIR_TTL_SECONDS {
+ warn!(
+ namespace = %config.namespace,
+ value = %config.object_name,
+ configured_ttl_seconds = ttl,
+ max_ttl_seconds = Self::MAX_READ_REPAIR_TTL_SECONDS,
+ "read repair TTL exceeds maximum; capping at maximum"
+ );
+ config.read_repair_ttl_seconds = Some(Self::MAX_READ_REPAIR_TTL_SECONDS);
+ }
+ }
+
Self {
redis_client,
s3_client,
@@ -600,12 +649,18 @@ impl HyperCacheReader {
s3_start.elapsed().as_secs_f64() * 1000.0,
);
match s3_result {
- Ok(Ok(data)) => {
+ Ok(Ok((data, raw_json))) => {
debug!(
cache_key = %s3_cache_key,
namespace = %self.config.namespace,
"HyperCache hit: S3"
);
+ // Repair only a confirmed Redis miss. Reaching S3 on a Redis error or
+ // timeout means the tier is degraded, and piling detached repair writes
+ // onto it would only add load.
+ if infra_error.is_none() {
+ self.spawn_read_repair(redis_cache_key, raw_json);
+ }
inc(
HYPERCACHE_COUNTER_NAME,
&[
@@ -880,25 +935,84 @@ impl HyperCacheReader {
}
}
+ /// Returns the deserialized value alongside the raw JSON it came from, so an S3 hit can
+ /// be written back into Redis verbatim without re-serializing (which would risk drifting
+ /// from the bytes Django wrote).
async fn try_get_typed_from_s3<T: DeserializeOwned>(
&self,
cache_key: &str,
- ) -> Result<T, HyperCacheError> {
+ ) -> Result<(T, String), HyperCacheError> {
let body_str = self.try_get_json_string_from_s3(cache_key).await?;
- serde_json::from_str::<T>(&body_str).map_err(|e| {
+ let value = serde_json::from_str::<T>(&body_str).map_err(|e| {
debug!(
"Failed to parse JSON from S3 data for key '{}': {}",
cache_key, e
);
HyperCacheError::Json(e)
- })
+ })?;
+ Ok((value, body_str))
+ }
+
+ /// Best-effort write-back of an S3 hit into Redis, after Django's read path
+ /// (`HyperCache.get_from_cache_with_source`, which repairs on S3 hit). Unlike Django,
+ /// the caller only invokes this for a confirmed Redis miss, not for an error or
+ /// timeout fall-through, where the Redis tier is degraded.
+ ///
+ /// Without this a key that is absent from Redis but present in S3 stays cold, so every
+ /// subsequent request for it pays another S3 read until the writer next touches it. The
+ /// work is detached and its failures are swallowed: a repair is an optimization, and the
+ /// caller already has the value it needs.
+ fn spawn_read_repair(&self, redis_cache_key: String, json_data: String) {
+ let Some(ttl_seconds) = self.config.read_repair_ttl_seconds else {
+ return;
+ };
+
+ let redis_client = self.redis_client.clone();
+ let namespace = self.config.namespace.clone();
+ let object_name = self.config.object_name.clone();
+
+ tokio::spawn(async move {
+ // NX: a repair must never overwrite an entry that already exists. The writer
+ // (or a concurrent repair) may have landed a fresher value after our S3 read.
+ let result = redis_client
+ .set_nx_ex_with_format(
+ redis_cache_key,
+ json_data,
+ ttl_seconds,
+ writer::REDIS_FORMAT,
+ )
+ .await;
+
+ let outcome = match result {
+ Ok(true) => "success",
+ Ok(false) => "skipped",
+ Err(ref e) => {
+ debug!(
+ namespace = %namespace,
+ value = %object_name,
+ error = %e,
+ "HyperCache read repair failed"
+ );
+ "error"
+ }
+ };
+ inc(
+ HYPERCACHE_READ_REPAIR_COUNTER_NAME,
+ &[
+ ("result".to_string(), outcome.to_string()),
+ ("namespace".to_string(), namespace),
+ ("value".to_string(), object_name),
+ ],
+ 1,
+ );
+ });
}
}
#[cfg(test)]
mod tests {
use super::*;
- use common_redis::{CustomRedisError, MockRedisClient};
+ use common_redis::{CustomRedisError, MockRedisClient, RedisValueFormat};
use serde_json::json;
// Test helper functions
@@ -950,6 +1064,68 @@ mod tests {
)
}
+ /// Mocks wired for a failed Redis read followed by an S3 hit: Redis returns
+ /// `redis_err` for the fixture's key, S3 serves `s3_payload`. Tests drive whichever
+ /// read API they exercise and can inspect everything the reader asked Redis to do
+ /// via `redis`.
+ #[cfg(feature = "mock-client")]
+ struct RedisMissS3HitFixture {
+ reader: HyperCacheReader,
+ redis: Arc<MockRedisClient>,
+ team_key: KeyType,
+ cache_key: String,
+ }
+
+ #[cfg(feature = "mock-client")]
+ fn redis_miss_s3_hit_fixture(
+ config: HyperCacheConfig,
+ s3_payload: &str,
+ ) -> RedisMissS3HitFixture {
+ redis_failure_s3_hit_fixture(config, s3_payload, CustomRedisError::NotFound)
+ }
+
+ #[cfg(feature = "mock-client")]
+ fn redis_failure_s3_hit_fixture(
+ config: HyperCacheConfig,
+ s3_payload: &str,
+ redis_err: CustomRedisError,
+ ) -> RedisMissS3HitFixture {
+ let team_key = KeyType::string("123");
+ let cache_key = config.get_redis_cache_key(&team_key);
+ let s3_key = config.get_s3_cache_key(&team_key);
+
+ let mut mock_redis = MockRedisClient::new();
+ mock_redis = mock_redis.get_raw_bytes_ret(&cache_key, Err(redis_err));
+ // Let a repair land, so the write-back path reaches its success outcome.
+ mock_redis = mock_redis.set_nx_ex_ret(&cache_key, Ok(true));
+ let redis = Arc::new(mock_redis);
+
+ let mut mock_s3 = MockS3Client::new();
+ mock_s3
+ .expect_get_string()
+ .with(predicate::eq("test-bucket"), predicate::eq(s3_key))
+ .returning({
+ let payload = s3_payload.to_string();
+ move |_, _| {
+ let data = payload.clone();
+ Box::pin(async move { Ok(data) })
+ }
+ });
+
+ let reader = HyperCacheReader::new_with_s3_client(
+ redis.clone() as Arc<dyn RedisClient + Send + Sync>,
+ Arc::new(mock_s3),
+ config,
+ );
+
+ RedisMissS3HitFixture {
+ reader,
+ redis,
+ team_key,
+ cache_key,
+ }
+ }
+
#[test]
fn test_hypercache_config_new() {
let config = HyperCacheConfig::new(
@@ -1150,47 +1326,17 @@ mod tests {
#[tokio::test]
#[cfg(feature = "mock-client")]
async fn test_get_with_source_redis_miss_s3_hit() {
- let team_key = KeyType::string("123");
let test_data = json!({"key": "value", "nested": {"data": "test"}});
- let test_data_str = serde_json::to_string(&test_data).unwrap();
-
- let config = HyperCacheConfig::new(
- "test".to_string(),
- "test".to_string(),
- "us-east-1".to_string(),
- "test-bucket".to_string(),
+ let fixture = redis_miss_s3_hit_fixture(
+ create_test_config(),
+ &serde_json::to_string(&test_data).unwrap(),
);
- let expected_cache_key = config.get_redis_cache_key(&team_key);
- let expected_s3_key = config.get_s3_cache_key(&team_key);
- // Redis returns NotFound
- let mut mock_redis = MockRedisClient::new();
- mock_redis = mock_redis.get_ret(&expected_cache_key, Err(CustomRedisError::NotFound));
- // S3 returns data
- let mut mock_s3 = MockS3Client::new();
- mock_s3
- .expect_get_string()
- .with(
- predicate::eq("test-bucket"),
- predicate::eq(expected_s3_key.clone()),
- )
- .returning({
- let test_data_str = test_data_str.clone();
- move |_, _| {
- let data = test_data_str.clone();
- Box::pin(async move { Ok(data) })
- }
- });
- let mock_s3 = Arc::new(mock_s3);
-
- let reader = HyperCacheReader {
- redis_client: Arc::new(mock_redis) as Arc<dyn RedisClient + Send + Sync>,
- s3_client: mock_s3,
- config,
- };
-
- // Both Redis and S3 miss should result in CacheMiss error
- let (result, source) = reader.get_with_source(&team_key).await.unwrap();
+ let (result, source) = fixture
+ .reader
+ .get_with_source(&fixture.team_key)
+ .await
+ .unwrap();
assert_eq!(source, CacheSource::S3);
assert_eq!(result, test_data);
}
@@ -1266,48 +1412,15 @@ mod tests {
#[cfg(feature = "mock-client")]
async fn test_get_with_source_or_fallback_cache_hit_s3() {
// Test that fallback is not called when S3 cache hits (after Redis miss)
- let team_key = KeyType::string("123");
let test_data = json!({"key": "value", "nested": {"data": "test"}});
- let test_data_str = serde_json::to_string(&test_data).unwrap();
-
- let config = HyperCacheConfig::new(
- "test".to_string(),
- "test".to_string(),
- "us-east-1".to_string(),
- "test-bucket".to_string(),
+ let fixture = redis_miss_s3_hit_fixture(
+ create_test_config(),
+ &serde_json::to_string(&test_data).unwrap(),
);
- let expected_cache_key = config.get_redis_cache_key(&team_key);
- let expected_s3_key = config.get_s3_cache_key(&team_key);
-
- // Redis returns NotFound
- let mut mock_redis = MockRedisClient::new();
- mock_redis = mock_redis.get_ret(&expected_cache_key, Err(CustomRedisError::NotFound));
-
- // S3 returns data
- let mut mock_s3 = MockS3Client::new();
- mock_s3
- .expect_get_string()
- .with(
- predicate::eq("test-bucket"),
- predicate::eq(expected_s3_key.clone()),
- )
- .returning({
- let test_data_str = test_data_str.clone();
- move |_, _| {
- let data = test_data_str.clone();
- Box::pin(async move { Ok(data) })
- }
- });
- let mock_s3 = Arc::new(mock_s3);
- let reader = HyperCacheReader {
- redis_client: Arc::new(mock_redis) as Arc<dyn RedisClient + Send + Sync>,
- s3_client: mock_s3,
- config,
- };
-
- let result: Result<(Value, CacheSource), HyperCacheError> = reader
- .get_with_source_or_fallback(&team_key, || async {
+ let result: Result<(Value, CacheSource), HyperCacheError> = fixture
+ .reader
+ .get_with_source_or_fallback(&fixture.team_key, || async {
// If this is called, the test should fail because we expect cache hit
panic!("Fallback should not be called when S3 cache hits!");
})
@@ -1319,6 +1432,125 @@ mod tests {
assert_eq!(data, test_data);
}
+ /// Drive one fixture read to its S3 hit and return every call the reader made to Redis.
+ /// Callers run under paused tokio time: the sleep parks this task, the runtime drives the
+ /// detached repair task to idle, and only then advances the clock, so any spawned repair
+ /// has landed before inspection.
+ #[cfg(feature = "mock-client")]
+ async fn redis_calls_after_s3_hit(
+ fixture: &RedisMissS3HitFixture,
+ ) -> Vec<common_redis::MockRedisCall> {
+ let (_, source) = fixture
+ .reader
+ .get_with_source(&fixture.team_key)
+ .await
+ .unwrap();
+ assert_eq!(source, CacheSource::S3);
+
+ tokio::time::sleep(Duration::from_millis(1)).await;
+ fixture.redis.get_calls()
+ }
+
+ #[tokio::test(start_paused = true)]
+ #[cfg(feature = "mock-client")]
+ async fn test_s3_hit_repairs_redis_when_ttl_configured() {
+ let payload = r#"{"key":"value"}"#;
+ let mut config = create_test_config();
+ config.read_repair_ttl_seconds = Some(600);
+
+ let fixture = redis_miss_s3_hit_fixture(config, payload);
+ let calls = redis_calls_after_s3_hit(&fixture).await;
+
+ let repair = calls
+ .iter()
+ .find(|c| c.op == "set_nx_ex_with_format")
+ .expect("expected the S3 hit to be written back to Redis");
+ assert_eq!(repair.key, fixture.cache_key);
+ match &repair.value {
+ common_redis::MockRedisValue::StringWithTTLAndFormat(value, ttl, format) => {
+ // Written back verbatim, in the pickle format Django reads.
+ assert_eq!(value, payload);
+ assert_eq!(*ttl, 600);
+ assert_eq!(*format, RedisValueFormat::Pickle);
+ }
+ other => panic!("expected StringWithTTLAndFormat, got {other:?}"),
+ }
+ }
+
+ #[tokio::test(start_paused = true)]
+ #[cfg(feature = "mock-client")]
+ async fn test_s3_hit_does_not_repair_redis_by_default() {
+ // The reader is read-only unless a caller opts in.
+ let fixture = redis_miss_s3_hit_fixture(create_test_config(), r#"{"key":"value"}"#);
+ let calls = redis_calls_after_s3_hit(&fixture).await;
+ assert!(calls.iter().all(|c| c.op != "set_nx_ex_with_format"));
+ }
+
+ #[tokio::test(start_paused = true)]
+ #[cfg(feature = "mock-client")]
+ async fn test_s3_hit_does_not_repair_etag_enabled_namespace() {
+ // Repairing the payload alone would leave it inconsistent with its companion etag.
+ let mut config = create_test_config();
+ config.read_repair_ttl_seconds = Some(600);
+ config.enable_etag = true;
+
+ let fixture = redis_miss_s3_hit_fixture(config, r#"{"key":"value"}"#);
+ let calls = redis_calls_after_s3_hit(&fixture).await;
+ assert!(calls.iter().all(|c| c.op != "set_nx_ex_with_format"));
+ }
+
+ #[cfg(feature = "mock-client")]
+ #[test]
+ fn test_read_repair_ttl_is_capped_at_construction() {
+ // A misconfigured env var (e.g. seconds vs. milliseconds) must not silently disable
+ // the short-TTL invariant that bounds a resurrected orphan's lifetime.
+ let mut config = create_test_config();
+ config.read_repair_ttl_seconds = Some(HyperCacheReader::MAX_READ_REPAIR_TTL_SECONDS + 1);
+
+ let reader = HyperCacheReader::new_with_s3_client(
+ Arc::new(MockRedisClient::new()) as Arc<dyn RedisClient + Send + Sync>,
+ create_dummy_s3_client(),
+ config,
+ );
+
+ assert_eq!(
+ reader.config().read_repair_ttl_seconds,
+ Some(HyperCacheReader::MAX_READ_REPAIR_TTL_SECONDS)
+ );
+ }
+
+ #[cfg(feature = "mock-client")]
+ #[test]
+ fn test_read_repair_ttl_at_max_is_unchanged() {
+ let mut config = create_test_config();
+ config.read_repair_ttl_seconds = Some(HyperCacheReader::MAX_READ_REPAIR_TTL_SECONDS);
+
+ let reader = HyperCacheReader::new_with_s3_client(
+ Arc::new(MockRedisClient::new()) as Arc<dyn RedisClient + Send + Sync>,
+ create_dummy_s3_client(),
+ config,
+ );
+
+ assert_eq!(
+ reader.config().read_repair_ttl_seconds,
+ Some(HyperCacheReader::MAX_READ_REPAIR_TTL_SECONDS)
+ );
+ }
+
+ #[tokio::test(start_paused = true)]
+ #[cfg(feature = "mock-client")]
+ async fn test_s3_hit_does_not_repair_after_redis_error() {
+ // Reaching S3 on a Redis error means the tier is degraded, not that the key is
+ // cold; writing to a degraded tier would only add load.
+ let mut config = create_test_config();
+ config.read_repair_ttl_seconds = Some(600);
+
+ let fixture =
+ redis_failure_s3_hit_fixture(config, r#"{"key":"value"}"#, CustomRedisError::Timeout);
+ let calls = redis_calls_after_s3_hit(&fixture).await;
+ assert!(calls.iter().all(|c| c.op != "set_nx_ex_with_format"));
+ }
+
#[tokio::test]
async fn test_get_with_source_or_fallback_uses_fallback() {
// Test that fallback is called when both cache tiers miss
@@ -1656,29 +1888,14 @@ mod tests {
#[tokio::test]
async fn test_get_typed_with_source_redis_miss_s3_hit() {
let expected = make_test_flags();
- let json_string = serde_json::to_string(&expected).unwrap();
-
- let mut mock_redis = MockRedisClient::new();
- let cache_key = create_test_config().get_redis_cache_key(&KeyType::int(42));
- mock_redis.get_raw_bytes_ret(&cache_key, Err(CustomRedisError::NotFound));
-
- let mut mock_s3 = MockS3Client::new();
- let s3_key = create_test_config().get_s3_cache_key(&KeyType::int(42));
- let json_clone = json_string.clone();
- mock_s3
- .expect_get_string()
- .with(
- predicate::eq("test-bucket".to_string()),
- predicate::eq(s3_key),
- )
- .returning(move |_, _| {
- let val = json_clone.clone();
- Box::pin(async move { Ok(val) })
- });
+ let fixture = redis_miss_s3_hit_fixture(
+ create_test_config(),
+ &serde_json::to_string(&expected).unwrap(),
+ );
- let reader = create_test_reader_with_mocks(mock_redis, Arc::new(mock_s3));
- let (data, source) = reader
- .get_typed_with_source::<TestFlags>(&KeyType::int(42))
+ let (data, source) = fixture
+ .reader
+ .get_typed_with_source::<TestFlags>(&fixture.team_key)
.await
.unwrap();
diff --git a/rust/common/hypercache/src/writer.rs b/rust/common/hypercache/src/writer.rs
index a78c2f5320fe..01f4e10026fc 100644
--- a/rust/common/hypercache/src/writer.rs
+++ b/rust/common/hypercache/src/writer.rs
@@ -12,7 +12,7 @@ use crate::{HyperCacheConfig, HyperCacheError, KeyType, ETAG_KEY_SUFFIX, HYPER_C
const HYPERCACHE_OPERATION_COUNTER_NAME: &str = "posthog_hypercache_operation";
/// HyperCache always writes Redis values in Pickle format for Django compatibility.
-const REDIS_FORMAT: RedisValueFormat = RedisValueFormat::Pickle;
+pub(crate) const REDIS_FORMAT: RedisValueFormat = RedisValueFormat::Pickle;
/// Multi-tier cache writer for PostHog, matching Django's HyperCache write behavior.
///
diff --git a/rust/feature-flags/src/config.rs b/rust/feature-flags/src/config.rs
index da99a6c62b16..0e1bdc4aa774 100644
--- a/rust/feature-flags/src/config.rs
+++ b/rust/feature-flags/src/config.rs
@@ -876,6 +876,12 @@ pub struct Config {
#[envconfig(from = "TEAM_NEGATIVE_CACHE_TTL_SECONDS", default = "30")]
pub team_negative_cache_ttl_seconds: u64,
+ // Write an S3 hit back into Redis so the next reader for that key is served by Redis
+ // instead of paying another S3 read. Applies to the team metadata and remote config
+ // hypercaches, which have no in-process cache in front of them. 0 disables.
+ #[envconfig(from = "HYPERCACHE_READ_REPAIR_TTL_SECONDS", default = "600")]
+ pub hypercache_read_repair_ttl_seconds: u64,
+
// TTL for the Redis-backed per-token auth cache (positive hits).
// Starts at 5 minutes as a conservative default; increase once invalidation
// signals are proven reliable in production.
@@ -1146,6 +1152,7 @@ impl Config {
thread_pool_cores: 0,
team_negative_cache_capacity: 10_000,
team_negative_cache_ttl_seconds: 30,
+ hypercache_read_repair_ttl_seconds: 600,
skip_pg_team_fallback: FlexBool(false),
service_mode: ServiceMode::All,
auth_token_cache_ttl_seconds: 300,
diff --git a/rust/feature-flags/src/server.rs b/rust/feature-flags/src/server.rs
index d552ef0c6d24..3e9467f2aefa 100644
--- a/rust/feature-flags/src/server.rs
+++ b/rust/feature-flags/src/server.rs
@@ -303,6 +303,8 @@ pub async fn serve(
config.object_storage_region.clone(),
config.object_storage_bucket.clone(),
);
+ // Etag-paired on the Django writer side, which makes HyperCacheReader refuse read repair.
+ flags_hypercache_config.enable_etag = true;
if !config.object_storage_endpoint.is_empty() {
flags_hypercache_config.s3_endpoint = Some(config.object_storage_endpoint.clone());
@@ -321,6 +323,18 @@ pub async fn serve(
}
};
+ // Read repair for the hypercaches that are read straight through to Redis on every
+ // request. Both feature_flags readers are left out: each carries a companion `:etag` key
+ // that a payload-only repair would leave stale, and FlagDefinitionsCache already absorbs
+ // repeat reads of a cold flags.json in process. team_metadata is left out too, below,
+ // for a different reason: it gates token authentication.
+ let read_repair_ttl_seconds =
+ if config.hypercache_read_repair_ttl_seconds == 0 || *config.skip_writes {
+ None
+ } else {
+ Some(config.hypercache_read_repair_ttl_seconds)
+ };
+
// Create HyperCacheReader for team metadata at startup
// Uses token-based lookup instead of team_id
let team_redis_client = dedicated_redis_client
@@ -334,6 +348,12 @@ pub async fn serve(
config.object_storage_bucket.clone(),
);
team_hypercache_config.token_based = true;
+ // Left out of read repair: a hit here is trusted as proof of a valid token (see
+ // get_team_from_cache_or_pg), with no Postgres re-check. Team deletion clears Redis
+ // before S3, so a request landing in that gap reads the deleted team from S3; repairing
+ // it would resurrect that team in Redis for up to the repair TTL, instead of the single
+ // stale response an unrepaired hit gives the one caller that landed in the gap.
+ team_hypercache_config.read_repair_ttl_seconds = None;
if !config.object_storage_endpoint.is_empty() {
team_hypercache_config.s3_endpoint = Some(config.object_storage_endpoint.clone());
@@ -362,6 +382,8 @@ pub async fn serve(
config.object_storage_region.clone(),
config.object_storage_bucket.clone(),
);
+ // Etag-paired, same as flags.json above.
+ flags_with_cohorts_config.enable_etag = true;
if !config.object_storage_endpoint.is_empty() {
flags_with_cohorts_config.s3_endpoint = Some(config.object_storage_endpoint.clone());
@@ -407,6 +429,7 @@ pub async fn serve(
config.object_storage_bucket.clone(),
);
config_hypercache_config.token_based = true;
+ config_hypercache_config.read_repair_ttl_seconds = read_repair_ttl_seconds;
if !config.object_storage_endpoint.is_empty() {
config_hypercache_config.s3_endpoint = Some(config.object_storage_endpoint.clone());
diff --git a/rust/hypercache-server/src/config.rs b/rust/hypercache-server/src/config.rs
index b2c001e0c8cc..8a0ccb88f033 100644
--- a/rust/hypercache-server/src/config.rs
+++ b/rust/hypercache-server/src/config.rs
@@ -43,6 +43,12 @@ pub struct Config {
#[envconfig(from = "REDIS_TIMEOUT_MS", default = "100")]
pub redis_timeout_ms: u64,
+ /// Write an S3 hit back into Redis so the next reader for that key is served by Redis
+ /// instead of paying another S3 read. Both readers here go straight through to Redis on
+ /// every request. 0 disables.
+ #[envconfig(from = "HYPERCACHE_READ_REPAIR_TTL_SECONDS", default = "600")]
+ pub read_repair_ttl_seconds: u64,
+
#[envconfig(from = "OBJECT_STORAGE_REGION", default = "us-east-1")]
pub object_storage_region: String,
diff --git a/rust/hypercache-server/src/server.rs b/rust/hypercache-server/src/server.rs
index 753036f305fe..ed38208d8d63 100644
--- a/rust/hypercache-server/src/server.rs
+++ b/rust/hypercache-server/src/server.rs
@@ -118,6 +118,12 @@ async fn create_hypercache_reader(
config.object_storage_bucket.clone(),
);
hc_config.token_based = true;
+ // Neither namespace here is etag-paired, so a payload-only repair is safe for both.
+ hc_config.read_repair_ttl_seconds = if config.read_repair_ttl_seconds == 0 {
+ None
+ } else {
+ Some(config.read_repair_ttl_seconds)
+ };
if !config.object_storage_endpoint.is_empty() {
hc_config.s3_endpoint = Some(config.object_storage_endpoint.clone());
diff --git a/rust/hypercache-server/tests/integration_test.rs b/rust/hypercache-server/tests/integration_test.rs
index 836d9159ae9b..f247bbb63751 100644
--- a/rust/hypercache-server/tests/integration_test.rs
+++ b/rust/hypercache-server/tests/integration_test.rs
@@ -166,6 +166,7 @@ impl TestServer {
redis_url: "redis://localhost:6379/".to_string(),
redis_reader_url: String::new(),
redis_timeout_ms: 1000,
+ read_repair_ttl_seconds: 600,
object_storage_region: "us-east-1".to_string(),
object_storage_bucket: "posthog".to_string(),
object_storage_endpoint: "http://localhost:19000".to_string(),