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(conversations): keep idle widget polls from blocking sends (#91627)

Alex V9c77b3e55f7b
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index 5f2069c7da46..ec762f87eea5 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -1340,14 +1340,12 @@ class WidgetUserBurstThrottle(SimpleRateThrottle):
return self.cache_format % {"scope": self.scope, "ident": ident}
-class WidgetTeamThrottle(SimpleRateThrottle):
- """Rate limit per team token."""
-
- scope = "widget_team"
+class _WidgetTeamTokenThrottle(SimpleRateThrottle):
rate = "3600/hour"
- def get_cache_key(self, request, view):
- # Throttle by team token if available, otherwise by IP
+ def get_cache_key(self, request: "Request", view: "APIView") -> str:
+ if not self.scope:
+ raise NotImplementedError("Set scope on WidgetTeamPollThrottle or WidgetTeamWriteThrottle")
token = request.headers.get("X-Conversations-Token", "")
if token:
ident = hashlib.sha256(token.encode()).hexdigest()
@@ -1356,6 +1354,23 @@ class WidgetTeamThrottle(SimpleRateThrottle):
return self.cache_format % {"scope": self.scope, "ident": ident}
+class WidgetTeamPollThrottle(_WidgetTeamTokenThrottle):
+ """Do not assign this to POST views. A shared bucket lets background list
+ polling 429 ticket creates."""
+
+ scope = "widget_team_poll"
+
+
+class WidgetTeamWriteThrottle(_WidgetTeamTokenThrottle):
+ """Keep this off GET poll views so list and message polling cannot exhaust it."""
+
+ scope = "widget_team_write"
+
+
+WIDGET_POLL_THROTTLES = (WidgetUserBurstThrottle, WidgetTeamPollThrottle)
+WIDGET_WRITE_THROTTLES = (WidgetUserBurstThrottle, WidgetTeamWriteThrottle)
+
+
class SymbolSetUploadSustainedRateThrottle(PersonalApiKeyRateThrottle):
scope = "symbol_set_upload_sustained"
rate = "12000/hour"
diff --git a/posthog/test/test_rate_limit.py b/posthog/test/test_rate_limit.py
index 0c9080b05660..b55991303c49 100644
--- a/posthog/test/test_rate_limit.py
+++ b/posthog/test/test_rate_limit.py
@@ -974,3 +974,20 @@ class TestProjectSecretApiKeyTeamRateThrottle(APIBaseTest):
def test_cache_key_is_keyed_per_team(self):
self.assertIn("psak-team:7", _PSAKTeamThrottleForTest().get_cache_key(self._psak_request(team_id=7), Mock()))
+
+
+class TestWidgetTeamPollWriteThrottleSplit(SimpleTestCase):
+ def setUp(self) -> None:
+ cache.clear()
+
+ def tearDown(self) -> None:
+ cache.clear()
+
+ def test_exhausted_poll_bucket_does_not_block_write(self) -> None:
+ request = Mock(headers={"X-Conversations-Token": "widget-token"})
+ view = Mock()
+ with patch.object(rate_limit.WidgetTeamPollThrottle, "rate", "1/minute"):
+ poll = rate_limit.WidgetTeamPollThrottle()
+ self.assertTrue(poll.allow_request(request, view))
+ self.assertFalse(poll.allow_request(request, view))
+ self.assertTrue(rate_limit.WidgetTeamWriteThrottle().allow_request(request, view))
diff --git a/products/conversations/backend/api/restore.py b/products/conversations/backend/api/restore.py
index a836e89c0031..0bee42abbbc9 100644
--- a/products/conversations/backend/api/restore.py
+++ b/products/conversations/backend/api/restore.py
@@ -22,12 +22,7 @@ from rest_framework.views import APIView
from posthog.auth import WidgetAuthentication
from posthog.models import Team
-from posthog.rate_limit import (
- RestoreRedeemThrottle,
- RestoreRequestThrottle,
- WidgetTeamThrottle,
- WidgetUserBurstThrottle,
-)
+from posthog.rate_limit import WIDGET_WRITE_THROTTLES, RestoreRedeemThrottle, RestoreRequestThrottle
from posthog.tasks.email import send_conversation_restore_email
from products.conversations.backend.api.serializers import (
@@ -77,7 +72,7 @@ class WidgetRestoreRequestView(APIView):
authentication_classes = [WidgetAuthentication]
permission_classes = [AllowAny]
- throttle_classes = [RestoreRequestThrottle, WidgetUserBurstThrottle, WidgetTeamThrottle]
+ throttle_classes = [RestoreRequestThrottle, *WIDGET_WRITE_THROTTLES]
def post(self, request: Request) -> Response:
team: Team | None = request.auth # type: ignore[assignment] # ty: ignore[invalid-assignment]
@@ -143,7 +138,7 @@ class WidgetRestoreRedeemView(APIView):
authentication_classes = [WidgetAuthentication]
permission_classes = [AllowAny]
- throttle_classes = [RestoreRedeemThrottle, WidgetUserBurstThrottle, WidgetTeamThrottle]
+ throttle_classes = [RestoreRedeemThrottle, *WIDGET_WRITE_THROTTLES]
def post(self, request: Request) -> Response:
team: Team | None = request.auth # type: ignore[assignment] # ty: ignore[invalid-assignment]
diff --git a/products/conversations/backend/api/tests/test_widget.py b/products/conversations/backend/api/tests/test_widget.py
index 4f2697d13d1d..79af5e6cae19 100644
--- a/products/conversations/backend/api/tests/test_widget.py
+++ b/products/conversations/backend/api/tests/test_widget.py
@@ -3,6 +3,7 @@ import uuid
from posthog.test.base import BaseTest
from unittest.mock import patch
+from django.core.cache import cache
from django.test import SimpleTestCase
from parameterized import parameterized
@@ -10,6 +11,7 @@ from rest_framework import status
from rest_framework.test import APIClient
from posthog.models.comment import Comment
+from posthog.rate_limit import WidgetTeamPollThrottle
from products.conversations.backend.api.serializers import WidgetMessageSerializer
from products.conversations.backend.models import SigningSecret, Ticket
@@ -85,6 +87,28 @@ class TestWidgetAPI(BaseTest):
self.assertEqual(ticket.status, "new")
self.assertEqual(ticket.unread_team_count, 1)
+ def test_exhausted_poll_throttle_does_not_block_send(self):
+ cache.clear()
+ tickets_url = f"/api/conversations/v1/widget/tickets?widget_session_id={self.widget_session_id}"
+ try:
+ with patch.object(WidgetTeamPollThrottle, "rate", "1/minute"):
+ self.assertEqual(self.client.get(tickets_url, **self._get_headers()).status_code, status.HTTP_200_OK)
+ self.assertEqual(
+ self.client.get(tickets_url, **self._get_headers()).status_code, status.HTTP_429_TOO_MANY_REQUESTS
+ )
+ send = self.client.post(
+ "/api/conversations/v1/widget/message",
+ {
+ "message": "Hello, I need help!",
+ "widget_session_id": self.widget_session_id,
+ "distinct_id": self.distinct_id,
+ },
+ **self._get_headers(),
+ )
+ self.assertEqual(send.status_code, status.HTTP_200_OK)
+ finally:
+ cache.clear()
+
def test_create_ticket_channel_detail_widget_enabled(self):
self.team.conversations_settings = {**self.team.conversations_settings, "widget_enabled": True}
self.team.save()
diff --git a/products/conversations/backend/api/widget.py b/products/conversations/backend/api/widget.py
index 6721d1abc43a..01c61e8e1011 100644
--- a/products/conversations/backend/api/widget.py
+++ b/products/conversations/backend/api/widget.py
@@ -29,7 +29,7 @@ from posthog.event_usage import report_team_action
from posthog.exceptions_capture import capture_exception
from posthog.models import Team
from posthog.models.comment import Comment
-from posthog.rate_limit import WidgetTeamThrottle, WidgetUserBurstThrottle
+from posthog.rate_limit import WIDGET_POLL_THROTTLES, WIDGET_WRITE_THROTTLES
from products.conversations.backend.api.serializers import (
WIDGET_TICKETS_DEFAULT_LIMIT,
@@ -153,7 +153,7 @@ class WidgetMessageView(APIView):
authentication_classes = [WidgetAuthentication]
permission_classes = [AllowAny]
- throttle_classes = [WidgetUserBurstThrottle, WidgetTeamThrottle]
+ throttle_classes = WIDGET_WRITE_THROTTLES
def post(self, request: Request) -> Response:
"""Handle incoming message from widget."""
@@ -349,7 +349,7 @@ class WidgetMessagesView(APIView):
authentication_classes = [WidgetAuthentication]
permission_classes = [AllowAny]
- throttle_classes = [WidgetUserBurstThrottle, WidgetTeamThrottle]
+ throttle_classes = WIDGET_POLL_THROTTLES
def get(self, request: Request, ticket_id: str) -> Response:
"""Get messages for a ticket."""
@@ -479,7 +479,7 @@ class WidgetTicketsView(APIView):
authentication_classes = [WidgetAuthentication]
permission_classes = [AllowAny]
- throttle_classes = [WidgetUserBurstThrottle, WidgetTeamThrottle]
+ throttle_classes = WIDGET_POLL_THROTTLES
def get(self, request: Request) -> Response:
"""List tickets for a widget_session_id."""
@@ -573,7 +573,7 @@ class WidgetMarkReadView(APIView):
authentication_classes = [WidgetAuthentication]
permission_classes = [AllowAny]
- throttle_classes = [WidgetUserBurstThrottle, WidgetTeamThrottle]
+ throttle_classes = WIDGET_WRITE_THROTTLES
def post(self, request: Request, ticket_id: str) -> Response:
"""Mark ticket messages as read by customer."""