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.

chore(flags): populate redis config cache (#58882)

Matheus Batistae94a562d5228
diff --git a/posthog/management/commands/test/test_warm_remote_configs_cache.py b/posthog/management/commands/test/test_warm_remote_configs_cache.py
new file mode 100644
index 000000000000..754ada3373e7
--- /dev/null
+++ b/posthog/management/commands/test/test_warm_remote_configs_cache.py
@@ -0,0 +1,129 @@
+from io import StringIO
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.core.management import call_command
+from django.core.management.base import CommandError
+from django.test import override_settings
+
+from parameterized import parameterized
+
+from posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIAS
+from posthog.models.project import Project
+from posthog.models.remote_config import RemoteConfig
+
+
+@override_settings(
+ CACHES={
+ "default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"},
+ FLAGS_DEDICATED_CACHE_ALIAS: {
+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
+ "LOCATION": "redis://stub:6379/",
+ },
+ }
+)
+class TestWarmRemoteConfigsCache(BaseTest):
+ """
+ Tests for the warm_remote_configs_cache management command.
+
+ In CI, `FLAGS_REDIS_URL` is unset, so `RemoteConfig.get_hypercache().cache_client`
+ resolves to the default LocMemCache. The roundtrip assertions in
+ `test_remote_config.py` cover the dedicated-alias path under `override_settings`.
+
+ These tests register the dedicated alias via `override_settings` so the
+ command's fail-fast guard passes and exercise the writer path the dedicated
+ alias selects.
+ """
+
+ def setUp(self):
+ super().setUp()
+ self.hypercache = RemoteConfig.get_hypercache()
+ # Drop any prior state so each test starts from a known cache and DB shape.
+ self.hypercache.cache_client.clear()
+ RemoteConfig.objects.filter(team=self.team).delete()
+ self.remote_config = RemoteConfig.objects.create(
+ team=self.team,
+ config={"token": self.team.api_token, "hasFeatureFlags": False},
+ )
+
+ def _cached_value(self, api_token: str):
+ return self.hypercache.cache_client.get(self.hypercache.get_cache_key(api_token))
+
+ def test_warms_redis_cache_for_persisted_config_rows(self):
+ out = StringIO()
+ call_command("warm_remote_configs_cache", stdout=out)
+
+ cached = self._cached_value(self.team.api_token)
+ assert cached is not None
+ assert self.team.api_token in cached
+ assert "warmed=1" in out.getvalue()
+ assert "failed=0" in out.getvalue()
+
+ def test_skips_teams_with_empty_config(self):
+ self.remote_config.config = {}
+ self.remote_config.save(update_fields=["config"])
+
+ out = StringIO()
+ call_command("warm_remote_configs_cache", stdout=out)
+
+ assert self._cached_value(self.team.api_token) is None
+ assert "Backfilling 0 RemoteConfig row(s)" in out.getvalue()
+ assert "warmed=0" in out.getvalue()
+
+ def test_dry_run_does_not_write_to_cache(self):
+ out = StringIO()
+ call_command("warm_remote_configs_cache", dry_run=True, stdout=out)
+
+ assert self._cached_value(self.team.api_token) is None
+ assert "(dry run)" in out.getvalue()
+
+ def test_team_ids_filters_backfill(self):
+ _, other_team = Project.objects.create_with_team(
+ initiating_user=self.user, organization=self.organization, name="Other"
+ )
+ RemoteConfig.objects.filter(team=other_team).delete()
+ RemoteConfig.objects.create(team=other_team, config={"token": other_team.api_token})
+ # Make "other_team has no cache entry" an explicit precondition rather than
+ # relying on TestCase swallowing the post_save on_commit hook.
+ self.hypercache.cache_client.delete(self.hypercache.get_cache_key(other_team.api_token))
+
+ call_command("warm_remote_configs_cache", team_ids=[self.team.id], stdout=StringIO())
+
+ assert self._cached_value(self.team.api_token) is not None
+ assert self._cached_value(other_team.api_token) is None
+
+ @parameterized.expand(
+ [
+ ("zero", 0),
+ ("over_max", 20_000),
+ ]
+ )
+ def test_invalid_batch_size_raises(self, _name, batch_size):
+ with self.assertRaisesMessage(CommandError, "--batch-size"):
+ call_command("warm_remote_configs_cache", batch_size=batch_size, stdout=StringIO())
+
+ def test_failed_writes_raise_command_error(self):
+ with patch(
+ "posthog.storage.hypercache.HyperCache._set_cache_value_redis",
+ side_effect=RuntimeError("boom"),
+ ):
+ with self.assertRaisesMessage(CommandError, "row(s) failed to warm"):
+ call_command("warm_remote_configs_cache", stdout=StringIO())
+
+ def test_does_not_write_to_s3(self):
+ # Regression guard: the warm path must be Redis-only. Writing to S3 per
+ # row would dominate runtime at the scale this command is built for
+ # (tens of thousands of teams). The Redis tier is what the Rust service
+ # reads first; S3 is already populated via the normal sync() path.
+ with patch("posthog.storage.object_storage.write") as mock_s3_write:
+ call_command("warm_remote_configs_cache", stdout=StringIO())
+
+ mock_s3_write.assert_not_called()
+ # Sanity: cache was populated
+ assert self._cached_value(self.team.api_token) is not None
+
+ def test_raises_when_dedicated_cache_not_configured(self):
+ with override_settings(CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}):
+ with self.assertRaisesMessage(CommandError, "FLAGS_REDIS_URL is not configured"):
+ call_command("warm_remote_configs_cache", stdout=StringIO())
diff --git a/posthog/management/commands/warm_remote_configs_cache.py b/posthog/management/commands/warm_remote_configs_cache.py
new file mode 100644
index 000000000000..17d9fb8f1f03
--- /dev/null
+++ b/posthog/management/commands/warm_remote_configs_cache.py
@@ -0,0 +1,139 @@
+"""
+One-shot backfill that writes already-built RemoteConfig.config blobs into the
+dedicated flags Redis so the Rust feature-flags service stops falling through to
+S3 on /flags config_response.
+
+After the writer wiring fix (RemoteConfig.get_hypercache() now targets the
+dedicated FLAGS_REDIS cache when configured), the dedicated cache is still cold
+for teams that haven't been organically re-synced. This command warms it from the
+persisted RemoteConfig.config column without calling build_config(), avoiding the
+expense and side effects of a full rebuild across tens of thousands of teams.
+
+Writes go through `HyperCache.set_cache_value_redis_only`, which writes to Redis
+only and skips S3 and expiry tracking. S3 already has fresh data via the normal
+sync() path, and the goal here is specifically to populate the Redis tier the
+Rust service reads first. A per-row S3 PUT would turn a fast Redis backfill
+into hours of synchronous boto3 round-trips for tens of thousands of teams.
+
+Race note: this reads `RemoteConfig.config` via a cursored snapshot and writes
+it to Redis. If an organic `sync()` for the same team writes a newer config to
+Redis between the row-read and Redis-write here, this backfill will overwrite
+that newer value with the snapshot. The team self-heals on its next signal-
+triggered sync, so the worst case is one sync-cycle of staleness — tolerable
+for a one-shot backfill. Avoid running this during a fleet-wide config push.
+
+Usage:
+ # Warm all teams (sequential, with batching)
+ python manage.py warm_remote_configs_cache
+
+ # Warm specific teams
+ python manage.py warm_remote_configs_cache --team-ids 12345 67890
+
+ # Dry run (count rows, don't write)
+ python manage.py warm_remote_configs_cache --dry-run
+
+ # Tune batch size
+ python manage.py warm_remote_configs_cache --batch-size 500
+"""
+
+import time
+
+from django.conf import settings
+from django.core.management.base import BaseCommand, CommandError
+
+import structlog
+
+from posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIAS
+from posthog.models.remote_config import RemoteConfig
+
+logger = structlog.get_logger(__name__)
+
+
+class Command(BaseCommand):
+ help = "Warm the array/config.json HyperCache from persisted RemoteConfig rows (one-shot backfill)."
+
+ def add_arguments(self, parser):
+ parser.add_argument(
+ "--team-ids",
+ nargs="+",
+ type=int,
+ default=None,
+ help="Restrict backfill to these team IDs. If omitted, warms every RemoteConfig row.",
+ )
+ parser.add_argument(
+ "--batch-size",
+ type=int,
+ default=1000,
+ help="Number of rows fetched per DB batch. Default 1000.",
+ )
+ parser.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Count eligible rows without writing to the cache.",
+ )
+
+ def handle(self, *args, **options):
+ team_ids: list[int] | None = options["team_ids"]
+ batch_size: int = options["batch_size"]
+ dry_run: bool = options["dry_run"]
+
+ if batch_size <= 0 or batch_size > 10_000:
+ raise CommandError("--batch-size must be between 1 and 10000")
+
+ if FLAGS_DEDICATED_CACHE_ALIAS not in settings.CACHES:
+ raise CommandError(
+ "FLAGS_REDIS_URL is not configured. This command backfills the dedicated "
+ "flags Redis the Rust feature-flags service reads. Without FLAGS_REDIS_URL "
+ "set, RemoteConfig.get_hypercache() falls back to the default cache and "
+ "this backfill would target the wrong Redis. Set FLAGS_REDIS_URL and re-run."
+ )
+
+ hypercache = RemoteConfig.get_hypercache()
+
+ # Read api_token from the related Team in the same query to avoid N+1 lookups.
+ # Exclude empty configs at the DB level so `total` matches the work to be done
+ # (the next organic sync will write the __missing__ sentinel for empty rows).
+ queryset = (
+ RemoteConfig.objects.select_related("team")
+ .only("team__api_token", "config")
+ .exclude(config={})
+ .order_by("team_id")
+ )
+ if team_ids is not None:
+ queryset = queryset.filter(team_id__in=team_ids)
+
+ total = queryset.count()
+ self.stdout.write(f"Backfilling {total} RemoteConfig row(s){' (dry run)' if dry_run else ''}")
+
+ warmed = 0
+ failed = 0
+ start = time.monotonic()
+
+ # Use .iterator() with chunk_size to stream rows instead of materializing all in memory.
+ for remote_config in queryset.iterator(chunk_size=batch_size):
+ team = remote_config.team
+
+ if dry_run:
+ warmed += 1
+ continue
+
+ try:
+ hypercache.set_cache_value_redis_only(team.api_token, remote_config.config)
+ warmed += 1
+ except Exception:
+ failed += 1
+ logger.exception(
+ "warm_remote_configs_cache: write failed",
+ team_id=team.id,
+ )
+
+ if warmed and warmed % 1000 == 0:
+ elapsed = time.monotonic() - start
+ rate = warmed / elapsed if elapsed > 0 else 0
+ self.stdout.write(f" ...warmed {warmed}/{total} ({rate:.0f}/s)")
+
+ elapsed = time.monotonic() - start
+ self.stdout.write(self.style.SUCCESS(f"Done in {elapsed:.1f}s. warmed={warmed} failed={failed}"))
+
+ if failed:
+ raise CommandError(f"{failed} row(s) failed to warm — see logs")
diff --git a/posthog/models/remote_config.py b/posthog/models/remote_config.py
index e48eca849ee3..5c66756256b4 100644
--- a/posthog/models/remote_config.py
+++ b/posthog/models/remote_config.py
@@ -12,6 +12,7 @@ import structlog
from opentelemetry import trace
from prometheus_client import Counter
+from posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIAS
from posthog.database_healthcheck import DATABASE_FOR_FLAG_MATCHING
from posthog.exceptions_capture import capture_exception
from posthog.models.feature_flag.feature_flag import FeatureFlag
@@ -79,6 +80,10 @@ class RemoteConfig(UUIDTModel):
value="config.json",
token_based=True, # We store and load via the team token
load_fn=load_config,
+ # Route writes to the dedicated cache the Rust feature-flags service reads from.
+ # Without this, prod writes land in the shared cache while Rust reads from the
+ # dedicated one, forcing every /flags config_response to fall through to S3.
+ cache_alias=FLAGS_DEDICATED_CACHE_ALIAS if FLAGS_DEDICATED_CACHE_ALIAS in settings.CACHES else None,
)
def _build_session_recording_config(self, team: Team) -> dict:
diff --git a/posthog/models/test/test_remote_config.py b/posthog/models/test/test_remote_config.py
index 77c9082d18e7..3f05af65cc9d 100644
--- a/posthog/models/test/test_remote_config.py
+++ b/posthog/models/test/test_remote_config.py
@@ -468,6 +468,40 @@ class TestRemoteConfigCaching(_RemoteConfigBase):
self.remote_config.sync()
assert RemoteConfig.get_hypercache().get_from_cache(self.team.api_token) is not None
+ def test_hypercache_uses_dedicated_cache_when_alias_registered(self):
+ from django.core.cache import caches
+
+ from posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIAS
+
+ # When cache_alias is set, HyperCache.__init__ calls get_cache_writer_url which
+ # reads CACHES[alias]["LOCATION"]. Provide a stub URL to satisfy that lookup;
+ # the in-memory backend ignores it.
+ with override_settings(
+ CACHES={
+ "default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"},
+ FLAGS_DEDICATED_CACHE_ALIAS: {
+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
+ "LOCATION": "redis://stub:6379/",
+ },
+ }
+ ):
+ hypercache = RemoteConfig.get_hypercache()
+ assert hypercache.cache_client is caches[FLAGS_DEDICATED_CACHE_ALIAS]
+
+ # Roundtrip: a value written via the hypercache must land in the
+ # dedicated backend (not just be reachable through cache_client) and
+ # be readable through both direct access and the hypercache reader.
+ hypercache.set_cache_value_redis_only(self.team.api_token, {"token": self.team.api_token, "v": 1})
+ direct_value = caches[FLAGS_DEDICATED_CACHE_ALIAS].get(hypercache.get_cache_key(self.team.api_token))
+ assert direct_value is not None
+ assert hypercache.get_from_cache(self.team.api_token) == {"token": self.team.api_token, "v": 1}
+
+ def test_hypercache_falls_back_to_default_cache_when_alias_absent(self):
+ from django.core.cache import cache
+
+ with override_settings(CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}):
+ assert RemoteConfig.get_hypercache().cache_client is cache
+
@patch("posthog.models.remote_config.requests.post")
def test_purges_cdn_cache_on_sync(self, mock_post):
with self.settings(
diff --git a/posthog/storage/hypercache.py b/posthog/storage/hypercache.py
index 4a2dea010c40..f401e1803876 100644
--- a/posthog/storage/hypercache.py
+++ b/posthog/storage/hypercache.py
@@ -380,6 +380,24 @@ class HyperCache:
self._track_expiry(key, data, ttl=ttl)
return size
+ def set_cache_value_redis_only(
+ self,
+ key: KeyType,
+ data: dict | None | HyperCacheStoreMissing,
+ ttl: Optional[int] = None,
+ ) -> int | None:
+ """
+ Write only to the configured cache backend (self.cache_client), skipping S3
+ and expiry tracking.
+
+ Use this for backfills where S3 is known to already hold fresh data
+ (e.g. populated by the normal sync() path) and the only cold tier is the
+ cache backend. In prod with cache_alias=FLAGS_DEDICATED_CACHE_ALIAS this is
+ the dedicated flags Redis; in dev/test it's whatever the alias resolves to.
+ Returns the serialized size in bytes, or None for None/missing values.
+ """
+ return self._set_cache_value_redis(key, data, ttl=ttl)
+
def clear_cache(self, key: KeyType, kinds: Optional[list[str]] = None):
"""
Only meant for use in tests