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.

feat(ingress): forward from the region a provider registered its URL against (#103605)

Julian Bez3e678518bb5d
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.md
index 3661a6686b9f..116d75de6740 100644
--- a/posthog/ingress/README.md
+++ b/posthog/ingress/README.md
@@ -184,7 +184,9 @@ Ingress carries both as general controls, so the next endpoint gets them without
## Regional forwarding
-A third party holds one callback URL, which points at the primary region (EU), so a delivery about a resource the other region (US) owns still arrives here first.
+A third party holds one callback URL, which points at one region, so a delivery about a resource the other region owns still arrives there first.
+For every App registered today that URL is the primary region (EU) and the forward runs to the secondary one (US).
+A provider whose App was registered against the secondary region instead overrides `receiving_region_domain()`, and the forward runs the other way.
Ingress owns the forward, because what is replayed is the signed body — a consumer only ever sees the parsed mapping.
A consumer whose resources are split by region declares `ownership`, a callable that takes the delivery and answers a `DeliveryOwnership`:
@@ -198,7 +200,7 @@ A fourth value, `FAILED`, is the dispatcher's own: a consumer never answers it,
Every delivery in the request is assessed first, and the request is then forwarded **once**, when any consumer answered `ELSEWHERE`.
One forward per request rather than per delivery, because the unit being replayed is the HTTP request.
Local dispatch runs either way: a consumer that answered `ELSEWHERE` no-ops on its own, and the other consumers on the endpoint are unaffected.
-Only the primary region forwards; on the secondary region an `ELSEWHERE` answer is logged as `ingress_delivery_unowned_here`, because a local miss there is that consumer's unresolved routing rather than proof that no region owns the delivery.
+Only the receiving region forwards; on the region that receives forwards an `ELSEWHERE` answer is logged as `ingress_delivery_unowned_here`, because a local miss there is that consumer's unresolved routing rather than proof that no region owns the delivery.
The replay carries the signed bytes and the provider's own headers, but never the headers that name the host this region answered on: `Host`, `X-Forwarded-Host`, `X-Forwarded-Port`, `X-Forwarded-Proto` and `Forwarded`.
The receiving region reads which region it is off the connection it receives, so a forwarded host would make it forward the delivery on again.
diff --git a/posthog/ingress/dispatch/forward.py b/posthog/ingress/dispatch/forward.py
index c2bcf977caec..9458df4ea994 100644
--- a/posthog/ingress/dispatch/forward.py
+++ b/posthog/ingress/dispatch/forward.py
@@ -1,7 +1,8 @@
"""Replay a verified request to the region that owns the resource it is about.
-A third party sends every delivery to the primary region, so a delivery for a resource the other
-region holds has to be forwarded there. The forward is the raw signed bytes, unchanged: the other
+A third party sends every delivery to the one region its callback URL names, so a delivery for a
+resource the other region holds has to be forwarded there. Which region receives is the provider's
+own fact, and the caller names the target. The forward is the raw signed bytes, unchanged: the other
region verifies the same signature over the same body, which is why no consumer can do this --
by the time a consumer sees a delivery, the body is a parsed mapping.
@@ -21,7 +22,6 @@ import structlog
from requests import RequestException
from posthog.ingress.observability.metrics import observe_forward
-from posthog.regions import SECONDARY_REGION_DOMAIN
logger = structlog.get_logger(__name__)
@@ -65,13 +65,15 @@ def _replay_kwargs(request: HttpRequest, headers: Mapping[str, str]) -> dict[str
HOST_IDENTIFYING_HEADERS = frozenset({"host", "x-forwarded-host", "x-forwarded-port", "x-forwarded-proto", "forwarded"})
-def forward_to_secondary_region(request: HttpRequest, *, provider: str, app: str, timeout: float = 3.0) -> bool:
- """Send this request on to the secondary region once. True only when it answered 2xx.
+def forward_to_other_region(
+ request: HttpRequest, *, target_domain: str, provider: str, app: str, timeout: float = 3.0
+) -> bool:
+ """Send this request on to the region that owns it, once. True only when it answered 2xx.
Forwarding once per request rather than once per delivery: the unit being replayed is the HTTP
request, so a batched body that carries several unowned deliveries still crosses once.
"""
- target_url = urlunparse(urlparse(request.build_absolute_uri())._replace(netloc=SECONDARY_REGION_DOMAIN))
+ target_url = urlunparse(urlparse(request.build_absolute_uri())._replace(netloc=target_domain))
headers = {key: value for key, value in request.headers.items() if key.lower() not in HOST_IDENTIFYING_HEADERS}
try:
diff --git a/posthog/ingress/providers.py b/posthog/ingress/providers.py
index 05bffdedd583..8df911cc122a 100644
--- a/posthog/ingress/providers.py
+++ b/posthog/ingress/providers.py
@@ -16,6 +16,7 @@ from django.http import HttpRequest, HttpResponse
from rest_framework.throttling import BaseThrottle
+from posthog import regions
from posthog.ingress.contracts import ProviderSpec, WebhookConsumer, WebhookDelivery
from posthog.ingress.verify.schemes import SignatureScheme, Verification, VerificationOutcome
@@ -126,6 +127,15 @@ class WebhookProvider(ABC):
that signs it, rather than handing a consumer a delivery it has to distrust.
"""
+ def receiving_region_domain(self) -> str:
+ """The region whose URL this App is registered against.
+
+ That region receives every delivery, and forwards the ones another region owns. Almost
+ every third party holds the primary region's URL, which is why this is not a field: a
+ provider that needs the other one overrides the method, and nothing else has to know.
+ """
+ return regions.PRIMARY_REGION_DOMAIN
+
def verify(self, request: HttpRequest) -> Verification:
scheme = self.scheme()
# Asked before `request.body`, so an unsigned probe cannot make every endpoint here
diff --git a/posthog/ingress/test/test_views.py b/posthog/ingress/test/test_views.py
index 8a0f053320cb..3b251af0cde3 100644
--- a/posthog/ingress/test/test_views.py
+++ b/posthog/ingress/test/test_views.py
@@ -1,5 +1,6 @@
import hmac
import json
+import importlib
from collections.abc import Mapping, Sequence
from dataclasses import replace
from typing import Any, cast
@@ -18,6 +19,7 @@ from requests import RequestException
from rest_framework.request import Request as DRFRequest
from rest_framework.throttling import BaseThrottle, ScopedRateThrottle
+from posthog import regions
from posthog.ingress.contracts import (
DeliveryDispatch,
DeliveryOwnership,
@@ -28,11 +30,11 @@ from posthog.ingress.contracts import (
)
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.forward import HOST_IDENTIFYING_HEADERS, forward_to_other_region
from posthog.ingress.dispatch.registry import ConsumerRegistry
from posthog.ingress.github.provider import GitHubProvider, build_github_provider
from posthog.ingress.pandadoc.provider import build_pandadoc_provider
-from posthog.ingress.providers import InvalidPayload, WebhookProvider
+from posthog.ingress.providers import _INCARNATION_MODULES, 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
@@ -63,6 +65,13 @@ class _RedeliveringGitHubProvider(GitHubProvider):
retry_status = 502
+class _SecondaryRegionGitHubProvider(GitHubProvider):
+ # Stands in for a provider whose App is registered against the secondary region, so deliveries
+ # arrive there and the forward runs the other way.
+ def receiving_region_domain(self) -> str:
+ return regions.SECONDARY_REGION_DOMAIN
+
+
class _SlowForwardGitHubProvider(GitHubProvider):
# Stands in for a provider whose deliveries carry uploaded files, which Mailgun's do.
forward_timeout_seconds = 10.0
@@ -638,6 +647,36 @@ class TestRegionalForwarding(_DispatchingViewTestCase):
self.handler.assert_called_once()
self.assertEqual([call.args[0] for call in logger.warning.call_args_list], ["ingress_delivery_unowned_here"])
+ def test_every_provider_on_the_package_receives_in_the_primary_region(self) -> None:
+ # The forward direction is shared machinery, so a provider that quietly overrides it
+ # redirects signed deliveries for an endpoint whose owners never asked for that.
+ overriding: list[str] = []
+ for module_name in _INCARNATION_MODULES:
+ module = importlib.import_module(module_name)
+ for candidate in vars(module).values():
+ if not isinstance(candidate, type) or not issubclass(candidate, WebhookProvider):
+ continue
+ if candidate.receiving_region_domain is not WebhookProvider.receiving_region_domain:
+ overriding.append(f"{module_name}.{candidate.__name__}")
+
+ self.assertEqual(overriding, [])
+
+ def test_a_provider_registered_against_the_secondary_region_forwards_the_other_way(self) -> None:
+ view = self._view(
+ [_consumer(GITHUB_SPEC, name="probe", handler=self.handler, answer=DeliveryOwnership.ELSEWHERE)],
+ provider=_SecondaryRegionGitHubProvider("posthog"),
+ )
+
+ with (
+ patch("posthog.regions.PRIMARY_REGION_DOMAIN", "eu.posthog.com"),
+ patch("posthog.regions.SECONDARY_REGION_DOMAIN", "testserver"),
+ ):
+ response = view(self._github_request())
+
+ self.assertEqual(response.status_code, 202)
+ self.assertIn("eu.posthog.com", self.requests.call_args.kwargs["url"])
+ self.handler.assert_called_once()
+
def test_a_batched_body_of_unowned_deliveries_forwards_the_request_once(self) -> None:
view = self._view(
[_consumer(PANDADOC_SPEC, name="probe", handler=self.handler, answer=DeliveryOwnership.ELSEWHERE)],
@@ -797,7 +836,9 @@ class TestForwardToSecondaryRegion(SimpleTestCase):
patch("posthog.ingress.dispatch.forward.requests.request", side_effect=error, return_value=response),
patch("posthog.ingress.dispatch.forward.observe_forward") as observe,
):
- result = forward_to_secondary_region(self.request, provider="github", app="posthog")
+ result = forward_to_other_region(
+ self.request, target_domain=SECONDARY_REGION_DOMAIN, provider="github", app="posthog"
+ )
self.assertEqual(result, forwarded)
self.assertEqual(observe.call_args.kwargs["outcome"], outcome)
@@ -805,7 +846,9 @@ class TestForwardToSecondaryRegion(SimpleTestCase):
def test_the_replay_carries_the_signed_bytes_unchanged(self) -> None:
with patch("posthog.ingress.dispatch.forward.requests.request") as request:
request.return_value = Mock(ok=True, status_code=202)
- forward_to_secondary_region(self.request, provider="github", app="posthog")
+ forward_to_other_region(
+ self.request, target_domain=SECONDARY_REGION_DOMAIN, provider="github", app="posthog"
+ )
kwargs = request.call_args.kwargs
self.assertEqual(kwargs["data"], self.body)
@@ -831,7 +874,7 @@ class TestForwardToSecondaryRegion(SimpleTestCase):
with patch("posthog.ingress.dispatch.forward.requests.request") as request:
request.return_value = Mock(ok=True, status_code=202)
- forward_to_secondary_region(multipart, provider="mailgun", app="inbound")
+ forward_to_other_region(multipart, target_domain=SECONDARY_REGION_DOMAIN, provider="mailgun", app="inbound")
kwargs = request.call_args.kwargs
self.assertIn(("token", "delivery-token"), kwargs["data"])
@@ -850,7 +893,9 @@ class TestForwardToSecondaryRegion(SimpleTestCase):
with patch("posthog.ingress.dispatch.forward.requests.request") as request:
request.return_value = Mock(ok=True, status_code=202)
- forward_to_secondary_region(urlencoded, provider="mailgun", app="inbound")
+ forward_to_other_region(
+ urlencoded, target_domain=SECONDARY_REGION_DOMAIN, provider="mailgun", app="inbound"
+ )
kwargs = request.call_args.kwargs
self.assertEqual(kwargs["data"], body)
diff --git a/posthog/ingress/views.py b/posthog/ingress/views.py
index bda3f2ac5b33..2b25b2c4d881 100644
--- a/posthog/ingress/views.py
+++ b/posthog/ingress/views.py
@@ -11,12 +11,12 @@ from rest_framework.request import Request as DRFRequest
from rest_framework.throttling import ScopedRateThrottle
from posthog.ingress.dispatch.budget import DeliveryBudget, delivery_budget_seconds
-from posthog.ingress.dispatch.forward import forward_to_secondary_region
+from posthog.ingress.dispatch.forward import forward_to_other_region
from posthog.ingress.dispatch.loading import get_dispatcher
from posthog.ingress.observability.metrics import observe_delivery
from posthog.ingress.providers import InvalidPayload, WebhookProvider
from posthog.ingress.verify.schemes import VerificationOutcome
-from posthog.regions import is_primary_region
+from posthog.regions import other_region_domain
logger = structlog.get_logger(__name__)
@@ -160,10 +160,11 @@ def build_webhook_view(provider: WebhookProvider) -> Callable[[HttpRequest], Htt
return _retry_refusal(provider, list(unanswered))
if elsewhere:
- if is_primary_region(request):
+ if request.get_host() == provider.receiving_region_domain():
# Once for the request, not once per delivery: what is replayed is the signed body.
- forwarded = forward_to_secondary_region(
+ forwarded = forward_to_other_region(
request,
+ target_domain=other_region_domain(provider.receiving_region_domain()),
provider=provider.provider,
app=provider.app,
timeout=provider.forward_timeout_seconds,
@@ -172,8 +173,8 @@ def build_webhook_view(provider: WebhookProvider) -> Callable[[HttpRequest], Htt
observe_delivery(provider=provider.provider, app=provider.app, outcome="forward_failed")
return HttpResponse(status=provider.retry_status)
else:
- # A local miss on the secondary region is that consumer's unresolved routing, not
- # proof that no region owns the delivery.
+ # This region is the one deliveries are forwarded to, so a local miss here is that
+ # consumer's unresolved routing, not proof that no region owns the delivery.
logger.warning(
"ingress_delivery_unowned_here",
provider=provider.provider,
diff --git a/posthog/regions.py b/posthog/regions.py
index f4e30a78a460..f6e4c6cc99fd 100644
--- a/posthog/regions.py
+++ b/posthog/regions.py
@@ -22,3 +22,12 @@ if settings.DEBUG:
def is_primary_region(request: HttpRequest) -> bool:
return request.get_host() == PRIMARY_REGION_DOMAIN
+
+
+def other_region_domain(domain: str) -> str:
+ """The region that is not the one named.
+
+ Most third parties hold the primary region's URL, so most forwards run to the secondary
+ one. A marketplace that registered the secondary region's URL is forwarded the other way.
+ """
+ return SECONDARY_REGION_DOMAIN if domain == PRIMARY_REGION_DOMAIN else PRIMARY_REGION_DOMAIN