: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
chore: remove nginx unit (#94467)
Raúl Negrón-Oterob994d420f9aa
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex 40d54754de79..786a3a8c1859 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -351,7 +351,6 @@ jobs:- bin/build-taxonomy-json.py- bin/check_uv_python_compatibility.py- bin/find_python_dependencies.py- - bin/unit_metrics.py- pyproject.toml- uv.lock- requirements.txt@@ -431,7 +430,6 @@ jobs:- bin/build-taxonomy-json.py- bin/check_uv_python_compatibility.py- bin/find_python_dependencies.py- - bin/unit_metrics.py- pyproject.toml- uv.lock- requirements.txtdiff --git a/.dockerignore b/.dockerignoreindex c31755ed29a3..dfb7ce59bc82 100644--- a/.dockerignore+++ b/.dockerignore@@ -77,7 +77,6 @@ services/agent-*/.next!tools/openapi-codegen!tools/owners!tsconfig.json-!unit.json.tplcommon/*/*/node_modulescommon/*/node_modulescommon/*/*/distdiff --git a/.github/scripts/trunk-impacted-targets.js b/.github/scripts/trunk-impacted-targets.jsindex b9f926a37d13..3dc038420ae1 100644--- a/.github/scripts/trunk-impacted-targets.js+++ b/.github/scripts/trunk-impacted-targets.js@@ -550,9 +550,6 @@ const TRIPWIRE_RULES = [['manage.py', PYTHON],['pytest_boot_gc.py', PYTHON],['dagster_cloud.yaml', PYTHON],- // Serves the Django app in the production image, so the module paths it- // names are the ones a Python change can rename out from under it.- ['unit.json.tpl', PYTHON],// The pnpm workspace's lockfile and manifests. A resolution change here can// red the python lanes, which install the root package and drive pytest@@ -688,7 +685,6 @@ const TRIPWIRE_RULES = [['bin/posthog-node', APP_IMAGE],['bin/temporal-django-worker', APP_IMAGE],['bin/granian_metrics.py', APP_IMAGE],- ['bin/unit_metrics.py', APP_IMAGE],['bin/start-backend', APP_IMAGE],['bin/start-frontend', APP_IMAGE],// The schema and taxonomy codegen pipeline, which turnsdiff --git a/.github/scripts/trunk-impacted-targets.test.js b/.github/scripts/trunk-impacted-targets.test.jsindex 6903fd7d87d6..f1984879ea4e 100644--- a/.github/scripts/trunk-impacted-targets.test.js+++ b/.github/scripts/trunk-impacted-targets.test.js@@ -444,7 +444,7 @@ test('single-language root configuration claims that language', () => {assert.deepEqual(computeTargets([file], CONTEXT), javascript, file)}const python = computeTargets(['mypy.ini'], CONTEXT)- for (const file of ['manage.py', 'pytest_boot_gc.py', 'dagster_cloud.yaml', 'unit.json.tpl']) {+ for (const file of ['manage.py', 'pytest_boot_gc.py', 'dagster_cloud.yaml']) {assert.deepEqual(computeTargets([file], CONTEXT), python, file)}})diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex d94ecfce44a4..89262048a8a5 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -203,7 +203,6 @@ jobs:- bin/build-taxonomy-json.py- bin/check_uv_python_compatibility.py- bin/find_python_dependencies.py- - bin/unit_metrics.py- pyproject.toml- uv.lock- requirements.txt@@ -283,7 +282,6 @@ jobs:- bin/build-taxonomy-json.py- bin/check_uv_python_compatibility.py- bin/find_python_dependencies.py- - bin/unit_metrics.py- pyproject.toml- uv.lock- requirements.txtdiff --git a/.github/workflows/ci-hobby.yml b/.github/workflows/ci-hobby.ymlindex ebbe853087f0..ad85e4ff9963 100644--- a/.github/workflows/ci-hobby.yml+++ b/.github/workflows/ci-hobby.yml@@ -75,7 +75,6 @@ jobs:- 'bin/docker-worker-beat'- 'bin/docker-worker-celery'- 'bin/docker-server'- - 'bin/docker-server-unit'- 'bin/celery-queues.env'- 'bin/migrate'- 'bin/migrate-check'diff --git a/.github/workflows/container-images-ci.yml b/.github/workflows/container-images-ci.ymlindex d8885055ac55..e0f25e49eaf3 100644--- a/.github/workflows/container-images-ci.yml+++ b/.github/workflows/container-images-ci.yml@@ -71,7 +71,6 @@ jobs:- 'bin/docker-worker-beat'- 'bin/docker-worker-celery'- 'bin/docker-server'- - 'bin/docker-server-unit'- 'bin/celery-queues.env'- 'bin/migrate'- 'bin/migrate-check'diff --git a/Dockerfile b/Dockerfileindex 9f0c9fd7117e..2ff1dfa3fea3 100644--- a/Dockerfile+++ b/Dockerfile@@ -272,56 +272,15 @@ RUN apt-get update && \## ---------------------------------------------------------#-# NOTE: v1.32 is running bullseye, v1.33+ is running bookworm-FROM unit:1.34.2-python3.13+FROM python:3.13.13-bookworm@sha256:0544e35a04d3d3272a5e180a402065bfa84402bf39431a727f8989e32ffce979WORKDIR /codeSHELL ["/bin/bash", "-e", "-o", "pipefail", "-c"]ENV PYTHONUNBUFFERED 1-# Unit embeds libpython instead of launching the python3 CLI, so PEP 538 C-locale+# Granian embeds libpython instead of launching the python3 CLI, so PEP 538 C-locale# coercion never runs and open() defaults to ASCII under the container's bare locale.# Force UTF-8 so file reads with non-ASCII bytes don't raise UnicodeDecodeError.ENV PYTHONUTF8 1ENV LANG C.UTF-8-ARG UNIT_GIT_TAG=1.35.0-ARG UNIT_GIT_REF=28404105810f53c570523c3e70006ad0ca210e58--# Build Unit from the upstream 1.35.0 release ref to ensure the Django 5 ASGI fix is present even when Docker tags lag.-RUN apt-get update && \- apt-get install -y --no-install-recommends \- "build-essential" \- "git" \- "libpcre2-dev" \- "zlib1g-dev" \- && \- git clone --depth 1 --branch "$UNIT_GIT_TAG" https://github.com/nginx/unit.git /tmp/unit && \- cd /tmp/unit && \- test "$(git rev-parse HEAD)" = "$UNIT_GIT_REF" && \- NCPU="$(getconf _NPROCESSORS_ONLN)" && \- DEB_HOST_MULTIARCH="$(gcc -print-multiarch)" && \- CONFIGURE_ARGS="--prefix=/usr \- --statedir=/var/lib/unit \- --control=unix:/var/run/control.unit.sock \- --runstatedir=/var/run \- --pid=/var/run/unit.pid \- --logdir=/var/log \- --log=/var/log/unit.log \- --tmpdir=/var/tmp \- --user=unit \- --group=unit \- --openssl \- --libdir=/usr/lib/$DEB_HOST_MULTIARCH \- --modulesdir=/usr/lib/unit/modules" && \- ./configure $CONFIGURE_ARGS && \- make -j "$NCPU" unitd && \- install -pm755 build/sbin/unitd /usr/sbin/unitd && \- make clean && \- ./configure $CONFIGURE_ARGS && \- ./configure python --config=/usr/local/bin/python3-config && \- make -j "$NCPU" python3-install && \- rm -rf /tmp/unit && \- apt-get purge -y --auto-remove "build-essential" "git" "libpcre2-dev" "zlib1g-dev" && \- rm -rf /var/lib/apt/lists/*-# Install OS runtime dependencies.# Note: please add in this stage runtime dependences only!# Runtime-only shared libs: lxml/xmlsec are compiled --no-binary in the build stage (which keeps@@ -329,7 +288,6 @@ RUN apt-get update && \# libxmlsec1-openssl provides the OpenSSL crypto backend that libxmlsec1-dev used to pull in.RUN apt-get update && \apt-get install -y --no-install-recommends --allow-downgrades \- "gettext-base" \"git" \"libpq5" \"libxmlsec1=1.2.37-2" \@@ -469,7 +427,7 @@ EXPOSE 8000# Expose the port from which we serve OpenMetrics data.EXPOSE 8001-COPY unit.json.tpl /docker-entrypoint.d/unit.json.tpl+# Root is needed only so bin/docker-server can drop the app to nobody with setpriv.# nosemgrep: dockerfile.security.last-user-is-root.last-user-is-rootUSER rootCMD ["./bin/docker"]diff --git a/bin/docker-server b/bin/docker-serverindex 96b5ef660bf8..acbe6ed3755c 100755--- a/bin/docker-server+++ b/bin/docker-server@@ -1,4 +1,53 @@#!/bin/bash-# Wrapper script for backward compatibility-# Calls the Nginx Unit server script-exec "$(dirname "$0")/docker-server-unit" "$@"+set -e++./bin/migrate-check++# prometheus_client needs a shared directory to aggregate metrics across workers.+export PROMETHEUS_MULTIPROC_DIR=$(mktemp -d)+chmod -R 777 $PROMETHEUS_MULTIPROC_DIR++export PROMETHEUS_METRICS_EXPORT_PORT=8001+export STATSD_PORT=${STATSD_PORT:-8125}++# The granian CLI reads every GRANIAN_* var natively, so these only set the+# defaults that differ from granian's own.++# asgi serves posthog.asgi:application, wsgi serves posthog.wsgi:application+export GRANIAN_INTERFACE=${GRANIAN_INTERFACE:-asgi}+export GRANIAN_HOST=${GRANIAN_HOST:-0.0.0.0}+# Under ASGI a sync view holds its worker for the whole request+# (thread_sensitive=True), so concurrency comes only from adding workers. Under+# WSGI it comes from the blocking thread pool, steered by+# GRANIAN_BACKPRESSURE/GRANIAN_BLOCKING_THREADS.+export GRANIAN_WORKERS=${GRANIAN_WORKERS:-4}+export GRANIAN_LOG_LEVEL=${GRANIAN_LOG_LEVEL:-warning}+export GRANIAN_LOG_ACCESS_ENABLED=${GRANIAN_LOG_ACCESS_ENABLED:-true}+export GRANIAN_RESPAWN_FAILED_WORKERS=${GRANIAN_RESPAWN_FAILED_WORKERS:-true}++# Granian's native Prometheus exporter (worker spawns/respawns, blocking+# pool utilization and queue depth, connections, GIL wait). Binds+# loopback-only (granian's default address); bin/granian_metrics.py merges+# its output into the port-8001 scrape response, so no extra scrape target+# is needed.+export GRANIAN_METRICS_ENABLED=${GRANIAN_METRICS_ENABLED:-true}+export GRANIAN_METRICS_PORT=${GRANIAN_METRICS_PORT:-9090}++if [ "$GRANIAN_INTERFACE" = "wsgi" ]; then+ APP_TARGET="posthog.wsgi:application"+else+ APP_TARGET="posthog.asgi:application"+ # uvloop drives the Python asyncio loop; WSGI has none.+ export GRANIAN_LOOP=${GRANIAN_LOOP:-uvloop}+fi++# The container runs as root, so drop the application itself to an unprivileged+# user. PROMETHEUS_MULTIPROC_DIR is world-writable and the ports are >1024.+DROP_PRIVILEGES="setpriv --reuid=nobody --regid=nogroup --clear-groups"++$DROP_PRIVILEGES python ./bin/granian_metrics.py &+METRICS_PID=$!++trap 'kill $METRICS_PID 2>/dev/null; rm -rf "$PROMETHEUS_MULTIPROC_DIR"' EXIT++exec $DROP_PRIVILEGES granian "$APP_TARGET"diff --git a/bin/docker-server-unit b/bin/docker-server-unitdeleted file mode 100755index 044a23039753..000000000000--- a/bin/docker-server-unit+++ /dev/null@@ -1,102 +0,0 @@-#!/bin/bash-set -e--./bin/migrate-check--# To ensure we are able to expose metrics from multiple processes, we need to-# provide a directory for `prometheus_client` to store a shared registry.-export PROMETHEUS_MULTIPROC_DIR=$(mktemp -d)-chmod -R 777 $PROMETHEUS_MULTIPROC_DIR--export PROMETHEUS_METRICS_EXPORT_PORT=8001-export STATSD_PORT=${STATSD_PORT:-8125}--# Dual-mode support: USE_GRANIAN env var switches between Granian and Unit (default)-if [ "${USE_GRANIAN:-false}" = "true" ]; then- # Granian config is env-only and uses granian's own documented GRANIAN_*- # env vars (the CLI reads them natively) — no aliases, no flag plumbing.- # The exports below only set PostHog defaults where they differ from- # granian's own; any deployment-provided GRANIAN_* var applies directly.-- # asgi serves posthog.asgi:application, wsgi serves posthog.wsgi:application- export GRANIAN_INTERFACE=${GRANIAN_INTERFACE:-asgi}- export GRANIAN_HOST=${GRANIAN_HOST:-0.0.0.0}- # Match Unit's 4 workers for equivalent sync view concurrency.- # ASGI + sync views (thread_sensitive=True): each worker handles one sync- # request at a time — only workers give concurrency. WSGI: per-worker- # concurrency comes from the blocking thread pool instead; steer it via- # GRANIAN_BACKPRESSURE/GRANIAN_BLOCKING_THREADS rather than more workers.- export GRANIAN_WORKERS=${GRANIAN_WORKERS:-4}- export GRANIAN_LOG_LEVEL=${GRANIAN_LOG_LEVEL:-warning}- export GRANIAN_LOG_ACCESS_ENABLED=${GRANIAN_LOG_ACCESS_ENABLED:-true}- export GRANIAN_RESPAWN_FAILED_WORKERS=${GRANIAN_RESPAWN_FAILED_WORKERS:-true}-- # Granian's native Prometheus exporter (worker spawns/respawns, blocking- # pool utilization and queue depth, connections, GIL wait). Binds- # loopback-only (granian's default address); bin/granian_metrics.py merges- # its output into the port-8001 scrape response, so no extra scrape target- # is needed.- export GRANIAN_METRICS_ENABLED=${GRANIAN_METRICS_ENABLED:-true}- export GRANIAN_METRICS_PORT=${GRANIAN_METRICS_PORT:-9090}-- if [ "$GRANIAN_INTERFACE" = "wsgi" ]; then- APP_TARGET="posthog.wsgi:application"- else- APP_TARGET="posthog.asgi:application"- # uvloop drives the Python asyncio loop; WSGI has none.- export GRANIAN_LOOP=${GRANIAN_LOOP:-uvloop}- fi-- echo "🚀 Starting with Granian ${GRANIAN_INTERFACE} server (opt-in via USE_GRANIAN=true)..."-- # The container runs as root (Unit needs it for its control socket), but the- # application must not: Unit drops its app processes to nobody via- # unit.json.tpl, so this branch drops privileges the same way before exec.- # PROMETHEUS_MULTIPROC_DIR is world-writable above, ports are >1024.- DROP_PRIVILEGES="setpriv --reuid=nobody --regid=nogroup --clear-groups"-- # Start metrics HTTP server in background on port 8001- $DROP_PRIVILEGES python ./bin/granian_metrics.py &- METRICS_PID=$!-- # Combined trap: kill metrics server and cleanup temp directory- trap 'kill $METRICS_PID 2>/dev/null; rm -rf "$PROMETHEUS_MULTIPROC_DIR"' EXIT-- exec $DROP_PRIVILEGES granian "$APP_TARGET"-else- echo "🔧 Starting with Nginx Unit server (default, stable)..."-- export NGINX_UNIT_PYTHON_PROTOCOL=${NGINX_UNIT_PYTHON_PROTOCOL:-wsgi}- export NGINX_UNIT_APP_PROCESSES=${NGINX_UNIT_APP_PROCESSES:-4}- export NGINX_UNIT_REQUEST_LIMIT=${NGINX_UNIT_REQUEST_LIMIT:-7500}-- if [ "${NGINX_UNIT_PRELOAD_CONFIG:-false}" = "true" ]; then- # Cleanup temp directories on exit- trap 'rm -rf "$PROMETHEUS_MULTIPROC_DIR" "$UNIT_STATEDIR"' EXIT-- # Pre-bake the Unit configuration into a state directory so unitd starts- # with config already loaded. This avoids the docker-entrypoint.sh pattern- # of: start unitd → apply config via API (loading all workers) → stop unitd- # → restart unitd (loading all workers again). That double-start means every- # worker process loads the full Django app twice on each pod startup.- UNIT_STATEDIR=$(mktemp -d)- envsubst < /docker-entrypoint.d/unit.json.tpl > "$UNIT_STATEDIR/conf.json"- chmod -R 700 "$UNIT_STATEDIR"- else- # Cleanup temp directory on exit- trap 'rm -rf "$PROMETHEUS_MULTIPROC_DIR"' EXIT-- envsubst < /docker-entrypoint.d/unit.json.tpl > /docker-entrypoint.d/unit.json- fi-- # We need to run as root so that nginx unit can proxy the control socket for stats- # However each application is run as "nobody"- if [ "${NGINX_UNIT_PRELOAD_CONFIG:-false}" = "true" ]; then- # nosemgrep: trailofbits.generic.container-user-root.container-user-root- exec unitd --no-daemon --user root --statedir "$UNIT_STATEDIR" \- --control unix:/var/run/control.unit.sock- else- # nosemgrep: trailofbits.generic.container-user-root.container-user-root- exec /usr/local/bin/docker-entrypoint.sh unitd --no-daemon --user root- fi-fidiff --git a/bin/unit_metrics.py b/bin/unit_metrics.pydeleted file mode 100644index 445be6aa5b02..000000000000--- a/bin/unit_metrics.py+++ /dev/null@@ -1,88 +0,0 @@-import json-import time-import logging-import http.client--from prometheus_client import CollectorRegistry, Gauge, generate_latest, multiprocess--logger = logging.getLogger(__name__)--UNIT_CONNECTIONS_ACCEPTED_TOTAL = Gauge(- "unit_connections_accepted_total",- "",- multiprocess_mode="livesum",-)-UNIT_CONNECTIONS_ACTIVE = Gauge(- "unit_connections_active",- "",- multiprocess_mode="livesum",-)-UNIT_CONNECTIONS_CLOSED = Gauge(- "unit_connections_closed",- "",- multiprocess_mode="livesum",-)-UNIT_CONNECTIONS_IDLE = Gauge(- "unit_connections_idle",- "",- multiprocess_mode="livesum",-)-UNIT_CONNECTIONS_TOTAL = Gauge(- "unit_requests_total",- "",- multiprocess_mode="livesum",-)-UNIT_PROCESSES_RUNNING_GAUGE = Gauge(- "unit_application_processes_running", "", multiprocess_mode="livesum", labelnames=["application"]-)-UNIT_PROCESSES_STARTING_GAUGE = Gauge(- "unit_application_processes_starting", "", multiprocess_mode="livesum", labelnames=["application"]-)-UNIT_PROCESSES_IDLE_GAUGE = Gauge(- "unit_application_processes_idle", "", multiprocess_mode="livesum", labelnames=["application"]-)-UNIT_REQUESTS_ACTIVE_GAUGE = Gauge(- "unit_application_requests_active", "", multiprocess_mode="livesum", labelnames=["application"]-)---def application(environ, start_response):- retries = 5- try:- connection = http.client.HTTPConnection("localhost:8181")- connection.request("GET", "/status")- response = connection.getresponse()-- statj = json.loads(response.read())- except Exception:- if retries > 0:- retries -= 1- time.sleep(1)- return application(environ, start_response)- else:- raise- finally:- try:- connection.close()- except Exception as e:- logger.exception("Failed to close connection to unit: ", e)-- UNIT_CONNECTIONS_ACCEPTED_TOTAL.set(statj["connections"]["accepted"])- UNIT_CONNECTIONS_ACTIVE.set(statj["connections"]["active"])- UNIT_CONNECTIONS_IDLE.set(statj["connections"]["idle"])- UNIT_CONNECTIONS_CLOSED.set(statj["connections"]["closed"])- UNIT_CONNECTIONS_TOTAL.set(statj["requests"]["total"])-- for app in statj["applications"].keys():- UNIT_PROCESSES_RUNNING_GAUGE.labels(application=app).set(statj["applications"][app]["processes"]["running"])- UNIT_PROCESSES_STARTING_GAUGE.labels(application=app).set(statj["applications"][app]["processes"]["starting"])- UNIT_PROCESSES_IDLE_GAUGE.labels(application=app).set(statj["applications"][app]["processes"]["idle"])- UNIT_REQUESTS_ACTIVE_GAUGE.labels(application=app).set(statj["applications"][app]["requests"]["active"])-- start_response("200 OK", [("Content-Type", "text/plain")])- # Create the prometheus multi-process metric registry here- # This will aggregate metrics we send from the Django app- # We prepend our unit metrics here.- registry = CollectorRegistry()- multiprocess.MultiProcessCollector(registry)- yield generate_latest(registry)diff --git a/docker-compose.dev-full.yml b/docker-compose.dev-full.ymlindex c0c6b6b10a06..ba7311101f0c 100644--- a/docker-compose.dev-full.yml+++ b/docker-compose.dev-full.yml@@ -127,7 +127,7 @@ services:ports:- 8000:8000build: .- command: ./bin/docker-server-unit+ command: ./bin/docker-servervolumes:- .:/app/posthogenvironment:diff --git a/docs/internal/django-startup-time.md b/docs/internal/django-startup-time.mdindex 0204b6cfdeba..fb9c6700780c 100644--- a/docs/internal/django-startup-time.md+++ b/docs/internal/django-startup-time.md@@ -24,7 +24,7 @@ Real submodules (`posthog.api.monitoring`, `.file_system`, …) resolve directlyThis is the laziness Django already intends: the URLconf is the entry point, and non-web processes never resolve it.Web is the exception and resolves it eagerly: `wsgi.py`/`asgi.py` build the URLconf at import, pre-fork, inside the GC window — because the k8s probes (`/_livez`, `/_readyz`) are served by short-circuiting middleware and never resolve URLs, each worker would otherwise build the router on its **first live request** (measured at multiple seconds per worker, after every deploy).-Pre-building lands the router in the frozen heap, copy-on-write-shared across workers — exactly the pre-lazy-router behavior for web, while every other process keeps the win.+Pre-building lands the router in the frozen heap at worker boot — exactly the pre-lazy-router behavior for web, while every other process keeps the win.`test_web_entrypoint_prebuilds_the_router` pins this; a prefork smoke (gunicorn `--preload`, 4 workers) verified workers inherit the built router and serve cold requests without it.### 2. Model registration@@ -43,7 +43,7 @@ Wire receivers from the owning app's `AppConfig.ready()` instead, so they connecBoot allocations are almost all permanent — modules, classes, registries, the generated pydantic schema — so the cyclic GC has nothing useful to reclaim while `django.setup()` runs, yet allocation thresholds trigger ~470 collections during it (~300ms of pauses, single gen2 passes up to ~100ms).The entrypoints that own a setup (`manage.py`, `posthog/wsgi.py`, `posthog/asgi.py`) wrap it in `gc.disable()` → boot → `gc.freeze()` → `gc.enable()`.-The freeze moves the ~600k surviving boot objects to the permanent generation, so they are excluded from every future full collection — which also makes post-boot work (management-command discovery, the first router build) collect almost for free, and maximizes copy-on-write page sharing when a prototype process forks workers.+The freeze moves the ~600k surviving boot objects to the permanent generation, so they are excluded from every future full collection — which also makes post-boot work (management-command discovery, the first router build) collect almost for free.There is deliberately no `gc.collect()` before the freeze: a full pass over the boot heap costs ~210ms and reclaims only ~4% of objects (a few MB), so the garbage is frozen along with everything else.The window must always close — GC left disabled in a long-lived process means unbounded cycle growth — hence the `try`/`finally` and the guard test asserting `gc.isenabled()` and a nonzero freeze count after a `manage.py` boot.Pytest processes get the same window via a dedicated early-loaded plugin, `pytest_boot_gc.py`, registered with `-p pytest_boot_gc` in `pytest.ini`.diff --git a/hogli.yaml b/hogli.yamlindex 9b0eb8a12348..e2ed731735b0 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -635,11 +635,7 @@ docker:hidden: truedocker:server:bin_script: docker-server- description: Run dual-mode server (Granian/Unit) with Prometheus metrics support- hidden: true- docker:server-unit:- bin_script: docker-server-unit- description: Run NGINX Unit application server with configurable workers+ description: Run the Granian application server with Prometheus metrics supporthidden: truedocker:worker-beat:bin_script: docker-worker-beat@@ -971,11 +967,6 @@ tools:tool:turbo:bin_script: turbodescription: Turborepo wrapper with automatic dependency installation- tool:unit-metrics:- bin_script: unit_metrics.py- description: WSGI app that aggregates Prometheus metrics from NGINX Unit status- endpoint- hidden: truetool:create-ch-migration:cmd: python manage.py create_ch_migrationdescription: Generate new ClickHouse migration scaffolddiff --git a/posthog/asgi.py b/posthog/asgi.pyindex 93a7980694db..eed0080d70d9 100644--- a/posthog/asgi.py+++ b/posthog/asgi.py@@ -24,12 +24,10 @@ logger = structlog.get_logger(__name__)# NOTE: OTel, continuous profiling, and the web-memory sampler init are deferred to first# request via _ensure_post_fork_init() below. They start background threads (OTel's# BatchSpanProcessor, Pyroscope's native profiler, the sampler's loop) that cannot survive-# fork(). Nginx Unit loads this module in a "prototype" process and then-# forks workers from it — the forked children inherit dead thread state and-# corrupted mutexes, causing SIGSEGV / SIGABRT on the worker. Deferring to-# first request ensures threads start in the actual worker process.-# This is safe across all server types: Granian uses spawn (not fork),-# runserver is single-process, and Celery doesn't import this file.+# fork(): a child inherits dead thread state and corrupted mutexes, causing SIGSEGV /+# SIGABRT on the worker. Deferring to first request ensures threads start in the actual+# worker process. This is safe across all server types: runserver is single-process,+# and Celery doesn't import this file._post_fork_initialized = False_LOOP_LAG_HEARTBEAT_SECONDS = 1.0@@ -169,8 +167,7 @@ def task_run_event_ingest_wrapper(func):# Boot allocations are almost all permanent, so cyclic GC during django.setup() only adds# pauses (~300ms). Disable it for the boot, then freeze the survivors so later full-# collections skip them — which also maximizes copy-on-write sharing when a prototype-# process forks workers. See docs/internal/django-startup-time.md.+# collections skip them. See docs/internal/django-startup-time.md.gc.disable()try:application = lifetime_wrapper(self_capture_wrapper(task_run_event_ingest_wrapper(get_asgi_application())))diff --git a/posthog/test/test_web_memory_sampler.py b/posthog/test/test_web_memory_sampler.pyindex c80846b07493..01b03f03d652 100644--- a/posthog/test/test_web_memory_sampler.py+++ b/posthog/test/test_web_memory_sampler.py@@ -49,9 +49,8 @@ def test_sampler_disabled_starts_no_thread(monkeypatch):def test_sampler_rearms_when_guard_inherited_from_another_process(monkeypatch):- # Unit forks workers from a prototype, so the once-flag is copy-on-write-inherited with- # the prototype's pid. A worker must re-arm on its own pid and start the thread, not see- # the inherited value and skip — a plain bool guard here would silently sample nothing.+ # A worker that inherits the once-flag must re-arm on its own pid and start the thread,+ # not see the inherited value and skip. A plain bool guard would silently sample nothing.started_threads = []class _RecordingThread:@@ -87,7 +86,7 @@ def test_sample_once_records_gauge_and_log_only_when_rss_available(mock.patch.object(sampler.WORKER_RSS_MB, "set", lambda value: gauge_sets.append(value)),capture_logs() as log_events,):- sampler._sample_once(structlog.get_logger("test"), "pod-1", "7500")+ sampler._sample_once(structlog.get_logger("test"), "pod-1", "2560")assert gauge_sets == expected_gauge_setsassert len(log_events) == expected_log_countdiff --git a/posthog/urls.py b/posthog/urls.pyindex 6378e58831fb..5a85b290ab32 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -768,8 +768,8 @@ if settings.CLOUD_DEPLOYMENT == "EU":if settings.DEBUG:# If we have DEBUG=1 set, then let's expose the metrics for debugging. Note# that in production we expose these metrics on a separate port (8001), to ensure- # external clients cannot see them. See bin/granian_metrics.py and bin/unit_metrics.py- # for details on the production metrics setup.+ # external clients cannot see them. See bin/granian_metrics.py for details on the+ # production metrics setup.# Use multiprocess mode to collect metrics from all processes (Django + Celery workers)import osdiff --git a/posthog/web_memory_probe.py b/posthog/web_memory_probe.pyindex 96b5799a4d04..5dbbde718bb3 100644--- a/posthog/web_memory_probe.py+++ b/posthog/web_memory_probe.py@@ -140,11 +140,10 @@ def _handle_probe(signum: int, frame: FrameType | None) -> None:def install_memory_probe_handler() -> None:"""Register the SIGUSR2 memory-probe handler, gated by WEB_MEMORY_PROBE_ENABLED.- MUST be called post-fork from inside each worker (see posthog/asgi.py and posthog/wsgi.py):- signal handlers can only be registered from the main thread, and the handler has to live- in the worker that serves requests, not the idle Nginx Unit prototype the workers fork- from. Registering post-fork also means it isn't clobbered by any signal reset Unit does- during worker init.+ MUST be called from inside each worker (see posthog/asgi.py and posthog/wsgi.py): signal+ handlers can only be registered from the main thread, and the handler has to live in the+ process that serves requests. Registering it there also keeps it clear of any signal reset+ the server does during worker init.Inert until armed: with the flag unset (default) nothing is registered at all, and evenwhen armed the handler does nothing until a SIGUSR2 actually arrives. So the safe way todiff --git a/posthog/web_memory_sampler.py b/posthog/web_memory_sampler.pyindex e71a95022606..fd4d2025c573 100644--- a/posthog/web_memory_sampler.py+++ b/posthog/web_memory_sampler.py@@ -10,10 +10,10 @@ logger = logging.getLogger(__name__)DEFAULT_SAMPLE_INTERVAL_SECONDS = 30.0-# Web-worker RSS, scraped via bin/unit_metrics.py's MultiProcessCollector. `livemax`+# Web-worker RSS, scraped via bin/granian_metrics.py's MultiProcessCollector. `livemax`# reports the maximum across live workers as a single series, so the worker nearest the# cgroup limit is visible without the per-pid cardinality — and stale-series-on-recycle,-# since a request-limited or OOM-killed worker never calls `mark_process_dead` — that+# since a recycled or OOM-killed worker never calls `mark_process_dead` — that# `liveall` would accumulate. Per-worker detail lives in the `worker_memory` log line.WORKER_RSS_MB = Gauge("posthog_web_worker_rss_mb",@@ -37,7 +37,7 @@ def current_rss_mb() -> float | None:return resident_pages * os.sysconf("SC_PAGE_SIZE") / (1024 * 1024)-def _sample_once(log: structlog.BoundLogger, pod: str | None, request_limit: str | None) -> None:+def _sample_once(log: structlog.BoundLogger, pod: str | None, max_rss_mb: str | None) -> None:rss_mb = current_rss_mb()if rss_mb is None:return@@ -47,18 +47,18 @@ def _sample_once(log: structlog.BoundLogger, pod: str | None, request_limit: str"worker_memory",rss_mb=rss_mb_rounded,pod=pod,- request_limit=request_limit,+ max_rss_mb=max_rss_mb,)def _sample_loop(interval_seconds: float) -> None:log = structlog.get_logger("posthog.web_memory_sampler")pod = os.getenv("K8S_POD_NAME") or os.getenv("HOSTNAME")- request_limit = os.getenv("NGINX_UNIT_REQUEST_LIMIT")+ max_rss_mb = os.getenv("GRANIAN_WORKERS_MAX_RSS")while True:time.sleep(interval_seconds)try:- _sample_once(log, pod, request_limit)+ _sample_once(log, pod, max_rss_mb)except Exception:logger.exception("web memory sample failed")@@ -69,11 +69,9 @@ def start_web_memory_sampler() -> None:gradual climb toward the cgroup limit that precedes an OOM kill is visible in bothmetrics and PostHog logs rather than only on infra dashboards.- MUST be called post-fork, from inside each worker (see posthog/wsgi.py). Nginx Unit- forks workers from a prototype process that imported this module, and a thread started- in the prototype does not survive the fork — an import-time start would only ever- sample the idle prototype, never the workers that serve requests. The pid guard re-arms- per process because the once-flag is copy-on-write-inherited from the prototype.+ MUST be called from inside each worker (see posthog/wsgi.py), because threads do not+ survive a fork and the idle process that started one is not the one serving requests.+ The pid guard re-arms per process so an inherited once-flag cannot suppress the start.Interval is set by WEB_MEMORY_SAMPLE_INTERVAL_SECONDS (default 30); set it to 0 or lessto disable. Best-effort and idempotent — never breaks startup."""diff --git a/posthog/wsgi.py b/posthog/wsgi.pyindex ea42fdde9943..2324bfae1ef3 100644--- a/posthog/wsgi.py+++ b/posthog/wsgi.py@@ -30,8 +30,7 @@ initialize_otel()# Boot allocations are almost all permanent, so cyclic GC during django.setup() only adds# pauses (~300ms). Disable it for the boot, then freeze the survivors so later full-# collections skip them — which also maximizes copy-on-write sharing when a prototype-# process forks workers. See docs/internal/django-startup-time.md.+# collections skip them. See docs/internal/django-startup-time.md.gc.disable()try:_django_application = get_wsgi_application()@@ -39,9 +38,7 @@ try:# Resolve the URLconf now, at module load. The lazy API router otherwise builds on# each worker's FIRST LIVE REQUEST — k8s probes (/_livez, /_readyz) short-circuit in# middleware and never warm it — costing seconds per worker after every deploy.- # Building it here keeps the cost to the prototype-process boot: Unit forks workers- # from that prototype after the module loads, so the built router lands in the frozen- # heap and is copy-on-write shared across all forked workers. Non-web processes+ # Building it here moves the cost to worker boot instead. Non-web processes# (celery, temporal, migrate, shell) never load this module and keep the lazy win.from django.urls import get_resolver@@ -59,9 +56,9 @@ finally:gc.enable()-# A web worker logs `web_worker_started` once, here at the end of boot. Nginx Unit recycles a-# worker after NGINX_UNIT_REQUEST_LIMIT requests, and the kernel respawns one whenever a worker-# is OOM-killed (SIGKILL is uncatchable, so the kill itself can't be logged from inside the+# A web worker logs `web_worker_started` once, here at the end of boot. Granian recycles a+# worker once it passes GRANIAN_WORKERS_MAX_RSS, and respawns one whenever a worker is+# OOM-killed (SIGKILL is uncatchable, so the kill itself can't be logged from inside the# worker). Either way the replacement boots and emits this line — so a burst of these on a pod# is the in-app fingerprint of worker churn / OOM kills, queryable in PostHog even though the# kill leaves no other application-level trace. Best-effort: never break worker startup.@@ -78,7 +75,7 @@ def _log_web_worker_started() -> None:"web_worker_started",pid=os.getpid(),rss_mb=round(rss_mb, 1) if rss_mb is not None else None,- request_limit=os.getenv("NGINX_UNIT_REQUEST_LIMIT"),+ max_rss_mb=os.getenv("GRANIAN_WORKERS_MAX_RSS"),pod=os.getenv("K8S_POD_NAME") or os.getenv("HOSTNAME"),)except Exception:@@ -87,11 +84,10 @@ def _log_web_worker_started() -> None:_log_web_worker_started()-# Nginx Unit forks workers from a prototype process that imported this module, so-# the query_cache RedisCluster must be discovered post-fork: a client built here at-# import time would be inherited -- sockets and all -- by every worker. Defer the-# prewarm to the first request so discovery runs in the worker; the factory also-# pid-guards the cache as a backstop. (start_continuous_profiling/initialize_otel+# The query_cache RedisCluster must be discovered by the process that uses it: a client+# built at import time is inherited, sockets and all, by anything forked afterwards.+# Defer the prewarm to the first request; the factory also pid-guards the cache as a+# backstop. (start_continuous_profiling/initialize_otel# above still run pre-fork here, unlike asgi.py which defers them -- that is a# separate, pre-existing concern, not addressed by this change.)#@@ -106,14 +102,11 @@ def application(environ, start_response):if not _prewarmed:prewarm_query_cache_cluster_in_background()validate_configured_web_bot_auth_private_keys_in_background()- # Start the RSS sampler post-fork, here in the worker. Unit forks workers from a- # prototype that already imported this module, and a thread started pre-fork does- # not survive into the worker — starting it on the worker's first call samples the- # process that actually serves requests and grows toward the OOM limit.+ # Threads do not survive a fork, so start the sampler from the process that+ # actually serves requests.start_web_memory_sampler()- # Register the SIGUSR2 memory probe on the same post-fork path (see asgi.py). On a- # single-threaded Unit worker this runs on the main thread; if Unit serves the app- # from a worker thread the install no-ops gracefully. Inert unless the env flag is set.+ # Signal handlers install only from the main thread, so this logs a handled failure+ # when the server calls the app off it. Inert unless the env flag is set.install_memory_probe_handler()_prewarmed = Truereturn _django_application(environ, start_response)diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 6d32d4e23106..7890b4452034 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -253,7 +253,7 @@ UUID_LOOKUP_REGEX = r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4TASK_RUN_STREAM_KEEPALIVE_INTERVAL_SECONDS = 20.0TASK_RUN_STREAM_KEEPALIVE_EVENT_NAME = "keepalive"TASK_RUN_STREAM_KEEPALIVE_PAYLOAD = {"type": "keepalive"}-# Long-lived SSE connections pin NGINX Unit processes during recycle-drain, so+# Long-lived SSE connections pin worker processes during recycle-drain, so# cap each one: emit `event: end` so clients can tell rotation from run# completion, then close. Clients resume from their Last-Event-ID cursor.TASK_RUN_STREAM_CONNECTION_MAX_SECONDS = 15 * 60diff --git a/products/wizard/backend/presentation/views.py b/products/wizard/backend/presentation/views.pyindex d70a1ef4a253..6def87bdd993 100644--- a/products/wizard/backend/presentation/views.py+++ b/products/wizard/backend/presentation/views.py@@ -98,7 +98,7 @@ def _log_request_auth(request: Request, *, action: str, team_id: int | None) ->SSE_HEARTBEAT_INTERVAL_SECONDS = 15.0SSE_POLL_TIMEOUT_SECONDS = 1.0-# Long-lived connections pin NGINX Unit processes during recycle-drain; the+# Long-lived connections pin worker processes during recycle-drain; the# `event: end` close makes EventSource reconnect, so the cap is near-invisible to# users (the progress tracker may show a brief "reconnecting" blip per rotation).SSE_MAX_DURATION_SECONDS = 15 * 60diff --git a/tools/hogbox-preview/STARTUP.md b/tools/hogbox-preview/STARTUP.mdindex 55d120f60046..368cabf650c3 100644--- a/tools/hogbox-preview/STARTUP.md+++ b/tools/hogbox-preview/STARTUP.md@@ -18,7 +18,7 @@ doesn't distort it):| `migrate` (pg) | **126s** | `run --rm web manage.py migrate` — a **no-op** on the golden (`No planned migration operations`) || `migrate_clickhouse` | **147s** | same, 281 CH migrations, all no-ops || `up-web` | 2s | create the web container |-| web `/_health` | **117s** | Nginx Unit + workers import `posthog.wsgi`, then serve |+| web `/_health` | **117s** | Workers import `posthog.wsgi`, then serve |> Numbers predate temporal. `up-deps` now also starts `temporal` and `up-web`> also recreates `temporal-django-worker` (needed so the worker runs the PR's@@ -54,13 +54,11 @@ pays for it:## Validated levers-- **Web: `NGINX_UNIT_APP_PROCESSES=1` + `NGINX_UNIT_PRELOAD_CONFIG=true` → first- `/_health` 118s → ~18s.** The biggest cheap win. `bin/docker-server-unit` runs- **4** Unit workers and, when `PRELOAD_CONFIG` is unset, **double-loads** Django- per worker (start → apply config → stop → restart) = 8 full imports. A preview- serves one user; one worker + a preloaded config kills the redundancy. Applied- in `stack.py` `write_override` and in the golden's own bake- (hogland `scripts/posthog-preview-setup.sh`).+- **Web: one worker.** `bin/docker-server` runs **4** by default, each paying a full+ Django import. A preview serves one user, so `GRANIAN_WORKERS=1` drops the rest.+ Applied in `stack.py` `write_override` and in the golden's own bake+ (hogland `scripts/posthog-preview-setup.sh`). The 118s→18s figure in the table+ above predates granian and has not been re-measured.- **Tighter poll intervals** (`run_long`/`wait_http_ok` 10s → 3s): each completedstep otherwise sits on up to 10s of dead air before we notice; a handful ofsteps adds up.@@ -140,10 +138,6 @@ encodes them, but they're easy to regress, so they live here too:- **`compose run` has no `--no-build`.** Only a _present_ image stops it fromsilently starting dev-full's ~20-min `build: .`. Pull the image upfront andhard-fail if it's absent — don't discover the build at the migrate step.-- **Never `compose restart web`.** Nginx Unit installs its `*:8000` listener only- on a fresh container's first boot (`/var/lib/unit` empty); a restart skips it- and comes up with `listeners: {}` serving nothing. Recreate with a clean `up`- (`--force-recreate` if web must be replaced).- **Restore sizing must match the baked spec exactly** — 8 vCPU / 16384 MiB /100 GiB / mirrored. "Omit to inherit" is unreliable server-side; a mismatch isrejected. (NB: the SDK sends `disk_mbps=0` = unthrottled; the `hogland` CLIdiff --git a/tools/hogbox-preview/hogbox_preview/stack.py b/tools/hogbox-preview/hogbox_preview/stack.pyindex 72720a183300..dbbdefd7f698 100644--- a/tools/hogbox-preview/hogbox_preview/stack.py+++ b/tools/hogbox-preview/hogbox_preview/stack.py@@ -10,15 +10,10 @@ Recipe (mount-over-image — the default, ~minutes per PR):- Run the ready-made published image (``ghcr.io/posthog/posthog:master``) andbind-mount the PR's backend source (``posthog``/``ee``/``products``) over theimage's ``/code``. The image is the prod Dockerfile: it runs from- ``WORKDIR /code`` via ``./bin/docker-server-unit`` with the frontend baked at+ ``WORKDIR /code`` via ``./bin/docker-server`` with the frontend baked at``/code/frontend/dist``. Mounting the source swaps the BACKEND code live — noper-PR build. (Frontend stays at the image's version; frontend hot-mount is alater iteration.) DEBUG=0 is required: the prod image lacks DEBUG-only apps.- - NEVER ``restart`` the web container. Nginx Unit applies its ``*:8000``- listener only on a fresh container's first boot (``/var/lib/unit`` empty); a- ``restart`` finds it non-empty, skips the listener, and the app comes up with- ``listeners: {}`` — nothing serves on 8000. ``wait_for_health`` just waits on- the clean ``up`` (use ``--force-recreate`` if web ever needs replacing).- DB coherence: the restored golden's DB was migrated + seeded against the sameimage tag, so a restore only needs the PR's *delta* migrations on top(``migrate`` + ``migrate_clickhouse``). Reseeding is skipped — the golden is@@ -169,8 +164,8 @@ class PostHogPreviewStack:if self.reset_db:self.reset_database()# Prepare the database and service-backed templates BEFORE web serves:- # web can't be restarted to pick up a PR's delta migrations (the- # Unit-listener gotcha), so all setup must finish before it boots.+ # web is not restarted to pick up a PR's delta migrations, so all setup+ # must finish before it boots.self.up_deps()self.migrate()self.start_cdp_service()@@ -283,8 +278,8 @@ class PostHogPreviewStack:## A web recreate still happens in up_web — but only to bind-mount the PR's# backend source over the image's /code (you can't add a mount to a- # running container). On the warm golden that's a ~18s warm import (1 Unit- # worker + preloaded config), not the old ~120s cold rebuild; #315's win+ # running container). On the warm golden that's a warm single-worker import+ # rather than a cold rebuild; #315's win# is making that recreate warm and serving the frontend relative# (JS_URL=""), not removing it. Keeping the env constant means web only# ever recreates for the mount, never for config drift.@@ -321,13 +316,9 @@ class PostHogPreviewStack:# (compose run --rm web) needs it too. Not shared across previews, so# a public preview URL can't be used to forge sessions on another.f" - SECRET_KEY={self.secret_key}",- # A preview serves one user, so one Unit worker is plenty — and the- # image's entrypoint otherwise double-loads Django on every boot- # (start→apply config→stop→restart), once per worker. Measured on a- # restored golden: the stock 4-worker double-load is ~118s to first- # /_health; one worker + a preloaded config is ~15-20s.- " - NGINX_UNIT_APP_PROCESSES=1",- " - NGINX_UNIT_PRELOAD_CONFIG=true",+ # A preview serves one user, and each worker costs a full Django import+ # at boot, so one worker reaches a serving /_health much sooner.+ " - GRANIAN_WORKERS=1",# master's Django hard-requires the personhog service for group-type# lookups (require_personhog_client() raises "personhog client not# configured" without it — #65968). Same addr the dev/hobby composes@@ -538,8 +529,7 @@ class PostHogPreviewStack:self.backend.run_long(script, name="up-deps", timeout=900)def up_web(self) -> None:- # Clean `up` (never `restart` — Unit-listener gotcha). --no-build reuses- # the pulled image; the override mounts PR source over its /code.+ # --no-build reuses the pulled image; the override mounts PR source over its /code.## The temporal worker comes up here, alongside web and for the same# reason: you can't add a bind mount to a running container, so the@@ -659,9 +649,6 @@ class PostHogPreviewStack:timing.stage("frontend swap done (collectstatic done)")def wait_for_health(self) -> None:- # Do NOT `restart web` with the pinned image: Nginx Unit binds its :8000- # listener only on a fresh container's first boot (/var/lib/unit empty);- # a restart skips it and leaves `listeners: {}`, so nothing serves.# up_services already brought web up cleanly — just wait for it to serve.# Django is a heavy import; first health can take ~7 min.with timing.span("health-poll"):diff --git a/unit.json.tpl b/unit.json.tpldeleted file mode 100644index 6cfbe6346e18..000000000000--- a/unit.json.tpl+++ /dev/null@@ -1,62 +0,0 @@-{- "settings": {- "http": {- "max_body_size": 22020096- }- },- "listeners": {- "*:8000": {- "pass": "applications/posthog"- },- "*:8001": {- "pass": "routes/metrics"- },- "*:8181": {- "pass": "routes/status"- }- },- "routes": {- "metrics": [- {- "match": {- "uri": ["/metrics"]- },- "action": {- "pass": "applications/metrics"- }- }- ],- "status": [- {- "match": {- "uri": ["/status"]- },- "action": {- "proxy": "http://unix:/var/run/control.unit.sock"- }- }- ]- },- "applications": {- "posthog": {- "type": "python 3",- "processes": $NGINX_UNIT_APP_PROCESSES,- "working_directory": "/code",- "path": ".",- "module": "posthog.$NGINX_UNIT_PYTHON_PROTOCOL",- "protocol": "$NGINX_UNIT_PYTHON_PROTOCOL",- "user": "nobody",- "limits": {- "requests": $NGINX_UNIT_REQUEST_LIMIT- }- },- "metrics": {- "type": "python 3",- "processes": 1,- "working_directory": "/code/bin",- "path": ".",- "module": "unit_metrics",- "user": "nobody"- }- }-}