: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
feat(granian): add opt-in shared listen socket for the query pool (#104220)
Julian Bez51cd14aa6889
diff --git a/.github/scripts/trunk-impacted-targets.js b/.github/scripts/trunk-impacted-targets.jsindex b1a5ce1e240e..1ebbe9626f8a 100644--- a/.github/scripts/trunk-impacted-targets.js+++ b/.github/scripts/trunk-impacted-targets.js@@ -690,6 +690,7 @@ const TRIPWIRE_RULES = [['bin/posthog-node', APP_IMAGE],['bin/temporal-django-worker', APP_IMAGE],['bin/granian_metrics.py', APP_IMAGE],+ ['bin/granian_shared_socket.py', APP_IMAGE],['bin/start-backend', APP_IMAGE],['bin/start-frontend', APP_IMAGE],// The schema and taxonomy codegen pipeline, which turnsdiff --git a/.github/workflows/ci-python.yml b/.github/workflows/ci-python.ymlindex 2c90d3b4f6fb..721389d0bd1a 100644--- a/.github/workflows/ci-python.yml+++ b/.github/workflows/ci-python.yml@@ -444,6 +444,13 @@ jobs:[ "$RUN_BIN_SCRIPTS" = "true" ] || { echo "bin/ unchanged — skipping"; exit 0; }pytest bin/test/test_find_python_dependencies.py -v --junitxml=junit-dependency-detection.xml+ - name: Run granian shared socket tests+ shell: bash+ # The bin_scripts filter includes uv.lock, so every granian upgrade runs this.+ run: |+ [ "$RUN_BIN_SCRIPTS" = "true" ] || { echo "bin/ unchanged — skipping"; exit 0; }+ pytest bin/test/test_granian_shared_socket.py -v --junitxml=junit-granian-shared-socket.xml+- name: Upload test resultsuses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0if: always()@@ -466,6 +473,14 @@ jobs:if-no-files-found: ignorepath: junit-dependency-detection.xml+ - name: Upload test results for granian shared socket+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0+ if: always()+ with:+ name: junit-results-granian-shared-socket+ if-no-files-found: ignore+ path: junit-granian-shared-socket.xml+# Collate job - single required status check for branch protection.# The code-quality job skips when no Python changes, but this job always# runs and reports success, allowing PRs to merge.diff --git a/bin/docker-server b/bin/docker-serverindex acbe6ed3755c..dfb9d88d3480 100755--- a/bin/docker-server+++ b/bin/docker-server@@ -50,4 +50,10 @@ METRICS_PID=$!trap 'kill $METRICS_PID 2>/dev/null; rm -rf "$PROMETHEUS_MULTIPROC_DIR"' EXIT+# One listen socket shared by all workers, for pools that run one request per+# worker. See bin/granian_shared_socket.py.+if [ "${POSTHOG_GRANIAN_SHARED_SOCKET:-false}" = "true" ]; then+ exec $DROP_PRIVILEGES python ./bin/granian_shared_socket.py "$APP_TARGET"+fi+exec $DROP_PRIVILEGES granian "$APP_TARGET"diff --git a/bin/granian_shared_socket.py b/bin/granian_shared_socket.pynew file mode 100755index 000000000000..1214a491540e--- /dev/null+++ b/bin/granian_shared_socket.py@@ -0,0 +1,53 @@+#!/usr/bin/env python3+"""+Run the granian CLI with one listen socket shared by all workers.++Since granian 2.8, each worker on Linux gets its own SO_REUSEPORT socket, and the+kernel hashes every new connection to one of them without looking at load. A pool+that runs one request per worker (backpressure 1) then queues connections behind a+busy worker while other workers idle. With one shared socket all workers take from+a single accept queue, so only a free worker picks up the next connection. That is+how granian 2.7 works on Linux, and how 2.8 still works on macOS, Windows and Unix+domain sockets.++This uses granian's private server API. bin/test/test_granian_shared_socket.py+checks the behaviour on Linux, so a granian upgrade that breaks it fails CI.++bin/docker-server runs this instead of `granian` when+POSTHOG_GRANIAN_SHARED_SOCKET=true. Every GRANIAN_* setting still applies.+"""++import socket++import granian.cli+from granian.net import SocketSpec+from granian.server import MPServer+++class SharedSocketServer(MPServer):+ def _init_shared_socket(self) -> None:+ """+ The non-Linux TCP branch of AbstractServer._init_shared_socket, plus the+ inheritable socket that MPServer hands to its workers.+ """+ if self.bind_uds:+ super()._init_shared_socket()+ return+ self._ssp = SocketSpec(self.bind_addr, self.bind_port, self.backlog)+ self._shd = self._ssp.build()+ self._sfd = self._shd.get_fd()+ self._ssp = None+ self._sso = socket.socket(fileno=self._sfd)+ self._sso.set_inheritable(True)+++def main() -> None:+ # Fail at boot, not silently, if granian stops building its servers this way.+ if granian.cli.Server is not MPServer or not hasattr(MPServer, "_init_shared_socket"):+ raise RuntimeError("granian internals changed, the shared socket override no longer applies")+ granian.cli.Server = SharedSocketServer+ granian.cli.entrypoint()+++if __name__ == "__main__":+ main()diff --git a/bin/test/test_granian_shared_socket.py b/bin/test/test_granian_shared_socket.pynew file mode 100644index 000000000000..507556c7382f--- /dev/null+++ b/bin/test/test_granian_shared_socket.py@@ -0,0 +1,122 @@+#!/usr/bin/env python3++import os+import sys+import time+import signal+import socket+import threading+import subprocess+import http.client+from pathlib import Path+from tempfile import TemporaryDirectory++import unittest++LAUNCHER = Path(__file__).resolve().parents[1] / "granian_shared_socket.py"++APP = """+import os+import time+++def app(environ, start_response):+ if environ["PATH_INFO"] == "/slow":+ open(os.environ["SLOW_MARKER"], "w").close()+ time.sleep(10)+ start_response("200 OK", [("Content-Type", "text/plain")])+ return [b"ok"]+"""+++def free_port() -> int:+ with socket.socket() as sock:+ sock.bind(("127.0.0.1", 0))+ return sock.getsockname()[1]+++def count_listen_sockets(port: int) -> int:+ suffix = f":{port:04X}"+ count = 0+ for table in ("/proc/net/tcp", "/proc/net/tcp6"):+ for line in Path(table).read_text().splitlines()[1:]:+ fields = line.split()+ # State 0A is TCP_LISTEN.+ if fields[1].endswith(suffix) and fields[3] == "0A":+ count += 1+ return count+++def get(port: int, path: str, timeout: float) -> str:+ conn = http.client.HTTPConnection("127.0.0.1", port, timeout=timeout)+ try:+ conn.request("GET", path)+ return str(conn.getresponse().status)+ except OSError as error:+ return type(error).__name__+ finally:+ conn.close()++[email protected](sys.platform == "linux", "granian splits listen sockets per worker only on Linux")+class TestGranianSharedSocket(unittest.TestCase):+ """Boots bin/granian_shared_socket.py the way the query pool runs it: 4 workers, one request each."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.tmp = TemporaryDirectory()+ Path(cls.tmp.name, "app.py").write_text(APP)+ cls.slow_marker = Path(cls.tmp.name, "slow.started")+ cls.port = free_port()+ env = {key: value for key, value in os.environ.items() if not key.startswith("GRANIAN_")}+ env.update(+ GRANIAN_INTERFACE="wsgi",+ GRANIAN_HOST="127.0.0.1",+ GRANIAN_PORT=str(cls.port),+ GRANIAN_WORKERS="4",+ GRANIAN_BLOCKING_THREADS="1",+ GRANIAN_BACKPRESSURE="1",+ GRANIAN_HTTP1_KEEP_ALIVE="false",+ GRANIAN_WORKERS_KILL_TIMEOUT="1",+ GRANIAN_LOG_LEVEL="error",+ SLOW_MARKER=str(cls.slow_marker),+ )+ cls.server = subprocess.Popen(+ [sys.executable, str(LAUNCHER), "app:app"],+ cwd=cls.tmp.name,+ env=env,+ start_new_session=True,+ )+ deadline = time.monotonic() + 30+ while get(cls.port, "/", timeout=1) != "200":+ if cls.server.poll() is not None or time.monotonic() > deadline:+ cls.tearDownClass()+ raise RuntimeError("granian did not start")+ time.sleep(0.2)++ @classmethod+ def tearDownClass(cls) -> None:+ cls.server.terminate()+ try:+ cls.server.wait(timeout=20)+ except subprocess.TimeoutExpired:+ os.killpg(cls.server.pid, signal.SIGKILL)+ cls.server.wait()+ cls.tmp.cleanup()++ def test_workers_share_one_listen_socket(self) -> None:+ self.assertEqual(count_listen_sockets(self.port), 1)++ def test_busy_worker_does_not_hold_new_connections(self) -> None:+ threading.Thread(target=get, args=(self.port, "/slow", 30), daemon=True).start()+ deadline = time.monotonic() + 10+ while not self.slow_marker.exists() and time.monotonic() < deadline:+ time.sleep(0.05)+ self.assertTrue(self.slow_marker.exists(), "the /slow request never reached a worker")+ # With per-worker sockets about a quarter of these land on the busy worker and time out.+ statuses = [get(self.port, "/", timeout=2) for _ in range(20)]+ self.assertEqual(statuses, ["200"] * 20)+++if __name__ == "__main__":+ unittest.main()diff --git a/hogli.yaml b/hogli.yamlindex 31f61e275719..5a927224e7b3 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -1038,6 +1038,10 @@ tools:bin_script: granian_metrics.pydescription: HTTP server that aggregates Prometheus metrics from Granian workershidden: true+ tool:granian-shared-socket:+ bin_script: granian_shared_socket.py+ description: Granian launcher that keeps one listen socket shared by all workers+ hidden: truesync:storage:bin_script: sync-storagedescription: 'TODO: add description for sync-storage'