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(ingress): read the dedup lease through a primary-only cache alias (#103574)

Julian Bezf12aec6a95c1
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.md
index a739bbaae337..3661a6686b9f 100644
--- a/posthog/ingress/README.md
+++ b/posthog/ingress/README.md
@@ -274,7 +274,7 @@ The lease exists because a process that dies mid-run leaves its mark behind and
Its cost is that a redelivery arriving after the lease ran out can run beside a first attempt that overran the budget, which is the exposure a provider without dedup has on every retry.
Because two runs can overlap, a second key (`<key>:holder`) names the run that holds the lease, and a run only deletes its own claim: a late failure from the first run cannot drop the second run's claim, nor the done mark a finished run wrote.
The token lives in its own key so that the mark itself stays the plain value every deployed version reads as in flight, which keeps a rolling deploy from receipting a delivery the new worker can still fail.
-That fence reads the cache primary rather than a read replica, because a replica can still serve a token the primary already replaced.
+The marks live in the `ingress_dedup` cache alias rather than the default one, because the default alias is replica aware and a replica can still serve a token the primary already replaced, which would have a run delete a mark a newer run holds.
Settling to done is not fenced that way, because a consumer that ran the delivery and returned makes the mark true whoever wrote the value it replaces; a run drops the mark only while it is still a lease, so a late failure cannot delete a mark another run settled.
Keying per consumer rather than per delivery matters: one delivery legitimately fans out to several consumers, and a delivery-wide key would starve every consumer but the first.
A cache error fails **open** — dropping deliveries during a cache outage is worse than running a consumer twice, and consumers carry their own idempotency underneath this.
diff --git a/posthog/ingress/dispatch/dedup.py b/posthog/ingress/dispatch/dedup.py
index 022d97e2b605..a79e96d44a4c 100644
--- a/posthog/ingress/dispatch/dedup.py
+++ b/posthog/ingress/dispatch/dedup.py
@@ -3,7 +3,8 @@
from enum import Enum
from uuid import uuid4
-from django.core.cache import cache
+from django.core.cache import caches
+from django.core.cache.backends.base import BaseCache
import structlog
@@ -12,6 +13,11 @@ from posthog.ingress.dispatch.budget import delivery_budget_seconds
logger = structlog.get_logger(__name__)
+# A cache alias with one client on the Redis primary. The default alias is replica aware when
+# REDIS_READER_URL is set, and the fence in `release()` needs the read and the delete to see the
+# same Redis.
+INGRESS_DEDUP_CACHE_ALIAS = "ingress_dedup"
+
DELIVERY_DEDUP_TTL_SECONDS = 24 * 60 * 60
# What the lease adds to the request's delivery budget. The budget is checked between consumers
@@ -36,23 +42,6 @@ def _holder_key(key: str) -> str:
return f"{key}:holder"
-def _read_lease(key: str, holder_key: str) -> dict[str, object]:
- """Read the mark and its holder token together, from the cache's primary.
-
- The default cache is django_redis, which is replica aware when REDIS_READER_URL is set: it
- serves a read from a replica and sends a delete to the primary. A fence that reads a replica
- can act on a token the primary already replaced, and then `release()` deletes a mark this run
- does not hold. Ask the write client so that the read and the delete see the same Redis.
-
- A backend with no replica-aware client, such as the LocMemCache the tests run on, has a
- single cache to answer from.
- """
- client = getattr(cache, "client", None)
- if client is None or not hasattr(client, "get_client"):
- return cache.get_many([key, holder_key])
- return client.get_many([key, holder_key], client=client.get_client(write=True))
-
-
def delivery_claim_lease_seconds() -> float:
"""How long an unsettled claim keeps a redelivery out.
@@ -112,19 +101,21 @@ class DeliveryDedup:
def key(*, provider: str, consumer: str, delivery_id: str) -> str:
return f"webhook_delivery:{provider}:{consumer}:{delivery_id}"
+ @property
+ def cache(self) -> BaseCache:
+ """Looked up per call, so overriding CACHES in a test reaches this."""
+ return caches[INGRESS_DEDUP_CACHE_ALIAS]
+
def claim(self, *, provider: str, consumer: str, delivery_id: str) -> DeliveryClaimResult:
"""Take the mark for this consumer, or say what state the holder left it in.
Fail-open on a cache error: dropping deliveries during a cache outage is worse than
running a consumer twice, and consumers carry their own idempotency.
-
- The follow-up read can be served by a replica, unlike the fenced read in `release()`. A
- stale value there answers in progress where the mark is free, which costs the delivery one
- redelivery and never a receipt the work did not earn.
"""
key = self.key(provider=provider, consumer=consumer, delivery_id=delivery_id)
token = uuid4().hex
lease_seconds = delivery_claim_lease_seconds()
+ cache = self.cache
try:
for _ in range(2):
if cache.add(key, _IN_PROGRESS, timeout=lease_seconds):
@@ -171,7 +162,7 @@ class DeliveryDedup:
mark of a run that outlived its lease, and let the provider redeliver finished work.
"""
try:
- cache.set(
+ self.cache.set(
self.key(provider=provider, consumer=consumer, delivery_id=delivery_id),
_DONE,
timeout=DELIVERY_DEDUP_TTL_SECONDS,
@@ -207,8 +198,9 @@ class DeliveryDedup:
return
key = self.key(provider=provider, consumer=consumer, delivery_id=delivery_id)
holder_key = _holder_key(key)
+ cache = self.cache
try:
- held = _read_lease(key, holder_key)
+ held = cache.get_many([key, holder_key])
if held.get(holder_key) != token or held.get(key) != _IN_PROGRESS:
return
cache.delete_many([key, holder_key])
diff --git a/posthog/ingress/test/__init__.py b/posthog/ingress/test/__init__.py
index e69de29bb2d1..66c1085afde9 100644
--- a/posthog/ingress/test/__init__.py
+++ b/posthog/ingress/test/__init__.py
@@ -0,0 +1,6 @@
+from posthog.ingress.dispatch.dedup import INGRESS_DEDUP_CACHE_ALIAS
+
+LOCMEM = {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}
+
+# Both aliases share one LocMemCache store, as the test settings do, so clearing one clears both.
+LOCMEM_CACHES = {"default": LOCMEM, INGRESS_DEDUP_CACHE_ALIAS: LOCMEM}
diff --git a/posthog/ingress/test/test_dispatcher.py b/posthog/ingress/test/test_dispatcher.py
index 1f303a01eda0..6c09d7f9dacd 100644
--- a/posthog/ingress/test/test_dispatcher.py
+++ b/posthog/ingress/test/test_dispatcher.py
@@ -4,7 +4,7 @@ from datetime import UTC, datetime
from unittest.mock import Mock, patch
-from django.core.cache import cache
+from django.core.cache import caches
from django.test import SimpleTestCase, override_settings
from parameterized import parameterized
@@ -17,9 +17,15 @@ from posthog.ingress.contracts import (
WebhookDelivery,
)
from posthog.ingress.dispatch.budget import DEFAULT_DELIVERY_BUDGET_SECONDS, DeliveryBudget, delivery_budget_seconds
-from posthog.ingress.dispatch.dedup import DeliveryClaim, DeliveryDedup, delivery_claim_lease_seconds
+from posthog.ingress.dispatch.dedup import (
+ INGRESS_DEDUP_CACHE_ALIAS,
+ DeliveryClaim,
+ DeliveryDedup,
+ delivery_claim_lease_seconds,
+)
from posthog.ingress.dispatch.dispatcher import WebhookDispatcher
from posthog.ingress.dispatch.registry import ConsumerRegistry
+from posthog.ingress.test import LOCMEM, LOCMEM_CACHES
SPEC = ProviderSpec(provider="github", app="posthog", event_types=frozenset({"pull_request"}))
@@ -64,10 +70,11 @@ def _dispatcher(consumers: list[WebhookConsumer], *, budget_seconds: float | Non
)
-@override_settings(CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}})
+@override_settings(CACHES=LOCMEM_CACHES)
class TestWebhookDispatcher(SimpleTestCase):
def setUp(self) -> None:
- cache.clear()
+ self.cache = caches[INGRESS_DEDUP_CACHE_ALIAS]
+ self.cache.clear()
@parameterized.expand(
[
@@ -116,8 +123,10 @@ class TestWebhookDispatcher(SimpleTestCase):
dispatched = dispatcher.dispatch(_delivery())
self.assertEqual(dispatched.unaccepted_consumers, ("alpha",))
- self.assertIsNone(cache.get(DeliveryDedup.key(provider="github", consumer="alpha", delivery_id="delivery-1")))
- self.assertTrue(cache.get(DeliveryDedup.key(provider="github", consumer="zulu", delivery_id="delivery-1")))
+ self.assertIsNone(
+ self.cache.get(DeliveryDedup.key(provider="github", consumer="alpha", delivery_id="delivery-1"))
+ )
+ self.assertTrue(self.cache.get(DeliveryDedup.key(provider="github", consumer="zulu", delivery_id="delivery-1")))
with patch("posthog.ingress.dispatch.dispatcher.capture_exception"):
dispatched = dispatcher.dispatch(_delivery())
@@ -146,11 +155,13 @@ class TestWebhookDispatcher(SimpleTestCase):
self.assertEqual(opted_out.call_count, 2)
self.assertEqual(sibling.call_count, 1)
- self.assertIsNone(cache.get(DeliveryDedup.key(provider="github", consumer="alpha", delivery_id="delivery-1")))
+ self.assertIsNone(
+ self.cache.get(DeliveryDedup.key(provider="github", consumer="alpha", delivery_id="delivery-1"))
+ )
def test_a_cache_outage_fails_open_rather_than_dropping_the_delivery(self) -> None:
handler = Mock()
- with patch.object(cache, "add", side_effect=RuntimeError("cache down")):
+ with patch.object(self.cache, "add", side_effect=RuntimeError("cache down")):
_dispatcher([_consumer("alpha", handler)]).dispatch(_delivery())
handler.assert_called_once()
@@ -176,7 +187,9 @@ class TestWebhookDispatcher(SimpleTestCase):
{"provider": "github", "consumer": "zulu", "outcome": "budget_exceeded"},
[call.kwargs for call in observe.call_args_list],
)
- self.assertIsNone(cache.get(DeliveryDedup.key(provider="github", consumer="zulu", delivery_id="delivery-1")))
+ self.assertIsNone(
+ self.cache.get(DeliveryDedup.key(provider="github", consumer="zulu", delivery_id="delivery-1"))
+ )
dispatcher_with_room = _dispatcher([_consumer("zulu", skipped)], budget_seconds=10)
dispatcher_with_room.dispatch(_delivery())
@@ -199,23 +212,11 @@ class TestWebhookDispatcher(SimpleTestCase):
second.assert_not_called()
-class _WriteClient:
- """A django_redis client that answers from the Redis primary, as its write client does."""
-
- def __init__(self, primary: dict[str, object]) -> None:
- self.primary = primary
-
- def get_client(self, write: bool = True) -> dict[str, object]:
- return self.primary
-
- def get_many(self, keys: list[str], version: int | None = None, client: dict | None = None) -> dict:
- return {key: self.primary[key] for key in keys if key in self.primary}
-
-
-@override_settings(CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}})
+@override_settings(CACHES=LOCMEM_CACHES)
class TestDeliveryDedup(SimpleTestCase):
def setUp(self) -> None:
- cache.clear()
+ self.cache = caches[INGRESS_DEDUP_CACHE_ALIAS]
+ self.cache.clear()
self.mark = {"provider": "github", "consumer": "alpha", "delivery_id": "delivery-1"}
def test_a_claim_reads_as_in_flight_to_the_version_that_knows_no_holder_token(self) -> None:
@@ -224,23 +225,22 @@ class TestDeliveryDedup(SimpleTestCase):
# The deployed version reads every value but this one as done. On a rolling deploy a token
# in the mark would have an old worker receipt a delivery the new worker can still fail.
key = DeliveryDedup.key(**self.mark)
- self.assertEqual(cache.get(key), "in_progress")
- self.assertEqual(cache.get(f"{key}:holder"), claim.token)
-
- def test_the_lease_fence_reads_the_cache_primary(self) -> None:
- dedup = DeliveryDedup()
- claim = dedup.claim(**self.mark)
- key = DeliveryDedup.key(**self.mark)
- # The lease ran out and a newer run took the key, so the primary names the newer run. The
- # LocMemCache beside it stands in for a replica that still serves this run's token.
- client = _WriteClient({key: "in_progress", f"{key}:holder": "a-token-from-a-newer-run"})
-
- with patch.object(cache, "client", client, create=True):
- dedup.release(**self.mark, token=claim.token)
+ self.assertEqual(self.cache.get(key), "in_progress")
+ self.assertEqual(self.cache.get(f"{key}:holder"), claim.token)
+
+ @override_settings(
+ CACHES={
+ "default": {**LOCMEM, "LOCATION": "default"},
+ INGRESS_DEDUP_CACHE_ALIAS: {**LOCMEM, "LOCATION": "ingress_dedup"},
+ }
+ )
+ def test_the_mark_is_written_through_the_dedicated_alias(self) -> None:
+ DeliveryDedup().claim(**self.mark)
- # A replica can still serve a token the primary already replaced, so a fence that read one
- # would drop the mark the newer run holds and start a third run beside the two going.
- self.assertEqual(dedup.claim(**self.mark).state, DeliveryClaim.IN_PROGRESS)
+ # The default alias is replica aware in production, and a replica can still serve a token
+ # the primary replaced, which would have a run delete a mark a newer run holds.
+ self.assertIsNone(caches["default"].get(DeliveryDedup.key(**self.mark)))
+ self.assertEqual(caches[INGRESS_DEDUP_CACHE_ALIAS].get(DeliveryDedup.key(**self.mark)), "in_progress")
def test_the_mark_reports_the_state_its_holder_left_it_in(self) -> None:
dedup = DeliveryDedup()
@@ -267,7 +267,7 @@ class TestDeliveryDedup(SimpleTestCase):
def test_a_mark_this_run_did_not_write_still_dedupes(
self, _name: str, held: object, expected: DeliveryClaim
) -> None:
- cache.set(DeliveryDedup.key(**self.mark), held)
+ self.cache.set(DeliveryDedup.key(**self.mark), held)
# Marks live for 24 hours, so a rollout meets the ones the previous version wrote. Reading
# a flag as in flight would cost a receipt for every delivery still holding it, and reading
@@ -286,7 +286,7 @@ class TestDeliveryDedup(SimpleTestCase):
dedup = DeliveryDedup()
stale = dedup.claim(**self.mark)
# The lease runs out while the first run is still working, and a second run takes the key.
- cache.delete(DeliveryDedup.key(**self.mark))
+ self.cache.delete(DeliveryDedup.key(**self.mark))
dedup.claim(**self.mark)
if settle:
dedup.complete(**self.mark)
@@ -300,7 +300,7 @@ class TestDeliveryDedup(SimpleTestCase):
def test_the_run_the_holder_key_names_cannot_drop_a_settled_mark(self) -> None:
dedup = DeliveryDedup()
dedup.claim(**self.mark)
- cache.delete(DeliveryDedup.key(**self.mark))
+ self.cache.delete(DeliveryDedup.key(**self.mark))
newer = dedup.claim(**self.mark)
dedup.complete(**self.mark)
@@ -319,7 +319,7 @@ class TestDeliveryDedup(SimpleTestCase):
def test_a_lease_that_expires_between_the_add_and_the_read_is_never_read_as_done(
self, _name: str, refusals: int, expected: DeliveryClaim
) -> None:
- real_add = cache.add
+ real_add = self.cache.add
refused = 0
def refuse_then_add(*args, **kwargs):
@@ -329,7 +329,7 @@ class TestDeliveryDedup(SimpleTestCase):
return False
return real_add(*args, **kwargs)
- with patch.object(cache, "add", refuse_then_add):
+ with patch.object(self.cache, "add", refuse_then_add):
claim = DeliveryDedup().claim(**self.mark)
# A refused add whose follow-up read finds nothing is a lease that ran out under the claim,
diff --git a/posthog/ingress/test/test_views.py b/posthog/ingress/test/test_views.py
index 9177c4053999..8a0f053320cb 100644
--- a/posthog/ingress/test/test_views.py
+++ b/posthog/ingress/test/test_views.py
@@ -7,7 +7,7 @@ from urllib.parse import urlencode
from unittest.mock import Mock, PropertyMock, patch
-from django.core.cache import cache
+from django.core.cache import caches
from django.core.files.uploadedfile import SimpleUploadedFile
from django.http import HttpRequest
from django.test import RequestFactory, SimpleTestCase, override_settings
@@ -26,6 +26,7 @@ from posthog.ingress.contracts import (
WebhookConsumer,
WebhookDelivery,
)
+from posthog.ingress.dispatch.dedup import INGRESS_DEDUP_CACHE_ALIAS
from posthog.ingress.dispatch.dispatcher import WebhookDispatcher
from posthog.ingress.dispatch.forward import HOST_IDENTIFYING_HEADERS, forward_to_secondary_region
from posthog.ingress.dispatch.registry import ConsumerRegistry
@@ -33,6 +34,7 @@ from posthog.ingress.github.provider import GitHubProvider, build_github_provide
from posthog.ingress.pandadoc.provider import build_pandadoc_provider
from posthog.ingress.providers import InvalidPayload, WebhookProvider
from posthog.ingress.slack.provider import build_slack_provider
+from posthog.ingress.test import LOCMEM_CACHES
from posthog.ingress.vapi.provider import VapiProvider
from posthog.ingress.verify.schemes import Verification, VerificationOutcome
from posthog.ingress.views import build_webhook_view
@@ -446,12 +448,12 @@ def _consumer(
)
-@override_settings(CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}})
+@override_settings(CACHES=LOCMEM_CACHES)
class _DispatchingViewTestCase(SimpleTestCase):
"""A view driving the real dispatcher and registry, rather than a mocked one."""
def setUp(self) -> None:
- cache.clear()
+ caches[INGRESS_DEDUP_CACHE_ALIAS].clear()
self.factory = RequestFactory()
self.handler = Mock()
diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.py
index 30f0f57a36db..187f55a9a008 100644
--- a/posthog/settings/data_stores.py
+++ b/posthog/settings/data_stores.py
@@ -717,6 +717,14 @@ CACHES["cohort_dependencies"] = {
"LOCATION": REDIS_URL,
}
+# The inbound webhook dedup lease must read what it wrote: the fence in `release()` compares a
+# holder token against the value the primary holds, and a replica that still serves the previous
+# token would let a run delete a mark a newer run owns.
+CACHES["ingress_dedup"] = {
+ **CACHES["default"],
+ "LOCATION": REDIS_URL,
+}
+
# Dedicated cache for the feature flags service (if configured)
# Django only writes to this cache (never reads), so no reader URL needed
if FLAGS_REDIS_URL:
@@ -781,6 +789,7 @@ if TEST:
CACHES["query_cache"] = CACHES["default"]
CACHES["organization_access"] = CACHES["default"]
CACHES["cohort_dependencies"] = CACHES["default"]
+ CACHES["ingress_dedup"] = CACHES["default"]
# Cache timeout for materialized columns metadata (in seconds)
MATERIALIZED_COLUMNS_CACHE_TIMEOUT: int = get_from_env("MATERIALIZED_COLUMNS_CACHE_TIMEOUT", 900, type_cast=int)