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): per-process sse concurrency cap with 503 and jittered retry-after (#67945)

Fernando Gomesa273fb1d82fc
diff --git a/.semgrep/rules/security/no-direct-streaming-http-response.py b/.semgrep/rules/security/no-direct-streaming-http-response.py
index 77fdc4890dca..c0491bb707e0 100644
--- a/.semgrep/rules/security/no-direct-streaming-http-response.py
+++ b/.semgrep/rules/security/no-direct-streaming-http-response.py
@@ -2,6 +2,7 @@
# ruff: noqa: F841, E501 — assignments exist solely to give semgrep something to match
from django.http import StreamingHttpResponse
+from django.http.response import HttpResponseBase
from posthog.api.streaming import sse_streaming_response, streaming_response
@@ -50,5 +51,5 @@ def ok_sse_streaming_response():
# ok: no-direct-streaming-http-response
-def ok_return_annotation() -> StreamingHttpResponse:
+def ok_return_annotation() -> HttpResponseBase:
return sse_streaming_response(stream())
diff --git a/ee/api/session_summaries.py b/ee/api/session_summaries.py
index c7709280ddd1..f13b3d473588 100644
--- a/ee/api/session_summaries.py
+++ b/ee/api/session_summaries.py
@@ -11,7 +11,7 @@ from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.db.models import Func, IntegerField, QuerySet, Subquery
from django.db.models.fields.json import KeyTransform
-from django.http import StreamingHttpResponse
+from django.http.response import HttpResponseBase
import structlog
from asgiref.sync import async_to_sync
@@ -503,7 +503,7 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
required_scopes=["session_recording:read"],
renderer_classes=[ServerSentEventRenderer],
)
- def stream_batch_session_summaries(self, request: Request, **kwargs) -> StreamingHttpResponse:
+ def stream_batch_session_summaries(self, request: Request, **kwargs) -> HttpResponseBase:
user = self._validate_user(request)
# Use _parse_input (not _validate_input) — the individual flow must surface bad
# session IDs as per-session error events, not fail the whole batch up front.
diff --git a/ee/hogai/sandbox/executor.py b/ee/hogai/sandbox/executor.py
index a5b0aa9c8084..5decdbc73d6c 100644
--- a/ee/hogai/sandbox/executor.py
+++ b/ee/hogai/sandbox/executor.py
@@ -6,7 +6,7 @@ from collections.abc import AsyncGenerator, Callable
from typing import Any
from django.conf import settings
-from django.http import StreamingHttpResponse
+from django.http.response import HttpResponseBase
import structlog
from asgiref.sync import async_to_sync as asgi_async_to_sync
@@ -53,7 +53,7 @@ def handle_sandbox_message(
user: User,
team: Team,
is_new_conversation: bool,
-) -> StreamingHttpResponse:
+) -> HttpResponseBase:
"""Handle a sandbox-mode message: create/resume a task run and stream events back."""
if not settings.DEBUG and not has_sandbox_mode_feature_flag(team, user):
raise exceptions.PermissionDenied("Sandbox mode is not enabled for this user.")
@@ -185,7 +185,7 @@ def handle_sandbox_message(
def _make_streaming_response(
async_generator_factory: Callable[[], AsyncGenerator[bytes]],
-) -> StreamingHttpResponse:
+) -> HttpResponseBase:
"""Create a StreamingHttpResponse that works under both ASGI and WSGI."""
return sse_streaming_response(
async_generator_factory()
diff --git a/posthog/api/query.py b/posthog/api/query.py
index ec2a1c67f8f7..6164240de833 100644
--- a/posthog/api/query.py
+++ b/posthog/api/query.py
@@ -3,7 +3,8 @@ from time import perf_counter
from typing import NoReturn
from django.core.cache import cache
-from django.http import JsonResponse, StreamingHttpResponse
+from django.http import JsonResponse
+from django.http.response import HttpResponseBase
import orjson
import structlog
@@ -499,7 +500,7 @@ class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMi
MAX_QUERY_TIMEOUT = 600
-async def progress(request: Request, *args, **kwargs) -> StreamingHttpResponse:
+async def progress(request: Request, *args, **kwargs) -> HttpResponseBase:
# TEMPORARY endpoint to avoid breaking changes
return sse_streaming_response(
diff --git a/posthog/api/streaming.py b/posthog/api/streaming.py
index a718809677e3..c95411be64aa 100644
--- a/posthog/api/streaming.py
+++ b/posthog/api/streaming.py
@@ -1,10 +1,14 @@
import time
+import random
import asyncio
-from collections.abc import AsyncIterable, AsyncIterator, Iterable, Iterator
+import threading
+from collections import deque
+from collections.abc import AsyncGenerator, AsyncIterable, AsyncIterator, Generator, Iterable, Iterator
from http import HTTPStatus
+from django.conf import settings
from django.db import connections
-from django.http import StreamingHttpResponse
+from django.http import HttpResponse, StreamingHttpResponse
from prometheus_client import Counter, Gauge, Histogram
@@ -48,14 +52,115 @@ SSE_STREAM_DURATION_HISTOGRAM = Histogram(
)
+SSE_REJECTED_OVER_CAP_COUNTER = Counter(
+ "posthog_sse_rejected_over_cap_total",
+ "SSE streams rejected with 503 because the per-process concurrency cap was reached",
+ labelnames=["endpoint"],
+)
+
+# Per-process count of admitted streams: a slot is reserved under the lock
+# before the response leaves the view and released exactly once per stream,
+# so parallel admissions cannot race past the cap. The lock guards only the
+# check-and-increment and the release, never a yield or await. This counts
+# reservations; the gauge and counters above keep counting streams that
+# actually started being consumed.
+_stream_cap_lock = threading.Lock()
+_active_stream_count = 0
+
+# Slots freed by the GC backstop while the cap lock was unavailable. ``__del__``
+# can fire at any allocation point, including on a thread that already holds the
+# non-reentrant lock, so it must never block on it; ``deque.append`` is atomic,
+# and admission drains this queue under the lock.
+_deferred_slot_releases: deque[None] = deque()
+
+# Rejected clients get "come back in base + [0, jitter) seconds" so a burst that
+# hits the cap spreads its retries out instead of reconnecting in lockstep.
+_RETRY_AFTER_BASE_SECONDS = 15
+_RETRY_AFTER_JITTER_SECONDS = 30
+
+
+def _record_stream_open(endpoint: str) -> None:
+ SSE_STREAM_OPENED_COUNTER.labels(endpoint=endpoint).inc()
+ SSE_OPEN_CONNECTIONS_GAUGE.labels(endpoint=endpoint).inc()
+
+
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.
+class _StreamSlotReservation:
+ """One admitted slot against the per-process stream cap.
+
+ ``release`` is idempotent: both afterlives of a response call it (the
+ instrumented iterator's ``finally`` when the stream ran, the response's
+ resource closer when it never did) and only the first call frees the slot.
+ ``__del__`` backstops responses dropped without ``close()`` at all (the
+ ASGI handler skips it when the client disconnects during the
+ response-middleware phase, and exception-converting middleware drops the
+ original response unclosed), which would otherwise leak the slot until the
+ process restarts.
+ """
+
+ __slots__ = ("_released",)
+
+ def __init__(self) -> None:
+ self._released = False
+
+ def release(self) -> None:
+ global _active_stream_count
+ with _stream_cap_lock:
+ if self._released:
+ return
+ self._released = True
+ _active_stream_count -= 1
+
+ def __del__(self) -> None:
+ # GC can run while this thread holds the cap lock, so never block on it
+ # here: decrement inline when the lock is free, otherwise defer to the
+ # queue the next admission drains. No lock guards the flag because an
+ # object being finalized has no other referents left to race with.
+ global _active_stream_count
+ if self._released:
+ return
+ if _stream_cap_lock.acquire(blocking=False):
+ try:
+ self._released = True
+ _active_stream_count -= 1
+ finally:
+ _stream_cap_lock.release()
+ else:
+ self._released = True
+ _deferred_slot_releases.append(None)
+
+
+def _try_reserve_stream_slot() -> _StreamSlotReservation | None:
+ global _active_stream_count
+ cap = settings.SSE_MAX_CONCURRENT_STREAMS_PER_PROCESS
+ with _stream_cap_lock:
+ while _deferred_slot_releases:
+ _deferred_slot_releases.popleft()
+ _active_stream_count -= 1
+ if cap is not None and _active_stream_count >= cap:
+ return None
+ _active_stream_count += 1
+ return _StreamSlotReservation()
+
+
+def _stream_cap_rejection(endpoint: str) -> HttpResponse:
+ SSE_REJECTED_OVER_CAP_COUNTER.labels(endpoint=endpoint).inc()
+ retry_after = _RETRY_AFTER_BASE_SECONDS + random.randrange(_RETRY_AFTER_JITTER_SECONDS)
+ return HttpResponse(
+ status=HTTPStatus.SERVICE_UNAVAILABLE,
+ headers={"Retry-After": str(retry_after), **_SSE_DEFAULT_HEADERS},
+ )
+
+
+async def _instrumented_aiter(
+ stream: AsyncIterable[bytes | str], endpoint: str, reservation: _StreamSlotReservation
+) -> AsyncGenerator[bytes | str]:
+ """Pass chunks through untouched, tracking the open gauge, 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
@@ -63,8 +168,7 @@ async def _instrumented_aiter(stream: AsyncIterable[bytes | str], endpoint: str)
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()
+ _record_stream_open(endpoint)
started_at = time.monotonic()
outcome = "completed"
try:
@@ -78,11 +182,13 @@ async def _instrumented_aiter(stream: AsyncIterable[bytes | str], endpoint: str)
raise
finally:
_record_stream_close(endpoint, outcome, started_at)
+ reservation.release()
-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()
+def _instrumented_iter(
+ stream: Iterable[bytes | str], endpoint: str, reservation: _StreamSlotReservation
+) -> Generator[bytes | str]:
+ _record_stream_open(endpoint)
started_at = time.monotonic()
outcome = "completed"
try:
@@ -95,12 +201,58 @@ def _instrumented_iter(stream: Iterable[bytes | str], endpoint: str) -> Iterator
raise
finally:
_record_stream_close(endpoint, outcome, started_at)
+ reservation.release()
+
+
+class _ReservedSyncStream:
+ """Ties the cap reservation to response cleanup for a sync stream.
+
+ ``StreamingHttpResponse`` registers ``close`` as a resource closer, which
+ runs whenever Django closes the response (WSGI servers per spec, the ASGI
+ handler on the normal path). Closing a generator whose body never started
+ skips its ``finally``, so this wrapper, not the generator, is what releases
+ the slot for a never-consumed response. Responses Django drops without
+ calling ``close()`` at all fall through to the reservation's ``__del__``.
+ """
+
+ def __init__(self, iterator: Generator[bytes | str], reservation: _StreamSlotReservation) -> None:
+ self._iterator = iterator
+ self._reservation = reservation
+
+ def __iter__(self) -> Iterator[bytes | str]:
+ return self._iterator
+
+ def close(self) -> None:
+ self._iterator.close()
+ self._reservation.release()
+
+
+class _ReservedAsyncStream:
+ """Async counterpart of ``_ReservedSyncStream``.
+ Deliberately has no ``__iter__`` so ``StreamingHttpResponse`` takes its
+ async path. The closer stays sync because Django invokes resource closers
+ synchronously; it cannot unwind a started async generator, but a started
+ generator already releases in its ``finally`` (the ASGI handler cancels it
+ on disconnect, the event loop finalizer closes it if abandoned), so only
+ the never-started case needs covering here.
+ """
+
+ def __init__(self, aiterator: AsyncGenerator[bytes | str], reservation: _StreamSlotReservation) -> None:
+ self._aiterator = aiterator
+ self._reservation = reservation
+
+ def __aiter__(self) -> AsyncIterator[bytes | str]:
+ return self._aiterator
-def _instrument_stream(stream: StreamContent, endpoint: str) -> StreamContent:
+ def close(self) -> None:
+ self._reservation.release()
+
+
+def _instrument_stream(stream: StreamContent, endpoint: str, reservation: _StreamSlotReservation) -> StreamContent:
if isinstance(stream, AsyncIterable):
- return _instrumented_aiter(stream, endpoint)
- return _instrumented_iter(stream, endpoint)
+ return _ReservedAsyncStream(_instrumented_aiter(stream, endpoint, reservation), reservation)
+ return _ReservedSyncStream(_instrumented_iter(stream, endpoint, reservation), reservation)
def _release_request_connections() -> None:
@@ -156,7 +308,7 @@ def sse_streaming_response(
endpoint: str = "unknown",
status: int = HTTPStatus.OK,
headers: dict[str, str] | None = None,
-) -> StreamingHttpResponse:
+) -> StreamingHttpResponse | HttpResponse:
"""Build a ``text/event-stream`` response for a long-lived SSE endpoint.
Use this instead of constructing ``StreamingHttpResponse`` directly. It
@@ -185,10 +337,32 @@ def sse_streaming_response(
``endpoint`` is a static, low-cardinality name for the stream (e.g.
``"wizard_session"``) used as the label on the SSE connection metrics.
+
+ Admission control: when this process is already serving
+ ``SSE_MAX_CONCURRENT_STREAMS_PER_PROCESS`` streams, the stream is not opened
+ and the client gets ``503`` with a jittered ``Retry-After``. Beware that a
+ native ``EventSource`` treats any non-200 response as fatal (readyState
+ CLOSED, no auto-reconnect) and ignores ``Retry-After``; the jittered header
+ only spreads out clients that retry at the HTTP layer, so ``EventSource``
+ consumers must schedule their own reconnect from ``onerror`` to recover
+ from a rejection. A slot is reserved atomically before the response is
+ returned, so parallel admissions cannot overshoot the cap; the slot is
+ released when the stream ends, when a never-consumed response is closed,
+ or by a GC backstop when the response is dropped without being closed.
"""
- return streaming_response(
- _instrument_stream(stream, endpoint),
- content_type="text/event-stream",
- status=status,
- headers={**_SSE_DEFAULT_HEADERS, **(headers or {})},
- )
+ reservation = _try_reserve_stream_slot()
+ if reservation is None:
+ return _stream_cap_rejection(endpoint)
+ try:
+ return streaming_response(
+ _instrument_stream(stream, endpoint, reservation),
+ content_type="text/event-stream",
+ status=status,
+ headers={**_SSE_DEFAULT_HEADERS, **(headers or {})},
+ )
+ except BaseException:
+ # Nothing owns the slot until the response exists: a failure here (a DB
+ # error while releasing connections, a bad caller-supplied header) must
+ # not strand the reservation until GC gets to it.
+ reservation.release()
+ raise
diff --git a/posthog/api/test/test_streaming.py b/posthog/api/test/test_streaming.py
index 8f52c5891673..a2e5a7edaa27 100644
--- a/posthog/api/test/test_streaming.py
+++ b/posthog/api/test/test_streaming.py
@@ -1,21 +1,42 @@
+import gc
import asyncio
-from collections.abc import AsyncIterator, Iterator
+from collections.abc import AsyncGenerator, AsyncIterable, AsyncIterator, Iterator
from http import HTTPStatus
from typing import cast
+import pytest
from unittest import mock
from django.http import StreamingHttpResponse
+from django.http.response import HttpResponseBase
+from django.test import override_settings
+from parameterized import parameterized
from prometheus_client import REGISTRY
-from posthog.api.streaming import _instrument_stream, sse_streaming_response, streaming_response
+from posthog.api import streaming
+from posthog.api.streaming import (
+ _instrument_stream,
+ _try_reserve_stream_slot,
+ sse_streaming_response,
+ streaming_response,
+)
def _gen() -> Iterator[bytes]:
yield b"data: hello\n\n"
+async def _agen() -> AsyncIterator[bytes]:
+ yield b"data: hello\n\n"
+
+
+def _reserve_slot() -> streaming._StreamSlotReservation:
+ reservation = _try_reserve_stream_slot()
+ assert reservation is not None
+ return reservation
+
+
class TestSSEStreamingResponse:
def test_releases_db_connections_before_streaming(self):
idle = mock.Mock(in_atomic_block=False)
@@ -52,13 +73,15 @@ 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.
+def _sync_content(response: HttpResponseBase) -> Iterator[bytes]:
+ # sse_streaming_response returns a union (it can 503); in these non-capped
+ # tests the response is always a stream, so narrow and cast.
+ assert isinstance(response, StreamingHttpResponse)
return cast(Iterator[bytes], response.streaming_content)
-def _async_content(response: StreamingHttpResponse) -> AsyncIterator[bytes]:
+def _async_content(response: HttpResponseBase) -> AsyncIterator[bytes]:
+ assert isinstance(response, StreamingHttpResponse)
return cast(AsyncIterator[bytes], response.streaming_content)
@@ -125,16 +148,22 @@ class TestSSEStreamMetrics:
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__()
+ # An abandoned async stream is aclosed by the event loop's async
+ # generator finalizer, not by response.close() (Django's resource
+ # closers are sync-only); drive that aclose() path directly. This is
+ # the only release on that path, so pin the slot count too, not just
+ # the metrics (baseline-relative: this test runs outside the
+ # slot-isolation fixture).
+ baseline = streaming._active_stream_count
+ stream = _instrument_stream(endless(), "test_async_disconnect", _reserve_slot())
+ assert isinstance(stream, AsyncIterable)
+ inner = cast(AsyncGenerator[bytes], aiter(stream))
+ await inner.__anext__()
assert _open_connections("test_async_disconnect") == 1.0
- await stream.aclose() # type: ignore[attr-defined]
+ await inner.aclose()
assert _open_connections("test_async_disconnect") == 0.0
assert _closed_total("test_async_disconnect", "client_disconnect") == 1.0
+ assert streaming._active_stream_count == baseline
class TestStreamingResponse:
@@ -155,8 +184,12 @@ class TestSSEAsyncCancellation:
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)
+ # ASGI cancellation is a path where response.close() never runs, so the
+ # generator's finally is the only thing releasing the cap slot; pin it
+ # (baseline-relative: this test runs outside the slot-isolation fixture).
+ baseline = streaming._active_stream_count
+ stream = _instrument_stream(blocking(), "test_async_cancel", _reserve_slot())
+ assert isinstance(stream, AsyncIterable)
async def consume():
async for _ in stream:
@@ -173,3 +206,137 @@ class TestSSEAsyncCancellation:
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
+ assert streaming._active_stream_count == baseline
+
+
+class TestSSEConcurrencyCap:
+ # Admission control is the guard against stream pile-up taking a process
+ # down; these tests pin the reject/admit boundary and that every afterlife
+ # of an admitted response releases its slot exactly once.
+
+ @pytest.fixture(autouse=True)
+ def _isolated_slot_count(self):
+ # The count is module-global: give each test a zero baseline and put
+ # the previous value back so a leak here cannot cascade into other tests.
+ with mock.patch.object(streaming, "_active_stream_count", 0):
+ yield
+
+ def test_over_cap_rejects_with_503_and_jittered_retry_after(self):
+ # The slot is reserved at admission, before any iterator is pulled:
+ # two requests admitted back to back must not both pass the cap check.
+ with override_settings(SSE_MAX_CONCURRENT_STREAMS_PER_PROCESS=1):
+ admitted = sse_streaming_response(_gen(), endpoint="test_cap")
+ assert isinstance(admitted, StreamingHttpResponse)
+ try:
+ rejected = sse_streaming_response(_gen(), endpoint="test_cap")
+ assert rejected.status_code == HTTPStatus.SERVICE_UNAVAILABLE
+ assert not isinstance(rejected, StreamingHttpResponse)
+ assert 15 <= int(rejected.headers["Retry-After"]) < 45
+ # A rejection holds no slot, so it must not touch the count.
+ assert streaming._active_stream_count == 1
+ finally:
+ # Always release the slot: a failed assertion must not leak the
+ # active-stream count into other tests.
+ admitted.close()
+ assert streaming._active_stream_count == 0
+
+ def test_capacity_frees_up_when_a_stream_closes(self):
+ def endless() -> Iterator[bytes]:
+ while True:
+ yield b": ping\n\n"
+
+ with override_settings(SSE_MAX_CONCURRENT_STREAMS_PER_PROCESS=1):
+ first = sse_streaming_response(endless(), endpoint="test_cap_release")
+ assert isinstance(first, StreamingHttpResponse)
+ next(_sync_content(first))
+ first.close()
+ second = sse_streaming_response(_gen(), endpoint="test_cap_release")
+ assert isinstance(second, StreamingHttpResponse)
+ assert b"".join(_sync_content(second)) == b"data: hello\n\n"
+
+ @parameterized.expand([("sync", _gen), ("async", _agen)])
+ def test_closing_a_never_consumed_response_releases_the_slot(self, _name, make_stream):
+ # Closing a never-started generator skips its finally, so this release
+ # rides on the response's resource closer; if that wiring breaks,
+ # every response abandoned before its first chunk leaks capacity.
+ with override_settings(SSE_MAX_CONCURRENT_STREAMS_PER_PROCESS=1):
+ first = sse_streaming_response(make_stream(), endpoint="test_cap_unconsumed")
+ assert isinstance(first, StreamingHttpResponse)
+ assert streaming._active_stream_count == 1
+ first.close()
+ assert streaming._active_stream_count == 0
+ second = sse_streaming_response(_gen(), endpoint="test_cap_unconsumed")
+ assert isinstance(second, StreamingHttpResponse)
+ second.close()
+
+ @parameterized.expand([("sync", _gen), ("async", _agen)])
+ def test_dropped_response_releases_the_slot_via_gc(self, _name, make_stream):
+ # Django can drop a streaming response without ever calling close():
+ # the ASGI handler skips it when the client disconnects during the
+ # response-middleware phase, and exception-converting middleware swaps
+ # in a 500 and abandons the original. Each occurrence must not consume
+ # a slot until the process restarts.
+ with override_settings(SSE_MAX_CONCURRENT_STREAMS_PER_PROCESS=1):
+ response = sse_streaming_response(make_stream(), endpoint="test_cap_gc")
+ assert isinstance(response, StreamingHttpResponse)
+ del response
+ gc.collect()
+ assert streaming._active_stream_count == 0
+ readmitted = sse_streaming_response(_gen(), endpoint="test_cap_gc")
+ assert isinstance(readmitted, StreamingHttpResponse)
+ readmitted.close()
+
+ def test_slot_deferred_under_lock_contention_is_reclaimed_at_next_admission(self):
+ # GC can finalize a dropped reservation on a thread that already holds
+ # the cap lock, where __del__ must defer instead of block; the slot is
+ # then reclaimed by the drain at the next admission. If the deferral or
+ # the drain breaks, each such finalization permanently shrinks the cap
+ # until the process restarts.
+ with override_settings(SSE_MAX_CONCURRENT_STREAMS_PER_PROCESS=1):
+ response = sse_streaming_response(_gen(), endpoint="test_cap_deferred")
+ assert isinstance(response, StreamingHttpResponse)
+ streaming._stream_cap_lock.acquire()
+ try:
+ del response
+ gc.collect()
+ # The lock was contended, so the slot cannot be freed yet.
+ assert streaming._active_stream_count == 1
+ finally:
+ streaming._stream_cap_lock.release()
+ readmitted = sse_streaming_response(_gen(), endpoint="test_cap_deferred")
+ assert isinstance(readmitted, StreamingHttpResponse)
+ readmitted.close()
+ assert streaming._active_stream_count == 0
+
+ def test_slot_released_when_building_the_response_fails(self):
+ # An exception between reserving the slot and returning the response
+ # (here: a DB error while releasing request connections) must release
+ # eagerly, not wait for GC. Keeping the traceback alive holds the
+ # reservation alive, so this catches a dropped except-and-release.
+ with override_settings(SSE_MAX_CONCURRENT_STREAMS_PER_PROCESS=1):
+ with mock.patch("posthog.api.streaming.connections") as connections:
+ connections.all.side_effect = RuntimeError("db went away")
+ with pytest.raises(RuntimeError) as excinfo:
+ sse_streaming_response(_gen(), endpoint="test_cap_build_error")
+ assert streaming._active_stream_count == 0
+ del excinfo
+
+ def test_consumed_then_closed_response_releases_only_once(self):
+ # A double release would drive the count negative and let the cap
+ # admit unbounded streams.
+ with override_settings(SSE_MAX_CONCURRENT_STREAMS_PER_PROCESS=1):
+ response = sse_streaming_response(_gen(), endpoint="test_cap_once")
+ assert isinstance(response, StreamingHttpResponse)
+ assert b"".join(_sync_content(response)) == b"data: hello\n\n"
+ assert streaming._active_stream_count == 0
+ response.close()
+ assert streaming._active_stream_count == 0
+
+ def test_cap_of_zero_rejects_everything(self):
+ with override_settings(SSE_MAX_CONCURRENT_STREAMS_PER_PROCESS=0):
+ rejected = sse_streaming_response(_gen(), endpoint="test_cap_zero")
+ assert rejected.status_code == HTTPStatus.SERVICE_UNAVAILABLE
+ rejected_count = REGISTRY.get_sample_value(
+ "posthog_sse_rejected_over_cap_total", {"endpoint": "test_cap_zero"}
+ )
+ assert rejected_count is not None and rejected_count >= 1.0
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 545609971014..39654d602d3a 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -1187,3 +1187,13 @@ _NO_JOIN_DEFAULT_ROLLOUT_PERCENT = 100 if (CLOUD_DEPLOYMENT or "").upper() in ("
WEB_ANALYTICS_NO_JOIN_ROLLOUT_PERCENT: int = get_from_env(
"WEB_ANALYTICS_NO_JOIN_ROLLOUT_PERCENT", _NO_JOIN_DEFAULT_ROLLOUT_PERCENT, type_cast=int
)
+
+# Admission control for long-lived SSE streams: the maximum number of streams
+# one worker process serves concurrently. Above the cap, sse_streaming_response()
+# returns 503 with a jittered Retry-After instead of opening the stream, keeping
+# processes unpinned and health probes responsive. Recovery depends on the
+# client: HTTP-level retriers honor Retry-After, but a native EventSource treats
+# any non-200 as fatal (readyState CLOSED, no auto-reconnect) and ignores the
+# header, so those consumers must reconnect from their onerror handler.
+# 0 rejects every stream (emergency lever).
+SSE_MAX_CONCURRENT_STREAMS_PER_PROCESS = get_from_env("SSE_MAX_CONCURRENT_STREAMS_PER_PROCESS", 500, type_cast=int)
diff --git a/products/ai_observability/backend/api/proxy.py b/products/ai_observability/backend/api/proxy.py
index 65bd8e61b130..00d7b8ab597b 100644
--- a/products/ai_observability/backend/api/proxy.py
+++ b/products/ai_observability/backend/api/proxy.py
@@ -13,7 +13,7 @@ from time import perf_counter
from typing import Any
from django.core.cache import cache
-from django.http import StreamingHttpResponse
+from django.http.response import HttpResponseBase
from django.utils import timezone
import structlog
@@ -194,12 +194,12 @@ class LLMProxyViewSet(viewsets.ViewSet):
except Exception:
logger.exception("llm_proxy_on_complete_callback_error")
- def _create_streaming_response(self, stream: Generator[bytes]) -> StreamingHttpResponse:
+ def _create_streaming_response(self, stream: Generator[bytes]) -> HttpResponseBase:
"""Creates a properly configured SSE streaming response"""
astream = SyncIterableToAsync(stream) if SERVER_GATEWAY_INTERFACE == "ASGI" else stream
return sse_streaming_response(astream, endpoint="ai_observability_proxy")
- def _handle_completion_request(self, request: Request) -> StreamingHttpResponse | Response:
+ def _handle_completion_request(self, request: Request) -> HttpResponseBase | Response:
"""Handler for completion requests using unified Client"""
try:
if not request.user or not request.user.is_authenticated:
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index c733ecc47511..99f63f64d9af 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -29,7 +29,7 @@ from django.db.models import (
Value,
)
from django.db.models.functions import Cast
-from django.http import StreamingHttpResponse
+from django.http.response import HttpResponseBase
from django.shortcuts import get_object_or_404
from django.utils.timezone import now
@@ -2328,7 +2328,7 @@ class DashboardsViewSet(
],
)
@action(methods=["GET"], detail=True, url_path="stream_tiles")
- def stream_tiles(self, request: Request, *args: Any, **kwargs: Any) -> StreamingHttpResponse:
+ def stream_tiles(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponseBase:
"""Stream dashboard metadata and tiles via Server-Sent Events. Sends metadata first, then tiles as they are rendered."""
dashboard = self.get_object() # This will raise 404 if not found - let it bubble up normally
diff --git a/products/mcp_store/backend/presentation/views.py b/products/mcp_store/backend/presentation/views.py
index b473fcd45f0d..9c88031010ce 100644
--- a/products/mcp_store/backend/presentation/views.py
+++ b/products/mcp_store/backend/presentation/views.py
@@ -9,7 +9,8 @@ from urllib.parse import urlencode, urlparse
from django.conf import settings
from django.db import IntegrityError, transaction
from django.db.models import Count, Q, QuerySet
-from django.http import HttpResponse, StreamingHttpResponse
+from django.http import HttpResponse
+from django.http.response import HttpResponseBase
from django.utils import timezone
import structlog
@@ -696,7 +697,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
required_scopes=["project:read"],
renderer_classes=[MCPProxyRenderer],
)
- def proxy(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponse | StreamingHttpResponse:
+ def proxy(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponseBase:
installation = self.get_object()
# Basic audit trail for who exercises which installation (especially
diff --git a/products/mcp_store/backend/proxy.py b/products/mcp_store/backend/proxy.py
index 44eec0a59257..31a1c676c1f4 100644
--- a/products/mcp_store/backend/proxy.py
+++ b/products/mcp_store/backend/proxy.py
@@ -4,6 +4,7 @@ from typing import Any
from urllib.parse import urljoin, urlparse
from django.http import HttpResponse, StreamingHttpResponse
+from django.http.response import HttpResponseBase
import httpx
import structlog
@@ -317,7 +318,7 @@ def enforce_tool_approval(
return HttpResponse(json.dumps(blocked), content_type="application/json", status=200)
-def proxy_mcp_request(request: Any, installation: MCPServerInstallation) -> HttpResponse | StreamingHttpResponse:
+def proxy_mcp_request(request: Any, installation: MCPServerInstallation) -> HttpResponseBase:
allowed, error = is_url_allowed(installation.url)
if not allowed:
logger.warning("SSRF: blocked proxy request", url=installation.url, reason=error)
@@ -441,11 +442,19 @@ def _stream_upstream(upstream_response: httpx.Response, client: httpx.Client) ->
client.close()
-def _build_sse_response(upstream_response: httpx.Response, client: httpx.Client) -> StreamingHttpResponse:
+def _build_sse_response(upstream_response: httpx.Response, client: httpx.Client) -> HttpResponseBase:
stream = _stream_upstream(upstream_response, client)
astream = SyncIterableToAsync(stream) if SERVER_GATEWAY_INTERFACE == "ASGI" else stream
response = sse_streaming_response(astream, endpoint="mcp_store_proxy")
+ if not isinstance(response, StreamingHttpResponse):
+ # Over-cap rejection: the generator that owns these resources never
+ # starts, so its finally never runs. Close them here (both closes are
+ # idempotent) instead of leaking them until the upstream timeout.
+ upstream_response.close()
+ client.close()
+ return response
+
upstream_session_id = upstream_response.headers.get("mcp-session-id")
if upstream_session_id:
response["Mcp-Session-Id"] = upstream_session_id
diff --git a/products/mcp_store/backend/test/test_proxy.py b/products/mcp_store/backend/test/test_proxy.py
index 5c8fc383839e..e568962be657 100644
--- a/products/mcp_store/backend/test/test_proxy.py
+++ b/products/mcp_store/backend/test/test_proxy.py
@@ -4,6 +4,7 @@ import uuid
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, QueryMatchingTest
from unittest.mock import MagicMock, patch
+from django.test import override_settings
from django.utils import timezone
import httpx
@@ -13,6 +14,7 @@ from rest_framework import status
from posthog.models import Organization, Team, User
from products.mcp_store.backend.models import MCPServerInstallation, MCPServerInstallationTool
+from products.mcp_store.backend.proxy import _build_sse_response
class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
@@ -895,3 +897,17 @@ class TestMCPProxyAccessControl(ClickhouseTestMixin, APIBaseTest, QueryMatchingT
assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED, (
f"Expected 405 for {method.upper()}, got {response.status_code}"
)
+
+
+class TestBuildSSEResponseOverCap:
+ def test_over_cap_rejection_closes_upstream_resources(self):
+ # The generator that owns these resources never starts on the 503
+ # path; without the explicit close a rejected admission leaks the
+ # upstream connection and client until the upstream timeout.
+ upstream_response = MagicMock(spec=httpx.Response)
+ client = MagicMock(spec=httpx.Client)
+ with override_settings(SSE_MAX_CONCURRENT_STREAMS_PER_PROCESS=0):
+ response = _build_sse_response(upstream_response, client)
+ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
+ upstream_response.close.assert_called_once()
+ client.close.assert_called_once()
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index 439cb6a58d1f..46784d9d5aab 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -5,7 +5,7 @@ from django.conf import settings
from django.db.models import Case, CharField, FloatField, Func, IntegerField, Q, QuerySet, Value, When
from django.db.models.fields.json import KeyTextTransform, KeyTransform
from django.db.models.functions import Cast
-from django.http import StreamingHttpResponse
+from django.http.response import HttpResponseBase
import structlog
import django_filters
@@ -847,7 +847,7 @@ class SessionReplayObservationViewSet(ReplayObservationViewSet):
@extend_schema(exclude=True)
@action(detail=True, methods=["GET"], url_path="progress", renderer_classes=[ServerSentEventRenderer])
- def progress(self, request: Request, **kwargs: Any) -> StreamingHttpResponse:
+ def progress(self, request: Request, **kwargs: Any) -> HttpResponseBase:
"""Stream live progress (phase + rendering frame counts) for one in-flight observation as SSE.
`get_object()` applies the same RBAC scoping as retrieve, so this can't leak observations the caller