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(infra): restore granian dual-mode image with wsgi interface support (#67735)

Julian Bezbbbcf2ea734e
diff --git a/bin/docker-server-unit b/bin/docker-server-unit
index 9dc6231b5596..044a23039753 100755
--- a/bin/docker-server-unit
+++ b/bin/docker-server-unit
@@ -11,38 +11,92 @@ chmod -R 777 $PROMETHEUS_MULTIPROC_DIR
export PROMETHEUS_METRICS_EXPORT_PORT=8001
export STATSD_PORT=${STATSD_PORT:-8125}
-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
+# 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.
- envsubst < /docker-entrypoint.d/unit.json.tpl > /docker-entrypoint.d/unit.json
-fi
+ # 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=$!
-# 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
+ # 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
- # nosemgrep: trailofbits.generic.container-user-root.container-user-root
- exec /usr/local/bin/docker-entrypoint.sh unitd --no-daemon --user root
+ 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
fi
diff --git a/bin/granian_metrics.py b/bin/granian_metrics.py
new file mode 100755
index 000000000000..c0a1f13c6422
--- /dev/null
+++ b/bin/granian_metrics.py
@@ -0,0 +1,141 @@
+#!/usr/bin/env python3
+"""
+Metrics HTTP server for Granian multi-process setup.
+
+Serves Prometheus metrics on port 8001 (configurable via PROMETHEUS_METRICS_EXPORT_PORT).
+Aggregates metrics from all Granian worker processes using prometheus_client multiprocess
+mode, and appends Granian's native runtime metrics (worker spawns/respawns, blocking pool
+utilization and queue depth, connections, GIL wait — available since Granian 2.7.0) so
+everything is scraped from the one port the charts already target.
+Exposes Granian-equivalent metrics to maintain dashboard compatibility with previous Gunicorn setup.
+"""
+
+import os
+import time
+import logging
+import threading
+import urllib.request
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+from prometheus_client import CONTENT_TYPE_LATEST, CollectorRegistry, Gauge, generate_latest, multiprocess
+
+logger = logging.getLogger(__name__)
+
+# Loopback fetch must bypass the egress proxy: urllib honors HTTP_PROXY env by
+# default, which routes 127.0.0.1 through Smokescreen — and Smokescreen blocks
+# loopback by design. Per-code-path opt-out, never NO_PROXY (see
+# charts docs/claude/egress-proxy.md).
+_LOOPBACK_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
+
+
+def create_granian_metrics() -> None:
+ """
+ Create Granian-equivalent metrics to maintain compatibility with existing Grafana dashboards.
+
+ These metrics mirror the Gunicorn metrics that were previously exposed, allowing existing
+ dashboards and alerts to continue working with minimal changes.
+ """
+ # Read Granian configuration from environment (granian's own env var names)
+ workers = int(os.environ.get("GRANIAN_WORKERS", 4))
+ threads = int(os.environ.get("GRANIAN_RUNTIME_THREADS", 1))
+
+ # Expose static configuration as gauges. With PROMETHEUS_MULTIPROC_DIR set,
+ # gauge writes land in the shared mmap files that MultiProcessCollector
+ # already exports — registering them on the scrape registry as well would
+ # export duplicate families, so registry stays None. multiprocess_mode="max"
+ # yields one pid-less sample (only this process sets them).
+ max_worker_threads = Gauge(
+ "granian_max_worker_threads",
+ "Maximum number of threads per worker",
+ registry=None,
+ multiprocess_mode="max",
+ )
+ max_worker_threads.set(threads)
+
+ total_workers = Gauge(
+ "granian_workers_total",
+ "Total number of Granian workers configured",
+ registry=None,
+ multiprocess_mode="max",
+ )
+ total_workers.set(workers)
+
+ # Configured backpressure isn't part of Granian's native metrics, so export it
+ # here when set — it's the WSGI concurrency ceiling dashboards should show.
+ # (Live blocking-thread counts DO come from the native metrics as
+ # granian_blocking_threads — don't shadow that family here.)
+ backpressure = os.environ.get("GRANIAN_BACKPRESSURE")
+ if backpressure is not None:
+ gauge = Gauge(
+ "granian_backpressure",
+ "Maximum in-flight requests per worker",
+ registry=None,
+ multiprocess_mode="max",
+ )
+ gauge.set(int(backpressure))
+
+
+_NATIVE_CACHE_TTL_SECONDS = 5.0
+_native_cache: tuple[float, bytes] = (0.0, b"")
+_native_lock = threading.Lock()
+
+
+def fetch_native_metrics() -> bytes:
+ """Fetch Granian's own Prometheus exporter output for merging.
+
+ The native exporter (GRANIAN_METRICS_ENABLED) binds loopback-only, so its
+ runtime metrics ride along on this scrape instead of needing a second
+ scrape target. Best-effort: a scrape must not fail while granian boots.
+
+ Cached for a short TTL with the fetch serialized behind a lock, so scrape
+ volume can't multiply loopback fetches — a stalled exporter costs at most
+ one 2s wait per TTL window, not one pinned thread per scrape.
+ """
+ global _native_cache
+ if os.environ.get("GRANIAN_METRICS_ENABLED", "false") != "true":
+ return b""
+ port = os.environ.get("GRANIAN_METRICS_PORT", "9090")
+ with _native_lock:
+ fetched_at, cached = _native_cache
+ now = time.monotonic()
+ if now - fetched_at < _NATIVE_CACHE_TTL_SECONDS:
+ return cached
+ try:
+ with _LOOPBACK_OPENER.open(f"http://127.0.0.1:{port}/metrics", timeout=2) as response:
+ body = response.read()
+ except OSError:
+ body = b""
+ _native_cache = (now, body)
+ return body
+
+
+def main():
+ """Start HTTP server exposing app multiprocess metrics merged with Granian's native metrics."""
+ registry = CollectorRegistry()
+ multiprocess.MultiProcessCollector(registry)
+
+ # Create Granian-specific metrics for dashboard compatibility (they reach
+ # the scrape via the multiprocess mmap files, not this registry)
+ create_granian_metrics()
+
+ port = int(os.environ.get("PROMETHEUS_METRICS_EXPORT_PORT", 8001))
+
+ class MetricsHandler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ body = generate_latest(registry) + fetch_native_metrics()
+ self.send_response(200)
+ self.send_header("Content-Type", CONTENT_TYPE_LATEST)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, format, *args):
+ # Per-scrape access logs are noise.
+ pass
+
+ logger.info(f"Starting Prometheus metrics server on port {port}")
+ ThreadingHTTPServer(("0.0.0.0", port), MetricsHandler).serve_forever()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/hogli.yaml b/hogli.yaml
index acf8c9bc8a5d..8f82c2b55d8c 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -616,7 +616,7 @@ docker:
hidden: true
docker:server:
bin_script: docker-server
- description: Run NGINX Unit application server
+ description: Run dual-mode server (Granian/Unit) with Prometheus metrics support
hidden: true
docker:server-unit:
bin_script: docker-server-unit
@@ -941,6 +941,10 @@ tools:
bin_script: create-notebook-node.sh
description: Create a new NotebookNode file and update types and editor references
hidden: true
+ tool:granian-metrics:
+ bin_script: granian_metrics.py
+ description: HTTP server that aggregates Prometheus metrics from Granian workers
+ hidden: true
sync:storage:
bin_script: sync-storage
description: 'TODO: add description for sync-storage'
diff --git a/posthog/urls.py b/posthog/urls.py
index c155049ab258..adbe99c2a628 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -498,7 +498,7 @@ 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/unit_metrics.py
+ # external clients cannot see them. See bin/granian_metrics.py and bin/unit_metrics.py
# for details on the production metrics setup.
# Use multiprocess mode to collect metrics from all processes (Django + Celery workers)
diff --git a/pyproject.toml b/pyproject.toml
index d82e93459b97..7527f3f6e348 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -63,6 +63,7 @@ dependencies = [
"google-cloud-bigquery-storage==2.32.0",
"google-cloud-iam==2.21",
"google-genai==1.46.0",
+ "granian[uvloop,reload,pname]==2.7.6",
"grimp~=3.14",
"grpcio~=1.71.0",
"gspread==6.2.1",
@@ -210,7 +211,6 @@ dev = [
"braintrust==0.2.4",
"braintrust-langchain==0.0.4",
"dagster-dg-cli~=1.10.18",
- "granian[uvloop,reload,pname]==2.7.6",
"datamodel-code-generator~=0.36.0",
"debugpy~=1.8.0",
"import-linter~=2.11",
diff --git a/uv.lock b/uv.lock
index c305e6977b1c..1c85a1dfc2c4 100644
--- a/uv.lock
+++ b/uv.lock
@@ -5602,6 +5602,7 @@ dependencies = [
{ name = "google-cloud-iam" },
{ name = "google-genai" },
{ name = "google-re2" },
+ { name = "granian", extra = ["pname", "reload", "uvloop"] },
{ name = "grimp" },
{ name = "grpcio" },
{ name = "gspread" },
@@ -5730,7 +5731,6 @@ dev = [
{ name = "faker" },
{ name = "fakeredis", extra = ["lua"] },
{ name = "freezegun" },
- { name = "granian", extra = ["pname", "reload", "uvloop"] },
{ name = "grpcio-tools" },
{ name = "hogli" },
{ name = "hypothesis" },
@@ -5877,6 +5877,7 @@ requires-dist = [
{ name = "google-cloud-iam", specifier = "==2.21" },
{ name = "google-genai", specifier = "==1.46.0" },
{ name = "google-re2", specifier = ">=1.1.20251105,<2" },
+ { name = "granian", extras = ["uvloop", "reload", "pname"], specifier = "==2.7.6" },
{ name = "grimp", specifier = "~=3.14" },
{ name = "grpcio", specifier = "~=1.71.0" },
{ name = "gspread", specifier = "==6.2.1" },
@@ -6005,7 +6006,6 @@ dev = [
{ name = "faker", specifier = "==17.5.0" },
{ name = "fakeredis", extras = ["lua"], specifier = "==2.23.3" },
{ name = "freezegun", specifier = "==1.5.5" },
- { name = "granian", extras = ["uvloop", "reload", "pname"], specifier = "==2.7.6" },
{ name = "grpcio-tools", specifier = "~=1.71.0" },
{ name = "hogli", editable = "tools/hogli" },
{ name = "hypothesis", specifier = "~=6.151.9" },