: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): delete replaced and evicted S3 blobs eagerly (#86837)
Sandy Spicer53413673aec9
diff --git a/docs/internal/workflows/s3-query-cache-setup.md b/docs/internal/workflows/s3-query-cache-setup.mdindex 9dda08e39e8a..bc7acf5e85e0 100644--- a/docs/internal/workflows/s3-query-cache-setup.md+++ b/docs/internal/workflows/s3-query-cache-setup.md@@ -9,7 +9,8 @@ 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.-- **The S3 lifecycle rule is garbage collection only.** It deletes blobs once nothing can reference them (expired or evicted pointers, shadow-mode uploads, rolled-back teams).+- **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.- Disabled: every result is stored inline in Redis, as always.- `shadow`: write the cache entry to both S3 and Redis, testing the write path; nothing reads the S3 copy.@@ -17,7 +18,7 @@ See `posthog/query_cache/storage.py`.## Object layout and tagging-Objects are written to `s3://{QUERY_CACHE_S3_BUCKET}/{OBJECT_STORAGE_S3_QUERY_CACHE_FOLDER}/{team_id}/{cache_key}/{upload_id}` with attribution tags (`cache_type=query_data`, `team_id=<id>`). Tags carry no expiry meaning. The per-upload suffix keeps overlapping recomputes of one query from overwriting each other's blob. Superseded objects sit unreferenced until the lifecycle rule collects them; eager deletion was considered and dropped, since 7-day retention of churn costs little and the machinery does not.+Objects are written to `s3://{QUERY_CACHE_S3_BUCKET}/{OBJECT_STORAGE_S3_QUERY_CACHE_FOLDER}/{team_id}/{cache_key}/{upload_id}` with attribution tags (`cache_type=query_data`, `team_id=<id>`). Tags carry no expiry meaning. The per-upload suffix keeps overlapping recomputes of one query from overwriting each other's blob. A superseded upload deletes its own object on the spot, and replaced or evicted pointers get theirs deleted by the delayed Celery task, so a frequently recomputed query does not accumulate a week of dead blobs.## Required S3 lifecycle rulediff --git a/posthog/query_cache/size_tracker.py b/posthog/query_cache/size_tracker.pyindex b014d6df2fad..33d1745d385c 100644--- a/posthog/query_cache/size_tracker.py+++ b/posthog/query_cache/size_tracker.py@@ -102,12 +102,46 @@ redis.call('EXPIRE', total_key, tracking_ttl)return {redis.call('GET', total_key), redis.call('ZCARD', entries_key)}"""+# Lua script for the entry write: store the new value and hand back the value it replaced,+# 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.+SET_ENTRY_RETURNING_OLD_POINTER_SCRIPT = """+local old = redis.call('GET', KEYS[1])+redis.call('SET', KEYS[1], ARGV[1], 'EX', tonumber(ARGV[2]))+if old and string.sub(old, 1, string.len(ARGV[3])) == ARGV[3] then+ return old+end+"""++# Lua script for eviction: delete the entry and report what was there. Returns nil when the+# key was already gone (TTL expiry), the old value when it was an S3 pointer (ARGV[1] is the+# pointer magic), and 1 otherwise, again keeping inline blobs off the wire.+DELETE_ENTRY_RETURNING_OLD_POINTER_SCRIPT = """+local old = redis.call('GET', KEYS[1])+if not old then+ return nil+end+redis.call('DEL', KEYS[1])+if string.sub(old, 1, string.len(ARGV[1])) == ARGV[1] then+ return old+end+return 1+"""+# Lua script for the pointer swap: replace the entry only while it still holds the exact bytes# the caller wrote, so a swap that lost a race to a newer write skips instead of clobbering it.# Compares the full expected value rather than a redis.sha1hex digest because fakeredis's Lua# runtime, which the tests run on, does not implement sha1hex.+# The already-swapped check makes the script idempotent: the cluster client retries EVALSHA+# 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].REPLACE_IF_UNCHANGED_SCRIPT = """local current = redis.call('GET', KEYS[1])+if current == ARGV[2] then+ return 2+endif current ~= ARGV[1] thenreturn 0end@@ -176,6 +210,8 @@ class TeamCacheSizeTracker:# redis-py's stubs omit register_script on RedisCluster; the runtime supports it.self._track_write_script = self.redis_client.register_script(TRACK_CACHE_WRITE_SCRIPT) # type: ignore[union-attr]+ self._set_entry_script = self.redis_client.register_script(SET_ENTRY_RETURNING_OLD_POINTER_SCRIPT) # type: ignore[union-attr]+ self._delete_entry_script = self.redis_client.register_script(DELETE_ENTRY_RETURNING_OLD_POINTER_SCRIPT) # type: ignore[union-attr]self._replace_if_unchanged_script = self.redis_client.register_script(REPLACE_IF_UNCHANGED_SCRIPT) # type: ignore[union-attr]self._remove_tracking_script = self.redis_client.register_script(REMOVE_TRACKING_SCRIPT) # type: ignore[union-attr]@@ -198,7 +234,11 @@ class TeamCacheSizeTracker:if size_before + data_size > limit:evicted = self.evict_until_under_limit(limit, data_size)- self.redis_client.set(storage.entry_redis_key(cache_key), data, ex=ttl)+ old_pointer = self._set_entry_script(+ keys=[storage.entry_redis_key(cache_key)],+ args=[data, ttl, storage.S3_POINTER_MAGIC],+ )+ storage.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)CACHE_SIZE_HISTOGRAM.observe(totals.total_bytes)@@ -262,15 +302,21 @@ class TeamCacheSizeTracker:if isinstance(cache_key, bytes):cache_key = cache_key.decode()- # Check if key still exists in cache (lazy cleanup for TTL-expired keys)- if not self.redis_client.exists(storage.entry_redis_key(cache_key)):+ old_value = self._delete_entry_script(+ keys=[storage.entry_redis_key(cache_key)],+ args=[storage.S3_POINTER_MAGIC],+ )+ if old_value is None:# Already expired via TTL, just clean up trackingremoved_size = self._remove_tracking(cache_key)current_size -= removed_sizecontinue- self.redis_client.delete(storage.entry_redis_key(cache_key))+ # Tracking removal stays immediately after the entry delete: a concurrent set() of+ # the same key landing between them loses its accounting (pre-existing, accepted,+ # self-heals on the key's next write), so the enqueue must not widen that gap.removed_size = self._remove_tracking(cache_key)+ storage.schedule_blob_delete(old_value, team_id=self.team_id, cache_key=cache_key, trigger="evicted")current_size -= removed_sizeevicted_keys.append(cache_key)diff --git a/posthog/query_cache/storage.py b/posthog/query_cache/storage.pyindex fa50358d29eb..9b53e1c72bf6 100644--- a/posthog/query_cache/storage.py+++ b/posthog/query_cache/storage.py@@ -112,6 +112,12 @@ S3_WRITE_BYTES_COUNTER = Counter(labelnames=["mode"],)+S3_DELETE_COUNTER = Counter(+ name="posthog_query_cache_s3_delete_total",+ documentation="Query cache blob deletes, by what orphaned the blob and outcome.",+ labelnames=["trigger", "outcome"],+)+LEGACY_VALUE_READ_COUNTER = Counter(name="posthog_query_cache_legacy_value_read_total",documentation="Successful reads of values written through django_redis before this module "@@ -227,8 +233,12 @@ def schedule_upload_for_pointer(if mode == "on" and pointer is not None:swapped = swap(pointer)if not swapped:- # The blob this upload wrote is unreferenced; the lifecycle rule collects it.logger.info("query_cache_s3_swap_superseded", team_id=team_id, cache_key=cache_key)+ superseded = decode_pointer(pointer)+ if superseded is not None:+ # This upload's blob never entered Redis, so no reader can hold its+ # pointer; delete immediately rather than through the delayed task.+ delete_blob(bucket=superseded.bucket, key=superseded.key, team_id=team_id, trigger="superseded")except Exception:logger.warning("query_cache_s3_swap_failed", team_id=team_id, cache_key=cache_key, exc_info=True)finally:@@ -381,6 +391,51 @@ def write_blob(return encode_pointer(S3BlobPointer(bucket=bucket, key=object_key, last_refresh=last_refresh))+# A reader resolves a pointer in two steps, the Redis GET and then the S3 fetch, with+# milliseconds between them. Delaying the delete far past that window means a reader holding+# a just-replaced pointer still completes its read instead of turning into a recompute.+BLOB_DELETE_DELAY_SECONDS = 60+++def delete_blob(*, bucket: str, key: str, team_id: int, trigger: str) -> None:+ """Best-effort delete of a blob nothing references anymore. Never raises: a blob that+ outlives its pointer is only a storage cost, and the bucket's lifecycle rule collects+ whatever this misses."""+ try:+ object_storage_client().delete(bucket=bucket, key=key)+ except Exception:+ S3_DELETE_COUNTER.labels(trigger=trigger, outcome="error").inc()+ logger.warning("query_cache_s3_delete_failed", team_id=team_id, bucket=bucket, key=key, exc_info=True)+ return+ S3_DELETE_COUNTER.labels(trigger=trigger, outcome="success").inc()+++def schedule_blob_delete(old_value: object, *, team_id: int, cache_key: str, trigger: str) -> None:+ """Enqueue a delayed best-effort delete for the blob behind a pointer that just left Redis.++ Callers pass a displacing script's raw return value; anything that isn't a pointer+ record is ignored. Never raises: cache writes happen in web, Celery, Temporal, and+ Dagster processes, and one of them failing to reach the broker must cost an orphaned+ blob (the lifecycle rule collects it), not the cache write.+ """+ if not isinstance(old_value, bytes) or not is_s3_pointer(old_value):+ return+ pointer = decode_pointer(old_value)+ if pointer is None:+ return+ try:+ from posthog.query_cache.tasks import (+ delete_query_cache_blob, # noqa: PLC0415 — circular: tasks.py imports this module+ )++ delete_query_cache_blob.apply_async(+ kwargs={"bucket": pointer.bucket, "key": pointer.key, "team_id": team_id, "trigger": trigger},+ countdown=BLOB_DELETE_DELAY_SECONDS,+ )+ except Exception:+ logger.warning("query_cache_s3_delete_enqueue_failed", team_id=team_id, cache_key=cache_key, exc_info=True)++def _read_blob(pointer_bytes: bytes, *, team_id: int, cache_key: str) -> Optional[bytes]:"""Resolve a pointer record to the decompressed payload bytes. Never raises."""pointer = decode_pointer(pointer_bytes)diff --git a/posthog/query_cache/tasks.py b/posthog/query_cache/tasks.pynew file mode 100644index 000000000000..d7c895965b4b--- /dev/null+++ b/posthog/query_cache/tasks.py@@ -0,0 +1,10 @@+from celery import shared_task++from posthog.query_cache.storage import delete_blob+++# Not an app-level tasks.py, so celery autodiscovery never imports it; registered via+# CELERY_IMPORTS in posthog/settings/celery.py.+@shared_task(ignore_result=True)+def delete_query_cache_blob(bucket: str, key: str, team_id: int, trigger: str) -> None:+ delete_blob(bucket=bucket, key=key, team_id=team_id, trigger=trigger)diff --git a/posthog/query_cache/test/test_size_tracker.py b/posthog/query_cache/test/test_size_tracker.pyindex 2efb53c4e20d..97e5c4b9a0e7 100644--- a/posthog/query_cache/test/test_size_tracker.py+++ b/posthog/query_cache/test/test_size_tracker.py@@ -5,10 +5,11 @@ from django.db import OperationalErrorfrom django.test import override_settingsimport fakeredis+from parameterized import parameterizedfrom posthog.models import Teamfrom posthog.query_cache.size_tracker import TeamCacheSizeTracker, get_team_cache_limit-from posthog.query_cache.storage import entry_redis_key+from posthog.query_cache.storage import BLOB_DELETE_DELAY_SECONDS, S3BlobPointer, encode_pointer, entry_redis_keyENTRY_KEYS = ["test_key",@@ -144,6 +145,59 @@ class TestTeamCacheSizeTracker(BaseTest):# Tracking should be updatedself.assertEqual(self.tracker.get_total_size(), len(data))+ @parameterized.expand(+ [+ ("pointer", encode_pointer(S3BlobPointer(bucket="cache-bucket", key="query_cache/1/old")), True),+ ("inline_blob", b"plain-old-bytes", False),+ ("absent", None, False),+ ]+ )+ def test_set_schedules_delayed_delete_only_for_replaced_pointers(self, _name, old_value, expect_delete):+ if old_value is not None:+ self._seed_entry("test_key_1", old_value)++ with patch("posthog.query_cache.tasks.delete_query_cache_blob.apply_async") as apply_async:+ self.tracker.set("test_key_1", b"new-data", 300)++ self.assertEqual(self._entry("test_key_1"), b"new-data")+ if not expect_delete:+ apply_async.assert_not_called()+ return+ apply_async.assert_called_once()+ self.assertEqual(apply_async.call_args.kwargs["countdown"], BLOB_DELETE_DELAY_SECONDS)+ task_kwargs = apply_async.call_args.kwargs["kwargs"]+ self.assertEqual(task_kwargs["bucket"], "cache-bucket")+ self.assertEqual(task_kwargs["key"], "query_cache/1/old")+ self.assertEqual(task_kwargs["trigger"], "replaced")++ 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._seed_entry("test_key_2", b"y" * 200)+ self.tracker.track_cache_write("test_key_2", 200)++ with patch("posthog.query_cache.tasks.delete_query_cache_blob.apply_async") as apply_async:+ evicted = self.tracker.evict_until_under_limit(300, 250)++ # Both entries go, but only the pointer-backed one has a blob to delete+ self.assertEqual(evicted, ["test_key_1", "test_key_2"])+ apply_async.assert_called_once()+ task_kwargs = apply_async.call_args.kwargs["kwargs"]+ self.assertEqual(task_kwargs["key"], "query_cache/1/evicted")+ self.assertEqual(task_kwargs["trigger"], "evicted")++ 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")))++ with patch(+ "posthog.query_cache.tasks.delete_query_cache_blob.apply_async", side_effect=Exception("broker down")+ ):+ self.tracker.set("test_key_1", b"new-data", 300)++ self.assertEqual(self._entry("test_key_1"), b"new-data")+ self.assertEqual(self.tracker.get_total_size(), len(b"new-data"))+@override_settings(TEAM_CACHE_SIZE_LIMIT_BYTES=500)def test_set_method_triggers_eviction_when_over_limit(self):# First write - under limitdiff --git a/posthog/query_cache/test/test_storage.py b/posthog/query_cache/test/test_storage.pyindex 5e6ac01ebcdb..a1d9cd7de990 100644--- a/posthog/query_cache/test/test_storage.py+++ b/posthog/query_cache/test/test_storage.py@@ -16,6 +16,7 @@ from posthog.query_cache import (storage as qc_storage,)from posthog.query_cache.serialization import QUERY_CACHE_SPLIT_MAGIC, encode_split_cached_response+from posthog.query_cache.size_tracker import TeamCacheSizeTrackerfrom posthog.query_cache.storage import (S3_POINTER_MAGIC,ZSTD_FRAME_MAGIC,@@ -32,6 +33,7 @@ from posthog.storage.object_storage import ObjectStorageErrorclass FakeObjectStorage:def __init__(self) -> None:self.objects: dict[tuple[str, str], bytes] = {}+ self.written_keys: list[str] = []self.fail_writes = Falseself.fail_reads = False@@ -39,6 +41,7 @@ class FakeObjectStorage:if self.fail_writes:raise ObjectStorageError("write failed")self.objects[(bucket, key)] = content+ self.written_keys.append(key)def read_bytes(self, bucket: str, key: str, *, missing_ok: bool = False) -> bytes | None:if self.fail_reads:@@ -49,6 +52,9 @@ class FakeObjectStorage:raise ObjectStorageError("read failed")return self.objects[(bucket, key)]+ def delete(self, bucket: str, key: str) -> None:+ self.objects.pop((bucket, key), None)+class TestS3PointerCodec(SimpleTestCase):def test_pointer_round_trips(self):@@ -251,10 +257,22 @@ class TestQueryCacheS3Routing(BaseTest):assert self._redis_holds_pointer(cache_key)older_upload()+ # The superseded upload deletes its own blob; only the winning upload's object remains.+ assert len(self.storage.objects) == 1entry = cache.lookup().entryassert entry is not Noneassert entry.as_full_response() == newer+ # A lost reply makes the redis client retry the swap script after it already landed.+ # The retry must report swapped even though `expected` no longer matches, because a+ # False return sends the upload down the superseded path, which deletes the blob the+ # live entry now points at.+ raw_pointer = _redis_raw(cache_key)+ assert raw_pointer is not None+ tracker = TeamCacheSizeTracker(team_id=self.team.pk)+ assert tracker.replace_value(cache_key, raw_pointer, ttl=600, expected=b"stale-inline-bytes") is True+ assert _redis_raw(cache_key) == raw_pointer+def test_on_mode_large_result_round_trips_via_pointer(self):cache_key = f"s3_on_large_{self.team.pk}"cache = QueryCache(team_id=self.team.pk, cache_key=cache_key, insight_id=1)@@ -269,7 +287,7 @@ class TestQueryCacheS3Routing(BaseTest):assert entry is not Noneassert entry.as_full_response() == response- def test_each_upload_writes_a_fresh_object(self):+ def test_replacing_a_pointer_entry_deletes_the_replaced_blob(self):cache_key = f"s3_fresh_object_{self.team.pk}"cache = QueryCache(team_id=self.team.pk, cache_key=cache_key, insight_id=1)first = self._large_response()@@ -280,7 +298,10 @@ class TestQueryCacheS3Routing(BaseTest):cache.store_result(response=second, target_age=None)# A shared object key would let overlapping recomputes overwrite each other's blob.- assert len(self.storage.objects) == 2+ assert len(set(self.storage.written_keys)) == 2+ # The second store replaced the first store's pointer, which enqueued a delete for its+ # blob (Celery runs eagerly under TEST); only the second store's object remains.+ assert len(self.storage.objects) == 1entry = cache.lookup().entryassert entry is not Noneassert entry.as_full_response() == seconddiff --git a/posthog/settings/celery.py b/posthog/settings/celery.pyindex 2a3b8f440c1f..ee689655f015 100644--- a/posthog/settings/celery.py+++ b/posthog/settings/celery.py@@ -22,6 +22,7 @@ CELERY_IMPORTS: list[str] = ["posthog.email","posthog.models.product_intent.product_intent","posthog.models.scoping",+ "posthog.query_cache.tasks","posthog.scoping_audit",# Not a `<app>/tasks.py`, so autodiscovery walks past it — the app package holds a `tasks/`# namespace package instead, and importing that doesn't reach the module inside.diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex cb6528701850..16ca5815d058 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -8,6 +8,7 @@'posthog.caching.warming.warm_insight_cache_task','posthog.email._send_email','posthog.models.product_intent.product_intent.calculate_product_activation',+ 'posthog.query_cache.tasks.delete_query_cache_blob','posthog.tasks.activity_log.broadcast_activity_log_to_organization','posthog.tasks.async_migrations.run_async_migration','posthog.tasks.auth_token_cache_verification.verify_and_fix_auth_token_cache_task',