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(exports): bound blocking API exports and rate limit creation (#111689)

Julian Bez4f02ee1a864b
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index f5f208adca27..f69d29ff5630 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -4000,6 +4000,7 @@ export interface ExportedAssetApi {
* * `application/x-ndjson` - application/x-ndjson */
readonly export_format: ExportedAssetExportFormatEnumApi
readonly created_at: string
+ /** Whether the export finished and its content is ready to download. Create can return before the export finishes; poll the asset until has_content is true or exception is set. */
readonly has_content: boolean
export_context?: unknown
readonly filename: string
@@ -4069,6 +4070,7 @@ export interface ExportedAssetCreateApi {
* * `application/json` - application/json */
export_format: ExportedAssetCreateExportFormatEnumApi
readonly created_at: string
+ /** Whether the export finished and its content is ready to download. Create can return before the export finishes; poll the asset until has_content is true or exception is set. */
readonly has_content: boolean
export_context?: unknown
readonly filename: string
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index a55f471baff1..68058d951dd9 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -787,6 +787,21 @@ class ReplayVisionSearchSustainedRateThrottle(_TeamBucketRateThrottle):
rate = "300/hour"
+# Creating an export renders it, and an API-created export holds a web worker while the render
+# runs. The default Burst/Sustained throttles bucket per personal API key and skip session traffic,
+# so a script with several keys, or a burst from the UI, is not capped per project. A person
+# exports one asset per click, so these rates leave room for normal use and scripts while capping
+# a bulk script that starts hundreds of exports at once.
+class ExportCreateBurstRateThrottle(_TeamBucketRateThrottle):
+ scope = "export_create_burst"
+ rate = "60/minute"
+
+
+class ExportCreateSustainedRateThrottle(_TeamBucketRateThrottle):
+ scope = "export_create_sustained"
+ rate = "600/hour"
+
+
class _AIThrottleBase(UserRateThrottle):
action_name: str
diff --git a/products/exports/backend/api/exports.py b/products/exports/backend/api/exports.py
index 2054670af6c5..37c9cea99d6a 100644
--- a/products/exports/backend/api/exports.py
+++ b/products/exports/backend/api/exports.py
@@ -1,3 +1,6 @@
+import asyncio
+from collections.abc import Iterator
+from contextlib import contextmanager
from datetime import timedelta
from typing import Any, Literal
@@ -14,15 +17,18 @@ from drf_spectacular.utils import extend_schema
from rest_framework import mixins, serializers, viewsets
from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
from rest_framework.request import Request
+from rest_framework.throttling import BaseThrottle
from temporalio.common import RetryPolicy, SearchAttributePair, TypedSearchAttributes, WorkflowIDReusePolicy
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
+from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded, ConcurrencySlot, RateLimit
from posthog.event_usage import EventSource, get_event_source, groups
from posthog.helpers.impersonation import is_impersonated
from posthog.models import Team, User
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
from posthog.models.organization import Organization
+from posthog.rate_limit import ExportCreateBurstRateThrottle, ExportCreateSustainedRateThrottle
from posthog.settings.temporal import TEMPORAL_WORKFLOW_MAX_ATTEMPTS
from posthog.slo.types import SloArea, SloConfig, SloOperation
from posthog.temporal.common.client import async_connect
@@ -66,6 +72,56 @@ def get_full_video_exports_limit_for_organization(organization: Organization | N
logger = structlog.get_logger(__name__)
+# An API caller waits on its export so that the response can carry the content. The wait stays
+# well under the web request timeout, and each team can hold only a few waiting requests, so a
+# burst of exports cannot occupy every web worker. An export past either bound keeps running and
+# the caller polls the asset for the result.
+BLOCKING_EXPORT_WAIT_TIMEOUT = timedelta(seconds=60)
+BLOCKING_EXPORTS_PER_TEAM = 5
+# The start RPC has no deadline by default, so a stalled Temporal call would hold the worker without the wait bound.
+EXPORT_WORKFLOW_START_TIMEOUT = timedelta(seconds=10)
+
+_blocking_exports_limiter = RateLimit(
+ max_concurrency=BLOCKING_EXPORTS_PER_TEAM,
+ limit_name="exports_blocking_per_team",
+ # Stable because use() exports it as a metric label. The team goes into the Redis key instead.
+ get_task_name=lambda *args, **kwargs: "exports:blocking:per-team",
+ get_task_key=lambda *args, **kwargs: f"exports:blocking:per-team:{kwargs['team_id']}",
+ get_task_id=lambda *args, **kwargs: kwargs["task_id"],
+ # The TTL frees a slot that a dead worker did not release, so it must outlast the wait.
+ ttl=int(BLOCKING_EXPORT_WAIT_TIMEOUT.total_seconds()) * 2,
+ # The limit protects web workers, not ClickHouse, so the ClickHouse kill switch and the
+ # per-team throttle bypass do not apply.
+ apply_clickhouse_kill_switch=False,
+ allow_team_bypass=False,
+)
+
+
+@contextmanager
+def _blocking_export_slot(team_id: int, asset_id: int) -> Iterator[bool]:
+ """Yield whether the request may wait on the export, and release the slot afterwards."""
+ slot: ConcurrencySlot | None = None
+ may_wait = True
+ try:
+ slot = _blocking_exports_limiter.use(team_id=team_id, task_id=str(asset_id))
+ except ConcurrencyLimitExceeded:
+ may_wait = False
+ logger.info("export_blocking_wait_limit_reached", team_id=team_id, asset_id=asset_id)
+ except Exception as e:
+ # Without the limiter nothing caps the waits, so the request falls back to the async path.
+ may_wait = False
+ logger.warning("export_blocking_slot_unavailable", team_id=team_id, asset_id=asset_id, error=str(e))
+
+ try:
+ yield may_wait
+ finally:
+ if slot is not None:
+ try:
+ _blocking_exports_limiter.release(slot)
+ except Exception as e:
+ # The TTL frees the slot when this release fails.
+ logger.warning("export_blocking_slot_release_failed", team_id=team_id, asset_id=asset_id, error=str(e))
+
class ExportedAssetSerializer(UserAccessControlSerializerMixin, serializers.ModelSerializer):
"""Standard ExportedAsset serializer that doesn't return content."""
@@ -75,7 +131,11 @@ class ExportedAssetSerializer(UserAccessControlSerializerMixin, serializers.Mode
read_only=True,
help_text="File format of the generated export.",
)
- has_content = serializers.BooleanField(read_only=True)
+ has_content = serializers.BooleanField(
+ read_only=True,
+ help_text="Whether the export finished and its content is ready to download. Create can return before the "
+ "export finishes; poll the asset until has_content is true or exception is set.",
+ )
filename = serializers.CharField(read_only=True)
class Meta:
@@ -417,6 +477,46 @@ class ExportedAssetSerializer(UserAccessControlSerializerMixin, serializers.Mode
return str(context["filename"])
return "an export"
+ def _run_export_workflow(
+ self, instance: ExportedAsset, workflow_inputs: ExportAssetWorkflowInputs, wait: bool
+ ) -> None:
+ async def _run() -> None:
+ client = await async_connect()
+ handle = await client.start_workflow(
+ ExportAssetWorkflow.run,
+ workflow_inputs,
+ id=f"export-asset-{instance.id}",
+ task_queue=settings.ANALYTICS_PLATFORM_TASK_QUEUE,
+ id_reuse_policy=WorkflowIDReusePolicy.TERMINATE_IF_RUNNING,
+ execution_timeout=timedelta(minutes=35),
+ rpc_timeout=EXPORT_WORKFLOW_START_TIMEOUT,
+ )
+ if wait:
+ # A timeout cancels only this wait. The workflow keeps running and stores the content on the asset.
+ await asyncio.wait_for(handle.result(), timeout=BLOCKING_EXPORT_WAIT_TIMEOUT.total_seconds())
+
+ try:
+ async_to_sync(_run)()
+ except TimeoutError:
+ logger.info("export_workflow_wait_timed_out", asset_id=instance.id)
+ return
+ except Exception as e:
+ # Swallow workflow failures so the API always returns a 201 with the
+ # ExportedAsset record. export_asset_direct populates the exception
+ # field before re-raising, so callers (frontend toast, sharing
+ # endpoint) can inspect the failure on the asset itself.
+ logger.info(
+ "export_workflow_failed_gracefully",
+ asset_id=instance.id,
+ error=str(e),
+ )
+ return
+
+ logger.info(
+ "export_workflow_completed" if wait else "export_workflow_dispatched",
+ asset_id=instance.id,
+ )
+
def _start_export_workflow(
self, instance: ExportedAsset, team: Team, user: User | None, force_async: bool = False
) -> None:
@@ -447,36 +547,12 @@ class ExportedAssetSerializer(UserAccessControlSerializerMixin, serializers.Mode
),
)
- async def _run():
- client = await async_connect()
- method = client.start_workflow if force_async else client.execute_workflow
- await method(
- ExportAssetWorkflow.run,
- workflow_inputs,
- id=f"export-asset-{instance.id}",
- task_queue=settings.ANALYTICS_PLATFORM_TASK_QUEUE,
- id_reuse_policy=WorkflowIDReusePolicy.TERMINATE_IF_RUNNING,
- execution_timeout=timedelta(minutes=35),
- )
-
- try:
- async_to_sync(_run)()
- except Exception as e:
- # Swallow workflow failures so the API always returns a 201 with the
- # ExportedAsset record. export_asset_direct populates the exception
- # field before re-raising, so callers (frontend toast, sharing
- # endpoint) can inspect the failure on the asset itself.
- logger.info(
- "export_workflow_failed_gracefully",
- asset_id=instance.id,
- error=str(e),
- )
+ if force_async:
+ self._run_export_workflow(instance, workflow_inputs, wait=False)
return
- logger.info(
- "export_workflow_dispatched" if force_async else "export_workflow_completed",
- asset_id=instance.id,
- )
+ with _blocking_export_slot(team_id=team.id, asset_id=instance.id) as may_wait:
+ self._run_export_workflow(instance, workflow_inputs, wait=may_wait)
class ExportedAssetCreateSerializer(ExportedAssetSerializer):
@@ -517,6 +593,11 @@ class ExportedAssetViewSet(
def get_serializer_class(self) -> type[serializers.BaseSerializer]:
return ExportedAssetCreateSerializer if self.action == "create" else ExportedAssetSerializer
+ def get_throttles(self) -> list[BaseThrottle]:
+ if self.action == "create":
+ return [ExportCreateBurstRateThrottle(), ExportCreateSustainedRateThrottle(), *super().get_throttles()]
+ return super().get_throttles()
+
def safely_get_queryset(self, queryset):
"""List shows only exports created by the current user."""
if self.action == "list":
diff --git a/products/exports/backend/api/test/test_exports.py b/products/exports/backend/api/test/test_exports.py
index 73ada334876d..25edd49946fa 100644
--- a/products/exports/backend/api/test/test_exports.py
+++ b/products/exports/backend/api/test/test_exports.py
@@ -1,3 +1,4 @@
+import asyncio
import ipaddress
from contextlib import nullcontext
from datetime import datetime, timedelta
@@ -11,6 +12,7 @@ from unittest.mock import ANY, AsyncMock, patch
from django.http import HttpResponse
from django.utils.timezone import now
+import redis.exceptions
import requests.exceptions
from boto3 import resource
from botocore.client import Config
@@ -27,6 +29,7 @@ from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team import Team
from posthog.models.user import User
from posthog.models.utils import generate_random_token_personal, hash_key_value
+from posthog.rate_limit import ExportCreateBurstRateThrottle
from posthog.settings import (
HOGQL_INCREASED_MAX_EXECUTION_TIME,
OBJECT_STORAGE_ACCESS_KEY_ID,
@@ -41,6 +44,7 @@ from posthog.test.insight_queries import browser_filtered_pageview_query
from products.access_control.backend.models.access_control import AccessControl
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.exports.backend.api.exports import BLOCKING_EXPORTS_PER_TEAM, _blocking_exports_limiter
from products.exports.backend.facade.api import EXPORT_WORKFLOW_TIMEOUT
from products.exports.backend.models.exported_asset import DATASET_EXPORT_KIND, ExportedAsset
from products.exports.backend.source_authentication import required_scopes_for_export_target
@@ -1877,11 +1881,17 @@ class TestExports(APIBaseTest):
self.assertEqual(asset.exception_type, "QueryError")
self.assertEqual(asset.failure_type, "user")
- @patch("products.exports.backend.api.exports.async_connect")
- def test_workflow_failure_returns_201_with_failed_asset(self, mock_async_connect) -> None:
+ def _mock_export_workflow_handle(self, mock_async_connect) -> AsyncMock:
+ mock_handle = AsyncMock()
mock_client = AsyncMock()
- mock_client.execute_workflow.side_effect = Exception("workflow failed")
+ mock_client.start_workflow.return_value = mock_handle
mock_async_connect.return_value = mock_client
+ return mock_handle
+
+ @patch("products.exports.backend.api.exports.async_connect")
+ def test_workflow_failure_returns_201_with_failed_asset(self, mock_async_connect) -> None:
+ mock_handle = self._mock_export_workflow_handle(mock_async_connect)
+ mock_handle.result.side_effect = Exception("workflow failed")
response = self.client.post(
f"/api/projects/{self.team.id}/exports",
@@ -1891,6 +1901,78 @@ class TestExports(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertFalse(response.json()["has_content"])
+ @patch("products.exports.backend.api.exports.BLOCKING_EXPORT_WAIT_TIMEOUT", timedelta(milliseconds=10))
+ @patch("products.exports.backend.api.exports.async_connect")
+ def test_export_wait_timeout_returns_201_and_leaves_workflow_running(self, mock_async_connect) -> None:
+ async def never_finishes() -> None:
+ await asyncio.Event().wait()
+
+ mock_handle = self._mock_export_workflow_handle(mock_async_connect)
+ mock_handle.result.side_effect = never_finishes
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/exports",
+ {"export_format": "text/csv", "insight": self.insight.id},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertFalse(response.json()["has_content"])
+ mock_handle.result.assert_awaited_once()
+ mock_handle.cancel.assert_not_awaited()
+ mock_handle.terminate.assert_not_awaited()
+ slots_key = f"exports:blocking:per-team:{self.team.id}"
+ self.assertEqual(_blocking_exports_limiter.redis_client.zcard(slots_key), 0)
+
+ @patch("products.exports.backend.api.exports.async_connect")
+ def test_export_over_team_wait_limit_starts_without_waiting(self, mock_async_connect) -> None:
+ for i in range(BLOCKING_EXPORTS_PER_TEAM):
+ slot = _blocking_exports_limiter.use(team_id=self.team.id, task_id=f"held-{i}")
+ assert slot is not None
+ self.addCleanup(_blocking_exports_limiter.release, slot)
+ mock_handle = self._mock_export_workflow_handle(mock_async_connect)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/exports",
+ {"export_format": "text/csv", "insight": self.insight.id},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ mock_async_connect.return_value.start_workflow.assert_awaited_once()
+ mock_handle.result.assert_not_awaited()
+
+ @patch.object(_blocking_exports_limiter, "use", side_effect=redis.exceptions.ConnectionError("unavailable"))
+ @patch("products.exports.backend.api.exports.async_connect")
+ def test_export_starts_without_waiting_when_wait_limiter_fails(self, mock_async_connect, _mock_use) -> None:
+ mock_handle = self._mock_export_workflow_handle(mock_async_connect)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/exports",
+ {"export_format": "text/csv", "insight": self.insight.id},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ mock_async_connect.return_value.start_workflow.assert_awaited_once()
+ mock_handle.result.assert_not_awaited()
+
+ @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)
+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")
+ def test_export_create_is_throttled_per_team_and_list_is_not(self, _mock_start, _enabled) -> None:
+ with patch.object(ExportCreateBurstRateThrottle, "rate", "2/minute"):
+ responses = [
+ self.client.post(
+ f"/api/projects/{self.team.id}/exports",
+ {"export_format": "text/csv", "insight": self.insight.id},
+ )
+ for _ in range(3)
+ ]
+ list_response = self.client.get(f"/api/projects/{self.team.id}/exports")
+
+ self.assertEqual(
+ [response.status_code for response in responses],
+ [status.HTTP_201_CREATED, status.HTTP_201_CREATED, status.HTTP_429_TOO_MANY_REQUESTS],
+ )
+ self.assertEqual(list_response.status_code, status.HTTP_200_OK)
+
class TestExportHeatmapSSRFValidation(APIBaseTest):
@parameterized.expand(
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6a7d5cb451f6..d198e9276eb6 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -44783,6 +44783,7 @@ export namespace Schemas {
* * `application/x-ndjson` - application/x-ndjson */
readonly export_format: ExportedAssetExportFormatEnum;
readonly created_at: string;
+ /** Whether the export finished and its content is ready to download. Create can return before the export finishes; poll the asset until has_content is true or exception is set. */
readonly has_content: boolean;
export_context?: unknown;
readonly filename: string;
@@ -44842,6 +44843,7 @@ export namespace Schemas {
* * `application/json` - application/json */
export_format: ExportedAssetCreateExportFormatEnum;
readonly created_at: string;
+ /** Whether the export finished and its content is ready to download. Create can return before the export finishes; poll the asset until has_content is true or exception is set. */
readonly has_content: boolean;
export_context?: unknown;
readonly filename: string;