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: Limit concurrent on demand batch exports (#60207)

Tomás Farías Santanab5f7e9106086
diff --git a/posthog/batch_exports/api/file_download.py b/posthog/batch_exports/api/file_download.py
index 65b2a0d0e3c6..e53da14ffa17 100644
--- a/posthog/batch_exports/api/file_download.py
+++ b/posthog/batch_exports/api/file_download.py
@@ -5,7 +5,7 @@ import datetime as dt
import posixpath
from django.conf import settings
-from django.db import transaction
+from django.db import connection, transaction
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
@@ -15,7 +15,7 @@ from botocore.client import Config
from botocore.exceptions import ClientError
from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema
from rest_framework import mixins, response, serializers, status, viewsets
-from rest_framework.exceptions import NotFound, ValidationError
+from rest_framework.exceptions import APIException, NotFound, ValidationError
from posthog.api.log_entries import LogEntryMixin
from posthog.api.routing import TeamAndOrgViewSetMixin
@@ -28,6 +28,11 @@ from products.batch_exports.backend.service import cancel_running_batch_export_r
SESSION = boto3.Session()
FILE_DOWNLOAD_MAX_RANGE = dt.timedelta(weeks=1)
LOGGER = structlog.get_logger(__name__)
+_FILE_DOWNLOAD_BATCH_EXPORTS_LOCK_KEY = int.from_bytes(
+ # 4 ASCII bytes to fill 32-bit PostgreSQL lock key
+ b"FDBE",
+ byteorder="big",
+)
class FileDownloadDestinationFileConfigSerializer(serializers.Serializer):
@@ -178,6 +183,14 @@ class RetrieveOutputSerializer(serializers.Serializer):
)
+class TooManyConcurrentFileDownloads(APIException):
+ """Raised when a team creates too many file download batch exports."""
+
+ status_code = status.HTTP_429_TOO_MANY_REQUESTS
+ default_code = "too_many_concurrent_file_downloads"
+ default_detail = "Too many concurrent file download batch exports for this team."
+
+
@extend_schema(tags=["batch_exports"])
class FileDownloadBatchExportOnDemandViewSet(
TeamAndOrgViewSetMixin, LogEntryMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet
@@ -211,7 +224,31 @@ class FileDownloadBatchExportOnDemandViewSet(
"""Create and start a batch export on demand run to download a file."""
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
- instance = serializer.save()
+
+ with transaction.atomic():
+ # Concurrent requests after the first one to obtain a lock will wait here
+ # until transaction is done. This prevents creating batch exports over the
+ # limit. Note we use our own 32-bit lock key additional to team_id to avoid
+ # conflicts with other parts of the application which may have also
+ # obtained a lock based on team_id.
+ # NOTE: If team_id ever becomes a 64-bit int update this.
+ with connection.cursor() as cursor:
+ cursor.execute(
+ "SELECT pg_advisory_xact_lock(%s::integer, %s::integer)",
+ (_FILE_DOWNLOAD_BATCH_EXPORTS_LOCK_KEY, self.team_id),
+ )
+
+ current_count = BatchExportRun.objects.filter(
+ status__in=(BatchExportRun.Status.STARTING, BatchExportRun.Status.RUNNING),
+ batch_export_on_demand__destination__type=BatchExportDestination.Destination.FILE_DOWNLOAD,
+ batch_export_on_demand__team_id=self.team_id,
+ batch_export_on_demand__deleted=False,
+ ).count()
+
+ if current_count >= settings.BATCH_EXPORT_MAX_CONCURRENT_ON_DEMAND_PER_TEAM:
+ raise TooManyConcurrentFileDownloads()
+
+ instance = serializer.save()
try:
start_file_download_batch_export(
diff --git a/posthog/settings/batch_exports.py b/posthog/settings/batch_exports.py
index a6c06896b59c..ca58062e3b8e 100644
--- a/posthog/settings/batch_exports.py
+++ b/posthog/settings/batch_exports.py
@@ -98,6 +98,10 @@ BATCH_EXPORTS_PERSONS_LIMITED_EXPORT_TEAM_IDS: list[str] = get_list(
BATCH_EXPORT_MAX_CONCURRENT_BACKFILLS_PER_TEAM: int = get_from_env(
"BATCH_EXPORT_MAX_CONCURRENT_BACKFILLS_PER_TEAM", 100, type_cast=int
)
+BATCH_EXPORT_MAX_CONCURRENT_ON_DEMAND_PER_TEAM: int = get_from_env(
+ "BATCH_EXPORT_MAX_CONCURRENT_ON_DEMAND_PER_TEAM", 20, type_cast=int
+)
+
BATCH_EXPORTS_FILE_DOWNLOAD_ROLE_ARN: str = os.getenv("BATCH_EXPORTS_FILE_DOWNLOAD_ROLE_ARN", "role")
BATCH_EXPORTS_FILE_DOWNLOAD_BUCKET: str = os.getenv("BATCH_EXPORTS_FILE_DOWNLOAD_BUCKET", "bucket")
BATCH_EXPORTS_FILE_DOWNLOAD_REGION: str = os.getenv("BATCH_EXPORTS_FILE_DOWNLOAD_REGION", "us-east-1")
diff --git a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py
index af8748f36c9e..be035e0137db 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py
@@ -316,6 +316,49 @@ async def test_file_download_download(
)
+@override_settings(BATCH_EXPORT_MAX_CONCURRENT_ON_DEMAND_PER_TEAM=1)
[email protected]_db(transaction=True)
+async def test_file_download_create_rejects_when_concurrency_limit_reached(
+ async_client: AsyncClient,
+ team,
+ user,
+ data_interval_start,
+ data_interval_end,
+):
+ destination = await BatchExportDestination.objects.acreate(
+ type=BatchExportDestination.Destination.FILE_DOWNLOAD, config={}
+ )
+ with team_scope(team_id=team.pk, canonical=True):
+ batch_export = await BatchExportOnDemand.objects.acreate(team=team, destination=destination, model="events")
+ await BatchExportRun.objects.acreate(
+ batch_export_on_demand=batch_export,
+ data_interval_start=data_interval_start,
+ data_interval_end=data_interval_end,
+ status=BatchExportRun.Status.RUNNING,
+ )
+
+ await async_client.aforce_login(user)
+
+ with unittest.mock.patch("posthog.batch_exports.api.file_download.start_file_download_batch_export") as mock_start:
+ response = await async_client.post(
+ f"/api/projects/{team.pk}/file_download_batch_exports",
+ {
+ "file": {
+ "format": "Parquet",
+ "compression": "zstd",
+ },
+ "model": "events",
+ "data_interval_start": data_interval_start,
+ "data_interval_end": data_interval_end,
+ },
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS, response.json()
+ assert response.json()["code"] == "too_many_concurrent_file_downloads"
+ mock_start.assert_not_called()
+
+
@pytest.mark.usefixtures("override_file_download_settings")
@pytest.mark.django_db(transaction=True)
async def test_file_download_end_to_end(