: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
perf(messaging): bound the work and the logging on discarded push registrations (#82727)
Daniel Marchuke82869227a81
diff --git a/products/messaging/backend/api/push_subscriptions.py b/products/messaging/backend/api/push_subscriptions.pyindex cccc4c981cdb..b7d948dc3dca 100644--- a/products/messaging/backend/api/push_subscriptions.py+++ b/products/messaging/backend/api/push_subscriptions.py@@ -1,5 +1,7 @@+import timefrom datetime import UTC, datetime+from django.core.cache import cachefrom django.db.models import Qfrom django.http import HttpResponse, JsonResponsefrom django.views.decorators.csrf import csrf_exempt@@ -48,6 +50,23 @@ PUSH_SUBSCRIPTION_DISCARD_COUNTER = Counter(logger = structlog.get_logger(__name__)+# Discarding a registration is this endpoint's normal case: a device registers on app open whether or+# not its project has a push integration, and most don't. The counter above carries that volume. The+# log line exists to name the project behind it, and that is the same team and app_id every time, so+# emitting it per request restates one fact indefinitely. One line per team per window keeps the+# identification and drops the repetition.+_DISCARD_LOG_WINDOW_SECONDS = 60++# That same path runs _find_integrations, a JSONB filter, on every request. Cache the team's+# configured app_ids so a registration for an app_id the team has never configured — the common case+# — answers from cache instead. Keyed on the team alone: the value is a small bounded list, whereas+# keying on the request's app_id would let one public project token mint unbounded entries.+#+# Staleness costs at most one window: a team that configures push keeps discarding for up to a minute,+# and the device re-posts on its next launch anyway.+_CONFIGURED_APP_IDS_CACHE_SECONDS = 60+_PUSH_INTEGRATION_KINDS = ("firebase", "apns")+VALID_PLATFORMS = ("android", "ios")# A device registration payload is a handful of short string fields (distinct_id, device_token,@@ -68,6 +87,43 @@ _encrypted_fields = EncryptedFieldMixin()_VERIFICATION_MODE_PRECEDENCE = {"disabled": 0, "optional": 1, "required": 2}+def _is_first_discard_in_window(team_id: int) -> bool:+ """Keyed on the team and the window only. app_id is request-controlled and can fill most of the+ 16 KiB body, and the project token that reaches this endpoint ships inside every copy of the app,+ so keying on it would let anyone mint unbounded cache entries. Keyed on the window so a missed+ expiry can never wedge the log shut, and fails open: losing the cache must not lose the only line+ that names the project."""+ window = int(time.time()) // _DISCARD_LOG_WINDOW_SECONDS+ try:+ return cache.add(f"push_subscriptions:discarded:{team_id}:{window}", 1, _DISCARD_LOG_WINDOW_SECONDS)+ except Exception:+ return True+++def _configurable_app_ids(team_id: int) -> list[str] | None:+ """The app_ids this team has a push integration for, or None when the cache is unavailable.+ None means "don't know", so the caller falls through to the real lookup rather than discarding a+ registration a team is entitled to."""+ key = f"push_subscriptions:app_ids:{team_id}"+ try:+ cached = cache.get(key)+ if cached is not None:+ return cached+ app_ids = [+ app_id+ for integration in Integration.objects.filter(team_id=team_id, kind__in=_PUSH_INTEGRATION_KINDS).only(+ "kind", "config"+ )+ if isinstance(+ app_id := integration.config.get("project_id" if integration.kind == "firebase" else "bundle_id"), str+ )+ ]+ cache.set(key, app_ids, _CONFIGURED_APP_IDS_CACHE_SECONDS)+ return app_ids+ except Exception:+ return None++# Resolve integrations from the app_id alone, not the device platform. An app_id is either a# Firebase project_id or an APNs bundle_id, so a device can register with either provider regardless# of its OS — e.g. an iOS device delivering through Firebase registers with the Firebase project_id.@@ -249,7 +305,12 @@ def push_subscriptions(request: Request):app_id=app_id,)- integrations = _find_integrations(team.id, app_id)+ # Skip the JSONB lookup when the team has no integration for this app_id, which is the endpoint's+ # normal case. A cache miss or outage returns None and falls through to the real query.+ known_app_ids = _configurable_app_ids(team.id)+ integrations = (+ [] if known_app_ids is not None and app_id not in known_app_ids else _find_integrations(team.id, app_id)+ )# A missing integration is an account state, not a request error: SDKs auto-register on every# app open, so for most teams this is the endpoint's normal case, and a 4xx here turns the# whole fleet into an error firehose. Acknowledge registration with a 200 and skip the store,@@ -258,7 +319,8 @@ def push_subscriptions(request: Request):# DELETE falls through: logout must clear any subscription stored while an integration existed.if not integrations and request.method == "POST":PUSH_SUBSCRIPTION_DISCARD_COUNTER.labels(reason="no_integration").inc()- logger.info("push_subscription_discarded", reason="no_integration", team_id=team.id, app_id=app_id)+ if _is_first_discard_in_window(team.id):+ logger.info("push_subscription_discarded", reason="no_integration", team_id=team.id, app_id=app_id)return cors_response(request,JsonResponse(diff --git a/products/messaging/backend/api/test/test_push_subscriptions.py b/products/messaging/backend/api/test/test_push_subscriptions.pyindex bf82c5380ec9..6f99a74a0842 100644--- a/products/messaging/backend/api/test/test_push_subscriptions.py+++ b/products/messaging/backend/api/test/test_push_subscriptions.py@@ -4,6 +4,7 @@ import jsonfrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch+from django.core.cache import cachefrom django.test import Clientfrom cryptography.hazmat.primitives import serialization@@ -60,6 +61,10 @@ class TestPushSubscriptionsAPI(BaseTest):config={"bundle_id": "com.example.app", "team_id": "TEAM123", "key_id": "KEY123"},sensitive_config={},)+ # The discard-log window counter lives in the cache, which no transaction rolls back and which+ # every test in the process shares. Tests here reuse one team id, so without this a test that+ # logged a discard would suppress the line another test asserts on.+ cache.clear()def _post(self, data: dict, api_key: str | None = None):payload = {**data, "api_key": api_key or self.team.api_token}@@ -295,6 +300,76 @@ class TestPushSubscriptionsAPI(BaseTest):mock_capture.assert_not_called()assert counter._value.get() == before + 1+ @patch("products.messaging.backend.api.push_subscriptions.capture_internal")+ def test_discard_is_logged_once_per_window_and_counted_every_time(self, mock_capture: MagicMock):+ # The log names the project behind the discards, so it has to survive. It also has to stay+ # bounded: discarding is this endpoint's most common request, so a line per discard restates+ # one fact indefinitely. The counter carries the volume.+ counter = PUSH_SUBSCRIPTION_DISCARD_COUNTER.labels(reason="no_integration")+ before = counter._value.get()+ payload = {+ "distinct_id": "user-1",+ "device_token": "device-token",+ "platform": "android",+ "app_id": "nonexistent-project",+ }++ with capture_logs() as logs:+ for _ in range(5):+ assert self._post(payload).status_code == status.HTTP_200_OK+ # A different app_id from the same team stays inside the same window. app_id is+ # request-controlled, so keying the window on it would let one public project token mint+ # unbounded cache entries.+ for _ in range(2):+ assert self._post({**payload, "app_id": "another-project"}).status_code == status.HTTP_200_OK++ discard_logs = [log for log in logs if log["event"] == "push_subscription_discarded"]+ assert len(discard_logs) == 1+ assert discard_logs[0]["team_id"] == self.team.id+ assert discard_logs[0]["app_id"] == "nonexistent-project"+ assert counter._value.get() == before + 7++ @patch("products.messaging.backend.api.push_subscriptions.capture_internal")+ def test_configured_app_registers_on_the_cached_path(self, mock_capture: MagicMock):+ # The first request fills the team's app_id cache and the second reads it. A short-circuit+ # that got those ids wrong would discard registrations the team is entitled to, and the device+ # would never retry, because a 200 marks the token delivered.+ mock_capture.return_value = MagicMock(status_code=200)+ payload = {+ "distinct_id": "user-1",+ "device_token": "fcm-device-token-abc",+ "platform": "android",+ "app_id": "my-firebase-project",+ }++ for _ in range(2):+ assert self._post(payload).status_code == status.HTTP_200_OK++ assert mock_capture.call_count == 2++ @patch("products.messaging.backend.api.push_subscriptions.cache")+ @patch("products.messaging.backend.api.push_subscriptions.capture_internal")+ def test_configured_app_registers_when_the_cache_is_unavailable(+ self, mock_capture: MagicMock, mock_cache: MagicMock+ ):+ # Failing closed here would turn a cache outage into silent fleet-wide discards, which the+ # devices would then record as delivered.+ mock_capture.return_value = MagicMock(status_code=200)+ mock_cache.get.side_effect = Exception("cache down")+ mock_cache.add.side_effect = Exception("cache down")++ response = self._post(+ {+ "distinct_id": "user-1",+ "device_token": "fcm-device-token-abc",+ "platform": "android",+ "app_id": "my-firebase-project",+ }+ )++ assert response.status_code == status.HTTP_200_OK+ mock_capture.assert_called_once()+@patch("products.messaging.backend.api.push_subscriptions.capture_internal")def test_team_isolation(self, mock_capture: MagicMock):other_team = Team.objects.create(organization=self.organization, name="Other Team")