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): add SSE connection metrics and event loop lag gauge (#67931)

Fernando Gomesaa863d3e005a
diff --git a/ee/api/conversation.py b/ee/api/conversation.py
index b63de58352b1..4cb341c1b123 100644
--- a/ee/api/conversation.py
+++ b/ee/api/conversation.py
@@ -602,7 +602,8 @@ class ConversationViewSet(
return sse_streaming_response(
async_stream(workflow_inputs)
if settings.SERVER_GATEWAY_INTERFACE == "ASGI"
- else async_to_sync(lambda: async_stream(workflow_inputs))
+ else async_to_sync(lambda: async_stream(workflow_inputs)),
+ endpoint="max_conversation",
)
@action(detail=True, methods=["GET", "POST"], url_path="queue")
diff --git a/ee/api/session_summaries.py b/ee/api/session_summaries.py
index d9374f5286c1..c7709280ddd1 100644
--- a/ee/api/session_summaries.py
+++ b/ee/api/session_summaries.py
@@ -601,7 +601,8 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
yield f"event: done\ndata: {done_data}\n\n".encode()
return sse_streaming_response(
- async_stream() if settings.SERVER_GATEWAY_INTERFACE == "ASGI" else async_generator_to_sync(async_stream)
+ async_stream() if settings.SERVER_GATEWAY_INTERFACE == "ASGI" else async_generator_to_sync(async_stream),
+ endpoint="session_summaries",
)
@extend_schema(
diff --git a/ee/hogai/sandbox/executor.py b/ee/hogai/sandbox/executor.py
index 83ec7908f516..a5b0aa9c8084 100644
--- a/ee/hogai/sandbox/executor.py
+++ b/ee/hogai/sandbox/executor.py
@@ -190,7 +190,8 @@ def _make_streaming_response(
return sse_streaming_response(
async_generator_factory()
if settings.SERVER_GATEWAY_INTERFACE == "ASGI"
- else async_to_sync(async_generator_factory)
+ else async_to_sync(async_generator_factory),
+ endpoint="sandbox_execute",
)
diff --git a/posthog/api/query.py b/posthog/api/query.py
index 9f4b69f70fc8..01a7f25e332f 100644
--- a/posthog/api/query.py
+++ b/posthog/api/query.py
@@ -454,4 +454,6 @@ MAX_QUERY_TIMEOUT = 600
async def progress(request: Request, *args, **kwargs) -> StreamingHttpResponse:
# TEMPORARY endpoint to avoid breaking changes
- return sse_streaming_response([], status=status.HTTP_200_OK, headers={"Connection": "keep-alive"})
+ return sse_streaming_response(
+ [], endpoint="query_progress_stub", status=status.HTTP_200_OK, headers={"Connection": "keep-alive"}
+ )
diff --git a/posthog/api/streaming.py b/posthog/api/streaming.py
index 1cf7cc7d325f..a718809677e3 100644
--- a/posthog/api/streaming.py
+++ b/posthog/api/streaming.py
@@ -1,9 +1,13 @@
-from collections.abc import AsyncIterable, Iterable
+import time
+import asyncio
+from collections.abc import AsyncIterable, AsyncIterator, Iterable, Iterator
from http import HTTPStatus
from django.db import connections
from django.http import StreamingHttpResponse
+from prometheus_client import Counter, Gauge, Histogram
+
# What StreamingHttpResponse actually accepts: sync or async iterables of bytes or
# str chunks (Django encodes str via the response charset). Broad on purpose — SSE
# views yield str, proxies yield bytes, and the empty-stream stub passes a list.
@@ -16,6 +20,88 @@ _SSE_DEFAULT_HEADERS = {
"X-Accel-Buffering": "no",
}
+# The `endpoint` label is a static name passed by each SSE view — never a raw
+# request path, which would blow up label cardinality.
+SSE_OPEN_CONNECTIONS_GAUGE = Gauge(
+ "posthog_open_sse_connections",
+ "SSE streams currently being served by this process",
+ labelnames=["endpoint"],
+ multiprocess_mode="livesum",
+)
+SSE_STREAM_OPENED_COUNTER = Counter(
+ "posthog_sse_stream_opened_total",
+ "SSE streams that started being consumed",
+ labelnames=["endpoint"],
+)
+SSE_STREAM_CLOSED_COUNTER = Counter(
+ "posthog_sse_stream_closed_total",
+ "SSE streams that ended, by outcome",
+ labelnames=["endpoint", "outcome"],
+)
+# Streams legitimately run for many minutes (rotation caps them at ~15 min),
+# so buckets extend well past the default 10s ceiling.
+SSE_STREAM_DURATION_HISTOGRAM = Histogram(
+ "posthog_sse_stream_duration_seconds",
+ "Wall-clock lifetime of an SSE stream, from first chunk pulled to close",
+ labelnames=["endpoint"],
+ buckets=(1, 5, 15, 60, 180, 420, 900, 1200, float("inf")),
+)
+
+
+def _record_stream_close(endpoint: str, outcome: str, started_at: float) -> None:
+ SSE_OPEN_CONNECTIONS_GAUGE.labels(endpoint=endpoint).dec()
+ SSE_STREAM_CLOSED_COUNTER.labels(endpoint=endpoint, outcome=outcome).inc()
+ SSE_STREAM_DURATION_HISTOGRAM.labels(endpoint=endpoint).observe(time.monotonic() - started_at)
+
+
+async def _instrumented_aiter(stream: AsyncIterable[bytes | str], endpoint: str) -> AsyncIterator[bytes | str]:
+ """Pass chunks through untouched, tracking open count, outcome, and duration.
+
+ Metric work happens only at stream start and end — nothing is added per
+ chunk. A client disconnect surfaces here as cancellation of the generator
+ (``GeneratorExit`` from ``aclose()``, or ``asyncio.CancelledError`` when the
+ ASGI handler cancels the streaming task), which is why both get their own
+ outcome rather than folding into ``error``.
+ """
+ SSE_STREAM_OPENED_COUNTER.labels(endpoint=endpoint).inc()
+ SSE_OPEN_CONNECTIONS_GAUGE.labels(endpoint=endpoint).inc()
+ started_at = time.monotonic()
+ outcome = "completed"
+ try:
+ async for chunk in stream:
+ yield chunk
+ except (GeneratorExit, asyncio.CancelledError):
+ outcome = "client_disconnect"
+ raise
+ except BaseException:
+ outcome = "error"
+ raise
+ finally:
+ _record_stream_close(endpoint, outcome, started_at)
+
+
+def _instrumented_iter(stream: Iterable[bytes | str], endpoint: str) -> Iterator[bytes | str]:
+ SSE_STREAM_OPENED_COUNTER.labels(endpoint=endpoint).inc()
+ SSE_OPEN_CONNECTIONS_GAUGE.labels(endpoint=endpoint).inc()
+ started_at = time.monotonic()
+ outcome = "completed"
+ try:
+ yield from stream
+ except GeneratorExit:
+ outcome = "client_disconnect"
+ raise
+ except BaseException:
+ outcome = "error"
+ raise
+ finally:
+ _record_stream_close(endpoint, outcome, started_at)
+
+
+def _instrument_stream(stream: StreamContent, endpoint: str) -> StreamContent:
+ if isinstance(stream, AsyncIterable):
+ return _instrumented_aiter(stream, endpoint)
+ return _instrumented_iter(stream, endpoint)
+
def _release_request_connections() -> None:
"""Close this thread's DB connections, unless a transaction is open.
@@ -67,6 +153,7 @@ def streaming_response(
def sse_streaming_response(
stream: StreamContent,
*,
+ endpoint: str = "unknown",
status: int = HTTPStatus.OK,
headers: dict[str, str] | None = None,
) -> StreamingHttpResponse:
@@ -95,9 +182,12 @@ def sse_streaming_response(
that touches the DB in ``process_response`` lazily reopens a connection that
then stays pinned for the whole stream. Keep response middleware DB-free on
SSE paths.
+
+ ``endpoint`` is a static, low-cardinality name for the stream (e.g.
+ ``"wizard_session"``) used as the label on the SSE connection metrics.
"""
return streaming_response(
- stream,
+ _instrument_stream(stream, endpoint),
content_type="text/event-stream",
status=status,
headers={**_SSE_DEFAULT_HEADERS, **(headers or {})},
diff --git a/posthog/api/test/test_streaming.py b/posthog/api/test/test_streaming.py
index 42c558d2cfb0..8f52c5891673 100644
--- a/posthog/api/test/test_streaming.py
+++ b/posthog/api/test/test_streaming.py
@@ -1,11 +1,15 @@
-from collections.abc import Iterator
+import asyncio
+from collections.abc import AsyncIterator, Iterator
from http import HTTPStatus
+from typing import cast
from unittest import mock
from django.http import StreamingHttpResponse
-from posthog.api.streaming import sse_streaming_response, streaming_response
+from prometheus_client import REGISTRY
+
+from posthog.api.streaming import _instrument_stream, sse_streaming_response, streaming_response
def _gen() -> Iterator[bytes]:
@@ -48,6 +52,91 @@ class TestSSEStreamingResponse:
assert response.headers["X-Custom"] == "1"
+def _sync_content(response: StreamingHttpResponse) -> Iterator[bytes]:
+ # streaming_content is typed as a sync/async union; these tests construct
+ # the response from a sync iterator, so the cast is safe.
+ return cast(Iterator[bytes], response.streaming_content)
+
+
+def _async_content(response: StreamingHttpResponse) -> AsyncIterator[bytes]:
+ return cast(AsyncIterator[bytes], response.streaming_content)
+
+
+def _open_connections(endpoint: str) -> float:
+ return REGISTRY.get_sample_value("posthog_open_sse_connections", {"endpoint": endpoint}) or 0.0
+
+
+def _closed_total(endpoint: str, outcome: str) -> float:
+ return (
+ REGISTRY.get_sample_value("posthog_sse_stream_closed_total", {"endpoint": endpoint, "outcome": outcome}) or 0.0
+ )
+
+
+class TestSSEStreamMetrics:
+ # If the gauge ever fails to decrement on an exit path, it reads permanently
+ # inflated — and anything keyed on it (dashboards, connection-based
+ # autoscaling) sees phantom load. These tests pin every exit path.
+
+ def test_sync_stream_counts_open_and_completed(self):
+ response = sse_streaming_response(_gen(), endpoint="test_sync_complete")
+ assert b"".join(_sync_content(response)) == b"data: hello\n\n"
+ assert _open_connections("test_sync_complete") == 0.0
+ assert _closed_total("test_sync_complete", "completed") == 1.0
+
+ def test_sync_stream_error_decrements_gauge_and_counts_error(self):
+ def boom() -> Iterator[bytes]:
+ yield b"data: one\n\n"
+ raise RuntimeError("stream died")
+
+ response = sse_streaming_response(boom(), endpoint="test_sync_error")
+ it = _sync_content(response)
+ next(it)
+ try:
+ next(it)
+ except RuntimeError:
+ pass
+ assert _open_connections("test_sync_error") == 0.0
+ assert _closed_total("test_sync_error", "error") == 1.0
+
+ def test_sync_stream_early_close_counts_client_disconnect(self):
+ def endless() -> Iterator[bytes]:
+ while True:
+ yield b": ping\n\n"
+
+ response = sse_streaming_response(endless(), endpoint="test_sync_disconnect")
+ it = _sync_content(response)
+ next(it)
+ assert _open_connections("test_sync_disconnect") == 1.0
+ response.close() # what Django does when the client goes away
+ assert _open_connections("test_sync_disconnect") == 0.0
+ assert _closed_total("test_sync_disconnect", "client_disconnect") == 1.0
+
+ async def test_async_stream_counts_open_and_completed(self):
+ async def agen():
+ yield b"data: hello\n\n"
+
+ response = sse_streaming_response(agen(), endpoint="test_async_complete")
+ assert [chunk async for chunk in _async_content(response)] == [b"data: hello\n\n"]
+ assert _open_connections("test_async_complete") == 0.0
+ assert _closed_total("test_async_complete", "completed") == 1.0
+
+ async def test_async_stream_early_close_counts_client_disconnect(self):
+ async def endless():
+ while True:
+ yield b": ping\n\n"
+
+ # Django registers the instrumented iterator itself as the response's
+ # resource closer, so closing it directly is the disconnect path — the
+ # outer streaming_content wrapper does not propagate aclose() eagerly.
+ stream = _instrument_stream(endless(), "test_async_disconnect")
+ assert isinstance(stream, AsyncIterator)
+ await stream.__anext__()
+ assert _open_connections("test_async_disconnect") == 1.0
+ await stream.aclose() # type: ignore[attr-defined]
+ assert _open_connections("test_async_disconnect") == 0.0
+ assert _closed_total("test_async_disconnect", "client_disconnect") == 1.0
+
+
class TestStreamingResponse:
def test_honors_content_type_and_does_not_inject_sse_headers(self):
# Non-SSE callers (audio, proxies) rely on the general wrapper passing their
@@ -56,3 +145,31 @@ class TestStreamingResponse:
assert response.headers["Content-Type"] == "audio/mpeg"
assert "X-Accel-Buffering" not in response.headers
assert response.status_code == HTTPStatus.OK
+
+
+class TestSSEAsyncCancellation:
+ async def test_task_cancellation_counts_client_disconnect_not_error(self):
+ first_chunk_pulled = asyncio.Event()
+
+ async def blocking():
+ yield b": ping\n\n"
+ await asyncio.Event().wait() # park forever; cancellation lands here
+
+ stream = _instrument_stream(blocking(), "test_async_cancel")
+ assert isinstance(stream, AsyncIterator)
+
+ async def consume():
+ async for _ in stream:
+ first_chunk_pulled.set()
+
+ task = asyncio.ensure_future(consume())
+ await first_chunk_pulled.wait()
+ assert _open_connections("test_async_cancel") == 1.0
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ assert _open_connections("test_async_cancel") == 0.0
+ assert _closed_total("test_async_cancel", "client_disconnect") == 1.0
+ assert _closed_total("test_async_cancel", "error") == 0.0
diff --git a/posthog/asgi.py b/posthog/asgi.py
index 3367e948b4b3..97cd71605544 100644
--- a/posthog/asgi.py
+++ b/posthog/asgi.py
@@ -1,5 +1,7 @@
import gc
import os
+import time
+import asyncio
# Django Imports
from django.conf import settings
@@ -28,6 +30,49 @@ logger = structlog.get_logger(__name__)
# runserver is single-process, and Celery doesn't import this file.
_post_fork_initialized = False
+_LOOP_LAG_HEARTBEAT_SECONDS = 1.0
+
+
+async def _event_loop_lag_heartbeat() -> None:
+ """Measure event-loop starvation: sleep 1s, record how late we woke up.
+
+ A busy-but-healthy loop wakes within milliseconds; sustained lag means
+ something is hogging the loop between awaits (CPU-bound work in a stream,
+ a sync iterator, ...) and health probes on this worker are at risk of
+ timing out. Exported as a gauge so operators can alert on it.
+ """
+ from prometheus_client import Gauge # noqa: PLC0415 — deferred with the rest of post-fork init
+
+ lag_gauge = Gauge(
+ "posthog_asgi_event_loop_lag_seconds",
+ "How late the 1s heartbeat task woke up on this worker's event loop",
+ multiprocess_mode="livemax",
+ )
+ while True:
+ try:
+ before = time.monotonic()
+ await asyncio.sleep(_LOOP_LAG_HEARTBEAT_SECONDS)
+ lag_gauge.set(max(0.0, time.monotonic() - before - _LOOP_LAG_HEARTBEAT_SECONDS))
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ logger.exception("event_loop_lag_heartbeat_error")
+ await asyncio.sleep(_LOOP_LAG_HEARTBEAT_SECONDS)
+
+
+# Strong reference so the heartbeat task cannot be garbage-collected mid-flight
+# (the event loop only keeps weak references to tasks).
+_loop_lag_heartbeat_task: "asyncio.Task[None] | None" = None
+
+
+def _start_event_loop_lag_heartbeat() -> None:
+ global _loop_lag_heartbeat_task
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ return # not on an event loop (e.g. WSGI import path); nothing to measure
+ _loop_lag_heartbeat_task = loop.create_task(_event_loop_lag_heartbeat())
+
def _ensure_post_fork_init():
global _post_fork_initialized
@@ -50,6 +95,7 @@ def _ensure_post_fork_init():
# threads (it starts none), but because signal handlers must be set on the worker's
# main thread, which this init runs on. Inert unless WEB_MEMORY_PROBE_ENABLED is set.
install_memory_probe_handler()
+ _start_event_loop_lag_heartbeat()
_post_fork_initialized = True
diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.py
index fdc2b249b4ac..6f9b9d7acf95 100644
--- a/posthog/session_recordings/session_recording_api.py
+++ b/posthog/session_recordings/session_recording_api.py
@@ -1675,7 +1675,8 @@ class SessionRecordingViewSet(
return sse_streaming_response(
self._generate_video_based_summary(
session_id, user, tracking_id, product_context, custom_tags, force_restart=force_restart
- )
+ ),
+ endpoint="session_recording_summary",
)
@extend_schema(exclude=True)
diff --git a/products/ai_observability/backend/api/proxy.py b/products/ai_observability/backend/api/proxy.py
index 2f624179f969..a765c3599369 100644
--- a/products/ai_observability/backend/api/proxy.py
+++ b/products/ai_observability/backend/api/proxy.py
@@ -196,7 +196,7 @@ class LLMProxyViewSet(viewsets.ViewSet):
def _create_streaming_response(self, stream: Generator[bytes]) -> StreamingHttpResponse:
"""Creates a properly configured SSE streaming response"""
astream = SyncIterableToAsync(stream) if SERVER_GATEWAY_INTERFACE == "ASGI" else stream
- return sse_streaming_response(astream)
+ return sse_streaming_response(astream, endpoint="ai_observability_proxy")
def _handle_completion_request(self, request: Request) -> StreamingHttpResponse | Response:
"""Handler for completion requests using unified Client"""
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index fee7670c6a4a..15573fb71d50 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -2391,7 +2391,8 @@ class DashboardsViewSet(
return sse_streaming_response(
async_tile_stream_generator()
if settings.SERVER_GATEWAY_INTERFACE == "ASGI"
- else async_to_sync(lambda: async_tile_stream_generator())
+ else async_to_sync(lambda: async_tile_stream_generator()),
+ endpoint="dashboard_tile_stream",
)
def _get_layout_size_from_request(self, request: Request) -> str:
diff --git a/products/mcp_store/backend/proxy.py b/products/mcp_store/backend/proxy.py
index 2ca6a9989dd2..44eec0a59257 100644
--- a/products/mcp_store/backend/proxy.py
+++ b/products/mcp_store/backend/proxy.py
@@ -444,7 +444,7 @@ def _stream_upstream(upstream_response: httpx.Response, client: httpx.Client) ->
def _build_sse_response(upstream_response: httpx.Response, client: httpx.Client) -> StreamingHttpResponse:
stream = _stream_upstream(upstream_response, client)
astream = SyncIterableToAsync(stream) if SERVER_GATEWAY_INTERFACE == "ASGI" else stream
- response = sse_streaming_response(astream)
+ response = sse_streaming_response(astream, endpoint="mcp_store_proxy")
upstream_session_id = upstream_response.headers.get("mcp-session-id")
if upstream_session_id:
diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.py
index 1e7ac874b738..a0725cd872d1 100644
--- a/products/notebooks/backend/presentation/views/notebook.py
+++ b/products/notebooks/backend/presentation/views/notebook.py
@@ -831,7 +831,7 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
yield f"event: error\ndata: {payload_json}\n\n".encode()
streaming_content = SyncIterableToAsync(stream()) if SERVER_GATEWAY_INTERFACE == "ASGI" else stream()
- return sse_streaming_response(streaming_content)
+ return sse_streaming_response(streaming_content, endpoint="notebook_stream")
@action(methods=["GET"], url_path="kernel/dataframe", detail=True)
def kernel_dataframe(self, request: Request, **kwargs):
@@ -1103,7 +1103,8 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
if SERVER_GATEWAY_INTERFACE == "ASGI"
else async_to_sync(
lambda: collab_stream.stream_collab_sse(team_id, notebook_id, last_event_id=last_event_id)
- )
+ ),
+ endpoint="notebook_collab",
)
@action(methods=["GET"], detail=False)
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index b4503f32485d..71378af84f37 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -600,4 +600,4 @@ class SessionReplayObservationViewSet(ReplayObservationViewSet):
if getattr(settings, "SERVER_GATEWAY_INTERFACE", "ASGI") != "ASGI":
raise RuntimeError("observation progress stream requires ASGI.")
observation = self.get_object()
- return sse_streaming_response(stream_observation_progress(observation))
+ return sse_streaming_response(stream_observation_progress(observation), endpoint="replay_vision_observation")
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index b5a52a4ffc77..8c70cf5f1693 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -1879,7 +1879,8 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
# long-lived stream begins — see sse_streaming_response. The stream body is
# Redis-only, so it never re-acquires one.
return sse_streaming_response(
- async_stream() if settings.SERVER_GATEWAY_INTERFACE == "ASGI" else async_to_sync(lambda: async_stream())
+ async_stream() if settings.SERVER_GATEWAY_INTERFACE == "ASGI" else async_to_sync(lambda: async_stream()),
+ endpoint="task_run_log",
)
@staticmethod
diff --git a/products/wizard/backend/presentation/views.py b/products/wizard/backend/presentation/views.py
index 701b43696a56..089926f41029 100644
--- a/products/wizard/backend/presentation/views.py
+++ b/products/wizard/backend/presentation/views.py
@@ -338,7 +338,7 @@ class WizardSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
# Releases the request-thread DB connection (auth, team resolution) before
# the long-lived stream begins — see sse_streaming_response.
- return sse_streaming_response(generator)
+ return sse_streaming_response(generator, endpoint="wizard_session")
async def _wizard_session_event_stream(