: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(web): sample per-worker RSS periodically as worker_memory (#65742)
Paul D'Ambra221327302800
diff --git a/posthog/test/test_web_memory_sampler.py b/posthog/test/test_web_memory_sampler.pynew file mode 100644index 000000000000..c80846b07493--- /dev/null+++ b/posthog/test/test_web_memory_sampler.py@@ -0,0 +1,93 @@+import os+import sys++import pytest+from unittest import mock++import structlog+from parameterized import parameterized+from structlog.testing import capture_logs++import posthog.web_memory_sampler as sampler++[email protected](sys.platform != "linux", reason="requires /proc (Linux only)")+def test_current_rss_mb_returns_positive_on_linux():+ rss = sampler.current_rss_mb()+ assert rss is not None+ assert rss > 0+++def test_current_rss_mb_handles_missing_proc(monkeypatch):+ def _boom(*_args, **_kwargs):+ raise OSError("no /proc here")++ monkeypatch.setattr("builtins.open", _boom)+ assert sampler.current_rss_mb() is None+++def test_sampler_disabled_starts_no_thread(monkeypatch):+ # A non-positive interval must be a no-op so the sampler can be turned off in prod+ # without a deploy, and so it never spawns a thread in environments that don't want it.+ started_threads: list[str] = []++ class _RecordingThread:+ def __init__(self, **kwargs):+ self._name = kwargs["name"]++ def start(self):+ started_threads.append(self._name)++ monkeypatch.setattr(sampler.threading, "Thread", _RecordingThread)+ monkeypatch.setattr(sampler, "_sampler_started_pid", None)+ monkeypatch.setenv("WEB_MEMORY_SAMPLE_INTERVAL_SECONDS", "0")++ sampler.start_web_memory_sampler()++ assert sampler._sampler_started_pid is None+ assert started_threads == []+++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.+ started_threads = []++ class _RecordingThread:+ def __init__(self, **kwargs):+ self._name = kwargs["name"]++ def start(self):+ started_threads.append(self._name)++ monkeypatch.setattr(sampler.threading, "Thread", _RecordingThread)+ monkeypatch.setattr(sampler, "_sampler_started_pid", os.getpid() + 1)+ monkeypatch.setenv("WEB_MEMORY_SAMPLE_INTERVAL_SECONDS", "30")++ sampler.start_web_memory_sampler()++ assert sampler._sampler_started_pid == os.getpid()+ assert started_threads == ["web-memory-sampler"]+++ [+ ("rss_present", 123.4, [123.4], 1),+ ("rss_unavailable", None, [], 0),+ ]+)+def test_sample_once_records_gauge_and_log_only_when_rss_available(+ _name, rss_value, expected_gauge_sets, expected_log_count+):+ gauge_sets: list[float] = []++ with (+ mock.patch.object(sampler, "current_rss_mb", lambda: rss_value),+ 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")++ assert gauge_sets == expected_gauge_sets+ assert len(log_events) == expected_log_countdiff --git a/posthog/web_memory_sampler.py b/posthog/web_memory_sampler.pynew file mode 100644index 000000000000..e71a95022606--- /dev/null+++ b/posthog/web_memory_sampler.py@@ -0,0 +1,103 @@+import os+import time+import logging+import threading++import structlog+from prometheus_client import Gauge++logger = logging.getLogger(__name__)++DEFAULT_SAMPLE_INTERVAL_SECONDS = 30.0++# Web-worker RSS, scraped via bin/unit_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+# `liveall` would accumulate. Per-worker detail lives in the `worker_memory` log line.+WORKER_RSS_MB = Gauge(+ "posthog_web_worker_rss_mb",+ "Maximum resident set size across live web worker processes, in MiB.",+ multiprocess_mode="livemax",+)++_sampler_started_pid: int | None = None+_lock = threading.Lock()+++def current_rss_mb() -> float | None:+ """Resident set size of the current worker process in MiB, read from+ /proc/self/statm (field 2 = resident pages). Returns None when unavailable,+ e.g. on non-Linux dev machines where /proc is absent."""+ try:+ with open("/proc/self/statm") as statm:+ resident_pages = int(statm.read().split()[1])+ except (OSError, ValueError, IndexError):+ return 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:+ rss_mb = current_rss_mb()+ if rss_mb is None:+ return+ rss_mb_rounded = round(rss_mb, 1)+ WORKER_RSS_MB.set(rss_mb_rounded)+ log.info(+ "worker_memory",+ rss_mb=rss_mb_rounded,+ pod=pod,+ request_limit=request_limit,+ )+++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")+ while True:+ time.sleep(interval_seconds)+ try:+ _sample_once(log, pod, request_limit)+ except Exception:+ logger.exception("web memory sample failed")+++def start_web_memory_sampler() -> None:+ """Start a daemon thread that periodically records this worker's RSS — as the+ `posthog_web_worker_rss_mb` Prometheus gauge and a `worker_memory` log line — so the+ gradual climb toward the cgroup limit that precedes an OOM kill is visible in both+ metrics 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.++ Interval is set by WEB_MEMORY_SAMPLE_INTERVAL_SECONDS (default 30); set it to 0 or less+ to disable. Best-effort and idempotent — never breaks startup."""+ global _sampler_started_pid+ try:+ try:+ interval_seconds = float(+ os.getenv("WEB_MEMORY_SAMPLE_INTERVAL_SECONDS", str(DEFAULT_SAMPLE_INTERVAL_SECONDS))+ )+ except ValueError:+ interval_seconds = DEFAULT_SAMPLE_INTERVAL_SECONDS+ if interval_seconds <= 0:+ return+ interval_seconds = max(interval_seconds, 1.0)+ pid = os.getpid()+ with _lock:+ if _sampler_started_pid == pid:+ return+ _sampler_started_pid = pid+ threading.Thread(+ target=_sample_loop,+ args=(interval_seconds,),+ name="web-memory-sampler",+ daemon=True,+ ).start()+ except Exception:+ logger.exception("failed to start web memory sampler")diff --git a/posthog/wsgi.py b/posthog/wsgi.pyindex 93e8ae3b5879..699d375c270e 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.web_memory_sampler import start_web_memory_sampleros.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")os.environ.setdefault("SERVER_GATEWAY_INTERFACE", "WSGI")@@ -35,11 +36,10 @@ 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 at worker boot, behind readiness. (Verified against- # the production image: Unit 1.35 loads this module once per application process — no- # prototype fork/COW — so each worker pays its own boot, exactly like before the lazy- # router.) Non-web processes (celery, temporal, migrate, shell) never load this module- # and keep the lazy win.+ # 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+ # (celery, temporal, migrate, shell) never load this module and keep the lazy win.from django.urls import get_resolver_ = get_resolver().url_patterns # property access triggers the build@@ -94,5 +94,10 @@ def application(environ, start_response):global _prewarmedif not _prewarmed:prewarm_query_cache_cluster_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.+ start_web_memory_sampler()_prewarmed = Truereturn _django_application(environ, start_response)