: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
fix(messaging): stop re-querying postgres for known-invalid push tokens (#94118)
Daniel Marchuk94c82cfd7734
diff --git a/products/messaging/backend/api/push_subscriptions.py b/products/messaging/backend/api/push_subscriptions.pyindex 9099c84e00ac..7816774f1181 100644--- a/products/messaging/backend/api/push_subscriptions.py+++ b/products/messaging/backend/api/push_subscriptions.py@@ -1,6 +1,7 @@import hmacimport timeimport hashlib+import threadingfrom datetime import UTC, datetimefrom django.conf import settings@@ -10,6 +11,7 @@ from django.http import HttpResponse, JsonResponsefrom django.views.decorators.csrf import csrf_exemptimport structlog+from cachetools import TTLCachefrom prometheus_client import Counterfrom rest_framework import statusfrom rest_framework.request import Request@@ -69,6 +71,23 @@ _DISCARD_LOG_WINDOW_SECONDS = 60# 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++# A token that resolves to no team costs a Redis miss and then a Postgres query on every request,+# and the lookup has no negative cache of its own. A misconfigured mobile client repeats the same+# unknown token on every app open, so that query runs at the client's retry rate indefinitely.+#+# This cache is in-process and size-bounded, not in Redis. The token is request-controlled and this+# endpoint is public, so a Redis key per submitted value would let anyone grow the shared cache and+# evict unrelated entries. A TTLCache holds at most _INVALID_TOKEN_CACHE_SIZE entries per worker and+# evicts its own oldest, so the memory cost is fixed no matter what callers send.+#+# The TTL is short on purpose. A token can become valid, for example when a project is recreated,+# and this bounds how long such a token keeps being rejected after that.+_INVALID_TOKEN_CACHE_SECONDS = 60+_INVALID_TOKEN_CACHE_SIZE = 2048+_invalid_token_cache: TTLCache = TTLCache(maxsize=_INVALID_TOKEN_CACHE_SIZE, ttl=_INVALID_TOKEN_CACHE_SECONDS)+# cachetools is not thread-safe and Granian serves requests on threads within a worker.+_invalid_token_lock = threading.Lock()_PUSH_INTEGRATION_KINDS = ("firebase", "apns")VALID_PLATFORMS = ("android", "ios")@@ -91,6 +110,18 @@ _encrypted_fields = EncryptedFieldMixin()_VERIFICATION_MODE_PRECEDENCE = {"disabled": 0, "optional": 1, "required": 2}+def _is_known_invalid_token(api_key: str) -> bool:+ """True when this worker resolved this token to no team recently. Stores a fingerprint rather+ than the token itself, so the raw value is never held."""+ with _invalid_token_lock:+ return _api_key_fingerprint(api_key) in _invalid_token_cache+++def _remember_invalid_token(api_key: str) -> None:+ with _invalid_token_lock:+ _invalid_token_cache[_api_key_fingerprint(api_key)] = True++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 the16 KiB body, and the project token that reaches this endpoint ships inside every copy of the app,@@ -286,8 +317,19 @@ def push_subscriptions(request: Request):status_code=status.HTTP_401_UNAUTHORIZED,)+ if _is_known_invalid_token(api_key):+ return _rejection_response(+ request,+ "Invalid project token.",+ error_type="authentication_error",+ code="invalid_api_key",+ status_code=status.HTTP_401_UNAUTHORIZED,+ api_key_fingerprint=_api_key_fingerprint(api_key),+ )+team = Team.objects.get_team_from_cache_or_token(api_key)if not team:+ _remember_invalid_token(api_key)# Fingerprint the rejected token so a cohort of these can be traced to one bad app# configuration, which is the usual cause of a burst of invalid-token rejections.return _rejection_response(diff --git a/products/messaging/backend/api/test/test_push_subscriptions.py b/products/messaging/backend/api/test/test_push_subscriptions.pyindex 562d2fa460cd..b3342704ccb4 100644--- a/products/messaging/backend/api/test/test_push_subscriptions.py+++ b/products/messaging/backend/api/test/test_push_subscriptions.py@@ -18,6 +18,7 @@ from posthog.models.integration import Integrationfrom posthog.models.team.team import Teamfrom posthog.models.team.team_caching import set_team_in_cache+from products.messaging.backend.api import push_subscriptionsfrom products.messaging.backend.api.push_identity_tokens import sign_push_identity_token, sign_push_identity_token_es256from products.messaging.backend.api.push_subscriptions import (PUSH_SUBSCRIPTION_DISCARD_COUNTER,@@ -69,6 +70,7 @@ class TestPushSubscriptionsAPI(BaseTest):# 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()+ push_subscriptions._invalid_token_cache.clear()def _post(self, data: dict, api_key: str | None = None):payload = {**data, "api_key": api_key or self.team.api_token}@@ -262,6 +264,19 @@ class TestPushSubscriptionsAPI(BaseTest):assert response.status_code == status.HTTP_401_UNAUTHORIZED+ def test_repeated_invalid_token_is_rejected_without_a_second_team_lookup(self):+ payload = {"distinct_id": "user-1", "device_token": "t", "platform": "android", "app_id": "proj"}++ with patch.object(+ Team.objects, "get_team_from_cache_or_token", wraps=Team.objects.get_team_from_cache_or_token+ ) as lookup:+ first = self._post(payload, api_key="phc_invalid_token")+ second = self._post(payload, api_key="phc_invalid_token")++ assert first.status_code == status.HTTP_401_UNAUTHORIZED+ assert second.status_code == status.HTTP_401_UNAUTHORIZED+ assert lookup.call_count == 1+def test_missing_required_fields(self):response = self._post({"distinct_id": "user-1"})