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(alerts): start platform insight batches past the pool size each tick (#124510)

Jimmy Zhub04b2dc5f9a5
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.md
index c7f1cbb220b6..bf055da32ba7 100644
--- a/docs/internal/alerts-platform-temporal.md
+++ b/docs/internal/alerts-platform-temporal.md
@@ -533,6 +533,7 @@ A full logs backfill hit ClickHouse's per-user concurrent query limit and had to
2. Watch the parallel run's ClickHouse cost in `query_log`: its `client_query_id` starts with `alerts-platform-insight:`.
3. Watch scheduler lag for `source=insight`, and the `capacity` skip reason on the platform's skipped-check counter. Capacity skips mean ClickHouse refused the query for load.
4. Widen the sample only while both stay flat. `ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_EVALUATIONS` caps the concurrent checks whatever the sample size. A batch refills the slots its finished checks free, in rounds within its tick, so the cap limits concurrency rather than checks per minute.
+ `ALERTS_PLATFORM_INSIGHT_KEYS_PER_TICK` bounds how many teams' batches start each minute, so a larger sample can need it raised. Sixty times its value must cover the batch keys due per hour. Otherwise the checks due at the top of the hour start later and later, while ClickHouse stays idle.
5. Raise that cap from its default of 10 only while the daily count of refused queries, `exception_code = 202` in `query_log`, stays flat for both `alerts_platform_insight` and the user that production insight alerts query as. The first shows the parallel run's own contention. The second shows whether it reaches production through the server-wide limit. Do not size it from per-second concurrency, which overcounts because short queries that run back to back inside one second read as concurrent. Code 202 also covers the server-wide limit, so a rise is a reason to look rather than proof that the cap caused it.
To stop either parallel run, logs or insight, pass `--disable` to its backfill, with `--team-id` to stop one team.
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index 54355b4be8fc..7dcb59a92d3b 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -411,6 +411,17 @@ if ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_EVALUATIONS <= 0:
raise ImproperlyConfigured(
"ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_EVALUATIONS must be a positive integer, or no platform insight check starts"
)
+# Insight batch keys the platform starts per tick, across every team. A key is one team's checks due
+# in one slot. With a tick a minute, 60 times this must cover the keys due per hour, or hourly alerts
+# fall behind their cadence. The pool above bounds concurrent queries, not this. A key that finds the
+# pool full polls for a slot within its tick, so a high value costs waiting runs rather than load.
+# The default is never below the pool size, so a larger pool is never left idle. Discovery returns
+# every key in one activity result, so the cap keeps it at the 1000 keys the other sources use.
+ALERTS_PLATFORM_INSIGHT_KEYS_PER_TICK: int = get_from_env(
+ "ALERTS_PLATFORM_INSIGHT_KEYS_PER_TICK", max(200, ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_EVALUATIONS), type_cast=int
+)
+if not 0 < ALERTS_PLATFORM_INSIGHT_KEYS_PER_TICK <= 1000:
+ raise ImproperlyConfigured("ALERTS_PLATFORM_INSIGHT_KEYS_PER_TICK must be between 1 and 1000")
# Chart renders for platform insight firings allowed to run at once, across every worker. A render
# blocks a worker thread for up to 90 seconds, so this keeps renders from taking the slots that
# planning and recording need.
diff --git a/products/alerts/backend/temporal/platform_evaluate.py b/products/alerts/backend/temporal/platform_evaluate.py
index e5f35ec57385..b32797a376d6 100644
--- a/products/alerts/backend/temporal/platform_evaluate.py
+++ b/products/alerts/backend/temporal/platform_evaluate.py
@@ -113,6 +113,8 @@ _PATCH_AI_DETECTOR_QUEUE = "platform-insight-ai-detector-queue-2026-10"
_PATCH_CHART_AFTER_CHECK = "platform-insight-chart-after-check-2026-10"
# Runs started before it recorded every outcome once the whole batch ended, and failed checks left none.
_PATCH_RECORD_AS_FINISHED = "platform-insight-record-as-finished-2026-10"
+# Runs started before it returned when their first round found the pool full, and replay must not poll.
+_PATCH_WAIT_FOR_POOL = "platform-insight-wait-for-pool-2026-10"
@frozen
@@ -588,6 +590,11 @@ class InsightAlertPlatformEvaluateWorkflow(PostHogWorkflow):
# The checks a round added can end while earlier ones record, and free slots for more.
if admitting and added:
continue
+ # A batch that has no slot yet found the pool full. Other batches free slots within
+ # seconds, so it polls for one rather than leave its checks to a later tick.
+ if admitting and not started and workflow.patched(_PATCH_WAIT_FOR_POOL):
+ await workflow.sleep(ADMISSION_POLL_INTERVAL)
+ continue
recorded += await self._record_waiting(inputs, waiting, last_chance=True)
await asyncio.gather(*stopping, return_exceptions=True)
return recorded
diff --git a/products/alerts/backend/test/test_platform_evaluate_workflow.py b/products/alerts/backend/test/test_platform_evaluate_workflow.py
index bc8b91fc40b3..aac68c3d8334 100644
--- a/products/alerts/backend/test/test_platform_evaluate_workflow.py
+++ b/products/alerts/backend/test/test_platform_evaluate_workflow.py
@@ -256,10 +256,11 @@ async def test_a_batch_over_the_payload_budget_records_in_chunks_and_starts_one_
@pytest.mark.parametrize(
- "fail_second_plan, expected",
+ "fail_second_plan, pool_full_rounds, expected",
[
(
False,
+ 0,
[
"00000000-0000-0000-0000-000000000001",
"00000000-0000-0000-0000-000000000002",
@@ -267,11 +268,21 @@ async def test_a_batch_over_the_payload_budget_records_in_chunks_and_starts_one_
],
),
# A later plan that fails stops admission, but the checks that already ran still record.
- (True, ["00000000-0000-0000-0000-000000000001"]),
+ (True, 0, ["00000000-0000-0000-0000-000000000001"]),
+ # Other batches hold every slot at first. The batch waits for one rather than leave its checks to a later tick.
+ (
+ False,
+ 2,
+ [
+ "00000000-0000-0000-0000-000000000001",
+ "00000000-0000-0000-0000-000000000002",
+ "00000000-0000-0000-0000-000000000003",
+ ],
+ ),
],
)
async def test_a_batch_refills_the_slots_its_finished_checks_free(
- environment: WorkflowEnvironment, fail_second_plan: bool, expected: list[str]
+ environment: WorkflowEnvironment, fail_second_plan: bool, pool_full_rounds: int, expected: list[str]
) -> None:
due = [f"00000000-0000-0000-0000-00000000000{n}" for n in range(1, 4)]
plans: list[tuple[str, ...]] = []
@@ -284,6 +295,8 @@ async def test_a_batch_refills_the_slots_its_finished_checks_free(
plans.append(inputs.exclude)
if fail_second_plan and len(plans) == 2:
raise ApplicationError("redis unavailable", non_retryable=True)
+ if len(plans) <= pool_full_rounds:
+ return []
if set(inputs.exclude) - set(evaluated):
return []
return [
diff --git a/products/alerts_platform/backend/temporal/sources.py b/products/alerts_platform/backend/temporal/sources.py
index 7492ab765256..2a939b56ac12 100644
--- a/products/alerts_platform/backend/temporal/sources.py
+++ b/products/alerts_platform/backend/temporal/sources.py
@@ -52,9 +52,9 @@ SOURCE_BINDINGS: dict[SourceKind, SourceBinding] = {
workflow="insight-alert-platform-evaluate",
task_queue=settings.ALERTS_PLATFORM_EVALUATION_TASK_QUEUE,
evaluation_timeout=dt.timedelta(minutes=20),
- # A key holds at least one check and the pool admits this many, so more keys than this
- # only start workflows that find the pool full.
- discovery_limit=settings.ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_EVALUATIONS,
+ # Not the pool size. A check frees its slot in seconds, so the pool turns over many times a
+ # tick, and a limit equal to its size caps checks per minute far below what it can run.
+ discovery_limit=settings.ALERTS_PLATFORM_INSIGHT_KEYS_PER_TICK,
),
SourceKind.BILLING: SourceBinding(
workflow="billing-alert-platform-evaluate",