: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(data-warehouse): speed up create and delete for large sources (#59741)
Marcus Hof90dde0c29a81
diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.pyindex 8a6520c16673..626e0f79bc86 100644--- a/products/data_warehouse/backend/api/external_data_source.py+++ b/products/data_warehouse/backend/api/external_data_source.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport uuidimport dataclassesfrom collections.abc import Callable-from datetime import timedelta+from datetime import UTC, datetime, timedeltafrom typing import Any, castfrom django.db import transaction@@ -59,13 +59,14 @@ from products.data_warehouse.backend.api.external_data_schema import (SimpleExternalDataSchemaSerializer,)from products.data_warehouse.backend.data_load.service import (+ bulk_create_external_data_job_schedules,+ bulk_delete_external_data_schedules,cancel_external_data_workflow,delete_discover_schemas_schedule,delete_external_data_schedule,is_any_external_data_schema_paused,is_cdc_enabled_for_team,sync_discover_schemas_schedule,- sync_external_data_job_workflow,trigger_external_data_source_workflow,)from products.data_warehouse.backend.direct_postgres import upsert_direct_postgres_table@@ -1363,11 +1364,23 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixiif should_sync and new_source_model.supports_scheduled_sync:active_schemas.append(schema_model)+ # Create all sync schedules over a single shared Temporal connection. Creating them+ # one call at a time reconnects to Temporal on every iteration, which does not scale+ # to sources with thousands of schemas (e.g. a Slack workspace with thousands of+ # channels).try:- for active_schema in active_schemas:- sync_external_data_job_workflow(active_schema, create=True, should_sync=active_schema.should_sync)+ schedule_errors = bulk_create_external_data_job_schedules(+ [(active_schema, active_schema.should_sync) for active_schema in active_schemas]+ )+ for schema_id, schedule_error in schedule_errors:+ # The source model was already created, so a partial schedule failure+ # shouldn't fail the request — log each failure and carry on.+ logger.exception(+ "Could not trigger external data job",+ exc_info=schedule_error,+ schema_id=schema_id,+ )except Exception as e:- # Log error but don't fail because the source model was already createdlogger.exception("Could not trigger external data job", exc_info=e)# Per-source schema discovery schedule. Runs every 6h so newly added@@ -1545,7 +1558,21 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixifor schema in schemas:if schema.table:schema.table.soft_delete()- schema.soft_delete()++ # Bulk soft-delete the schema rows in a single UPDATE. Per-row soft_delete()+ # runs a SELECT + UPDATE + activity-log write each, which does not scale to+ # sources with thousands of schemas (e.g. a Slack workspace with thousands of+ # channels).+ deleted_at = datetime.now(UTC)+ ExternalDataSchema.objects.filter(team_id=self.team_id, id__in=[schema.id for schema in schemas]).update(+ deleted=True, deleted_at=deleted_at+ )+ # Mirror the bulk update onto the in-memory objects so the post-atomic+ # `schema.delete_table()` save() below doesn't overwrite deleted=True with the+ # stale in-memory value.+ for schema in schemas:+ schema.deleted = True+ schema.deleted_at = deleted_at# Clean up CDC companion tables (e.g. {name}_cdc) — these are standalone# DataWarehouseTable records linked to the source but not to schema.table.@@ -1581,12 +1608,17 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixiif latest_running_job and latest_running_job.workflow_id and latest_running_job.status == "Running":cancel_external_data_workflow(latest_running_job.workflow_id)- for schema in schemas:- try:- delete_external_data_schedule(str(schema.id))- except Exception as e:- capture_exception(e)+ # Delete all schema sync schedules over a single shared Temporal connection — see+ # the matching comment in `create`. Guarded so a Temporal-connect failure here+ # doesn't skip the source/discovery schedule and S3 cleanup below.+ try:+ schedule_delete_errors = bulk_delete_external_data_schedules([str(schema.id) for schema in schemas])+ for schema_id, schedule_delete_error in schedule_delete_errors:+ capture_exception(schedule_delete_error, {"schema_id": schema_id})+ except Exception as e:+ capture_exception(e)+ for schema in schemas:try:schema.delete_table()except Exception as e:diff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.pyindex 3ca6ecbd7d56..6aad2c69fdfd 100644--- a/products/data_warehouse/backend/api/test/test_external_data_source.py+++ b/products/data_warehouse/backend/api/test/test_external_data_source.py@@ -1241,12 +1241,16 @@ class TestExternalDataSource(APIBaseTest):mock_delete_discover.assert_called_once_with(str(source.pk))@patch("products.data_warehouse.backend.api.external_data_source.capture_exception")+ @patch(+ "products.data_warehouse.backend.api.external_data_source.bulk_delete_external_data_schedules",+ return_value=[("schema-id", Exception("Schema schedule delete failed"))],+ )@patch("products.data_warehouse.backend.api.external_data_source.delete_external_data_schedule",side_effect=Exception("External delete failed"),)def test_delete_external_data_source_soft_deletes_even_if_external_cleanup_fails(- self, _mock_delete_schedule, mock_capture_exception+ self, _mock_delete_schedule, _mock_bulk_delete, mock_capture_exception):source = self._create_external_data_source()table = DataWarehouseTable.objects.create(diff --git a/products/data_warehouse/backend/api/test/test_external_data_source_end_to_end.py b/products/data_warehouse/backend/api/test/test_external_data_source_end_to_end.pyindex 6cac3088badb..d3fccf8775da 100644--- a/products/data_warehouse/backend/api/test/test_external_data_source_end_to_end.py+++ b/products/data_warehouse/backend/api/test/test_external_data_source_end_to_end.py@@ -44,7 +44,8 @@ def api_client(user):return_value=(True, None),),mock.patch(- "products.data_warehouse.backend.api.external_data_source.sync_external_data_job_workflow",+ "products.data_warehouse.backend.api.external_data_source.bulk_create_external_data_job_schedules",+ return_value=[],) as mock_sync_workflow,mock.patch.object(DataWarehouseSavedQuery, "schedule_materialization"),):diff --git a/products/data_warehouse/backend/data_load/service.py b/products/data_warehouse/backend/data_load/service.pyindex 2dc756e74651..7b04ed6f1084 100644--- a/products/data_warehouse/backend/data_load/service.py+++ b/products/data_warehouse/backend/data_load/service.py@@ -1,6 +1,7 @@from __future__ import annotationsimport random+import asynciofrom dataclasses import asdictfrom datetime import UTC, datetime, time, timedeltafrom typing import TYPE_CHECKING@@ -248,6 +249,83 @@ async def a_delete_external_data_schedule(external_data_source: ExternalDataSourraise+# Bounded concurrency for bulk schedule operations. High enough to parallelise the+# per-RPC latency across thousands of schemas — each create_schedule with an immediate+# trigger is a relatively heavy server-side operation (it also starts a workflow) — but+# low enough to stay friendly to the Temporal frontend service.+_BULK_SCHEDULE_CONCURRENCY = 100+++@async_to_sync+async def bulk_create_external_data_job_schedules(+ schemas: list[tuple[ExternalDataSchema, bool]],+) -> list[tuple[str, BaseException]]:+ """Create sync schedules for many schemas over a single shared Temporal connection.++ `sync_external_data_job_workflow` opens a fresh Temporal connection on every call, so+ looping it over thousands of schemas (e.g. a Slack workspace with thousands of+ channels) spends almost all of its time reconnecting. This connects once and runs the+ creates concurrently. Returns ``(schema_id, exception)`` pairs for any schedules that+ failed — a partial failure does not abort the rest, so the caller decides how to+ surface them and can attribute each failure to a specific schema.+ """+ if not schemas:+ return []++ temporal = await async_connect()+ semaphore = asyncio.Semaphore(_BULK_SCHEDULE_CONCURRENCY)++ async def _create_one(external_data_schema: ExternalDataSchema, should_sync: bool) -> None:+ async with semaphore:+ schedule = get_sync_schedule(external_data_schema, should_sync=should_sync)+ schedule_id = str(external_data_schema.id)+ try:+ await a_create_schedule(temporal, id=schedule_id, schedule=schedule, trigger_immediately=True)+ except ScheduleAlreadyRunningError:+ await a_update_schedule(temporal, id=schedule_id, schedule=schedule)+ await a_trigger_schedule(temporal, schedule_id=schedule_id)++ schema_ids = [str(schema.id) for schema, _ in schemas]+ results = await asyncio.gather(+ *(_create_one(schema, should_sync) for schema, should_sync in schemas),+ return_exceptions=True,+ )+ return [(schema_id, result) for schema_id, result in zip(schema_ids, results) if isinstance(result, BaseException)]+++@async_to_sync+async def bulk_delete_external_data_schedules(schedule_ids: list[str]) -> list[tuple[str, BaseException]]:+ """Delete many Temporal schedules over a single shared connection.++ The bulk counterpart to `delete_external_data_schedule`: reuses one connection,+ deletes concurrently, and ignores schedules that no longer exist. Returns+ ``(schedule_id, exception)`` pairs for any deletes that failed for another reason.+ """+ if not schedule_ids:+ return []++ temporal = await async_connect()+ semaphore = asyncio.Semaphore(_BULK_SCHEDULE_CONCURRENCY)++ async def _delete_one(schedule_id: str) -> None:+ async with semaphore:+ try:+ await a_delete_schedule(temporal, schedule_id=schedule_id)+ except temporalio.service.RPCError as e:+ # Swallow error if schedule does not exist already+ if e.status == temporalio.service.RPCStatusCode.NOT_FOUND:+ return+ raise++ results = await asyncio.gather(+ *(_delete_one(schedule_id) for schedule_id in schedule_ids),+ return_exceptions=True,+ )+ return [+ (schedule_id, result) for schedule_id, result in zip(schedule_ids, results) if isinstance(result, BaseException)+ ]++def cancel_external_data_workflow(workflow_id: str):temporal = sync_connect()cancel_workflow(temporal, workflow_id)