: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
fix(wizard): release pinned DB connection on the SSE stream (#61509)
Stephen Schmidtbdc84c8a7f94
diff --git a/posthog/api/streaming.py b/posthog/api/streaming.pynew file mode 100644index 000000000000..3e94e5d92733--- /dev/null+++ b/posthog/api/streaming.py@@ -0,0 +1,48 @@+from collections.abc import AsyncIterator, Iterator+from http import HTTPStatus++from django.db import close_old_connections+from django.http import StreamingHttpResponse++# Disable proxy buffering/caching so SSE chunks reach the client immediately+# (nginx/Envoy in front of web-django otherwise buffer the stream).+_SSE_DEFAULT_HEADERS = {+ "Cache-Control": "no-cache, no-transform",+ "X-Accel-Buffering": "no",+}+++def sse_streaming_response(+ stream: Iterator[bytes] | AsyncIterator[bytes],+ *,+ status: int = HTTPStatus.OK,+ headers: dict[str, str] | None = None,+) -> StreamingHttpResponse:+ """Build a ``text/event-stream`` response for a long-lived SSE endpoint.++ Use this instead of constructing ``StreamingHttpResponse`` directly. It+ enforces the invariant that's otherwise easy to forget:++ sync DB work before a long-lived SSE stream must release its connection+ before streaming starts.++ PostHog runs with ``CONN_MAX_AGE = 0``, so any connection still open when the+ stream begins (from authentication, team resolution, ``get_object``, or+ serializer/ORM reads in the sync view) stays pinned to a pgbouncer client+ slot for the *entire* stream — ``request_finished`` only frees it once the+ stream ends, which for SSE is many minutes. At scale that turns every+ concurrent subscriber into a held connection and exhausts the pool. Calling+ ``close_old_connections()`` here releases the request-thread connection+ before the stream starts.++ The stream body must not rely on the request-thread connection: do any+ in-stream DB work through ``posthog.sync.database_sync_to_async`` so it+ acquires and releases its own connection.+ """+ close_old_connections()+ return StreamingHttpResponse(+ stream,+ status=status,+ content_type="text/event-stream",+ headers={**_SSE_DEFAULT_HEADERS, **(headers or {})},+ )diff --git a/posthog/api/test/test_streaming.py b/posthog/api/test/test_streaming.pynew file mode 100644index 000000000000..d9038689fb12--- /dev/null+++ b/posthog/api/test/test_streaming.py@@ -0,0 +1,38 @@+from collections.abc import Iterator+from http import HTTPStatus++from unittest import mock++from django.http import StreamingHttpResponse++from posthog.api.streaming import sse_streaming_response+++def _gen() -> Iterator[bytes]:+ yield b"data: hello\n\n"+++class TestSSEStreamingResponse:+ def test_releases_db_connection_before_streaming(self):+ with mock.patch("posthog.api.streaming.close_old_connections") as release:+ sse_streaming_response(_gen())+ release.assert_called_once()++ def test_sets_event_stream_content_type_and_default_headers(self):+ response = sse_streaming_response(_gen())+ assert isinstance(response, StreamingHttpResponse)+ assert response.headers["Content-Type"] == "text/event-stream"+ assert response.headers["Cache-Control"] == "no-cache, no-transform"+ assert response.headers["X-Accel-Buffering"] == "no"+ assert response.status_code == HTTPStatus.OK++ def test_caller_headers_and_status_override_defaults(self):+ response = sse_streaming_response(+ _gen(),+ status=HTTPStatus.ACCEPTED,+ headers={"Cache-Control": "no-cache", "X-Custom": "1"},+ )+ assert response.status_code == HTTPStatus.ACCEPTED+ assert response.headers["Cache-Control"] == "no-cache"+ assert response.headers["X-Accel-Buffering"] == "no"+ assert response.headers["X-Custom"] == "1"diff --git a/products/wizard/backend/presentation/views.py b/products/wizard/backend/presentation/views.pyindex f27aec628fb0..f1a47ca7fc48 100644--- a/products/wizard/backend/presentation/views.py+++ b/products/wizard/backend/presentation/views.py@@ -10,12 +10,11 @@ from collections.abc import AsyncIteratorfrom typing import Anyfrom django.conf import settings-from django.http import HttpResponse, StreamingHttpResponse+from django.http import HttpResponsefrom django.http.response import HttpResponseBaseimport structlogimport posthoganalytics-from asgiref.sync import sync_to_asyncfrom drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schemafrom rest_framework import status, viewsetsfrom rest_framework.decorators import action@@ -25,7 +24,9 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.streaming import sse_streaming_responsefrom posthog.models.scoping import team_scope+from posthog.sync import database_sync_to_asyncfrom products.wizard.backend.facade import api as wizard_facadefrom products.wizard.backend.facade.contracts import (@@ -281,15 +282,9 @@ class WizardSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):skill_id=skill_id,request=request,)- return StreamingHttpResponse(- generator,- status=status.HTTP_200_OK,- content_type="text/event-stream",- headers={- "Cache-Control": "no-cache, no-transform",- "X-Accel-Buffering": "no",- },- )+ # Releases the request-thread DB connection (auth, team resolution) before+ # the long-lived stream begins — see sse_streaming_response.+ return sse_streaming_response(generator)async def _wizard_session_event_stream(@@ -311,7 +306,9 @@ async def _wizard_session_event_stream(with team_scope(team_id):return wizard_facade.get_latest(team_id, workflow_id, skill_id)- latest = await sync_to_async(_get_initial, thread_sensitive=False)()+ # database_sync_to_async releases the DB connection after the read so it+ # isn't pinned for the whole SSE stream (CONN_MAX_AGE=0; loop is Redis-only).+ latest = await database_sync_to_async(_get_initial, thread_sensitive=False)()if latest is not None:yield b"data: " + wizard_facade.serialize_dto(latest) + b"\n\n"