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.

feat(customer-analytics): set account property source concurrency by flag (#120241)

Arthur Moreira de Deusd4adb1c000bd
diff --git a/products/customer_analytics/backend/facade/temporal_contracts.py b/products/customer_analytics/backend/facade/temporal_contracts.py
index 6ef31ca6e402..5c6b44e7d5a1 100644
--- a/products/customer_analytics/backend/facade/temporal_contracts.py
+++ b/products/customer_analytics/backend/facade/temporal_contracts.py
@@ -2,6 +2,8 @@ from typing import Literal
from posthog.dataclasses import frozen
+DEFAULT_ACCOUNT_PROPERTY_SOURCE_CONCURRENCY = 3
+
@frozen
class StageAccountPropertySyncInput:
@@ -37,6 +39,7 @@ class AccountPropertySyncInput:
saved_query_id: str
job_id: str
segment: str
+ source_concurrency: int = DEFAULT_ACCOUNT_PROPERTY_SOURCE_CONCURRENCY
@frozen
diff --git a/products/customer_analytics/backend/logic/account_property_fanout_flags.py b/products/customer_analytics/backend/logic/account_property_fanout_flags.py
index 83919554a87f..a2867064ca55 100644
--- a/products/customer_analytics/backend/logic/account_property_fanout_flags.py
+++ b/products/customer_analytics/backend/logic/account_property_fanout_flags.py
@@ -1,11 +1,18 @@
+import json
+
import posthoganalytics
from posthog.exceptions_capture import capture_exception
from posthog.models import Team
+from products.customer_analytics.backend.facade.temporal_contracts import DEFAULT_ACCOUNT_PROPERTY_SOURCE_CONCURRENCY
+
# Selects the per-source fanout workflow for new account-property segment syncs. The flag is
# created default-off, so an absent flag keeps every team on the legacy workflow.
ACCOUNT_PROPERTY_SYNC_FANOUT_FLAG = "warehouse-account-property-sync-fanout"
+ACCOUNT_PROPERTY_SYNC_SOURCE_CONCURRENCY_FLAG = "warehouse-account-property-sync-source-concurrency"
+ACCOUNT_PROPERTY_SYNC_SOURCE_CONCURRENCY_PAYLOAD_KEY = "source_concurrency"
+MAX_ACCOUNT_PROPERTY_SOURCE_CONCURRENCY = 20
def account_property_sync_fanout_enabled(team_id: int) -> bool:
@@ -14,7 +21,7 @@ def account_property_sync_fanout_enabled(team_id: int) -> bool:
Fails closed: an unknown team, a missing flag, or any lookup or flag-service error selects the legacy workflow.
"""
try:
- organization_id = str(Team.objects.only("organization_id").get(id=team_id).organization_id)
+ organization_id = _get_organization_id(team_id)
enabled = posthoganalytics.feature_enabled(
ACCOUNT_PROPERTY_SYNC_FANOUT_FLAG,
organization_id,
@@ -28,3 +35,32 @@ def account_property_sync_fanout_enabled(team_id: int) -> bool:
capture_exception(error)
return False
return enabled is True
+
+
+def get_account_property_sync_source_concurrency(team_id: int) -> int:
+ try:
+ organization_id = _get_organization_id(team_id)
+ payload = posthoganalytics.get_feature_flag_payload(
+ ACCOUNT_PROPERTY_SYNC_SOURCE_CONCURRENCY_FLAG,
+ organization_id,
+ groups={"organization": organization_id},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ if isinstance(payload, str):
+ payload = json.loads(payload)
+ except Team.DoesNotExist:
+ return DEFAULT_ACCOUNT_PROPERTY_SOURCE_CONCURRENCY
+ except Exception as error:
+ capture_exception(error)
+ return DEFAULT_ACCOUNT_PROPERTY_SOURCE_CONCURRENCY
+ concurrency = (
+ payload.get(ACCOUNT_PROPERTY_SYNC_SOURCE_CONCURRENCY_PAYLOAD_KEY) if isinstance(payload, dict) else None
+ )
+ if isinstance(concurrency, bool) or not isinstance(concurrency, int) or concurrency < 1:
+ return DEFAULT_ACCOUNT_PROPERTY_SOURCE_CONCURRENCY
+ return min(concurrency, MAX_ACCOUNT_PROPERTY_SOURCE_CONCURRENCY)
+
+
+def _get_organization_id(team_id: int) -> str:
+ return str(Team.objects.only("organization_id").get(id=team_id).organization_id)
diff --git a/products/customer_analytics/backend/logic/account_property_fanout_flags_test.py b/products/customer_analytics/backend/logic/account_property_fanout_flags_test.py
index 976fd57e30ef..ea63c1d51bf3 100644
--- a/products/customer_analytics/backend/logic/account_property_fanout_flags_test.py
+++ b/products/customer_analytics/backend/logic/account_property_fanout_flags_test.py
@@ -5,12 +5,14 @@ from parameterized import parameterized
from products.customer_analytics.backend.logic.account_property_fanout_flags import (
ACCOUNT_PROPERTY_SYNC_FANOUT_FLAG,
+ ACCOUNT_PROPERTY_SYNC_SOURCE_CONCURRENCY_FLAG,
account_property_sync_fanout_enabled,
+ get_account_property_sync_source_concurrency,
)
-_FEATURE_ENABLED = (
- "products.customer_analytics.backend.logic.account_property_fanout_flags.posthoganalytics.feature_enabled"
-)
+_MODULE = "products.customer_analytics.backend.logic.account_property_fanout_flags"
+_FEATURE_ENABLED = f"{_MODULE}.posthoganalytics.feature_enabled"
+_FEATURE_FLAG_PAYLOAD = f"{_MODULE}.posthoganalytics.get_feature_flag_payload"
class AccountPropertySyncFanoutFlagTest(BaseTest):
@@ -29,7 +31,7 @@ class AccountPropertySyncFanoutFlagTest(BaseTest):
with (
patch(_FEATURE_ENABLED, side_effect=[flag_result]) as feature_enabled,
- patch("products.customer_analytics.backend.logic.account_property_fanout_flags.capture_exception"),
+ patch(f"{_MODULE}.capture_exception"),
):
assert account_property_sync_fanout_enabled(self.team.id) is expected
@@ -46,3 +48,38 @@ class AccountPropertySyncFanoutFlagTest(BaseTest):
assert account_property_sync_fanout_enabled(self.team.id + 10_000) is False
feature_enabled.assert_not_called()
+
+
+class AccountPropertySyncSourceConcurrencyFlagTest(BaseTest):
+ @parameterized.expand(
+ [
+ ("payload_value", {"source_concurrency": 8}, 8),
+ ("json_string_payload", '{"source_concurrency": 5}', 5),
+ ("above_maximum", {"source_concurrency": 500}, 20),
+ ("missing_flag", None, 3),
+ ("missing_key", {}, 3),
+ ("zero", {"source_concurrency": 0}, 3),
+ ("float", {"source_concurrency": 4.5}, 3),
+ ("boolean", {"source_concurrency": True}, 3),
+ ("malformed_json", "{not json", 3),
+ ("flag_service_error", RuntimeError("flag service unavailable"), 3),
+ ]
+ )
+ def test_targets_the_team_organization_and_falls_back_to_the_default(
+ self, _name: str, payload: object, expected: int
+ ) -> None:
+ organization_id = str(self.team.organization_id)
+
+ with (
+ patch(_FEATURE_FLAG_PAYLOAD, side_effect=[payload]) as feature_flag_payload,
+ patch(f"{_MODULE}.capture_exception"),
+ ):
+ assert get_account_property_sync_source_concurrency(self.team.id) == expected
+
+ feature_flag_payload.assert_called_once_with(
+ ACCOUNT_PROPERTY_SYNC_SOURCE_CONCURRENCY_FLAG,
+ organization_id,
+ groups={"organization": organization_id},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
diff --git a/products/customer_analytics/backend/temporal/account_property_sync.py b/products/customer_analytics/backend/temporal/account_property_sync.py
index e7e696ddc1cc..9554b1390708 100644
--- a/products/customer_analytics/backend/temporal/account_property_sync.py
+++ b/products/customer_analytics/backend/temporal/account_property_sync.py
@@ -15,6 +15,7 @@ from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.heartbeat import LivenessHeartbeater as Heartbeater
from products.customer_analytics.backend.facade.temporal_contracts import (
+ DEFAULT_ACCOUNT_PROPERTY_SOURCE_CONCURRENCY,
AccountPropertySegmentTelemetryInput,
AccountPropertySourceSyncInput,
AccountPropertySyncInput,
@@ -37,6 +38,7 @@ with workflow.unsafe.imports_passed_through():
from products.customer_analytics.backend.logic.account_property_fanout_flags import (
account_property_sync_fanout_enabled,
+ get_account_property_sync_source_concurrency,
)
from products.customer_analytics.backend.logic.account_property_runs import (
AccountPropertySyncRunContext,
@@ -69,7 +71,6 @@ ACCOUNT_PROPERTY_SYNC_FANOUT_WORKFLOW_NAME = "sync-warehouse-account-properties-
ACCOUNT_PROPERTY_RUN_HISTORY_PATCH = "account-property-run-history-2026-08"
ACCOUNT_PROPERTY_SEGMENT_TELEMETRY_PATCH = "account-property-segment-telemetry-2026-10"
ACCOUNT_PROPERTY_ACTIVITY_MAX_ATTEMPTS = 5
-ACCOUNT_PROPERTY_SOURCE_CONCURRENCY = 3
# Source IDs are UUID strings, so this keeps the discovery result far below the 256 KB field rule.
ACCOUNT_PROPERTY_FANOUT_MAX_SOURCES = 2_000
@@ -293,6 +294,11 @@ async def dispatch_warehouse_account_property_sync_activity(input: DispatchAccou
use_fanout = await database_sync_to_async_pool(account_property_sync_fanout_enabled)(input.team_id)
workflow_name = ACCOUNT_PROPERTY_SYNC_FANOUT_WORKFLOW_NAME if use_fanout else ACCOUNT_PROPERTY_SYNC_WORKFLOW_NAME
path: _SyncPath = "fanout" if use_fanout else "legacy"
+ source_concurrency = (
+ await database_sync_to_async_pool(get_account_property_sync_source_concurrency)(input.team_id)
+ if use_fanout
+ else DEFAULT_ACCOUNT_PROPERTY_SOURCE_CONCURRENCY
+ )
client = await async_connect()
for segment in ("tracked", "ignored"):
try:
@@ -303,6 +309,7 @@ async def dispatch_warehouse_account_property_sync_activity(input: DispatchAccou
saved_query_id=input.saved_query_id,
job_id=input.job_id,
segment=segment,
+ source_concurrency=source_concurrency,
),
id=_segment_workflow_id(input.job_id, segment),
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,
@@ -333,6 +340,7 @@ async def dispatch_warehouse_account_property_sync_activity(input: DispatchAccou
job_id=input.job_id,
segment=segment,
path=path,
+ source_concurrency=source_concurrency,
)
@@ -698,7 +706,7 @@ class _SettledSources:
async def _sync_sources(input: AccountPropertySyncInput, source_ids: list[str]) -> _SettledSources:
- semaphore = asyncio.Semaphore(ACCOUNT_PROPERTY_SOURCE_CONCURRENCY)
+ semaphore = asyncio.Semaphore(input.source_concurrency)
async def sync_source(source_id: str) -> dict[str, int]:
async with semaphore:
diff --git a/products/customer_analytics/backend/temporal/account_property_sync_test.py b/products/customer_analytics/backend/temporal/account_property_sync_test.py
index 5852a03c2667..35ba14292a2b 100644
--- a/products/customer_analytics/backend/temporal/account_property_sync_test.py
+++ b/products/customer_analytics/backend/temporal/account_property_sync_test.py
@@ -1,5 +1,6 @@
import uuid
import asyncio
+import dataclasses
from collections.abc import AsyncIterator, Callable
from contextlib import asynccontextmanager
from datetime import timedelta
@@ -251,6 +252,7 @@ async def test_dispatch_selects_one_workflow_type_and_keeps_stable_segment_ids(
with (
patch(f"{_MODULE}.async_connect", return_value=client),
patch(f"{_MODULE}.account_property_sync_fanout_enabled", return_value=fanout_enabled) as flag,
+ patch(f"{_MODULE}.get_account_property_sync_source_concurrency", return_value=8) as concurrency_flag,
patch(
"products.customer_analytics.backend.logic.account_property_sync_monitoring.ph_background_capture"
) as capture_factory,
@@ -265,6 +267,9 @@ async def test_dispatch_selects_one_workflow_type_and_keeps_stable_segment_ids(
calls = client.start_workflow.await_args_list
assert [call.args[0] for call in calls] == [workflow_name, workflow_name]
assert [call.args[1].segment for call in calls] == ["tracked", "ignored"]
+ assert concurrency_flag.call_count == (1 if fanout_enabled else 0)
+ expected_concurrency = 8 if fanout_enabled else 3
+ assert [call.args[1].source_concurrency for call in calls] == [expected_concurrency, expected_concurrency]
# Both workflow types share these IDs, so a retry after a flag change finds the running segment.
assert [call.kwargs["id"] for call in calls] == [
"sync-warehouse-account-properties-job-1-tracked",
@@ -411,7 +416,14 @@ async def _wait(event: asyncio.Event) -> None:
await asyncio.wait_for(event.wait(), timeout=5)
-async def test_fanout_runs_sources_in_parallel_up_to_the_cap() -> None:
+ "segment_input,cap",
+ [
+ (_segment_input(), 3),
+ (dataclasses.replace(_segment_input(), source_concurrency=2), 2),
+ ],
+)
+async def test_fanout_runs_sources_in_parallel_up_to_the_cap(segment_input: AccountPropertySyncInput, cap: int) -> None:
source_ids = ["source-1", "source-2", "source-3", "source-4", "source-5"]
fake = _FakeFanoutActivities(source_ids)
@@ -419,21 +431,21 @@ async def test_fanout_runs_sources_in_parallel_up_to_the_cap() -> None:
patch.object(workflow, "execute_activity", new=fake.execute_activity),
patch.object(workflow, "time", side_effect=[100.0, 145.0]),
):
- run = asyncio.create_task(SyncWarehouseAccountPropertiesFanoutWorkflow().run(_segment_input()))
- await _wait(fake.started["source-3"])
- assert fake.started_sources() == ["source-1", "source-2", "source-3"]
+ run = asyncio.create_task(SyncWarehouseAccountPropertiesFanoutWorkflow().run(segment_input))
+ await _wait(fake.started[source_ids[cap - 1]])
+ assert fake.started_sources() == source_ids[:cap]
fake.results["source-2"].set_result(dict(_FANOUT_COUNTS))
- await _wait(fake.started["source-4"])
- assert fake.in_flight == 3
- assert fake.started_sources() == ["source-1", "source-2", "source-3", "source-4"]
+ await _wait(fake.started[source_ids[cap]])
+ assert fake.in_flight == cap
+ assert fake.started_sources() == source_ids[: cap + 1]
- for source_id in ("source-1", "source-3", "source-4", "source-5"):
+ for source_id in source_ids:
if not fake.results[source_id].done():
fake.results[source_id].set_result(dict(_FANOUT_COUNTS))
await asyncio.wait_for(run, timeout=5)
- assert fake.max_in_flight == 3
+ assert fake.max_in_flight == cap
complete = complete_warehouse_account_property_segment_activity.__name__
assert fake.log.count(complete) == 1
assert all(fake.log.index(f"completed:{source_id}") < fake.log.index(complete) for source_id in source_ids)