: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(data-warehouse): prewarm sources before Granian readiness (#83283)
Bill Guowei Yange6ae3970bc2a
diff --git a/docs/internal/django-startup-time.md b/docs/internal/django-startup-time.mdindex 6ca04381682b..4d0e7440bd21 100644--- a/docs/internal/django-startup-time.md+++ b/docs/internal/django-startup-time.md@@ -196,6 +196,9 @@ If the constant lives in a heavy module (a Temporal destination, an SDK wrapper)Deferring an import does not delete the work; it moves it to first use, and first use may be a live request.The general question to ask of any deferral: _which process pays now, on what path, and is that path latency-sensitive?_Background workers paying lazily is almost always fine; web workers paying on first requests usually is not.+When first use is latency-sensitive, move the cost back deliberately with a targeted, per-process warm-up rather than re-eagering the import for everyone.+The warehouse source catalog (every vendor SDK, lazy via `SourceRegistry`) has two of these: temporal workers whose queues run data-import syncs call `load_all_sources()` at worker boot, and web workers call `posthog/warehouse_source_prewarm.py` at startup (during `posthog.wsgi` module import, inside the boot GC window; during lifespan startup for ASGI), behind `PREWARM_WAREHOUSE_SOURCE_REGISTRY`, which deployment configuration enables only for the dedicated Granian deployment that serves warehouse queries (the shared launcher leaves it off).+Both warm synchronously before the process starts serving; a failed prewarm logs and leaves the worker to the lazy path, and every other process keeps that path.**Pydantic `defer_build` on the generated schema: attempted and reverted.**Generating `posthog.schema` against a `defer_build` base took ~400ms of core-schema construction off every setup, and looked safe — validation, `model_dump`, `model_json_schema`, and `TypeAdapter` all build on demand in round-trip tests.diff --git a/posthog/asgi.py b/posthog/asgi.pyindex 97cd71605544..397ff30b415d 100644--- a/posthog/asgi.py+++ b/posthog/asgi.py@@ -10,6 +10,8 @@ from django.core.asgi import get_asgi_application# Structlog Importimport structlog+from posthog.warehouse_source_prewarm import prewarm_warehouse_source_registry+os.environ["DJANGO_SETTINGS_MODULE"] = "posthog.settings"# Try to ensure SERVER_GATEWAY_INTERFACE is fresh for the child processif "SERVER_GATEWAY_INTERFACE" in os.environ:@@ -113,6 +115,9 @@ def lifetime_wrapper(func):message_type = message.get("type")if message_type == "lifespan.startup":+ # No-op unless PREWARM_WAREHOUSE_SOURCE_REGISTRY is set; never raises,+ # so a broken catalog can't fail startup and trigger a respawn loop.+ prewarm_warehouse_source_registry()await send({"type": "lifespan.startup.complete"})elif message_type == "lifespan.shutdown":await send({"type": "lifespan.shutdown.complete"})diff --git a/posthog/settings/data_warehouse.py b/posthog/settings/data_warehouse.pyindex b3dfd6238ffa..97447d9fece8 100644--- a/posthog/settings/data_warehouse.py+++ b/posthog/settings/data_warehouse.py@@ -33,6 +33,16 @@ USE_LOCAL_SETUP = get_from_env("USE_LOCAL_SETUP", USE_LOCAL_SETUP_DEFAULT, type_PYARROW_DEBUG_LOGGING = get_from_env("PYARROW_DEBUG_LOGGING", False, type_cast=str_to_bool)+# Load the full warehouse source catalog (every vendor SDK) at web-worker startup, before+# the worker starts serving, so its first warehouse query doesn't pay the multi-second+# catalog import at request time. WSGI workers load while importing posthog.wsgi, ASGI+# workers during lifespan startup; a failed prewarm logs and leaves the worker to lazy+# loading. Off by default everywhere, including the shared web launcher: deployment+# config enables it only for the dedicated Granian deployment that serves warehouse+# queries, so web and report workers, shells, migrations, tests, and Celery keep lazy+# source loading.+PREWARM_WAREHOUSE_SOURCE_REGISTRY = get_from_env("PREWARM_WAREHOUSE_SOURCE_REGISTRY", False, type_cast=str_to_bool)+# Region hosting BUCKET_URL. Only used to build the bucket's virtual-hosted hostname for the# egress-proxy bypass in products/data_warehouse/backend/s3_proxy.py; the AWS clients resolve their# own region as before. Falls back to the ambient AWS_REGION, and an empty value leaves the bypassdiff --git a/posthog/settings/logs.py b/posthog/settings/logs.pyindex e02139e4fa5f..be55fbfe95ea 100644--- a/posthog/settings/logs.py+++ b/posthog/settings/logs.py@@ -173,6 +173,10 @@ LOGGING: dict[str, Any] = {},"posthog.auth.mfa": {"level": "INFO", "handlers": ["console"], "propagate": False},"posthog.security.command_exec_audit": {"level": "INFO", "handlers": ["console"], "propagate": False},+ # The posthoganalytics SDK claims the "posthog" logger name and clamps it to WARNING+ # at client init, so the source-registry prewarm's INFO lifecycle logs need an+ # explicit level to be visible.+ "posthog.warehouse_source_prewarm": {"level": "INFO", "handlers": ["console"], "propagate": False},"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load": {"level": "DEBUG","handlers": ["console"],diff --git a/posthog/test/test_asgi_lifespan.py b/posthog/test/test_asgi_lifespan.pyindex d0291aab7bea..2665dae9cd25 100644--- a/posthog/test/test_asgi_lifespan.py+++ b/posthog/test/test_asgi_lifespan.py@@ -2,11 +2,16 @@ import socketimport asyncioimport pytest+from unittest import mock++from django.test import override_settingsimport requestsfrom posthog.asgi import application+from products.warehouse_sources.backend.facade.source_management import SourceRegistry+uvicorn = pytest.importorskip("uvicorn")@@ -99,3 +104,67 @@ async def test_lifespan_events_handled_directly() -> None:await asyncio.sleep(0.1)await taskassert shutdown_completed, "lifespan.shutdown should have been completed"+++class _LifespanDriver:+ # Feeds the application queued server messages and records what it sends back.+ def __init__(self, messages: list[dict]) -> None:+ self.sent: list[dict] = []+ self._incoming: asyncio.Queue[dict] = asyncio.Queue()+ for message in messages:+ self._incoming.put_nowait(message)++ async def _receive(self) -> dict:+ return await self._incoming.get()++ async def _send(self, message: dict) -> None:+ self.sent.append(message)++ async def run(self) -> None:+ # A hang here means the application kept waiting for messages it should not expect.+ await asyncio.wait_for(application({"type": "lifespan"}, self._receive, self._send), timeout=5)+++async def test_lifespan_startup_skips_source_registry_prewarm_when_disabled() -> None:+ driver = _LifespanDriver([{"type": "lifespan.startup"}, {"type": "lifespan.shutdown"}])++ with override_settings(PREWARM_WAREHOUSE_SOURCE_REGISTRY=False):+ with mock.patch.object(SourceRegistry, "get_all_sources") as mock_load:+ await driver.run()++ mock_load.assert_not_called()+ assert driver.sent == [{"type": "lifespan.startup.complete"}, {"type": "lifespan.shutdown.complete"}]+++async def test_lifespan_startup_prewarms_source_registry_before_reporting_ready() -> None:+ driver = _LifespanDriver([{"type": "lifespan.startup"}, {"type": "lifespan.shutdown"}])+ sent_when_load_ran: list[dict] | None = None++ def record_send_state() -> dict:+ nonlocal sent_when_load_ran+ sent_when_load_ran = list(driver.sent)+ return {}++ with override_settings(PREWARM_WAREHOUSE_SOURCE_REGISTRY=True):+ with mock.patch.object(SourceRegistry, "get_all_sources", side_effect=record_send_state) as mock_load:+ await driver.run()++ assert mock_load.call_count == 1+ # Nothing had been sent when the load ran: it finished before lifespan.startup.complete.+ assert sent_when_load_ran == []+ assert driver.sent == [{"type": "lifespan.startup.complete"}, {"type": "lifespan.shutdown.complete"}]+++async def test_lifespan_startup_prewarm_failure_still_reports_startup_complete() -> None:+ driver = _LifespanDriver([{"type": "lifespan.startup"}, {"type": "lifespan.shutdown"}])++ with override_settings(PREWARM_WAREHOUSE_SOURCE_REGISTRY=True):+ with mock.patch.object(SourceRegistry, "get_all_sources", side_effect=RuntimeError("catalog broke")):+ await driver.run()++ # A broken catalog must not fail worker startup (respawn loops); the worker serves+ # cold and the registry's lazy loading retries on first use.+ assert driver.sent == [{"type": "lifespan.startup.complete"}, {"type": "lifespan.shutdown.complete"}]diff --git a/posthog/warehouse_source_prewarm.py b/posthog/warehouse_source_prewarm.pynew file mode 100644index 000000000000..e5208cd5c5d5--- /dev/null+++ b/posthog/warehouse_source_prewarm.py@@ -0,0 +1,37 @@+import time++from django.conf import settings++import structlog++logger = structlog.get_logger(__name__)+++def prewarm_warehouse_source_registry() -> None:+ """Load the full warehouse source catalog (every vendor SDK) at web-worker startup so+ the worker's first warehouse query doesn't pay the multi-second import at request time.++ Gated by PREWARM_WAREHOUSE_SOURCE_REGISTRY and best-effort by design: on failure the+ worker starts cold and the registry's lazy loading retries on first use (its loaded+ flag flips only on success). A broken catalog must not fail startup of a web tier+ that mostly serves non-warehouse traffic, especially with worker respawning on.+ """+ if not settings.PREWARM_WAREHOUSE_SOURCE_REGISTRY:+ return++ logger.info("warehouse_source_registry_prewarm_started")+ start = time.monotonic()+ try:+ from products.warehouse_sources.backend.facade.source_management import ( # noqa: PLC0415 — keeps the source catalog's vendor SDKs off startup for processes that don't opt in+ SourceRegistry,+ )++ sources = SourceRegistry.get_all_sources()+ except Exception:+ logger.exception("warehouse_source_registry_prewarm_failed")+ return+ logger.info(+ "warehouse_source_registry_prewarm_completed",+ elapsed_ms=round((time.monotonic() - start) * 1000),+ source_count=len(sources),+ )diff --git a/posthog/wsgi.py b/posthog/wsgi.pyindex 76bc44dc4ca4..ebde2d35e2f6 100644--- a/posthog/wsgi.py+++ b/posthog/wsgi.py@@ -17,6 +17,7 @@ import structlogfrom posthog.caching.redis_cluster_connection_factory import prewarm_query_cache_cluster_in_backgroundfrom posthog.continuous_profiling import start_continuous_profilingfrom posthog.otel_instrumentation import initialize_otel+from posthog.warehouse_source_prewarm import prewarm_warehouse_source_registryfrom posthog.web_memory_probe import install_memory_probe_handlerfrom posthog.web_memory_sampler import start_web_memory_sampler@@ -44,6 +45,14 @@ try:from django.urls import get_resolver_ = get_resolver().url_patterns # property access triggers the build++ # Load the warehouse source catalog before this worker serves, so its first warehouse+ # query skips the multi-second import. No-op unless PREWARM_WAREHOUSE_SOURCE_REGISTRY+ # is set, which deployment config enables only for the Granian deployment that serves+ # warehouse queries; each Granian worker imports this module itself. Running inside+ # the GC window lands the catalog in the frozen heap, so future full collections+ # skip it.+ prewarm_warehouse_source_registry()finally:gc.freeze()gc.enable()