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.

fix(streaming): release DB connections before starting SSE streams (#66282)

Sam Penningtona8adf26b84b0
diff --git a/ee/api/conversation.py b/ee/api/conversation.py
index 4fd39d830e6f..4a3b033e49ab 100644
--- a/ee/api/conversation.py
+++ b/ee/api/conversation.py
@@ -27,6 +27,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.event_usage import report_user_action
from posthog.exceptions import Conflict, QuotaLimitExceeded
from posthog.exceptions_capture import capture_exception
@@ -599,6 +600,7 @@ class ConversationViewSet(
event = await serializer.dumps(chunk)
yield event.encode("utf-8")
+ _release_request_connections()
return StreamingHttpResponse(
(
async_stream(workflow_inputs)
diff --git a/ee/api/session_summaries.py b/ee/api/session_summaries.py
index 99f30d9b1a24..37474bf70a1f 100644
--- a/ee/api/session_summaries.py
+++ b/ee/api/session_summaries.py
@@ -28,6 +28,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.clickhouse.query_tagging import Product, tag_queries
from posthog.cloud_utils import is_cloud
from posthog.event_usage import EventSource, get_event_source
@@ -599,6 +600,7 @@ 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",
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index 4ee370c15723..1dfbe4c99444 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -36,7 +36,6 @@ from django.utils.timezone import now
import structlog
import pydantic_core
import posthoganalytics
-from asgiref.sync import sync_to_async
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_view
from opentelemetry import trace
@@ -54,6 +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.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin
from posthog.api.utils import action
from posthog.clickhouse.client.async_task_chain import task_chain_context
@@ -76,6 +76,7 @@ from posthog.resource_limits import LimitKey, check_count_limit
from posthog.session_recordings.session_recording_api import get_replay_listing_throttle_error
from posthog.slo.context import SloSpec, slo_operation
from posthog.slo.types import SloArea, SloOperation
+from posthog.sync import database_sync_to_async
from posthog.user_permissions import UserPermissionsSerializerMixin
from posthog.utils import filters_override_requested_by_client, str_to_bool, variables_override_requested_by_client
@@ -2345,7 +2346,7 @@ class DashboardsViewSet(
for order in range(initial_tile_count):
tile = sorted_tiles[order]
try:
- order_result, tile_data = await sync_to_async(
+ order_result, tile_data = await database_sync_to_async(
serialize_tile_with_context, thread_sensitive=True
)(tile, order, context)
initial_tiles.append(tile_data)
@@ -2368,7 +2369,7 @@ class DashboardsViewSet(
for order in range(initial_tile_count, len(sorted_tiles)):
tile = sorted_tiles[order]
try:
- order_result, tile_data = await sync_to_async(
+ order_result, tile_data = await database_sync_to_async(
serialize_tile_with_context, thread_sensitive=True
)(tile, order, context)
tile_json = renderer.render({"type": "tile", "order": order, "tile": tile_data}).decode()
@@ -2387,6 +2388,7 @@ 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()
diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.py
index 78119326f2ff..fa8a8ab0a81f 100644
--- a/products/notebooks/backend/presentation/views/notebook.py
+++ b/products/notebooks/backend/presentation/views/notebook.py
@@ -29,6 +29,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.utils import action
from posthog.exceptions import Conflict
from posthog.models import User
@@ -827,6 +828,7 @@ 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
@@ -1100,6 +1102,7 @@ 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)