: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
chore(user_interviews): throttle the Vapi webhook through the ingress lane (#102895)
Julian Bez0b6737924e8d
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.mdindex f117e9d011ff..8e33ccf7cfc8 100644--- a/posthog/ingress/README.md+++ b/posthog/ingress/README.md@@ -82,8 +82,7 @@ The customer-facing GitHub App is shared across products, so its two endpoints aEvery other endpoint is declared by the product that registered the App, in its own `routes.py`.The SES endpoint is the exception for now, because its view still lives in `backend/api/` rather than behind the ingress builders.-The Vapi endpoint sits behind a per-IP throttle the product owns, from before ingress had a throttle lane.-It moves onto `throttle_class` next.+The Vapi endpoint is the only one that caps request volume: its provider sets `throttle_class` to a per-IP throttle, because the endpoint is public and Vapi's egress is shared across tenants.## Non-goalsdiff --git a/posthog/ingress/vapi/README.md b/posthog/ingress/vapi/README.mdindex d9bc6e209511..4a0fa174a272 100644--- a/posthog/ingress/vapi/README.md+++ b/posthog/ingress/vapi/README.md@@ -35,6 +35,11 @@ The public interview surface already relies on both codes.A delivery a consumer did not accept answers 500 rather than the 202 receipt, because Vapi sends the delivery again after a 5xx.The report is the only copy of an interview, so losing it to a receipt costs the transcript.+The provider sets `throttle_class` to `VapiWebhookIPThrottle`, a per-IP cap of 1200/minute from `posthog/rate_limit.py`.+The endpoint is public and unauthenticated, so the cap bounds how much HMAC-verification CPU and structured-log volume one source can drive.+Vapi's egress is shared across all tenants, so the bucket sits well above legitimate aggregate volume: a busy interview hour must not bleed onto a normal one.+The refusal is the shared lane's 429 with a `Retry-After`.+## ConsumersOne consumer, `user_interviews_vapi`, declared in `products/user_interviews/backend/webhook_consumers.py`.@@ -44,6 +49,3 @@ The enqueue is the only work on the request path, so a failure there is what theThe task persists the end-of-call report and retries a transient database error, so a lost connection does not lose the transcript.It acknowledges late, so a worker that dies mid-task gives the report back to the broker.The handler is idempotent on the call id, which is what makes both the retry and the redelivery safe.--The product keeps a per-IP throttle in front of the endpoint, because the endpoint is public and Vapi calls it a small number of times per interview.-See the [Endpoints table](../README.md#endpoints).diff --git a/posthog/ingress/vapi/provider.py b/posthog/ingress/vapi/provider.pyindex 39d1168bf80e..4666bf17aa99 100644--- a/posthog/ingress/vapi/provider.py+++ b/posthog/ingress/vapi/provider.py@@ -15,6 +15,7 @@ from django.utils import timezonefrom posthog.ingress.contracts import ProviderSpec, WebhookDeliveryfrom posthog.ingress.providers import WebhookProviderfrom posthog.ingress.verify.schemes import HmacSha256, SignatureScheme+from posthog.rate_limit import VapiWebhookIPThrottleVAPI_EVENT_TYPES = frozenset({"status-update", "end-of-call-report"})@@ -38,6 +39,9 @@ class VapiProvider(WebhookProvider):# replays an interview. The consumer hands the report to a queue and does no other work, so a# consumer failure means the report reached no queue at all, and a receipt would drop it.retry_status = 500+ # The endpoint is public and unauthenticated, so the per-IP cap bounds how much+ # HMAC-verification CPU and structured-log volume one source can drive.+ throttle_class = VapiWebhookIPThrottledef __init__(self) -> None:self._scheme = HmacSha256(diff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex 342d6db9418c..0de0bdd4280a 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -389,6 +389,20 @@ class LeakedKeyReportThrottle(IPThrottle):rate = "10/minute"+class VapiWebhookIPThrottle(IPThrottle):+ """Per-IP cap on the public Vapi webhook endpoint, run by the ingress throttle lane.++ Vapi calls us a small handful of times per interview (status-update + end-of-call-report),+ but its egress is shared across all of our tenants, so the bucket has to be generous enough+ that a noisy concurrent interview hour doesn't bleed onto a normal one. 1200/min is well+ above legitimate aggregate volume while still stopping a persistent attacker from driving+ HMAC-verification CPU or structured-log volume from a single IP.+ """++ scope = "user_interviews_vapi_webhook_ip"+ rate = "1200/minute"++class SignupEmailPrecheckThrottle(IPThrottle):"""Rate limit signup email precheck requests by IP.diff --git a/products/user_interviews/backend/presentation/webhooks.py b/products/user_interviews/backend/presentation/webhooks.pyindex 1986bbc31d41..c4c12248a269 100644--- a/products/user_interviews/backend/presentation/webhooks.py+++ b/products/user_interviews/backend/presentation/webhooks.py@@ -4,20 +4,17 @@ Two surfaces live here, both keyed on a SharingConfiguration access token:* ``start_call`` — called by the public interview page when the recipient clicksStart. Creates one Vapi web call server-side and returns only its join payload.-* ``vapi_webhook`` — the endpoint Vapi calls during and after a call. Verification and- fan-out are the ingress vapi incarnation's, and the consumer it dispatches to lives in- ``backend/webhook_consumers.py``.+* ``vapi_webhook`` — the endpoint Vapi calls during and after a call. The throttle,+ verification and fan-out are the ingress vapi incarnation's, and the consumer it+ dispatches to lives in ``backend/webhook_consumers.py``."""import json-import mathimport stringimport hashlibfrom typing import Anyfrom django.conf import settings-from django.http import HttpRequest, HttpResponse-from django.views.decorators.csrf import csrf_exemptimport requestsimport structlog@@ -84,19 +81,6 @@ class InterviewStartCallIPThrottle(_RateLimitMetricsMixin, IPThrottle):rate = "200/minute"-class VapiWebhookIPThrottle(_RateLimitMetricsMixin, IPThrottle):- """Per-IP cap on `vapi_webhook`. Vapi calls us a small handful of times per interview- (status-update + end-of-call-report), but its egress is shared across all of our tenants,- so the bucket has to be generous enough that a noisy concurrent interview hour doesn't- bleed onto a normal one. 1200/min is well above legitimate aggregate volume while still- stopping a persistent attacker from driving HMAC-verification CPU or structured-log- volume from a single IP. Rejection emits `rate_limit_exceeded_total` via the parent- mixin so we can alert if it ever trips."""-- scope = "user_interviews_vapi_webhook_ip"- rate = "1200/minute"--class InterviewStartCallTokenThrottle(_RateLimitMetricsMixin):"""Sustained per-share-token ceiling on `start_call`. One token maps to either a single invitedperson (personalised link) or many self-serve respondents (a shared topic link), so this is a@@ -416,21 +400,6 @@ def start_call(request: Request, access_token: str) -> Response:# Built once per process: the provider holds a secret getter, and reads the secret per request.-_vapi_ingress_view = build_webhook_view(build_vapi_provider())---@csrf_exempt-def vapi_webhook(request: HttpRequest) -> HttpResponse:- """The ingress Vapi endpoint, behind the per-IP cap this endpoint has always carried.-- ingress has no throttle lane, and the endpoint is public and unauthenticated, so the cap- stays in front of the view rather than being dropped on the way in.- """- throttle = VapiWebhookIPThrottle()- if not throttle.allow_request(Request(request), None):- throttled = HttpResponse(status=status.HTTP_429_TOO_MANY_REQUESTS)- wait = throttle.wait()- if wait:- throttled["Retry-After"] = str(math.ceil(wait))- return throttled- return _vapi_ingress_view(request)+# The per-IP cap rides on the provider's `throttle_class`, so the throttle, the 429 and its+# `Retry-After` are the ingress lane's, the same as every other provider that caps.+vapi_webhook = build_webhook_view(build_vapi_provider())diff --git a/products/user_interviews/backend/test_interview_sharing.py b/products/user_interviews/backend/test_interview_sharing.pyindex ca9940c86f97..4a1340fa1df3 100644--- a/products/user_interviews/backend/test_interview_sharing.py+++ b/products/user_interviews/backend/test_interview_sharing.py@@ -12,6 +12,7 @@ import time_machinefrom posthog.test.base import APIBaseTestfrom unittest.mock import Mock, patch+from django.core.cache import cachefrom django.db import InterfaceError, OperationalError, connectionfrom django.db.models import QuerySetfrom django.template.loader import get_template@@ -27,6 +28,7 @@ from rest_framework.exceptions import PermissionDeniedfrom posthog.api.sharing import check_can_access_sharing_configurationfrom posthog.api.test.test_sharing import mock_exporter_templatefrom posthog.models.sharing_configuration import SharingConfiguration+from posthog.rate_limit import VapiWebhookIPThrottlefrom products.user_interviews.backend.models import IntervieweeContext, UserInterview, UserInterviewTopicfrom products.user_interviews.backend.presentation.webhooks import (@@ -861,6 +863,31 @@ class TestVapiWebhook(APIBaseTest):self.assertEqual(resent.status_code, status.HTTP_202_ACCEPTED, resent.content)self.assertEqual(UserInterview.objects.count(), 1)+ @parameterized.expand(+ [+ ("under_the_rate", 0, status.HTTP_202_ACCEPTED),+ ("over_the_rate", 1, status.HTTP_429_TOO_MANY_REQUESTS),+ ]+ )+ @override_settings(VAPI_WEBHOOK_SECRET="topsecret")+ @patch.object(VapiWebhookIPThrottle, "rate", "1/minute")+ def test_webhook_caps_deliveries_from_one_ip(self, _name: str, already_spent: int, expected_status: int):+ # The cap is the provider's `throttle_class`, so this also pins that the ingress lane+ # actually runs it: a provider that dropped the attribute would answer 202 to both.+ cache.clear()+ share = self._create_share()+ self.client.logout()+ for _ in range(already_spent):+ self._signed_post("topsecret", self._end_of_call_payload(share.access_token))++ response = self._signed_post("topsecret", self._end_of_call_payload(share.access_token))++ self.assertEqual(response.status_code, expected_status, response.content)+ if expected_status == status.HTTP_429_TOO_MANY_REQUESTS:+ self.assertGreater(int(response.headers["Retry-After"]), 0)+ else:+ self.assertNotIn("Retry-After", response.headers)+@override_settings(VAPI_WEBHOOK_SECRET="")def test_webhook_fails_closed_when_secret_unset(self):share = self._create_share()