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(api): enforce streaming-response wrapper that releases DB connections (#66813)

Paul D'Ambrac963cafc1680
diff --git a/.semgrep/rules/no-direct-streaming-http-response.py b/.semgrep/rules/no-direct-streaming-http-response.py
new file mode 100644
index 000000000000..77fdc4890dca
--- /dev/null
+++ b/.semgrep/rules/no-direct-streaming-http-response.py
@@ -0,0 +1,54 @@
+# Test cases for no-direct-streaming-http-response rule
+# ruff: noqa: F841, E501 — assignments exist solely to give semgrep something to match
+
+from django.http import StreamingHttpResponse
+
+from posthog.api.streaming import sse_streaming_response, streaming_response
+
+
+def stream():
+ yield b""
+
+
+# ============================================================
+# Should flag: direct construction
+# ============================================================
+
+
+def flag_bare_import():
+ # ruleid: no-direct-streaming-http-response
+ return StreamingHttpResponse(stream(), content_type="text/event-stream")
+
+
+def flag_with_kwargs():
+ # ruleid: no-direct-streaming-http-response
+ response = StreamingHttpResponse(streaming_content=stream(), content_type="audio/mpeg")
+ response["Cache-Control"] = "no-cache"
+ return response
+
+
+def flag_fully_qualified():
+ import django.http
+
+ # ruleid: no-direct-streaming-http-response
+ return django.http.StreamingHttpResponse(stream(), content_type="text/event-stream")
+
+
+# ============================================================
+# Should NOT flag: using the wrappers, or annotation-only use
+# ============================================================
+
+
+def ok_streaming_response():
+ # ok: no-direct-streaming-http-response
+ return streaming_response(stream(), content_type="audio/mpeg")
+
+
+def ok_sse_streaming_response():
+ # ok: no-direct-streaming-http-response
+ return sse_streaming_response(stream())
+
+
+# ok: no-direct-streaming-http-response
+def ok_return_annotation() -> StreamingHttpResponse:
+ return sse_streaming_response(stream())
diff --git a/.semgrep/rules/no-direct-streaming-http-response.yaml b/.semgrep/rules/no-direct-streaming-http-response.yaml
new file mode 100644
index 000000000000..a724655bade0
--- /dev/null
+++ b/.semgrep/rules/no-direct-streaming-http-response.yaml
@@ -0,0 +1,25 @@
+rules:
+ - id: no-direct-streaming-http-response
+ message: >-
+ Do not construct `StreamingHttpResponse` directly. Use
+ `streaming_response(...)` (or `sse_streaming_response(...)` for SSE) from
+ `posthog.api.streaming`. The wrapper releases the request thread's DB
+ connections before streaming starts — PostHog runs with `CONN_MAX_AGE = 0`,
+ so a connection left open when a long-lived stream begins stays pinned to a
+ pgbouncer slot for the entire stream and exhausts the pool at scale.
+ Importing the class for a type hint (e.g. `-> StreamingHttpResponse`) is fine
+ — only direct construction is flagged.
+ severity: ERROR
+ languages: [python]
+ pattern-either:
+ - pattern: StreamingHttpResponse(...)
+ - pattern: django.http.StreamingHttpResponse(...)
+ paths:
+ exclude:
+ # The wrappers live here — the only allowed construction site.
+ - /posthog/api/streaming.py
+ # Rule fixtures and tests construct it directly on purpose.
+ - '**/.semgrep/**'
+ - '**/test/**'
+ - '**/tests/**'
+ - '**/test_*.py'
diff --git a/ee/api/conversation.py b/ee/api/conversation.py
index 4a3b033e49ab..b63de58352b1 100644
--- a/ee/api/conversation.py
+++ b/ee/api/conversation.py
@@ -6,7 +6,6 @@ from typing import cast
from django.conf import settings
from django.core.exceptions import ValidationError
-from django.http import StreamingHttpResponse
from django.utils import timezone
import pydantic
@@ -27,7 +26,7 @@ from rest_framework.viewsets import GenericViewSet
from posthog.schema import AgentMode, AssistantMessage, HumanMessage, MaxBillingContext
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.api.streaming import _release_request_connections
+from posthog.api.streaming import sse_streaming_response
from posthog.event_usage import report_user_action
from posthog.exceptions import Conflict, QuotaLimitExceeded
from posthog.exceptions_capture import capture_exception
@@ -600,14 +599,10 @@ class ConversationViewSet(
event = await serializer.dumps(chunk)
yield event.encode("utf-8")
- _release_request_connections()
- return StreamingHttpResponse(
- (
- async_stream(workflow_inputs)
- if settings.SERVER_GATEWAY_INTERFACE == "ASGI"
- else async_to_sync(lambda: async_stream(workflow_inputs))
- ),
- content_type="text/event-stream",
+ return sse_streaming_response(
+ async_stream(workflow_inputs)
+ if settings.SERVER_GATEWAY_INTERFACE == "ASGI"
+ else async_to_sync(lambda: async_stream(workflow_inputs))
)
@action(detail=True, methods=["GET", "POST"], url_path="queue")
diff --git a/ee/api/hands_free.py b/ee/api/hands_free.py
index 9fe48a416250..ae38471059f8 100644
--- a/ee/api/hands_free.py
+++ b/ee/api/hands_free.py
@@ -27,6 +27,7 @@ from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.streaming import streaming_response
from posthog.permissions import PostHogFeatureFlagPermission
from posthog.rate_limit import (
MaxHandsFreeSynthesizeBurstRateThrottle,
@@ -233,8 +234,9 @@ class MaxHandsFreeViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
finally:
upstream.close()
- response = StreamingHttpResponse(stream_and_close(), content_type="audio/mpeg")
- response["Cache-Control"] = "no-store"
+ response = streaming_response(
+ stream_and_close(), content_type="audio/mpeg", headers={"Cache-Control": "no-store"}
+ )
except Exception:
upstream.close()
raise
diff --git a/ee/api/session_summaries.py b/ee/api/session_summaries.py
index 9c11f91973f1..d9374f5286c1 100644
--- a/ee/api/session_summaries.py
+++ b/ee/api/session_summaries.py
@@ -27,7 +27,7 @@ from rest_framework.viewsets import GenericViewSet
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
-from posthog.api.streaming import _release_request_connections
+from posthog.api.streaming import sse_streaming_response
from posthog.clickhouse.query_tagging import Product, tag_queries
from posthog.cloud_utils import is_cloud
from posthog.event_usage import EventSource, get_event_source
@@ -600,14 +600,8 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
done_data = json.dumps({"completed": completed_ids, "failed": failed_ids})
yield f"event: done\ndata: {done_data}\n\n".encode()
- _release_request_connections()
- return StreamingHttpResponse(
- (async_stream() if settings.SERVER_GATEWAY_INTERFACE == "ASGI" else async_generator_to_sync(async_stream)),
- content_type="text/event-stream",
- headers={
- "Cache-Control": "no-cache",
- "X-Accel-Buffering": "no",
- },
+ return sse_streaming_response(
+ async_stream() if settings.SERVER_GATEWAY_INTERFACE == "ASGI" else async_generator_to_sync(async_stream)
)
@extend_schema(
diff --git a/ee/api/test/test_hands_free.py b/ee/api/test/test_hands_free.py
index 6d088cce8d8b..44ba7eae4ad8 100644
--- a/ee/api/test/test_hands_free.py
+++ b/ee/api/test/test_hands_free.py
@@ -129,7 +129,7 @@ class TestMaxHandsFreeAPI(APIBaseTest):
response = self.client.post(self._synthesize_url(), data={"text": "hello"}, format="json")
assert response.status_code in (401, 403)
- @patch("ee.api.hands_free.StreamingHttpResponse")
+ @patch("posthog.api.streaming.StreamingHttpResponse")
@patch("ee.api.hands_free.requests.post")
def test_synthesize_closes_upstream_when_response_construction_fails(
self, mock_post: MagicMock, mock_streaming_response: MagicMock
diff --git a/ee/api/test/test_session_summaries.py b/ee/api/test/test_session_summaries.py
index f911455bd7c8..8f5d8fe00f5e 100644
--- a/ee/api/test/test_session_summaries.py
+++ b/ee/api/test/test_session_summaries.py
@@ -654,7 +654,7 @@ class TestStreamSessionSummariesAPI(APIBaseTest):
self.assertEqual(response.status_code, 200)
self.assertEqual(response.get("Content-Type"), "text/event-stream")
- self.assertEqual(response.get("Cache-Control"), "no-cache")
+ self.assertEqual(response.get("Cache-Control"), "no-cache, no-transform")
self.assertEqual(response.get("X-Accel-Buffering"), "no")
@patch("ee.api.session_summaries.capture_session_summary_generated")
diff --git a/ee/api/tests/test_conversation.py b/ee/api/tests/test_conversation.py
index 481ac56322c9..5fed1f03bced 100644
--- a/ee/api/tests/test_conversation.py
+++ b/ee/api/tests/test_conversation.py
@@ -119,7 +119,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
) as mock_start_workflow_and_stream:
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
trace_id = str(uuid.uuid4())
response = self.client.post(
f"/api/environments/{self.team.id}/conversations/",
@@ -147,7 +147,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
) as mock_start_workflow_and_stream:
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
conversation = Conversation.objects.create(user=self.user, team=self.team)
trace_id = str(uuid.uuid4())
response = self.client.post(
@@ -178,7 +178,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
) as mock_start_workflow_and_stream:
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
trace_id = str(uuid.uuid4())
response = self.client.post(
f"/api/environments/{self.team.id}/conversations/",
@@ -236,7 +236,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
):
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
for _ in range(11): # Assuming burst limit is less than this
response = self.client.post(
f"/api/environments/{self.team.id}/conversations/",
@@ -268,7 +268,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
) as mock_stream_conversation:
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
trace_id = str(uuid.uuid4())
response = self.client.post(
f"/api/environments/{self.team.id}/conversations/",
@@ -304,7 +304,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
):
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
response = self.client.post(
f"/api/environments/{self.team.id}/conversations/",
{
@@ -470,7 +470,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
) as mock_stream_conversation:
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
response = self.client.post(
f"/api/environments/{self.team.id}/conversations/",
{
@@ -656,7 +656,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
):
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
# First 3 requests should succeed (3/minute limit)
for i in range(3):
response = self.client.post(
@@ -693,7 +693,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
):
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
# First 3 new research conversations should succeed (3/minute limit)
for i in range(3):
response = self.client.post(
@@ -734,7 +734,7 @@ class TestConversation(APIBaseTest):
return_value=_async_generator(),
):
with patch(
- "ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response
+ "posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response
):
# Should exceed the 3/minute burst limit without being throttled
for i in range(5):
@@ -756,7 +756,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
):
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
# First 10 requests should succeed (10/minute limit)
for i in range(10):
response = self.client.post(
@@ -792,7 +792,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
) as mock_start_workflow_and_stream:
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
trace_id = str(uuid.uuid4())
response = self.client.post(
f"/api/environments/{self.team.id}/conversations/",
@@ -816,7 +816,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
) as mock_start_workflow_and_stream:
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
trace_id = str(uuid.uuid4())
response = self.client.post(
f"/api/environments/{self.team.id}/conversations/",
@@ -862,7 +862,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
):
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
response = self.client.post(
f"/api/environments/{self.team.id}/conversations/",
{
@@ -884,7 +884,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
) as mock_start_workflow_and_stream:
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
trace_id = str(uuid.uuid4())
response = self.client.post(
f"/api/environments/{self.team.id}/conversations/",
@@ -924,7 +924,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
) as mock_start_workflow_and_stream:
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
# Not patching is_impersonated_session, so it defaults to False (not impersonated)
response = self.client.post(
f"/api/environments/{self.team.id}/conversations/",
@@ -955,7 +955,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
) as mock_astream:
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
response = self.client.post(
f"/api/environments/{self.team.id}/conversations/",
{
@@ -990,7 +990,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
) as mock_astream:
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
response = self.client.post(
f"/api/environments/{self.team.id}/conversations/",
{
@@ -1021,7 +1021,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
) as mock_astream:
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
response = self.client.post(
f"/api/environments/{self.team.id}/conversations/",
{
@@ -1054,7 +1054,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
):
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
# First message converts DEEP_RESEARCH → ASSISTANT
self.client.post(
f"/api/environments/{self.team.id}/conversations/",
@@ -1083,7 +1083,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
) as mock_start_workflow_and_stream:
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
response = self.client.post(
f"/api/environments/{self.team.id}/conversations/",
{
@@ -1124,7 +1124,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
) as mock_astream:
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
billing_data = self.billing_context.model_dump()
billing_data["spend_history"] = self._make_spend_history(21)
response = self.client.post(
@@ -1145,7 +1145,7 @@ class TestConversation(APIBaseTest):
"ee.hogai.core.executor.AgentExecutor.astream",
return_value=_async_generator(),
) as mock_astream:
- with patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
+ with patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._create_mock_streaming_response):
billing_data = self.billing_context.model_dump()
billing_data["spend_history"] = self._make_spend_history(20)
response = self.client.post(
@@ -2006,7 +2006,7 @@ class TestConversationCreateRuntime(APIBaseTest):
patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),
patch("ee.api.conversation.SandboxSession") as m_routing,
patch("ee.hogai.core.executor.AgentExecutor.astream", return_value=_async_generator()),
- patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._mock_streaming_response),
+ patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._mock_streaming_response),
):
response = self.client.post(
f"/api/environments/{self.team.id}/conversations/",
@@ -2054,7 +2054,7 @@ class TestConversationCreateRuntime(APIBaseTest):
patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=False),
patch("ee.api.conversation.SandboxSession") as m_routing,
patch("ee.hogai.core.executor.AgentExecutor.astream", return_value=_async_generator()),
- patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._mock_streaming_response),
+ patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._mock_streaming_response),
):
response = self._send(conversation, content="keep me on langgraph")
diff --git a/ee/hogai/sandbox/executor.py b/ee/hogai/sandbox/executor.py
index 675457156e41..83ec7908f516 100644
--- a/ee/hogai/sandbox/executor.py
+++ b/ee/hogai/sandbox/executor.py
@@ -16,6 +16,7 @@ from rest_framework import exceptions
from posthog.schema import AssistantEventType, AssistantMessage, HumanMessage
+from posthog.api.streaming import sse_streaming_response
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.temporal.common.client import sync_connect
@@ -186,13 +187,10 @@ def _make_streaming_response(
async_generator_factory: Callable[[], AsyncGenerator[bytes]],
) -> StreamingHttpResponse:
"""Create a StreamingHttpResponse that works under both ASGI and WSGI."""
- return StreamingHttpResponse(
- (
- async_generator_factory()
- if settings.SERVER_GATEWAY_INTERFACE == "ASGI"
- else async_to_sync(async_generator_factory)
- ),
- content_type="text/event-stream",
+ return sse_streaming_response(
+ async_generator_factory()
+ if settings.SERVER_GATEWAY_INTERFACE == "ASGI"
+ else async_to_sync(async_generator_factory)
)
diff --git a/posthog/api/query.py b/posthog/api/query.py
index 52ca90b0c123..2f8487ab6c2c 100644
--- a/posthog/api/query.py
+++ b/posthog/api/query.py
@@ -42,6 +42,7 @@ from posthog.api.monitoring import (
from posthog.api.query_coalescer import QueryCoalescingMixin
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.services.query import process_query_model
+from posthog.api.streaming import sse_streaming_response
from posthog.api.utils import action, is_async_query, is_insight_actors_options_query, is_insight_actors_query
from posthog.clickhouse.client.execute_async import cancel_query, get_query_status
from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
@@ -442,13 +443,4 @@ MAX_QUERY_TIMEOUT = 600
async def progress(request: Request, *args, **kwargs) -> StreamingHttpResponse:
# TEMPORARY endpoint to avoid breaking changes
- return StreamingHttpResponse(
- [],
- status=status.HTTP_200_OK,
- content_type="text/event-stream",
- headers={
- "Cache-Control": "no-cache",
- "X-Accel-Buffering": "no",
- "Connection": "keep-alive",
- },
- )
+ return sse_streaming_response([], status=status.HTTP_200_OK, headers={"Connection": "keep-alive"})
diff --git a/posthog/api/streaming.py b/posthog/api/streaming.py
index fceb53e90589..1cf7cc7d325f 100644
--- a/posthog/api/streaming.py
+++ b/posthog/api/streaming.py
@@ -1,9 +1,14 @@
-from collections.abc import AsyncIterator, Iterator
+from collections.abc import AsyncIterable, Iterable
from http import HTTPStatus
from django.db import connections
from django.http import StreamingHttpResponse
+# 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.
+StreamContent = Iterable[bytes | str] | AsyncIterable[bytes | str]
+
# 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 = {
@@ -33,8 +38,34 @@ def _release_request_connections() -> None:
conn.close()
+def streaming_response(
+ stream: StreamContent,
+ *,
+ content_type: str,
+ status: int = HTTPStatus.OK,
+ headers: dict[str, str] | None = None,
+) -> StreamingHttpResponse:
+ """Build a ``StreamingHttpResponse``, releasing request-thread DB connections first.
+
+ Use this (or ``sse_streaming_response`` for SSE) instead of constructing
+ ``StreamingHttpResponse`` directly — a semgrep rule enforces it. See
+ ``sse_streaming_response`` for why releasing connections matters.
+
+ 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.
+ """
+ _release_request_connections()
+ return StreamingHttpResponse(
+ stream,
+ status=status,
+ content_type=content_type,
+ headers=headers or {},
+ )
+
+
def sse_streaming_response(
- stream: Iterator[bytes] | AsyncIterator[bytes],
+ stream: StreamContent,
*,
status: int = HTTPStatus.OK,
headers: dict[str, str] | None = None,
@@ -65,10 +96,9 @@ def sse_streaming_response(
then stays pinned for the whole stream. Keep response middleware DB-free on
SSE paths.
"""
- _release_request_connections()
- return StreamingHttpResponse(
+ return streaming_response(
stream,
- status=status,
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 a93af5008cc0..42c558d2cfb0 100644
--- a/posthog/api/test/test_streaming.py
+++ b/posthog/api/test/test_streaming.py
@@ -5,7 +5,7 @@ from unittest import mock
from django.http import StreamingHttpResponse
-from posthog.api.streaming import sse_streaming_response
+from posthog.api.streaming import sse_streaming_response, streaming_response
def _gen() -> Iterator[bytes]:
@@ -46,3 +46,13 @@ class TestSSEStreamingResponse:
assert response.headers["Cache-Control"] == "no-cache"
assert response.headers["X-Accel-Buffering"] == "no"
assert response.headers["X-Custom"] == "1"
+
+
+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
+ # content_type through and NOT forcing the SSE-only proxy-buffering header.
+ response = streaming_response(_gen(), content_type="audio/mpeg")
+ assert response.headers["Content-Type"] == "audio/mpeg"
+ assert "X-Accel-Buffering" not in response.headers
+ assert response.status_code == HTTPStatus.OK
diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.py
index f3733e3e7fb7..fdc2b249b4ac 100644
--- a/posthog/session_recordings/session_recording_api.py
+++ b/posthog/session_recordings/session_recording_api.py
@@ -16,7 +16,7 @@ from urllib.parse import urlparse
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.core.cache import cache
-from django.http import HttpResponse, JsonResponse, StreamingHttpResponse
+from django.http import HttpResponse, JsonResponse
import requests
import structlog
@@ -58,7 +58,7 @@ from posthog.schema import (
from posthog.api.person import MinimalPersonSerializer
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.api.streaming import _release_request_connections
+from posthog.api.streaming import sse_streaming_response
from posthog.api.utils import ServerTimingsGathered, action, safe_clickhouse_string
from posthog.auth import (
ExportRendererAuthentication,
@@ -90,7 +90,6 @@ from posthog.rate_limit import (
)
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
from posthog.rbac.user_access_control import UserAccessControlSerializerMixin
-from posthog.renderers import ServerSentEventRenderer
from posthog.session_recordings.ai_data.ai_regex_prompts import AI_REGEX_PROMPTS
from posthog.session_recordings.ai_data.ai_regex_schema import AiRegexSchema
from posthog.session_recordings.models.session_recording import SessionRecording
@@ -1673,16 +1672,11 @@ class SessionRecordingViewSet(
session_ids=[session_id],
video_based=True,
)
- _release_request_connections()
- response = StreamingHttpResponse(
+ return sse_streaming_response(
self._generate_video_based_summary(
session_id, user, tracking_id, product_context, custom_tags, force_restart=force_restart
- ),
- content_type=ServerSentEventRenderer.media_type,
+ )
)
- response["Cache-Control"] = "no-cache"
- response["X-Accel-Buffering"] = "no"
- return response
@extend_schema(exclude=True)
@action(methods=["POST"], detail=True, url_path="summarize/cancel")
diff --git a/products/agent_platform/backend/presentation/views.py b/products/agent_platform/backend/presentation/views.py
index 0b68cf8539b6..6f15ab0e2a48 100644
--- a/products/agent_platform/backend/presentation/views.py
+++ b/products/agent_platform/backend/presentation/views.py
@@ -62,6 +62,7 @@ from posthog.schema import ProductKey
from posthog.api.log_entries import LogEntryRequestSerializer, LogEntrySerializer, fetch_log_entries
from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.streaming import streaming_response
from posthog.auth import OAuthAccessTokenAuthentication, SessionAuthentication
from posthog.clickhouse.query_tagging import Feature, tag_queries
from posthog.helpers.encrypted_fields import EncryptedTextField
@@ -786,10 +787,10 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
finally:
await sync_to_async(upstream.close, thread_sensitive=False)()
- resp = StreamingHttpResponse(
+ resp = streaming_response(
_stream(),
- status=upstream.status_code,
content_type=upstream.headers.get("Content-Type", "application/octet-stream"),
+ status=upstream.status_code,
)
# Forward upstream response headers verbatim minus connection-control
# ones that Django handles itself.
diff --git a/products/ai_observability/backend/api/proxy.py b/products/ai_observability/backend/api/proxy.py
index 730400694ac0..8de30f3edd72 100644
--- a/products/ai_observability/backend/api/proxy.py
+++ b/products/ai_observability/backend/api/proxy.py
@@ -24,6 +24,7 @@ from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.monitoring import monitor
+from posthog.api.streaming import sse_streaming_response
from posthog.auth import SessionAuthentication
from posthog.event_usage import groups, report_user_action
from posthog.rate_limit import (
@@ -193,14 +194,8 @@ class LLMProxyViewSet(viewsets.ViewSet):
def _create_streaming_response(self, stream: Generator[bytes]) -> StreamingHttpResponse:
"""Creates a properly configured SSE streaming response"""
- if SERVER_GATEWAY_INTERFACE == "ASGI":
- astream = SyncIterableToAsync(stream)
- response = StreamingHttpResponse(streaming_content=astream, content_type=ServerSentEventRenderer.media_type)
- else:
- response = StreamingHttpResponse(streaming_content=stream, content_type=ServerSentEventRenderer.media_type)
- response["Cache-Control"] = "no-cache"
- response["X-Accel-Buffering"] = "no"
- return response
+ astream = SyncIterableToAsync(stream) if SERVER_GATEWAY_INTERFACE == "ASGI" else stream
+ return sse_streaming_response(astream)
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 1dfbe4c99444..fee7670c6a4a 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -53,7 +53,7 @@ from posthog.api.monitoring import Feature, monitor
from posthog.api.openapi_parameters import make_filters_override_param, make_variables_override_param
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializer
-from posthog.api.streaming import _release_request_connections
+from posthog.api.streaming import sse_streaming_response
from posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin
from posthog.api.utils import action
from posthog.clickhouse.client.async_task_chain import task_chain_context
@@ -2388,16 +2388,11 @@ class DashboardsViewSet(
error_json = renderer.render({"type": "error", "error": str(e)}).decode()
yield f"data: {error_json}\n\n".encode()
- _release_request_connections()
- response = StreamingHttpResponse(
- streaming_content=(
- async_tile_stream_generator()
- if settings.SERVER_GATEWAY_INTERFACE == "ASGI"
- else async_to_sync(lambda: async_tile_stream_generator())
- ),
- content_type=ServerSentEventRenderer.media_type,
+ return sse_streaming_response(
+ async_tile_stream_generator()
+ if settings.SERVER_GATEWAY_INTERFACE == "ASGI"
+ else async_to_sync(lambda: async_tile_stream_generator())
)
- return response
def _get_layout_size_from_request(self, request: Request) -> str:
"""Extract layout size parameter from request."""
diff --git a/products/mcp_store/backend/proxy.py b/products/mcp_store/backend/proxy.py
index 0eeee0cfbd62..2ca6a9989dd2 100644
--- a/products/mcp_store/backend/proxy.py
+++ b/products/mcp_store/backend/proxy.py
@@ -8,7 +8,7 @@ from django.http import HttpResponse, StreamingHttpResponse
import httpx
import structlog
-from posthog.api.streaming import _release_request_connections
+from posthog.api.streaming import sse_streaming_response
from posthog.security.url_validation import is_url_allowed
from posthog.settings import SERVER_GATEWAY_INTERFACE
@@ -404,7 +404,6 @@ def proxy_mcp_request(request: Any, installation: MCPServerInstallation) -> Http
content_type = upstream_response.headers.get("content-type", "")
if "text/event-stream" in content_type:
- _release_request_connections()
return _build_sse_response(upstream_response, client)
# Read body then close to avoid memory leaks from buffered responses
@@ -444,21 +443,8 @@ 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)
-
- if SERVER_GATEWAY_INTERFACE == "ASGI":
- astream = SyncIterableToAsync(stream)
- response = StreamingHttpResponse(
- streaming_content=astream,
- content_type="text/event-stream",
- )
- else:
- response = StreamingHttpResponse(
- streaming_content=stream,
- content_type="text/event-stream",
- )
-
- response["Cache-Control"] = "no-cache"
- response["X-Accel-Buffering"] = "no"
+ astream = SyncIterableToAsync(stream) if SERVER_GATEWAY_INTERFACE == "ASGI" else stream
+ response = sse_streaming_response(astream)
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 97c4666f8aa5..1e7ac874b738 100644
--- a/products/notebooks/backend/presentation/views/notebook.py
+++ b/products/notebooks/backend/presentation/views/notebook.py
@@ -5,7 +5,7 @@ from typing import Any, cast
from django.db import transaction
from django.db.models import Q, QuerySet
-from django.http import JsonResponse, StreamingHttpResponse
+from django.http import JsonResponse
from django.utils.timezone import now
import structlog
@@ -28,7 +28,7 @@ from posthog.hogql.query import execute_hogql_query
from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
-from posthog.api.streaming import _release_request_connections
+from posthog.api.streaming import sse_streaming_response
from posthog.api.utils import action
from posthog.exceptions import Conflict
from posthog.helpers.impersonation import is_impersonated
@@ -830,14 +830,8 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
payload_json = renderer.render(payload).decode()
yield f"event: error\ndata: {payload_json}\n\n".encode()
- _release_request_connections()
streaming_content = SyncIterableToAsync(stream()) if SERVER_GATEWAY_INTERFACE == "ASGI" else stream()
- response = StreamingHttpResponse(
- streaming_content=streaming_content, content_type=ServerSentEventRenderer.media_type
- )
- response["Cache-Control"] = "no-cache"
- response["X-Accel-Buffering"] = "no"
- return response
+ return sse_streaming_response(streaming_content)
@action(methods=["GET"], url_path="kernel/dataframe", detail=True)
def kernel_dataframe(self, request: Request, **kwargs):
@@ -1104,20 +1098,13 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
# On ASGI (Granian in prod) the async generator runs as one cheap task per connection.
# On WSGI (tests, fallback) async_to_sync bridges it via a worker thread + queue.
- _release_request_connections()
- response = StreamingHttpResponse(
- streaming_content=(
- collab_stream.stream_collab_sse(team_id, notebook_id, last_event_id=last_event_id)
- 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)
- )
- ),
- content_type=ServerSentEventRenderer.media_type,
+ return sse_streaming_response(
+ collab_stream.stream_collab_sse(team_id, notebook_id, last_event_id=last_event_id)
+ 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)
+ )
)
- response["Cache-Control"] = "no-cache"
- response["X-Accel-Buffering"] = "no"
- return response
@action(methods=["GET"], detail=False)
def recording_comments(self, request: Request, **kwargs):
diff --git a/products/notebooks/backend/test/test_collab_api.py b/products/notebooks/backend/test/test_collab_api.py
index 114e3a0b365e..76e5099f22bf 100644
--- a/products/notebooks/backend/test/test_collab_api.py
+++ b/products/notebooks/backend/test/test_collab_api.py
@@ -341,7 +341,7 @@ class TestNotebookCollabStreamAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert response["Content-Type"] == "text/event-stream"
- assert response["Cache-Control"] == "no-cache"
+ assert response["Cache-Control"] == "no-cache, no-transform"
assert response["X-Accel-Buffering"] == "no"
body = self._consume_stream(response)
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index bcc045c35a88..b4503f32485d 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -20,7 +20,7 @@ from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
-from posthog.api.streaming import _release_request_connections
+from posthog.api.streaming import sse_streaming_response
from posthog.renderers import ServerSentEventRenderer
from products.replay_vision.backend.api.filters import MultiChoiceFilter, OrderByFilter, ordering_enum
@@ -600,11 +600,4 @@ class SessionReplayObservationViewSet(ReplayObservationViewSet):
if getattr(settings, "SERVER_GATEWAY_INTERFACE", "ASGI") != "ASGI":
raise RuntimeError("observation progress stream requires ASGI.")
observation = self.get_object()
- _release_request_connections()
- response = StreamingHttpResponse(
- stream_observation_progress(observation),
- content_type=ServerSentEventRenderer.media_type,
- )
- response["Cache-Control"] = "no-cache"
- response["X-Accel-Buffering"] = "no"
- return response
+ return sse_streaming_response(stream_observation_progress(observation))