: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(caching): dedicated cache alias for ai-gateway hypercache reads (#61525)
Brandon4f24bbeea50c
diff --git a/posthog/caching/ai_gateway_redis_cache.py b/posthog/caching/ai_gateway_redis_cache.pynew file mode 100644index 000000000000..c6ef70f227cc--- /dev/null+++ b/posthog/caching/ai_gateway_redis_cache.py@@ -0,0 +1 @@+AI_GATEWAY_DEDICATED_CACHE_ALIAS = "ai_gateway_dedicated"diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.pyindex 68cdc89c1e0e..b33754a17571 100644--- a/posthog/settings/data_stores.py+++ b/posthog/settings/data_stores.py@@ -530,6 +530,9 @@ if not EMBEDDING_API_URL:# This allows feature-flags service to have dedicated Redis for better resource isolationFLAGS_REDIS_URL = os.getenv("FLAGS_REDIS_URL", None)+# Dedicated Redis for ai-gateway HyperCache reads+AI_GATEWAY_REDIS_URL = os.getenv("AI_GATEWAY_REDIS_URL", None)+# Rust feature flags service URL# This is used to proxy flag evaluation requests to the Rust feature flags serviceFEATURE_FLAGS_SERVICE_URL = os.getenv("FEATURE_FLAGS_SERVICE_URL", "http://localhost:3001")@@ -577,6 +580,20 @@ if FLAGS_REDIS_URL:"KEY_PREFIX": "posthog",}+# Dedicated cache for the ai-gateway service (if configured)+if AI_GATEWAY_REDIS_URL:+ from posthog.caching.ai_gateway_redis_cache import AI_GATEWAY_DEDICATED_CACHE_ALIAS++ CACHES[AI_GATEWAY_DEDICATED_CACHE_ALIAS] = {+ "BACKEND": "django_redis.cache.RedisCache",+ "LOCATION": AI_GATEWAY_REDIS_URL,+ "OPTIONS": {+ "CLIENT_CLASS": "django_redis.client.DefaultClient",+ "COMPRESSOR": "posthog.caching.zstd_compressor.ZstdCompressor",+ },+ "KEY_PREFIX": "posthog",+ }+QUERY_CACHE_REDIS_CLUSTER_URL: str | None = os.getenv("QUERY_CACHE_REDIS_CLUSTER_URL", None)if QUERY_CACHE_REDIS_CLUSTER_URL:diff --git a/posthog/storage/team_llm_gateway_policy_cache.py b/posthog/storage/team_llm_gateway_policy_cache.pyindex 58525d2fac6b..75a8d620996b 100644--- a/posthog/storage/team_llm_gateway_policy_cache.py+++ b/posthog/storage/team_llm_gateway_policy_cache.py@@ -27,7 +27,7 @@ from django.db import OperationalErrorimport structlog-from posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIAS+from posthog.caching.ai_gateway_redis_cache import AI_GATEWAY_DEDICATED_CACHE_ALIASfrom posthog.models.team.team import Teamfrom posthog.storage.cache_expiry_manager import refresh_expiring_caches as refresh_genericfrom posthog.storage.hypercache import HyperCache, HyperCacheStoreMissing, KeyType@@ -95,7 +95,7 @@ team_llm_gateway_policy_hypercache = HyperCache(batch_load_fn=_batch_load_llm_gateway_policy,cache_ttl=LLM_GATEWAY_POLICY_CACHE_TTL,cache_miss_ttl=LLM_GATEWAY_POLICY_CACHE_MISS_TTL,- cache_alias=FLAGS_DEDICATED_CACHE_ALIAS if FLAGS_DEDICATED_CACHE_ALIAS in settings.CACHES else None,+ cache_alias=(AI_GATEWAY_DEDICATED_CACHE_ALIAS if AI_GATEWAY_DEDICATED_CACHE_ALIAS in settings.CACHES else None),expiry_sorted_set_key=LLM_GATEWAY_POLICY_CACHE_EXPIRY_SORTED_SET,)diff --git a/posthog/storage/team_llm_gateway_policy_signal_handlers.py b/posthog/storage/team_llm_gateway_policy_signal_handlers.pyindex 05ddda33eb6e..b4dc384d380c 100644--- a/posthog/storage/team_llm_gateway_policy_signal_handlers.py+++ b/posthog/storage/team_llm_gateway_policy_signal_handlers.py@@ -106,7 +106,7 @@ def _value_changed(instance: Team, snapshot_attr: str, field_name: str) -> bool:def _update_cache_on_save(sender: type[Team], instance: Team, created: bool, **kwargs: Any) -> None:- if not settings.FLAGS_REDIS_URL:+ if not settings.AI_GATEWAY_REDIS_URL:returnold_api_token: str | None = instance.__dict__.get(_LOADED_API_TOKEN_ATTR)@@ -153,7 +153,7 @@ def _update_cache_on_save(sender: type[Team], instance: Team, created: bool, **kdef _clear_cache_on_delete(sender: type[Team], instance: Team, **kwargs: Any) -> None:- if not settings.FLAGS_REDIS_URL:+ if not settings.AI_GATEWAY_REDIS_URL:returnkinds = ["redis"] if settings.TEST else Nonediff --git a/posthog/storage/test/test_team_llm_gateway_policy_cache.py b/posthog/storage/test/test_team_llm_gateway_policy_cache.pyindex f837b997f8f3..082fc4cf37ad 100644--- a/posthog/storage/test/test_team_llm_gateway_policy_cache.py+++ b/posthog/storage/test/test_team_llm_gateway_policy_cache.py@@ -116,7 +116,7 @@ class TestLLMGatewayPolicySignals(BaseTest):@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.settings")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.update_team_llm_gateway_policy_cache_task.delay")def test_team_save_enqueues_update(self, mock_delay, mock_settings, mock_transaction):- mock_settings.FLAGS_REDIS_URL = "redis://localhost"+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"mock_transaction.on_commit.side_effect = lambda fn: fn()self.team.llm_gateway_revoked_at = datetime(2026, 5, 20, 12, 0, 0, tzinfo=UTC)@@ -126,8 +126,8 @@ class TestLLMGatewayPolicySignals(BaseTest):@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.settings")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.update_team_llm_gateway_policy_cache_task.delay")- def test_team_save_noop_without_flags_redis_url(self, mock_delay, mock_settings):- mock_settings.FLAGS_REDIS_URL = None+ def test_team_save_noop_without_ai_gateway_redis_url(self, mock_delay, mock_settings):+ mock_settings.AI_GATEWAY_REDIS_URL = Noneself.team.llm_gateway_revoked_at = datetime(2026, 5, 20, 12, 0, 0, tzinfo=UTC)self.team.save()@@ -137,7 +137,7 @@ class TestLLMGatewayPolicySignals(BaseTest):@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.settings")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.clear_team_llm_gateway_policy_cache")def test_team_delete_clears_cache(self, mock_clear, mock_settings):- mock_settings.FLAGS_REDIS_URL = "redis://localhost"+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"mock_settings.TEST = Trueteam = Team.objects.create(organization=self.organization, name="Doomed")@@ -155,7 +155,7 @@ class TestLLMGatewayPolicySignals(BaseTest):Otherwise a holder of the rotated token keeps hitting the gateway viathe stale cached policy until the 7-day TTL expires."""- mock_settings.FLAGS_REDIS_URL = "redis://localhost"+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"mock_settings.TEST = Truemock_transaction.on_commit.side_effect = lambda fn: fn()@@ -174,7 +174,7 @@ class TestLLMGatewayPolicySignals(BaseTest):"""A save that touches no tracked field (api_token, llm_gateway_enabled_at,llm_gateway_revoked_at) must not invalidate the cache; the async task stillrefreshes the blob."""- mock_settings.FLAGS_REDIS_URL = "redis://localhost"+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"mock_settings.TEST = Truemock_transaction.on_commit.side_effect = lambda fn: fn()@@ -198,7 +198,7 @@ class TestLLMGatewayPolicySignals(BaseTest):for the full cache TTL and a holder of the token keeps hitting thegateway as if the team were active."""- mock_settings.FLAGS_REDIS_URL = "redis://localhost"+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"mock_settings.TEST = Truemock_transaction.on_commit.side_effect = lambda fn: fn()@@ -221,7 +221,7 @@ class TestLLMGatewayPolicySignals(BaseTest):gateway would keep treating the team as not-enrolled and 401 everyrequest even after admin flips them on."""- mock_settings.FLAGS_REDIS_URL = "redis://localhost"+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"mock_settings.TEST = Truemock_transaction.on_commit.side_effect = lambda fn: fn()@@ -243,7 +243,7 @@ class TestLLMGatewayPolicySignals(BaseTest):B. post_save re-snapshots the saved token so the second save comparesagainst B, instead of clearing A twice and leaking B for the full cache TTL."""- mock_settings.FLAGS_REDIS_URL = "redis://localhost"+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"mock_settings.TEST = Truemock_transaction.on_commit.side_effect = lambda fn: fn()@@ -271,7 +271,7 @@ class TestLLMGatewayPolicySignals(BaseTest):snapshot to avoid a lazy load; the pre_save fallback captures the oldvalue from the DB before the UPDATE runs."""- mock_settings.FLAGS_REDIS_URL = "redis://localhost"+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"mock_settings.TEST = Truemock_transaction.on_commit.side_effect = lambda fn: fn()@@ -296,7 +296,7 @@ class TestLLMGatewayPolicySignals(BaseTest):signals; a future refactor that fires clear per field would double theRedis traffic on every admin enable-after-revoke."""- mock_settings.FLAGS_REDIS_URL = "redis://localhost"+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"mock_settings.TEST = Truemock_transaction.on_commit.side_effect = lambda fn: fn()@@ -320,7 +320,7 @@ class TestLLMGatewayPolicySignals(BaseTest):avoid a lazy load; the pre_save fallback captures the old value fromthe DB before the UPDATE runs."""- mock_settings.FLAGS_REDIS_URL = "redis://localhost"+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"mock_settings.TEST = Truemock_transaction.on_commit.side_effect = lambda fn: fn()@@ -343,7 +343,7 @@ class TestLLMGatewayPolicySignals(BaseTest):invalidate twice. post_save re-snapshots the saved value so the secondsave compares against t1 instead of seeing "unchanged" and skipping."""- mock_settings.FLAGS_REDIS_URL = "redis://localhost"+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"mock_settings.TEST = Truemock_transaction.on_commit.side_effect = lambda fn: fn()diff --git a/posthog/tasks/team_llm_gateway_policy.py b/posthog/tasks/team_llm_gateway_policy.pyindex 85cad5758d20..b99b94f0d37d 100644--- a/posthog/tasks/team_llm_gateway_policy.py+++ b/posthog/tasks/team_llm_gateway_policy.py@@ -54,8 +54,8 @@ def refresh_expiring_llm_gateway_policy_cache_entries() -> None:threshold, so simultaneous expiry of the 7-day TTL across the team poolcannot cause a DB-lookup spike."""- if not settings.FLAGS_REDIS_URL:- logger.info("Flags Redis URL not set, skipping llm-gateway policy cache refresh")+ if not settings.AI_GATEWAY_REDIS_URL:+ logger.info("AI gateway Redis URL not set, skipping llm-gateway policy cache refresh")returnstart_time = time.time()