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(temporal): size the @asyncify thread pool to the worker's activity slots (#101760)

Alessandro Pogliaghi76d95d640b8c
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index 47516b85c79a..f68d86cd432d 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -25,6 +25,10 @@ MAX_CONCURRENT_WORKFLOW_TASKS: int | None = get_from_env(
"MAX_CONCURRENT_WORKFLOW_TASKS", None, optional=True, type_cast=int
)
MAX_CONCURRENT_ACTIVITIES: int | None = get_from_env("MAX_CONCURRENT_ACTIVITIES", None, optional=True, type_cast=int)
+# Caps the @asyncify pool. An asyncify thread can hold a Django connection for its whole call, so the
+# pool is a pgbouncer client-connection multiplier: worker replicas x pool size must stay under the
+# pooler's max_client_conn at its minimum replica count. Raise only with that arithmetic redone.
+ASYNCIFY_MAX_WORKERS: int = get_from_env("ASYNCIFY_MAX_WORKERS", 32, type_cast=int)
TARGET_MEMORY_USAGE: float | None = get_from_env("TARGET_MEMORY_USAGE", None, optional=True, type_cast=float)
TARGET_CPU_USAGE: float | None = get_from_env("TARGET_CPU_USAGE", None, optional=True, type_cast=float)
diff --git a/posthog/temporal/common/utils.py b/posthog/temporal/common/utils.py
index f9a9ce5b47de..8352bb5799da 100644
--- a/posthog/temporal/common/utils.py
+++ b/posthog/temporal/common/utils.py
@@ -2,6 +2,7 @@ import time
import inspect
import threading
from collections.abc import Callable, Coroutine
+from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from functools import wraps
from typing import Any, ParamSpec, TypeVar, cast
@@ -15,6 +16,47 @@ from temporalio import activity, workflow
P = ParamSpec("P")
T = TypeVar("T")
+ASYNCIFY_SLOW_THRESHOLD_SECONDS = 1.0
+
+_asyncify_executor: ThreadPoolExecutor | None = None
+
+
+def configure_asyncify_executor(max_workers: int) -> ThreadPoolExecutor:
+ """Give `@asyncify` activities a thread pool sized to the worker's activity slots.
+
+ Without an explicit executor, ``sync_to_async(thread_sensitive=False)`` runs on the event
+ loop's default executor, which CPython caps at ``min(32, os.cpu_count() + 4)`` threads. That
+ cap is independent of, and usually below, the worker's ``max_concurrent_activities``, so
+ asyncified activities queue for a thread while their slots sit idle. One family of activities
+ blocking on a slow dependency then starves every other activity in the process.
+
+ Call this once at worker startup. Processes that never call it keep the previous behaviour.
+ """
+ global _asyncify_executor
+
+ # Non-daemon threads, so a replaced pool would keep the process alive with nothing to run.
+ if _asyncify_executor is not None:
+ _asyncify_executor.shutdown(wait=False)
+
+ _asyncify_executor = ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix="asyncify")
+ return _asyncify_executor
+
+
+def shutdown_asyncify_executor() -> None:
+ """Release the pool created by `configure_asyncify_executor`, and fall back to the loop default."""
+ global _asyncify_executor
+
+ if _asyncify_executor is None:
+ return
+
+ _asyncify_executor.shutdown(wait=False)
+ _asyncify_executor = None
+
+
+def get_asyncify_executor() -> ThreadPoolExecutor | None:
+ """Return the pool `@asyncify` submits to, or `None` to fall back to the loop's default."""
+ return _asyncify_executor
+
def close_stale_db_connections() -> None:
"""Close expired or errored Postgres connections accumulated by long-lived worker threads.
@@ -87,19 +129,17 @@ def asyncify(fn: Callable[P, T]) -> Callable[P, Coroutine[Any, Any, T]]:
now = time.monotonic()
thread_wait = start_time - submit_time
execution_time = now - start_time
- if activity.in_activity():
+ if activity.in_activity() and max(thread_wait, execution_time) >= ASYNCIFY_SLOW_THRESHOLD_SECONDS:
+ # The structlog chain has no ExtraAdder, so stdlib `extra=` fields never reach the log.
activity.logger.warning(
- "asyncify_slow",
- extra={
- "function": fn.__name__,
- "thread_wait_seconds": round(thread_wait, 3),
- "execution_seconds": round(execution_time, 3),
- "thread_name": threading.current_thread().name,
- "activity_id": activity.info().activity_id,
- },
+ f"asyncify_slow function={fn.__name__} "
+ f"thread_wait_seconds={thread_wait:.3f} execution_seconds={execution_time:.3f} "
+ f"thread_name={threading.current_thread().name}"
)
- return await sync_to_async(thread_sensitive=False)(close_db_connections(instrumented))()
+ return await sync_to_async(thread_sensitive=False, executor=get_asyncify_executor())(
+ close_db_connections(instrumented)
+ )()
return wrapper
diff --git a/posthog/temporal/common/worker.py b/posthog/temporal/common/worker.py
index f89e3e2dd058..34d11f0aaa7d 100644
--- a/posthog/temporal/common/worker.py
+++ b/posthog/temporal/common/worker.py
@@ -33,6 +33,7 @@ from posthog.temporal.common.liveness_tracker import LivenessInterceptor
from posthog.temporal.common.logger import get_write_only_logger
from posthog.temporal.common.posthog_client import PostHogClientInterceptor
from posthog.temporal.common.slo_interceptor import SloInterceptor
+from posthog.temporal.common.utils import configure_asyncify_executor, shutdown_asyncify_executor
from posthog.temporal.data_modeling.metrics import (
DATA_MODELING_LATENCY_HISTOGRAM_BUCKETS,
DATA_MODELING_LATENCY_HISTOGRAM_METRICS,
@@ -185,7 +186,7 @@ ALL_INTERCEPTOR_CLASSES = [
]
-@dataclass
+@dataclass(frozen=False)
class ManagedWorker:
"""A Temporal worker bundled with its associated resources for unified lifecycle management."""
@@ -204,6 +205,10 @@ class ManagedWorker:
await self.worker.shutdown()
if self.metrics_server:
await self.metrics_server.stop()
+ shutdown_asyncify_executor()
+
+
+DEFAULT_MAX_CONCURRENT_TASKS = 50
async def create_worker(
@@ -398,6 +403,11 @@ async def create_worker(
interceptor() for interceptor in ALL_INTERCEPTOR_CLASSES if is_task_queue_supported(task_queue, interceptor)
]
+ # `activity_executor` below only serves sync activity functions, so `@asyncify` coroutines need their own.
+ configure_asyncify_executor(
+ min(max_concurrent_activities or DEFAULT_MAX_CONCURRENT_TASKS, settings.ASYNCIFY_MAX_WORKERS)
+ )
+
if target_memory_usage is not None:
worker = Worker(
client,
@@ -407,12 +417,16 @@ async def create_worker(
workflow_runner=UnsandboxedWorkflowRunner(),
graceful_shutdown_timeout=graceful_shutdown_timeout or dt.timedelta(minutes=5),
interceptors=supported_interceptors,
- activity_executor=ThreadPoolExecutor(max_workers=max_concurrent_activities or 50),
+ activity_executor=ThreadPoolExecutor(max_workers=max_concurrent_activities or DEFAULT_MAX_CONCURRENT_TASKS),
tuner=WorkerTuner.create_resource_based(
target_memory_usage=target_memory_usage,
target_cpu_usage=target_cpu_usage or 1.0,
- workflow_config=ResourceBasedSlotConfig(maximum_slots=max_concurrent_workflow_tasks or 50),
- activity_config=ResourceBasedSlotConfig(maximum_slots=max_concurrent_activities or 50),
+ workflow_config=ResourceBasedSlotConfig(
+ maximum_slots=max_concurrent_workflow_tasks or DEFAULT_MAX_CONCURRENT_TASKS
+ ),
+ activity_config=ResourceBasedSlotConfig(
+ maximum_slots=max_concurrent_activities or DEFAULT_MAX_CONCURRENT_TASKS
+ ),
),
# Worker will flush heartbeats every
# min(heartbeat_timeout * 0.8, max_heartbeat_throttle_interval).
@@ -427,9 +441,9 @@ async def create_worker(
workflow_runner=UnsandboxedWorkflowRunner(),
graceful_shutdown_timeout=graceful_shutdown_timeout or dt.timedelta(minutes=5),
interceptors=supported_interceptors,
- activity_executor=ThreadPoolExecutor(max_workers=max_concurrent_activities or 50),
- max_concurrent_activities=max_concurrent_activities or 50,
- max_concurrent_workflow_tasks=max_concurrent_workflow_tasks or 50,
+ activity_executor=ThreadPoolExecutor(max_workers=max_concurrent_activities or DEFAULT_MAX_CONCURRENT_TASKS),
+ max_concurrent_activities=max_concurrent_activities or DEFAULT_MAX_CONCURRENT_TASKS,
+ max_concurrent_workflow_tasks=max_concurrent_workflow_tasks or DEFAULT_MAX_CONCURRENT_TASKS,
# Worker will flush heartbeats every
# min(heartbeat_timeout * 0.8, max_heartbeat_throttle_interval).
max_heartbeat_throttle_interval=dt.timedelta(seconds=5),
diff --git a/posthog/temporal/tests/test_asyncify.py b/posthog/temporal/tests/test_asyncify.py
new file mode 100644
index 000000000000..e38034b35b4c
--- /dev/null
+++ b/posthog/temporal/tests/test_asyncify.py
@@ -0,0 +1,137 @@
+import asyncio
+import threading
+from collections.abc import Iterator
+from concurrent.futures import ThreadPoolExecutor
+from typing import Protocol
+
+import pytest
+from unittest import mock
+
+from django.conf import settings
+
+from posthog.temporal.common import utils, worker
+from posthog.temporal.common.utils import asyncify, configure_asyncify_executor, get_asyncify_executor
+
+pytestmark = pytest.mark.asyncio
+
+BARRIER_TIMEOUT_SECONDS = 5
+
+
+class ConfigureExecutor(Protocol):
+ def __call__(self, max_workers: int) -> ThreadPoolExecutor: ...
+
+
+def asyncify_executor() -> Iterator[ConfigureExecutor]:
+ previous = get_asyncify_executor()
+ try:
+ yield configure_asyncify_executor
+ finally:
+ configured = get_asyncify_executor()
+ if configured is not previous and configured is not None:
+ configured.shutdown(wait=False)
+ utils._asyncify_executor = previous
+
+
+async def test_asyncify_runs_on_the_configured_executor(asyncify_executor: ConfigureExecutor) -> None:
+ asyncify_executor(2)
+
+ @asyncify
+ def current_thread_name() -> str:
+ return threading.current_thread().name
+
+ assert (await current_thread_name()).startswith("asyncify")
+
+
+async def test_asyncify_runs_as_many_calls_as_the_executor_has_threads(
+ asyncify_executor: ConfigureExecutor,
+) -> None:
+ asyncify_executor(4)
+ barrier = threading.Barrier(4)
+
+ @asyncify
+ def wait_for_the_others() -> int:
+ # Without a timeout a regression parks non-daemon threads here and hangs the interpreter on exit.
+ return barrier.wait(timeout=BARRIER_TIMEOUT_SECONDS)
+
+ results = await asyncio.wait_for(
+ asyncio.gather(*(wait_for_the_others() for _ in range(4))),
+ timeout=BARRIER_TIMEOUT_SECONDS * 2,
+ )
+
+ assert sorted(results) == [0, 1, 2, 3]
+
+
+async def test_asyncify_keeps_unrelated_calls_off_a_saturated_pool(asyncify_executor: ConfigureExecutor) -> None:
+ # Guards the incident: calls blocked on a slow dependency filled the pool and stalled everything else.
+ pool_size = 4
+ occupied = threading.Barrier(pool_size + 1)
+ release = threading.Event()
+
+ asyncify_executor(pool_size + 1)
+
+ @asyncify
+ def block_until_released() -> None:
+ occupied.wait(timeout=BARRIER_TIMEOUT_SECONDS)
+ release.wait(timeout=BARRIER_TIMEOUT_SECONDS)
+
+ @asyncify
+ def unrelated_call() -> str:
+ return "done"
+
+ saturating = [asyncio.create_task(block_until_released()) for _ in range(pool_size)]
+ try:
+ # Clears only once every blocker holds a thread, so the pool is provably saturated below.
+ await asyncio.to_thread(occupied.wait, BARRIER_TIMEOUT_SECONDS)
+ assert await asyncio.wait_for(unrelated_call(), timeout=BARRIER_TIMEOUT_SECONDS) == "done"
+ finally:
+ release.set()
+ await asyncio.gather(*saturating)
+
+
+async def test_asyncify_falls_back_to_the_default_executor() -> None:
+ previous = get_asyncify_executor()
+ utils._asyncify_executor = None
+
+ @asyncify
+ def answer() -> int:
+ return 42
+
+ try:
+ assert await answer() == 42
+ finally:
+ utils._asyncify_executor = previous
+
+
+ "max_concurrent_activities,expected_workers",
+ [
+ (7, 7),
+ (None, settings.ASYNCIFY_MAX_WORKERS),
+ (settings.ASYNCIFY_MAX_WORKERS + 10, settings.ASYNCIFY_MAX_WORKERS),
+ ],
+)
+async def test_create_worker_sizes_the_pool_to_the_activity_slots(
+ asyncify_executor: ConfigureExecutor,
+ max_concurrent_activities: int | None,
+ expected_workers: int,
+) -> None:
+ with (
+ mock.patch.object(worker, "connect", new=mock.AsyncMock()),
+ mock.patch.object(worker, "Worker"),
+ mock.patch.object(worker, "CombinedMetricsServer"),
+ ):
+ await worker.create_worker(
+ host="localhost",
+ port=7233,
+ metrics_port=0,
+ namespace="test",
+ task_queue="test-queue",
+ workflows=[],
+ activities=[],
+ max_concurrent_activities=max_concurrent_activities,
+ )
+
+ configured = get_asyncify_executor()
+ assert configured is not None
+ assert configured._max_workers == expected_workers