: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(query-cache): shorter retention for programmatic query results (#91815)
Sandy Spicer628c23785294
diff --git a/docs/internal/workflows/s3-query-cache-setup.md b/docs/internal/workflows/s3-query-cache-setup.mdindex bc7acf5e85e0..05cc4f9b4785 100644--- a/docs/internal/workflows/s3-query-cache-setup.md+++ b/docs/internal/workflows/s3-query-cache-setup.md@@ -8,7 +8,7 @@ See `posthog/query_cache/storage.py`.## Semantics-- **Expiry is governed by the Redis pointer's TTL** (`CACHED_RESULTS_TTL`), not by S3. Once the pointer expires or is evicted, the entry is gone regardless of whether the S3 object still exists.+- **Expiry is governed by the Redis pointer's TTL**, not by S3. Attached and UI-initiated entries live for `CACHED_RESULTS_TTL`; programmatic writes outside an insight or dashboard live for the shorter `CACHED_RESULTS_PROGRAMMATIC_TTL`. Once the pointer expires or is evicted, the entry is gone regardless of whether the S3 object still exists.- **Blobs are deleted eagerly once nothing references them.** Replacing or evicting a pointer entry enqueues a best-effort Celery delete, delayed by `BLOB_DELETE_DELAY_SECONDS` (60s) so a reader that just fetched the pointer from Redis can still complete its S3 read. An upload whose pointer swap lost to a newer write deletes its own blob immediately, since that pointer never entered Redis.- **The S3 lifecycle rule is the garbage collection backstop.** It deletes whatever the eager path misses: pointers that expired by TTL, shadow-mode uploads, rolled-back teams, failed deletes, and writes from a process that could not reach the Celery broker.- Rollout is controlled by the `query-cache-s3-writes` multivariate feature flag on the organization group. It gates writes only; reads never evaluate the flag, they follow whatever the stored record says.diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex c6c16de22321..bebe8ede6be8 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -149,7 +149,7 @@ from posthog.models import Team, Userfrom posthog.models.instance_setting import get_instance_settingfrom posthog.models.team import WeekStartDayfrom posthog.models.team.event_retention import events_retention_months_for_team-from posthog.query_cache import QueryCache, count_query_cache_hit+from posthog.query_cache import QueryCache, count_query_cache_hit, retention_ttlfrom posthog.query_cache.failures import (BUDGET_EXTENDED,QUERY_FAILURE_CACHE_COUNTER,@@ -2241,6 +2241,11 @@ class QueryRunner(ABC, Generic[Q, R, CR]):cache_key=cache_key,insight_id=insight_id,dashboard_id=dashboard_id,+ ttl=retention_ttl(+ insight_id=insight_id,+ dashboard_id=dashboard_id,+ access_method=get_query_tag_value("access_method"),+ ),)if execution_mode == ExecutionMode.CALCULATE_ASYNC_ALWAYS:diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.pyindex f60e395874d9..d62d20312c61 100644--- a/posthog/hogql_queries/test/test_query_runner.py+++ b/posthog/hogql_queries/test/test_query_runner.py@@ -59,6 +59,7 @@ from posthog.hogql.database.database import Databasefrom posthog.hogql.errors import QueryError, ResolutionErrorfrom posthog.clickhouse.client.limit import ConcurrencyLimitExceeded+from posthog.clickhouse.query_tagging import reset_query_tags, tag_queriesfrom posthog.constants import AvailableFeaturefrom posthog.errors import ExposedCHQueryErrorfrom posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQuerySizeExceeded, ClickHouseQueryTimeOut@@ -83,6 +84,7 @@ from posthog.models.sharing_configuration import SharingConfigurationfrom posthog.models.team.team import Team, WeekStartDayfrom posthog.models.team.team_revenue_analytics_config import TeamRevenueAnalyticsConfigfrom posthog.models.user import User+from posthog.query_cache import storage as qc_storagefrom posthog.query_cache.failures import (BASE_BACKOFF,BUDGET_EXTENDED,@@ -91,6 +93,7 @@ from posthog.query_cache.failures import (QUERY_FAILURE_CACHING_FLAG,QueryFailureCache,)+from posthog.query_cache.storage import entry_redis_keyfrom posthog.shared_link_user import SharedLinkUserfrom posthog.slo.types import SloOutcome@@ -1994,3 +1997,26 @@ class TestRunnersBuildDatabaseOnce(ClickhouseTestMixin, APIBaseTest):runner.calculate()assert create_for.call_count == 1assert any("build_shared_database" in key for key in runner.timings.to_dict())+++class TestQueryRunnerRetentionTtl(BaseTest):+ def tearDown(self) -> None:+ super().tearDown()+ cache.clear()++ def test_run_applies_programmatic_retention_ttl(self) -> None:+ TestQueryRunner = setup_test_query_runner_class()+ runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)+ redis_key = entry_redis_key(runner.get_cache_key())++ try:+ tag_queries(access_method="personal_api_key")+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)+ finally:+ reset_query_tags()++ assert 0 < qc_storage.query_cache_raw_client().ttl(redis_key) <= settings.CACHED_RESULTS_PROGRAMMATIC_TTL++ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS, insight_id=1)++ assert qc_storage.query_cache_raw_client().ttl(redis_key) > settings.CACHED_RESULTS_PROGRAMMATIC_TTLdiff --git a/posthog/query_cache/__init__.py b/posthog/query_cache/__init__.pyindex 15a10cb11628..32b597c5054e 100644--- a/posthog/query_cache/__init__.py+++ b/posthog/query_cache/__init__.py@@ -1,4 +1,4 @@-from posthog.query_cache.cache import CacheLookup, QueryCache+from posthog.query_cache.cache import CacheLookup, QueryCache, retention_ttlfrom posthog.query_cache.failures import FailureKind, QueryFailureRecordfrom posthog.query_cache.freshness_index import clean_up_stale_insights, get_stale_insightsfrom posthog.query_cache.metrics import count_query_cache_hit@@ -15,4 +15,5 @@ __all__ = ["clean_up_stale_insights","count_query_cache_hit","get_stale_insights",+ "retention_ttl",]diff --git a/posthog/query_cache/cache.py b/posthog/query_cache/cache.pyindex b79733a48925..9cbe05b1fb6b 100644--- a/posthog/query_cache/cache.py+++ b/posthog/query_cache/cache.py@@ -7,6 +7,7 @@ from django.conf import settingsimport structlogfrom posthog.cache_utils import OrjsonJsonSerializer+from posthog.clickhouse.query_tagging import AccessMethodfrom posthog.query_cache.failures import Budget, FailureKind, QueryFailureCache, QueryFailureRecordfrom posthog.query_cache.freshness_index import remove_last_refresh, update_target_agefrom posthog.query_cache.metrics import count_cache_write_data@@ -33,6 +34,24 @@ class CacheLookup:failure: Optional[QueryFailureRecord] = None+# Session logins carry no access_method tag, and sharing tokens render shared links: both are a+# person in a browser and keep the full TTL. Every other tag is code calling the API.+EXTENDED_TTL_ACCESS_METHODS: frozenset[AccessMethod | None] = frozenset({None, AccessMethod.SHARING_TOKEN})+++def retention_ttl(*, insight_id: Optional[int], dashboard_id: Optional[int], access_method: Optional[str]) -> int:+ """TTL in seconds for one cache entry write.++ Entries that belong to an insight or dashboard keep the full TTL whoever wrote them: every+ insight surface defaults to cache-only reads (posthog/hogql_queries/refresh_policy.py), so+ those entries are served at any age. Other programmatic writes get a short TTL, because no+ read path treats a result older than a day as fresh.+ """+ if insight_id is None and dashboard_id is None and access_method not in EXTENDED_TTL_ACCESS_METHODS:+ return settings.CACHED_RESULTS_PROGRAMMATIC_TTL+ return settings.CACHED_RESULTS_TTL++class QueryCache:"""Facade over query result cache storage: blob store, wire format, per-team size limits,the freshness index, and the failure circuit breaker. Code outside posthog/query_cache@@ -45,11 +64,13 @@ class QueryCache:cache_key: str,insight_id: Optional[int] = None,dashboard_id: Optional[int] = None,+ ttl: Optional[int] = None,) -> None:self.team_id = team_idself.cache_key = cache_keyself.insight_id = insight_idself.dashboard_id = dashboard_id+ self.ttl = ttl if ttl is not None else settings.CACHED_RESULTS_TTLdef lookup(self, *, include_failure: bool = False) -> CacheLookup:# The failure read is opt-in so callers that never consult the breaker (and the@@ -89,7 +110,7 @@ class QueryCache:try:storage_bytes = encode_inline_value(fresh_response_serialized)tracker = TeamCacheSizeTracker(self.team_id)- tracker.set(self.cache_key, storage_bytes, settings.CACHED_RESULTS_TTL)+ tracker.set(self.cache_key, storage_bytes, self.ttl)# The S3 upload runs on a background thread after the inline write: the fresh# result is already cached, so the requester never waits on S3, and a failed or# skipped upload leaves the valid inline entry in place. The swap only lands while@@ -100,9 +121,7 @@ class QueryCache:cache_key=self.cache_key,inline_value=storage_bytes,last_refresh=_last_refresh_iso(response),- swap=lambda pointer: tracker.replace_value(- self.cache_key, pointer, settings.CACHED_RESULTS_TTL, expected=storage_bytes- ),+ swap=lambda pointer: tracker.replace_value(self.cache_key, pointer, self.ttl, expected=storage_bytes),)except Exception:logger.exception("query_cache_store_result_failed", team_id=self.team_id, cache_key=self.cache_key)diff --git a/posthog/query_cache/size_tracker.py b/posthog/query_cache/size_tracker.pyindex 33d1745d385c..1a08c2f205e2 100644--- a/posthog/query_cache/size_tracker.py+++ b/posthog/query_cache/size_tracker.py@@ -32,9 +32,9 @@ CACHE_EVICTION_BYTES_COUNTER = Counter("Bytes evicted due to per-team size limits",)-CACHE_EVICTION_AGE_HISTOGRAM = Histogram(- "query_cache_eviction_age_seconds",- "Age of cache entries at eviction time (seconds since write)",+CACHE_EVICTION_REMAINING_TTL_HISTOGRAM = Histogram(+ "query_cache_eviction_remaining_ttl_seconds",+ "Remaining TTL of live cache entries at eviction time",buckets=[1800, # 30 min3600, # 1 hour@@ -80,7 +80,7 @@ local total_key = KEYS[3]local cache_key = ARGV[1]local size_bytes = tonumber(ARGV[2])-local timestamp = tonumber(ARGV[3])+local expires_at = tonumber(ARGV[3])local tracking_ttl = tonumber(ARGV[4])-- Atomically handle overwrite: only decrement if key exists@@ -89,8 +89,8 @@ if old_size thenredis.call('INCRBY', total_key, -tonumber(old_size))end--- Update tracking-redis.call('ZADD', entries_key, timestamp, cache_key)+-- The score is the entry's expiry time, so eviction pops the entries closest to expiry first.+redis.call('ZADD', entries_key, expires_at, cache_key)redis.call('HSET', sizes_key, cache_key, size_bytes)redis.call('INCRBY', total_key, size_bytes)@@ -106,12 +106,24 @@ return {redis.call('GET', total_key), redis.call('ZCARD', entries_key)}# but only when that value is an S3 pointer record (ARGV[3] is the pointer magic). Capturing# atomically with the write guarantees a returned pointer is dereferenced, so its blob is# safe to delete; filtering server-side keeps multi-megabyte inline blobs off the wire.+# The write never shortens the entry's remaining TTL: the same cache_key can be written from+# an attached surface (full retention) and from a programmatic one (short retention), and the+# entry must honor the longest retention promised for it. The pointer-swap script below+# repeats the guard for the same reason.+# Returns {applied_ttl} or {applied_ttl, old_pointer}. The caller scores the tracking zset+# by expiry, and only this script knows the TTL the guard finally applied.SET_ENTRY_RETURNING_OLD_POINTER_SCRIPT = """+local ttl = tonumber(ARGV[2])+local remaining = redis.call('TTL', KEYS[1])+if remaining > ttl then+ ttl = remaining+endlocal old = redis.call('GET', KEYS[1])-redis.call('SET', KEYS[1], ARGV[1], 'EX', tonumber(ARGV[2]))+redis.call('SET', KEYS[1], ARGV[1], 'EX', ttl)if old and string.sub(old, 1, string.len(ARGV[3])) == ARGV[3] then- return old+ return {ttl, old}end+return {ttl}"""# Lua script for eviction: delete the entry and report what was there. Returns nil when the@@ -137,16 +149,24 @@ return 1# when a reply is lost, and a retry after the swap landed must read as swapped, not as# superseded, because the superseded path deletes the blob the entry now points at. Pointer# records embed a per-upload uuid, so only this caller's own swap can have written ARGV[2].+# Returns {status} or {status, applied_ttl}: 0 superseded (no swap), 1 swapped, 2 already+# swapped by this caller's earlier attempt. For 2 the applied TTL is the key's remaining TTL,+# which the guard on the earlier attempt already set.REPLACE_IF_UNCHANGED_SCRIPT = """local current = redis.call('GET', KEYS[1])if current == ARGV[2] then- return 2+ return {2, redis.call('TTL', KEYS[1])}endif current ~= ARGV[1] then- return 0+ return {0}end-redis.call('SET', KEYS[1], ARGV[2], 'EX', tonumber(ARGV[3]))-return 1+local ttl = tonumber(ARGV[3])+local remaining = redis.call('TTL', KEYS[1])+if remaining > ttl then+ ttl = remaining+end+redis.call('SET', KEYS[1], ARGV[2], 'EX', ttl)+return {1, ttl}"""# Lua script for atomic and idempotent tracking removal@@ -234,12 +254,14 @@ class TeamCacheSizeTracker:if size_before + data_size > limit:evicted = self.evict_until_under_limit(limit, data_size)- old_pointer = self._set_entry_script(+ set_result = self._set_entry_script(keys=[storage.entry_redis_key(cache_key)],args=[data, ttl, storage.S3_POINTER_MAGIC],)+ applied_ttl = int(set_result[0])+ old_pointer = set_result[1] if len(set_result) > 1 else Nonestorage.schedule_blob_delete(old_pointer, team_id=self.team_id, cache_key=cache_key, trigger="replaced")- totals = self.track_cache_write(cache_key, data_size)+ totals = self.track_cache_write(cache_key, data_size, applied_ttl)CACHE_SIZE_HISTOGRAM.observe(totals.total_bytes)@@ -263,21 +285,23 @@ class TeamCacheSizeTracker:usage, and a store that landed mid-upload must not be replaced by an older upload'spointer. Also runs on upload worker threads, so it must stay free of Django ORM calls."""- swapped = self._replace_if_unchanged_script(+ swap_result = self._replace_if_unchanged_script(keys=[storage.entry_redis_key(cache_key)],args=[expected, data, ttl],)- if not swapped:+ status = int(swap_result[0])+ if status == 0:return False- self.track_cache_write(cache_key, len(data))+ applied_ttl = int(swap_result[1])+ self.track_cache_write(cache_key, len(data), applied_ttl)return True- def track_cache_write(self, cache_key: str, size_bytes: int) -> "TeamCacheTotals":+ def track_cache_write(self, cache_key: str, size_bytes: int, applied_ttl: int) -> "TeamCacheTotals":"""Track a cache write with its size, returning the team's totals after it. Atomic via Lua script."""tracking_ttl = settings.CACHED_RESULTS_TTL + 86400total_bytes, entry_count = self._track_write_script(keys=[self.entries_key, self.sizes_key, self.total_key],- args=[cache_key, size_bytes, time.time(), tracking_ttl],+ args=[cache_key, size_bytes, time.time() + applied_ttl, tracking_ttl],)return TeamCacheTotals(total_bytes=int(total_bytes), entry_count=int(entry_count))@@ -286,7 +310,7 @@ class TeamCacheSizeTracker:def evict_until_under_limit(self, limit_bytes: int, new_entry_size: int) -> list[str]:"""- Evict oldest entries (LRU) until total + new_entry_size <= limit.+ Evict entries in expiry order, soonest first, until total + new_entry_size <= limit.Uses ZPOPMIN for atomic dequeue - prevents double-eviction races.Lazy cleanup happens here - removes tracking for TTL-expired keys."""@@ -298,7 +322,7 @@ class TeamCacheSizeTracker:if not result:break- cache_key, write_timestamp = result[0]+ cache_key, expires_at = result[0]if isinstance(cache_key, bytes):cache_key = cache_key.decode()@@ -323,8 +347,10 @@ class TeamCacheSizeTracker:CACHE_EVICTION_COUNTER.inc()CACHE_EVICTION_BYTES_COUNTER.inc(removed_size)- eviction_age = time.time() - float(write_timestamp)- CACHE_EVICTION_AGE_HISTOGRAM.observe(eviction_age)+ # The score can be in the past for a live entry (a legacy write-time score, or expiry+ # racing this eviction), so clamp instead of observing a negative TTL.+ remaining_ttl = max(0.0, float(expires_at) - time.time())+ CACHE_EVICTION_REMAINING_TTL_HISTOGRAM.observe(remaining_ttl)return evicted_keysdiff --git a/posthog/query_cache/test/test_cache.py b/posthog/query_cache/test/test_cache.pyindex e54c17881c07..7ec507d524cd 100644--- a/posthog/query_cache/test/test_cache.py+++ b/posthog/query_cache/test/test_cache.py@@ -4,12 +4,17 @@ from datetime import UTC, datetime, timedeltafrom posthog.test.base import BaseTestfrom unittest.mock import patch+from django.conf import settingsfrom django.db import OperationalError+from django.test import SimpleTestCase++from parameterized import parameterizedfrom posthog.cache_utils import OrjsonJsonSerializerfrom posthog.query_cache import (QueryCache,get_stale_insights,+ retention_ttl,storage as qc_storage,)from posthog.query_cache.storage import entry_redis_key@@ -72,3 +77,48 @@ class TestQueryCacheFacade(BaseTest):cache.store_result(response={"results": []}, target_age=None)assert "42:" not in get_stale_insights(team_id=self.team.pk)+++class TestRetentionTtl(SimpleTestCase):+ @parameterized.expand(+ [+ ("api_key_unattached", None, None, "personal_api_key", "short"),+ ("oauth_unattached", None, None, "oauth", "short"),+ ("project_secret_unattached", None, None, "project_secret_api_key", "short"),+ ("api_key_insight", 1, None, "personal_api_key", "long"),+ ("api_key_dashboard", None, 2, "personal_api_key", "long"),+ ("session_unattached", None, None, None, "long"),+ ("sharing_token", None, None, "sharing_token", "long"),+ ]+ )+ def test_retention_ttl(+ self,+ _name: str,+ insight_id: int | None,+ dashboard_id: int | None,+ access_method: str | None,+ expected: str,+ ) -> None:+ ttl = retention_ttl(insight_id=insight_id, dashboard_id=dashboard_id, access_method=access_method)++ expected_ttl = settings.CACHED_RESULTS_PROGRAMMATIC_TTL if expected == "short" else settings.CACHED_RESULTS_TTL+ assert ttl == expected_ttl+++class TestQueryCacheRetention(BaseTest):+ def test_store_result_applies_ttl_and_a_rewrite_never_shortens_it(self) -> None:+ cache_key = f"cache_ttl_test_{self.team.pk}"+ redis_key = entry_redis_key(cache_key)+ client = qc_storage.query_cache_raw_client()+ response = {"is_cached": False, "results": [{"data": [1]}], "cache_key": "k"}++ QueryCache(team_id=self.team.pk, cache_key=cache_key, ttl=1000).store_result(response=response, target_age=None)+ assert 0 < client.ttl(redis_key) <= 1000++ QueryCache(team_id=self.team.pk, cache_key=cache_key, ttl=5000).store_result(response=response, target_age=None)+ assert client.ttl(redis_key) > 1000++ QueryCache(team_id=self.team.pk, cache_key=cache_key, ttl=1000).store_result(response=response, target_age=None)+ assert client.ttl(redis_key) > 1000++ client.delete(redis_key)diff --git a/posthog/query_cache/test/test_size_tracker.py b/posthog/query_cache/test/test_size_tracker.pyindex 97e5c4b9a0e7..1b6f75a32d15 100644--- a/posthog/query_cache/test/test_size_tracker.py+++ b/posthog/query_cache/test/test_size_tracker.py@@ -1,3 +1,5 @@+import time+from posthog.test.base import BaseTestfrom unittest.mock import patch@@ -42,37 +44,37 @@ class TestTeamCacheSizeTracker(BaseTest):def test_track_cache_write_increments_total(self):self.assertEqual(self.tracker.get_total_size(), 0)- self.tracker.track_cache_write("test_key_1", 1000)+ self.tracker.track_cache_write("test_key_1", 1000, 300)self.assertEqual(self.tracker.get_total_size(), 1000)- self.tracker.track_cache_write("test_key_2", 500)+ self.tracker.track_cache_write("test_key_2", 500, 300)self.assertEqual(self.tracker.get_total_size(), 1500)def test_track_cache_write_handles_overwrite(self):- self.tracker.track_cache_write("test_key_1", 1000)+ self.tracker.track_cache_write("test_key_1", 1000, 300)self.assertEqual(self.tracker.get_total_size(), 1000)# Overwrite with larger value- self.tracker.track_cache_write("test_key_1", 2000)+ self.tracker.track_cache_write("test_key_1", 2000, 300)self.assertEqual(self.tracker.get_total_size(), 2000)# Overwrite with smaller value- self.tracker.track_cache_write("test_key_1", 500)+ self.tracker.track_cache_write("test_key_1", 500, 300)self.assertEqual(self.tracker.get_total_size(), 500)def test_get_total_size_returns_correct_value(self):self.assertEqual(self.tracker.get_total_size(), 0)- self.tracker.track_cache_write("test_key_1", 100)- self.tracker.track_cache_write("test_key_2", 200)- self.tracker.track_cache_write("test_key_3", 300)+ self.tracker.track_cache_write("test_key_1", 100, 300)+ self.tracker.track_cache_write("test_key_2", 200, 300)+ self.tracker.track_cache_write("test_key_3", 300, 300)self.assertEqual(self.tracker.get_total_size(), 600)- def test_evict_until_under_limit_removes_oldest(self):- self.tracker.track_cache_write("test_key_1", 100)- self.tracker.track_cache_write("test_key_2", 200)- self.tracker.track_cache_write("test_key_3", 300)+ def test_evict_until_under_limit_removes_soonest_expiry(self) -> None:+ self.tracker.track_cache_write("test_key_1", 100, 300)+ self.tracker.track_cache_write("test_key_2", 200, 300)+ self.tracker.track_cache_write("test_key_3", 300, 300)self._seed_entry("test_key_1", b"data1")self._seed_entry("test_key_2", b"data2")self._seed_entry("test_key_3", b"data3")@@ -95,12 +97,23 @@ class TestTeamCacheSizeTracker(BaseTest):# Newest entry should still existself.assertIsNotNone(self._entry("test_key_3"))+ def test_evict_pops_short_ttl_entry_before_older_long_ttl_entry(self) -> None:+ self._seed_entry("test_key_1", b"a" * 300)+ self.tracker.track_cache_write("test_key_1", 300, 604800)+ self._seed_entry("test_key_2", b"b" * 300)+ self.tracker.track_cache_write("test_key_2", 300, 86400)++ evicted = self.tracker.evict_until_under_limit(500, 100)++ self.assertEqual(evicted, ["test_key_2"])+ self.assertIsNotNone(self._entry("test_key_1"))+def test_evict_cleans_up_expired_keys(self):# Track a key but don't actually store an entry for it (simulates TTL expiration)- self.tracker.track_cache_write("expired_key", 1000)+ self.tracker.track_cache_write("expired_key", 1000, 300)# Track a real key- self.tracker.track_cache_write("real_key", 500)+ self.tracker.track_cache_write("real_key", 500, 300)self._seed_entry("real_key", b"data")# Total includes the "expired" key@@ -117,7 +130,7 @@ class TestTeamCacheSizeTracker(BaseTest):self.assertEqual(self.tracker.get_total_size(), 500)def test_evict_returns_empty_when_under_limit(self):- self.tracker.track_cache_write("test_key_1", 100)+ self.tracker.track_cache_write("test_key_1", 100, 300)self._seed_entry("test_key_1", b"data1")# Already under limit@@ -126,8 +139,8 @@ class TestTeamCacheSizeTracker(BaseTest):self.assertEqual(self.tracker.get_total_size(), 100)def test_purge_removes_all_tracking_data(self):- self.tracker.track_cache_write("test_key_1", 1000)- self.tracker.track_cache_write("test_key_2", 2000)+ self.tracker.track_cache_write("test_key_1", 1000, 300)+ self.tracker.track_cache_write("test_key_2", 2000, 300)self.assertEqual(self.tracker.get_total_size(), 3000)self.tracker.purge()@@ -173,9 +186,9 @@ class TestTeamCacheSizeTracker(BaseTest):def test_eviction_schedules_delete_for_evicted_pointer_entries(self):pointer = encode_pointer(S3BlobPointer(bucket="cache-bucket", key="query_cache/1/evicted"))self._seed_entry("test_key_1", pointer)- self.tracker.track_cache_write("test_key_1", 200)+ self.tracker.track_cache_write("test_key_1", 200, 300)self._seed_entry("test_key_2", b"y" * 200)- self.tracker.track_cache_write("test_key_2", 200)+ self.tracker.track_cache_write("test_key_2", 200, 300)with patch("posthog.query_cache.tasks.delete_query_cache_blob.apply_async") as apply_async:evicted = self.tracker.evict_until_under_limit(300, 250)@@ -187,6 +200,15 @@ class TestTeamCacheSizeTracker(BaseTest):self.assertEqual(task_kwargs["key"], "query_cache/1/evicted")self.assertEqual(task_kwargs["trigger"], "evicted")+ def test_replace_value_never_shortens_remaining_ttl(self) -> None:+ self.tracker.redis_client.set(entry_redis_key("test_key"), b"inline-bytes", ex=5000)++ assert self.tracker.replace_value("test_key", b"new-pointer", 1000, expected=b"inline-bytes")++ assert self.tracker.redis_client.ttl(entry_redis_key("test_key")) > 1000+ score = self.tracker.redis_client.zscore(self.tracker.entries_key, "test_key")+ assert score is not None and score - time.time() > 1000+def test_broker_failure_does_not_break_the_cache_write(self):self._seed_entry("test_key_1", encode_pointer(S3BlobPointer(bucket="cache-bucket", key="query_cache/1/old")))@@ -203,11 +225,11 @@ class TestTeamCacheSizeTracker(BaseTest):# First write - under limitdata1 = b"x" * 200self._seed_entry("test_key_1", data1)- self.tracker.track_cache_write("test_key_1", len(data1))+ self.tracker.track_cache_write("test_key_1", len(data1), 300)data2 = b"y" * 200self._seed_entry("test_key_2", data2)- self.tracker.track_cache_write("test_key_2", len(data2))+ self.tracker.track_cache_write("test_key_2", len(data2), 300)# This should trigger eviction of test_key_1data3 = b"z" * 200@@ -220,7 +242,7 @@ class TestTeamCacheSizeTracker(BaseTest):self.assertIsNotNone(self._entry("test_key_3"))def test_remove_tracking_is_idempotent(self):- self.tracker.track_cache_write("test_key", 1000)+ self.tracker.track_cache_write("test_key", 1000, 300)self.assertEqual(self.tracker.get_total_size(), 1000)# Pop it from sorted set (simulating zpopmin in eviction)@@ -236,10 +258,10 @@ class TestTeamCacheSizeTracker(BaseTest):def test_stale_tracking_cleaned_during_eviction(self):# Track keys but don't store entries for them (simulates TTL expiration)- self.tracker.track_cache_write("stale_key_1", 1000)- self.tracker.track_cache_write("stale_key_2", 1000)+ self.tracker.track_cache_write("stale_key_1", 1000, 300)+ self.tracker.track_cache_write("stale_key_2", 1000, 300)# Also add a real key- self.tracker.track_cache_write("real_key", 500)+ self.tracker.track_cache_write("real_key", 500, 300)self._seed_entry("real_key", b"data")# Total is inflated due to stale entries@@ -261,8 +283,8 @@ class TestTeamCacheSizeTracker(BaseTest):tracker_team_b = TeamCacheSizeTracker(team_b.pk)tracker_team_b.purge()- tracker_team_a.track_cache_write("key_a", 1000)- tracker_team_b.track_cache_write("key_b", 2000)+ tracker_team_a.track_cache_write("key_a", 1000, 300)+ tracker_team_b.track_cache_write("key_b", 2000, 300)self.assertEqual(tracker_team_a.get_total_size(), 1000)self.assertEqual(tracker_team_b.get_total_size(), 2000)@@ -273,9 +295,9 @@ class TestTeamCacheSizeTracker(BaseTest):@override_settings(TEAM_CACHE_SIZE_LIMIT_BYTES=500)def test_entry_larger_than_limit_evicts_all(self):self._seed_entry("test_key_1", b"x" * 100)- self.tracker.track_cache_write("test_key_1", 100)+ self.tracker.track_cache_write("test_key_1", 100, 300)self._seed_entry("test_key_2", b"y" * 100)- self.tracker.track_cache_write("test_key_2", 100)+ self.tracker.track_cache_write("test_key_2", 100, 300)self.assertEqual(self.tracker.get_total_size(), 200)diff --git a/posthog/settings/schedules.py b/posthog/settings/schedules.pyindex 52694c10db22..1309974cbbbc 100644--- a/posthog/settings/schedules.py+++ b/posthog/settings/schedules.py@@ -40,6 +40,10 @@ COUNT_TILES_WITH_NO_FILTERS_HASH_INTERVAL_SECONDS = get_from_env(CACHED_RESULTS_TTL_DAYS = 7CACHED_RESULTS_TTL = CACHED_RESULTS_TTL_DAYS * 24 * 60 * 60+# TTL for cache entries written by API keys or OAuth clients outside any insight or dashboard.+# retention_ttl in posthog/query_cache/cache.py decides which writes get it.+CACHED_RESULTS_PROGRAMMATIC_TTL = get_from_env("CACHED_RESULTS_PROGRAMMATIC_TTL", 24 * 60 * 60, type_cast=int)+# Per-team cache size limit (default 1GB, can be overridden per-team via Team.extra_settings)TEAM_CACHE_SIZE_LIMIT_BYTES = get_from_env("TEAM_CACHE_SIZE_LIMIT_BYTES", 1_000_000_000, type_cast=int)