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(dags): ramp shadow lane processors before starting consumers (#114818)

Zach Brown9f03ba6d0df6
diff --git a/posthog/dags/personhog_shadow_lane.py b/posthog/dags/personhog_shadow_lane.py
index 411466cb4bda..c910db00c29d 100644
--- a/posthog/dags/personhog_shadow_lane.py
+++ b/posthog/dags/personhog_shadow_lane.py
@@ -276,10 +276,12 @@ class ShadowLaneStartConfig(dagster.Config):
reset_offsets: bool = False
consumer_replicas: int = Field(default=4, gt=0, le=512)
processor_replicas: int = Field(default=8, gt=0, le=512)
+ processor_step_replicas: int = Field(default=64, gt=0, le=512)
namespace: str = SHADOW_NAMESPACE
consumer_deployment: str = SHADOW_CONSUMER_DEPLOYMENT
processor_deployment: str = SHADOW_PROCESSOR_DEPLOYMENT
shadow_db_env_var: str = SHADOW_DB_URL_ENV_VAR
+ # Applies to each processor step and to the consumers separately.
ready_timeout_seconds: int = 600
# How long the reset waits for in-flight writes to stop before truncating.
reset_settle_poll_seconds: int = 10
@@ -402,6 +404,42 @@ def _reset_consumer_offsets(
return True
+def processor_ramp(current: int, target: int, step: int) -> list[int]:
+ """Replica counts to scale the processors through, ending at target.
+
+ A partly scaled deployment repeats its current count first, so a retried run waits for
+ pods still pending from the last run before it adds more. A scale down goes straight to
+ target, since removing pods needs no new nodes.
+ """
+ if target <= current:
+ return [target]
+ first = current if current > 0 else step
+ return [*range(first, target, step), target]
+
+
+def _scale_and_wait(
+ context: dagster.OpExecutionContext,
+ config: ShadowLaneStartConfig,
+ apps: k8s_client.AppsV1Api,
+ deployment: str,
+ replicas: int,
+) -> None:
+ context.log.info(f"Scaling {config.namespace}/{deployment} to {replicas} replicas")
+ scale_deployment(apps, config.namespace, deployment, replicas)
+
+ def is_ready(name: str) -> bool:
+ return deployment_ready_replicas(apps, config.namespace, name) >= replicas
+
+ if wait_for_deployments([deployment], is_ready, timeout_seconds=config.ready_timeout_seconds):
+ raise dagster.Failure(
+ description=(
+ f"{deployment} did not reach {replicas} ready replicas within {config.ready_timeout_seconds}s. "
+ "The scale was applied; check the pods in the lane namespace."
+ )
+ )
+ context.log.info(f"{deployment} is ready with {replicas} replica(s)")
+
+
def record_start_gauges(registry: CollectorRegistry, config: ShadowLaneStartConfig, completed_at: float) -> None:
Gauge(
"posthog_personhog_shadow_lane_start_last_success_timestamp_seconds",
@@ -443,31 +481,14 @@ def start_shadow_lane(context: dagster.OpExecutionContext, config: ShadowLaneSta
else:
context.log.info("reset_offsets is false, the lane resumes from its committed offsets")
- targets = [
- (config.consumer_deployment, config.consumer_replicas),
- (config.processor_deployment, config.processor_replicas),
- ]
- for deployment, replicas in targets:
- context.log.info(f"Scaling {config.namespace}/{deployment} to {replicas} replicas")
- scale_deployment(apps, config.namespace, deployment, replicas)
-
- wanted = dict(targets)
-
- def is_ready(deployment: str) -> bool:
- ready = deployment_ready_replicas(apps, config.namespace, deployment)
- if ready < wanted[deployment]:
- return False
- context.log.info(f"{deployment} is ready with {ready} replica(s)")
- return True
-
- pending = wait_for_deployments(wanted, is_ready, timeout_seconds=config.ready_timeout_seconds)
- if pending:
- raise dagster.Failure(
- description=(
- f"Deployments not ready after {config.ready_timeout_seconds}s: {', '.join(sorted(pending))}. "
- "The scale was applied; check the pods in the lane namespace."
- )
- )
+ # Every processor is ready before any consumer starts. A consumer that starts first pins its keys to the
+ # few processors already up, and those keys stay on them while they have work in flight.
+ current = apps.read_namespaced_deployment(name=config.processor_deployment, namespace=config.namespace)
+ for replicas in processor_ramp(
+ current.spec.replicas or 0, config.processor_replicas, config.processor_step_replicas
+ ):
+ _scale_and_wait(context, config, apps, config.processor_deployment, replicas)
+ _scale_and_wait(context, config, apps, config.consumer_deployment, config.consumer_replicas)
with pushed_metrics_registry(f"{START_METRICS_JOB}_{config.namespace}") as registry:
record_start_gauges(registry, config, time.time())
@@ -490,6 +511,8 @@ def personhog_shadow_lane_start_job():
Set ops.start_shadow_lane.config.reset_state to true to truncate both
paths' tables before starting, which every fresh validation run needs.
Set reset_offsets to true to start from the end of the topic instead.
- Both resets refuse to run while the lane has pods.
+ Both resets refuse to run while the lane has pods. Processors scale up in
+ steps of processor_step_replicas, and the consumers start only once every
+ processor is ready.
"""
start_shadow_lane()
diff --git a/posthog/dags/tests/test_personhog_shadow_lane.py b/posthog/dags/tests/test_personhog_shadow_lane.py
index f04349bb18c8..271929799980 100644
--- a/posthog/dags/tests/test_personhog_shadow_lane.py
+++ b/posthog/dags/tests/test_personhog_shadow_lane.py
@@ -1,6 +1,8 @@
import uuid
from collections.abc import Callable
from concurrent.futures import Future
+from contextlib import nullcontext
+from functools import partial
from types import SimpleNamespace
import pytest
@@ -14,14 +16,18 @@ from parameterized import parameterized
from posthog.dags.personhog_shadow_lane import (
GROUP_ID_NOT_FOUND,
NON_EMPTY_GROUP,
+ SHADOW_CONSUMER_DEPLOYMENT,
SHADOW_CONSUMER_GROUP,
SHADOW_KAFKA_BOOTSTRAP_ENV_VAR,
+ SHADOW_PROCESSOR_DEPLOYMENT,
ShadowLaneStartConfig,
_reset_consumer_offsets,
_reset_shadow_state,
+ processor_ramp,
read_shadow_write_counter,
require_shadow_dsn,
shadow_kafka_admin,
+ start_shadow_lane,
wait_for_deployments,
wait_for_quiescence,
)
@@ -115,6 +121,94 @@ class TestWaitForDeployments:
assert pending == expected_pending
+class TestProcessorRamp:
+ @parameterized.expand(
+ [
+ ("from_zero", 0, 256, 64, [64, 128, 192, 256]),
+ ("partial_last_step", 0, 150, 64, [64, 128, 150]),
+ ("holds_at_current_before_stepping", 200, 512, 128, [200, 328, 456, 512]),
+ ("target_below_one_step", 0, 8, 64, [8]),
+ ("scale_down_is_direct", 512, 256, 64, [256]),
+ ]
+ )
+ def test_steps(self, _name: str, current: int, target: int, step: int, expected: list[int]) -> None:
+ assert processor_ramp(current, target, step) == expected
+
+
+class _ScalingAppsApi:
+ def __init__(self, ready_cap: int | None = None, processor_replicas: int = 0) -> None:
+ self.replicas = {SHADOW_PROCESSOR_DEPLOYMENT: processor_replicas, SHADOW_CONSUMER_DEPLOYMENT: 0}
+ self.ready_cap = ready_cap
+ self.scales: list[tuple[str, int]] = []
+
+ def read_namespaced_deployment(self, name: str, namespace: str) -> SimpleNamespace:
+ desired = self.replicas[name]
+ ready = desired if self.ready_cap is None else min(desired, self.ready_cap)
+ return SimpleNamespace(spec=SimpleNamespace(replicas=desired), status=SimpleNamespace(ready_replicas=ready))
+
+ def patch_namespaced_deployment_scale(self, name: str, namespace: str, body: dict) -> None:
+ self.replicas[name] = body["spec"]["replicas"]
+ self.scales.append((name, self.replicas[name]))
+
+
+class _FakeClock:
+ def __init__(self) -> None:
+ self.now = 0.0
+
+ def monotonic(self) -> float:
+ return self.now
+
+ def time(self) -> float:
+ return self.now
+
+ def sleep(self, seconds: float) -> None:
+ self.now += seconds
+
+
+def scaling_apps(monkeypatch: pytest.MonkeyPatch) -> Callable[..., _ScalingAppsApi]:
+ def install(**kwargs: int) -> _ScalingAppsApi:
+ apps = _ScalingAppsApi(**kwargs)
+ clock = _FakeClock()
+ monkeypatch.setattr("posthog.dags.personhog_shadow_lane.apps_api", lambda: apps)
+ monkeypatch.setattr("posthog.dags.personhog_shadow_lane.pushed_metrics_registry", lambda _job: nullcontext())
+ monkeypatch.setattr("posthog.dags.personhog_shadow_lane.time", clock)
+ monkeypatch.setattr(
+ "posthog.dags.personhog_shadow_lane.wait_for_deployments",
+ partial(wait_for_deployments, sleep=clock.sleep),
+ )
+ return apps
+
+ return install
+
+
+def test_start_steps_processors_up_before_any_consumer(scaling_apps: Callable[..., _ScalingAppsApi]) -> None:
+ apps = scaling_apps()
+ config = ShadowLaneStartConfig(processor_replicas=150, processor_step_replicas=64, consumer_replicas=4)
+
+ start_shadow_lane(dagster.build_op_context(), config)
+
+ assert apps.scales == [
+ (SHADOW_PROCESSOR_DEPLOYMENT, 64),
+ (SHADOW_PROCESSOR_DEPLOYMENT, 128),
+ (SHADOW_PROCESSOR_DEPLOYMENT, 150),
+ (SHADOW_CONSUMER_DEPLOYMENT, 4),
+ ]
+
+
[email protected]("processor_replicas", [0, 64], ids=["fresh_start", "retry_with_pods_still_pending"])
+def test_start_leaves_consumers_down_while_a_processor_step_is_unready(
+ scaling_apps: Callable[..., _ScalingAppsApi], processor_replicas: int
+) -> None:
+ apps = scaling_apps(ready_cap=0, processor_replicas=processor_replicas)
+ config = ShadowLaneStartConfig(processor_replicas=150, consumer_replicas=4, ready_timeout_seconds=60)
+
+ with pytest.raises(dagster.Failure, match="did not reach 64 ready replicas"):
+ start_shadow_lane(dagster.build_op_context(), config)
+
+ assert apps.scales == [(SHADOW_PROCESSOR_DEPLOYMENT, 64)]
+
+
class _FakeAppsApi:
def __init__(self, desired_replicas: int) -> None:
self.desired_replicas = desired_replicas