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(api): roll out environments->projects redirect incrementally per team (#68316)

Yasen08af24f2655a
diff --git a/posthog/api/test/test_environments_redirect.py b/posthog/api/test/test_environments_redirect.py
index 31e11a341241..513a255bfe6f 100644
--- a/posthog/api/test/test_environments_redirect.py
+++ b/posthog/api/test/test_environments_redirect.py
@@ -9,6 +9,7 @@ from unittest.mock import patch
from django.http import HttpResponse
from django.test import (
Client as DjangoTestClient,
+ SimpleTestCase,
override_settings,
)
from django.urls import get_resolver
@@ -105,6 +106,32 @@ class TestEveryEnvironmentsRouteHasAProjectsCounterpart(APIBaseTest):
)
+class TestFlagDistinctId(SimpleTestCase):
+ # The distinct id fed to the flag is what makes the rollout incremental: a per-team id
+ # buckets by team, the constant id rides the global switch. If id extraction regresses,
+ # numeric-team paths silently fall back to the constant and the flag becomes a kill
+ # switch again — these cases catch that (and the reverse: @current must NOT get a team id).
+ @parameterized.expand(
+ [
+ (
+ "numeric id buckets per team",
+ "/api/environments/123/feature_flags/",
+ "environments_api_redirect:team:123",
+ ),
+ ("numeric id no trailing slash", "/api/environments/42", "environments_api_redirect:team:42"),
+ (
+ "current alias falls back to constant",
+ "/api/environments/@current/insights/",
+ "environments_api_redirect",
+ ),
+ ("non-numeric id falls back to constant", "/api/environments/abc/foo/", "environments_api_redirect"),
+ ("keyless path falls back to constant", "/api/environments", "environments_api_redirect"),
+ ]
+ )
+ def test_flag_distinct_id(self, _name: str, path: str, expected: str) -> None:
+ self.assertEqual(EnvironmentsRedirectMiddleware._flag_distinct_id(path), expected)
+
+
class TestEnvironmentsRedirect(APIBaseTest):
def setUp(self):
super().setUp()
diff --git a/posthog/middleware.py b/posthog/middleware.py
index 829d8d672752..37577bf46d87 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -609,11 +609,13 @@ class EnvironmentsRedirectMiddleware:
Gated by the `api-environments-redirect` feature flag, evaluated locally per request
(no network call, no flag events) — turning the flag off disables the redirect
- instantly without a deploy or restart. If the flag can't be evaluated (missing,
- local evaluation unavailable, SDK disabled) the redirect stays OFF. Whether or not
- the redirect is enabled, redirectable /api/environments/* responses carry
- `Deprecation`, `Sunset`, and `Link` headers announcing the successor path to
- integrators.
+ instantly without a deploy or restart. The flag is bucketed on the team/project id
+ from the path (see _flag_distinct_id), so a percentage rollout redirects that
+ fraction of teams (0% off, 100% on) rather than flipping the whole instance at once.
+ If the flag can't be evaluated (missing, local evaluation unavailable, SDK disabled)
+ the redirect stays OFF. Whether or not the redirect is enabled, redirectable
+ /api/environments/* responses carry `Deprecation`, `Sunset`, and `Link` headers
+ announcing the successor path to integrators.
"""
ENVIRONMENTS_PREFIX = "/api/environments"
@@ -637,7 +639,7 @@ class EnvironmentsRedirectMiddleware:
location = f"{target_path}?{query_string}" if query_string else target_path
response: HttpResponse
- if self._redirect_enabled():
+ if self._redirect_enabled(self._flag_distinct_id(path)):
response = HttpResponseTemporaryRedirectPreserveMethod(location)
else:
response = self.get_response(request)
@@ -650,13 +652,28 @@ class EnvironmentsRedirectMiddleware:
return response
@classmethod
- def _redirect_enabled(cls) -> bool:
- # only_evaluate_locally keeps this off the network on every request; a constant
- # distinct id makes the flag an instance-wide on/off switch (roll out 0% or 100%).
+ def _flag_distinct_id(cls, path: str) -> str:
+ # Bucket the flag on the team/project id already present in the path so the
+ # redirect can roll out incrementally per team (0% off, 100% on, anything
+ # between = that fraction of teams, stable per team). Paths without a numeric
+ # id here (@current, keyless) can't name a team without resolving auth — this
+ # middleware runs pre-auth — so they fall back to the constant id and ride the
+ # global switch. Purely string work: no DB query, no session read, no lookups.
+ remainder = path[len(cls.ENVIRONMENTS_PREFIX) :].strip("/")
+ team_id = remainder.split("/", 1)[0] if remainder else ""
+ if team_id.isdigit():
+ return f"{cls.FEATURE_FLAG_DISTINCT_ID}:team:{team_id}"
+ return cls.FEATURE_FLAG_DISTINCT_ID
+
+ @classmethod
+ def _redirect_enabled(cls, distinct_id: Optional[str] = None) -> bool:
+ # only_evaluate_locally keeps this off the network on every request; a per-team
+ # distinct id lets a percentage rollout bucket by team instead of flipping the
+ # whole instance at once (see _flag_distinct_id).
return bool(
posthoganalytics.feature_enabled(
cls.FEATURE_FLAG_KEY,
- cls.FEATURE_FLAG_DISTINCT_ID,
+ distinct_id or cls.FEATURE_FLAG_DISTINCT_ID,
only_evaluate_locally=True,
send_feature_flag_events=False,
)