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.

fix(slack-app): cache claim probe and proxy optimistically on flake (#60898)

Vojta Bartoš576bbb553594
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 03a35d23c7a4..dd29321f419c 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -512,7 +512,9 @@ def resolve_slack_user(
# - hit US, local match -> handle locally
# - hit US, no local match -> proxy to EU (loop header set)
# - hit EU, US says "I have it" -> proxy to US (loop header set)
-# - hit EU, US says "no" / errs -> handle locally if found, else drop
+# - hit EU, US says "no" -> handle locally if found, else drop
+# - hit EU, probe errs / unknown -> assume US claims and proxy (optimistic); US drops if it
+# also has nothing, which is the same outcome as before
# - hit either with loop header -> never proxy again; handle locally or drop
#
# This keeps the slack manifest endpoint swappable between us.posthog.com and eu.posthog.com
@@ -521,8 +523,12 @@ REGION_PROXY_HEADER = "X-PostHog-Region-Proxied"
REGION_PROXY_TIMEOUT_SECONDS = 3
# Tight budget: the workspace_claims endpoint is just a DB .exists(), and EU calls it inline
# before deciding whether to proxy. Slack's webhook ack deadline is 3s total, so we want this
-# call to fail fast (and fall back to local handling) rather than eat into the proxy budget.
+# call to fail fast (and fall back to optimistic proxy) rather than eat into the proxy budget.
WORKSPACE_CLAIMS_TIMEOUT_SECONDS = (1, 1)
+# Cache definitive (True/False) claim answers per workspace so a single probe flake does not
+# re-flap routing for every subsequent event. Short TTL keeps us responsive when an integration
+# moves between regions; None answers are never cached.
+WORKSPACE_CLAIMS_CACHE_TTL_SECONDS = 60
def _us_region_domain() -> str:
@@ -599,13 +605,28 @@ def _proxy_event_and_return_route(request: HttpRequest, target_domain: str) -> s
return ROUTE_PROXIED if _proxy_event_to_region(request, target_domain) is not None else ROUTE_PROXY_FAILED
+def _workspace_claims_cache_key(slack_team_id: str, kinds: list[str]) -> str:
+ kinds_token = ",".join(sorted(kinds))
+ return f"slack_app:ws_claims:{slack_team_id}:{kinds_token}"
+
+
def does_other_region_claim_workspace(*, slack_team_id: str, kinds: list[str], incoming_host: str) -> bool | None:
"""Ask the other region whether it claims the given workspace for any of the kinds.
Returns True/False on a definitive answer, or None on transport failure or bad response.
- Callers must treat None as "unknown" — typically by falling back to local handling so the
- event is not silently dropped.
+ Definitive answers are cached for ``WORKSPACE_CLAIMS_CACHE_TTL_SECONDS`` so a single probe
+ flake does not reroute the next event. None is never cached so the next event re-probes.
"""
+ cache_key = _workspace_claims_cache_key(slack_team_id, kinds)
+ cached = cache.get(cache_key)
+ if isinstance(cached, bool):
+ logger.info(
+ "slack_app_workspace_claims_cache_hit",
+ slack_team_id=slack_team_id,
+ claimed=cached,
+ )
+ return cached
+
target_domain = _other_region_domain(incoming_host)
scheme = "http" if settings.DEBUG else "https"
target_url = f"{scheme}://{target_domain}/slack/workspace/claims/"
@@ -648,6 +669,8 @@ def does_other_region_claim_workspace(*, slack_team_id: str, kinds: list[str], i
if not isinstance(claimed, bool):
logger.warning("slack_app_workspace_claims_bad_payload", target_url=target_url)
return None
+
+ cache.set(cache_key, claimed, timeout=WORKSPACE_CLAIMS_CACHE_TTL_SECONDS)
return claimed
@@ -1522,19 +1545,25 @@ def route_posthog_code_event_to_relevant_region(
def _us_should_handle_instead(slack_team_id: str, kinds: list[str], can_defer: bool, incoming_host: str) -> bool:
"""US-precedence guard. EU yields to US when both claim a workspace.
- Skipped when we're already US (we win), when we were proxied to (the other region already
- deferred), or when the lookup transport fails (None) — in that last case the caller should
- prefer handling locally over dropping.
+ Skipped when we're already US (we win) or when we were proxied to (the other region already
+ deferred). When the probe transport itself fails (None), bias toward proxying to US: during
+ a region cutover both regions hold a row for the same workspace and US is the rightful owner,
+ so a single probe flake should not pin the event to EU. If US in fact has no row, it sees the
+ proxied event with the loop header set and drops it — the same outcome the caller would have
+ reached by handling locally.
"""
if not can_defer:
return False
claimed = does_other_region_claim_workspace(slack_team_id=slack_team_id, kinds=kinds, incoming_host=incoming_host)
+ decision = True if claimed is None else claimed
logger.info(
"posthog_code_route_us_probe_result",
slack_team_id=slack_team_id,
claimed=claimed,
+ decision=decision,
+ optimistic_proxy=claimed is None,
)
- return bool(claimed)
+ return decision
def _route_to_other_region_or_drop(
diff --git a/products/slack_app/backend/tests/test_posthog_code_event_handler.py b/products/slack_app/backend/tests/test_posthog_code_event_handler.py
index 52a4784b3f2c..afdc55afc021 100644
--- a/products/slack_app/backend/tests/test_posthog_code_event_handler.py
+++ b/products/slack_app/backend/tests/test_posthog_code_event_handler.py
@@ -485,24 +485,30 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):
mock_sync_connect.return_value.start_workflow.assert_called_once()
@patch("products.slack_app.backend.api.does_other_region_claim_workspace")
+ @patch("products.slack_app.backend.api._proxy_event_and_return_route")
@patch("products.slack_app.backend.api.asyncio.run")
@patch("products.slack_app.backend.api.sync_connect")
@override_settings(DEBUG=False)
- def test_eu_local_match_with_us_lookup_failure_falls_back_to_local(
- self, mock_sync_connect, mock_asyncio_run, mock_lookup
+ def test_eu_local_match_with_us_lookup_failure_optimistically_proxies(
+ self, mock_sync_connect, mock_asyncio_run, mock_proxy, mock_lookup
):
- # Lookup returns None on transport failure / bad response. Falling back to local handling
- # is safer than dropping — at worst we double-handle if US later turns out to own this.
+ # Lookup returns None on transport failure / bad response. We optimistically proxy to US
+ # rather than handle locally: during cutover both regions hold a row, US is the rightful
+ # owner, and one flake should not pin the event to EU. If US in fact has no row it sees
+ # the proxied event with the loop header set and drops, which matches the prior outcome.
mock_lookup.return_value = None
+ mock_proxy.return_value = "proxied"
request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")
- from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region
+ from products.slack_app.backend.api import ROUTE_PROXIED, route_posthog_code_event_to_relevant_region
result = route_posthog_code_event_to_relevant_region(request, self.event, "T12345")
- assert result == ROUTE_HANDLED_LOCALLY
+ assert result == ROUTE_PROXIED
mock_lookup.assert_called_once()
- mock_sync_connect.assert_called_once()
+ mock_proxy.assert_called_once()
+ assert mock_proxy.call_args.args[1] == "us.posthog.com"
+ mock_sync_connect.assert_not_called()
@patch("products.slack_app.backend.api.does_other_region_claim_workspace")
@patch("products.slack_app.backend.api._proxy_event_and_return_route")
diff --git a/products/slack_app/backend/tests/test_workspace_claims.py b/products/slack_app/backend/tests/test_workspace_claims.py
index 6d3e0a590124..c199de9bda83 100644
--- a/products/slack_app/backend/tests/test_workspace_claims.py
+++ b/products/slack_app/backend/tests/test_workspace_claims.py
@@ -3,6 +3,7 @@ from typing import Any
from unittest.mock import MagicMock, patch
+from django.core.cache import cache
from django.test import RequestFactory, TestCase, override_settings
import requests
@@ -120,6 +121,7 @@ class TestDoesOtherRegionClaimWorkspace(TestCase):
"""
def setUp(self):
+ cache.clear()
self.signing_secret = "posthog-code-helper-test-secret"
def _call(self, mock_post_return, **call_overrides) -> bool | None:
@@ -196,6 +198,86 @@ class TestDoesOtherRegionClaimWorkspace(TestCase):
)
assert result is None
+ def test_definitive_true_answer_is_cached(self):
+ # Second call with the same workspace must not re-issue the HTTP probe — a single flake
+ # in a follow-up request should not re-flap routing for a workspace we just confirmed.
+ from products.slack_app.backend.api import does_other_region_claim_workspace
+
+ with (
+ patch("products.slack_app.backend.api.SlackIntegration.slack_config") as mock_config,
+ patch("products.slack_app.backend.api.requests.post") as mock_post,
+ ):
+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ mock_post.return_value = self._response(200, {"claimed": True})
+ first = does_other_region_claim_workspace(
+ slack_team_id="T_CACHE", kinds=["slack"], incoming_host="eu.posthog.com"
+ )
+ second = does_other_region_claim_workspace(
+ slack_team_id="T_CACHE", kinds=["slack"], incoming_host="eu.posthog.com"
+ )
+ assert first is True
+ assert second is True
+ assert mock_post.call_count == 1
+
+ def test_definitive_false_answer_is_cached(self):
+ from products.slack_app.backend.api import does_other_region_claim_workspace
+
+ with (
+ patch("products.slack_app.backend.api.SlackIntegration.slack_config") as mock_config,
+ patch("products.slack_app.backend.api.requests.post") as mock_post,
+ ):
+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ mock_post.return_value = self._response(200, {"claimed": False})
+ first = does_other_region_claim_workspace(
+ slack_team_id="T_CACHE_FALSE", kinds=["slack"], incoming_host="eu.posthog.com"
+ )
+ second = does_other_region_claim_workspace(
+ slack_team_id="T_CACHE_FALSE", kinds=["slack"], incoming_host="eu.posthog.com"
+ )
+ assert first is False
+ assert second is False
+ assert mock_post.call_count == 1
+
+ def test_none_answer_is_not_cached(self):
+ # A flake must not poison the cache: the next event re-probes and may get a real answer.
+ from products.slack_app.backend.api import does_other_region_claim_workspace
+
+ with (
+ patch("products.slack_app.backend.api.SlackIntegration.slack_config") as mock_config,
+ patch("products.slack_app.backend.api.requests.post") as mock_post,
+ ):
+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ mock_post.side_effect = [
+ requests.ConnectionError("transient"),
+ self._response(200, {"claimed": True}),
+ ]
+ first = does_other_region_claim_workspace(
+ slack_team_id="T_FLAKE", kinds=["slack"], incoming_host="eu.posthog.com"
+ )
+ second = does_other_region_claim_workspace(
+ slack_team_id="T_FLAKE", kinds=["slack"], incoming_host="eu.posthog.com"
+ )
+ assert first is None
+ assert second is True
+ assert mock_post.call_count == 2
+
+ def test_cache_is_keyed_by_kinds(self):
+ # Two different kind sets for the same workspace must probe independently — claims can
+ # differ per integration kind even though the workspace id is shared.
+ from products.slack_app.backend.api import does_other_region_claim_workspace
+
+ with (
+ patch("products.slack_app.backend.api.SlackIntegration.slack_config") as mock_config,
+ patch("products.slack_app.backend.api.requests.post") as mock_post,
+ ):
+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ mock_post.return_value = self._response(200, {"claimed": True})
+ does_other_region_claim_workspace(slack_team_id="T_KIND", kinds=["slack"], incoming_host="eu.posthog.com")
+ does_other_region_claim_workspace(
+ slack_team_id="T_KIND", kinds=["slack", "slack-posthog-code"], incoming_host="eu.posthog.com"
+ )
+ assert mock_post.call_count == 2
+
def test_signed_request_is_accepted_by_validator(self):
# End-to-end roundtrip: the sent headers + body, fed into the receiver's verifier, must
# validate cleanly. This is the actual contract we care about — the matched constant-time