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(data-warehouse): bound duckgres backfill concurrency (per-org + global caps) (#66833)

Eric Duongd907ed27f7bb
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.py
index 8142547f56de..f329475ef2d4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.py
@@ -78,7 +78,13 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
logger = structlog.get_logger(__name__)
-MAX_CONCURRENT_BACKFILLS_PER_ORG = 1 # best-effort across pods (see _plan_pending)
+MAX_CONCURRENT_BACKFILLS_PER_ORG = 3 # best-effort across pods (see _plan_pending)
+# Global ceiling on backfills in flight across ALL orgs. Backfill chunks and live
+# batches share the consumer's group-concurrency pool (BatchConsumerConfig.max_concurrency),
+# so this bounds how much of the duckgres worker budget backfills may consume and
+# reserves headroom for live application. Tune to (worker ceiling − live headroom);
+# keep <= max_concurrency. The per-org cap then keeps one org from eating the whole budget.
+MAX_CONCURRENT_BACKFILLS_GLOBAL = 5
# A claim that never produced a durable run plan within this window is
# considered crashed and is returned to PENDING by the reconciler. Planning is
# metadata-only (Delta log read + row inserts), so minutes of lease are ample.
@@ -227,8 +233,15 @@ def _plan_pending(team_ids: list[int] | None) -> None:
# Oldest-touched first so a failing schema cannot starve the rest of the slice.
for state in pending.select_related("team").order_by("updated_at")[:50]:
+ # Global ceiling: backfills share the consumer worker pool with live
+ # application, so once the global budget is full no org may claim —
+ # stop scanning this tick. Re-evaluated each iteration since earlier
+ # iterations may have claimed slots.
+ if _global_at_capacity():
+ break
+
org_id = state.team.organization_id
- if _org_busy(org_id):
+ if _org_at_capacity(org_id):
continue
# Lease claim: exactly one pod proceeds past this line per schema.
@@ -238,17 +251,11 @@ def _plan_pending(team_ids: list[int] | None) -> None:
if not claimed:
continue
- # Re-check the org cap after winning the claim; the pre-check raced
- # against other pods. (Still best-effort across orgs — a transient
- # second concurrent backfill per org is wasteful, not incorrect.)
- if (
- DuckgresSinkSchemaState.objects.filter(
- state=DuckgresSinkSchemaState.State.BACKFILLING,
- team__organization_id=org_id,
- )
- .exclude(id=state.id)
- .exists()
- ):
+ # Re-check both caps after winning the claim; the pre-checks raced against
+ # other pods. Excluding self (now BACKFILLING), revert if either the org or
+ # the global budget is already at capacity. (Still best-effort across pods —
+ # a transient over-the-cap backfill is wasteful, not incorrect.)
+ if _org_at_capacity(org_id, exclude_id=state.id) or _global_at_capacity(exclude_id=state.id):
_revert_to_pending(state.id)
continue
@@ -267,14 +274,25 @@ def _plan_pending(team_ids: list[int] | None) -> None:
_revert_to_pending(state.id, error=str(e)[:2000])
-def _org_busy(org_id: Any) -> bool:
- return (
- DuckgresSinkSchemaState.objects.filter(
- state=DuckgresSinkSchemaState.State.BACKFILLING,
- team__organization_id=org_id,
- ).count()
- >= MAX_CONCURRENT_BACKFILLS_PER_ORG
+def _org_at_capacity(org_id: Any, *, exclude_id: Any = None) -> bool:
+ """Is this org at its per-org backfill cap? Pass exclude_id to ignore the
+ just-claimed row when re-checking after a claim."""
+ qs = DuckgresSinkSchemaState.objects.filter(
+ state=DuckgresSinkSchemaState.State.BACKFILLING,
+ team__organization_id=org_id,
)
+ if exclude_id is not None:
+ qs = qs.exclude(id=exclude_id)
+ return qs.count() >= MAX_CONCURRENT_BACKFILLS_PER_ORG
+
+
+def _global_at_capacity(*, exclude_id: Any = None) -> bool:
+ """Is the global backfill budget (across all orgs) full? Counts every
+ BACKFILLING row, since all backfills draw from one shared worker pool."""
+ qs = DuckgresSinkSchemaState.objects.filter(state=DuckgresSinkSchemaState.State.BACKFILLING)
+ if exclude_id is not None:
+ qs = qs.exclude(id=exclude_id)
+ return qs.count() >= MAX_CONCURRENT_BACKFILLS_GLOBAL
def _revert_to_pending(state_id: Any, error: str | None = None) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.py
index d7dd10b506f1..2c73e5b85d86 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.py
@@ -1,3 +1,15 @@
+import uuid
+
+import pytest
+
+from posthog.models import DuckgresSinkSchemaState, Organization, Team
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres import (
+ backfill as backfill_module,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill import (
+ _plan_pending,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill_queue import (
backfill_run_uuid,
)
@@ -8,6 +20,12 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
_group_files_into_chunks,
)
+_State = DuckgresSinkSchemaState.State
+
+
+def _sink_state(team: Team, state: str) -> DuckgresSinkSchemaState:
+ return DuckgresSinkSchemaState.objects.create(team=team, schema_id=uuid.uuid4(), state=state)
+
class TestChunkGrouping:
def test_groups_small_files_up_to_target(self):
@@ -67,3 +85,59 @@ def test_committed_batch_keys_filters_to_snapshot_version():
("flat-layout", 2),
("nested-layout", 3),
]
+
+
+class TestPlanPendingConcurrencyCaps:
+ # Caps are patched to explicit values so these stay deterministic if the
+ # production constants are later tuned. _plan_one is the queue-DB + Delta
+ # boundary; blocked candidates must never reach it, claimed ones must.
+
+ def test_global_cap_blocks_further_claims(self, monkeypatch):
+ monkeypatch.setattr(backfill_module, "MAX_CONCURRENT_BACKFILLS_GLOBAL", 2)
+ monkeypatch.setattr(backfill_module, "_plan_one", lambda state: pytest.fail("planned past the global cap"))
+
+ busy_team = Team.objects.create(organization=Organization.objects.create(name="busy"), name="t")
+ for _ in range(2):
+ _sink_state(busy_team, _State.BACKFILLING)
+
+ candidate = _sink_state(
+ Team.objects.create(organization=Organization.objects.create(name="new"), name="t"), _State.PENDING_BACKFILL
+ )
+
+ _plan_pending(team_ids=[candidate.team_id])
+
+ candidate.refresh_from_db()
+ # Different org, so per-org never blocks it — only the full global budget does.
+ assert candidate.state == _State.PENDING_BACKFILL
+
+ def test_per_org_cap_blocks_same_org(self, monkeypatch):
+ monkeypatch.setattr(backfill_module, "MAX_CONCURRENT_BACKFILLS_PER_ORG", 1)
+ monkeypatch.setattr(backfill_module, "MAX_CONCURRENT_BACKFILLS_GLOBAL", 99) # global is not the limiter here
+ monkeypatch.setattr(backfill_module, "_plan_one", lambda state: pytest.fail("planned past the per-org cap"))
+
+ team = Team.objects.create(organization=Organization.objects.create(name="org"), name="t")
+ _sink_state(team, _State.BACKFILLING)
+ candidate = _sink_state(team, _State.PENDING_BACKFILL)
+
+ _plan_pending(team_ids=[team.id])
+
+ candidate.refresh_from_db()
+ assert candidate.state == _State.PENDING_BACKFILL
+
+ def test_under_cap_claims_and_plans(self, monkeypatch):
+ monkeypatch.setattr(backfill_module, "MAX_CONCURRENT_BACKFILLS_PER_ORG", 1)
+ monkeypatch.setattr(backfill_module, "MAX_CONCURRENT_BACKFILLS_GLOBAL", 5)
+ planned: list = []
+ monkeypatch.setattr(backfill_module, "_plan_one", lambda state: planned.append(state.id))
+
+ candidate = _sink_state(
+ Team.objects.create(organization=Organization.objects.create(name="org"), name="t"),
+ _State.PENDING_BACKFILL,
+ )
+
+ _plan_pending(team_ids=[candidate.team_id])
+
+ candidate.refresh_from_db()
+ assert candidate.state == _State.BACKFILLING
+ assert planned == [candidate.id]