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(csp): buffer capture-forward off the request path (#67731)

Julian Bez618eec1aff32
diff --git a/posthog/api/report.py b/posthog/api/report.py
index 3133c8b8516d..e7ff6de7be6d 100644
--- a/posthog/api/report.py
+++ b/posthog/api/report.py
@@ -1,3 +1,4 @@
+from django.conf import settings
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
@@ -6,6 +7,7 @@ from rest_framework import status
from posthog.api.capture import CaptureInternalError, capture_batch_internal, capture_internal
from posthog.api.csp import process_csp_report
+from posthog.api.report_buffer import csp_report_buffer
from posthog.api.utils import get_token
from posthog.exceptions import generate_exception_response
from posthog.exceptions_capture import capture_exception
@@ -58,6 +60,24 @@ def get_csp_event(request):
if not token:
token = ""
+ if settings.CSP_REPORT_BUFFERED_FORWARD:
+ # Buffered mode never makes the synchronous capture call that would
+ # reject an empty token, so reject it here before enqueueing.
+ if not token:
+ return cors_response(
+ request,
+ generate_exception_response(
+ "csp_report_capture",
+ f"Failed to submit CSP report",
+ code="capture_error",
+ type="capture_error",
+ status_code=status.HTTP_400_BAD_REQUEST,
+ ),
+ )
+ events = csp_report if isinstance(csp_report, list) else [csp_report]
+ csp_report_buffer.enqueue(events, token=token)
+ return cors_response(request, HttpResponse(status=status.HTTP_204_NO_CONTENT))
+
if isinstance(csp_report, list):
result = capture_batch_internal(
events=csp_report, event_source="get_csp_report", token=token, process_person_profile=False
diff --git a/posthog/api/report_buffer.py b/posthog/api/report_buffer.py
new file mode 100644
index 000000000000..687d1b4ff6bf
--- /dev/null
+++ b/posthog/api/report_buffer.py
@@ -0,0 +1,302 @@
+"""Bounded in-process buffer for the CSP report capture-forward.
+
+The /report/ endpoint forwards every accepted report to capture-rs. Doing that
+synchronously ties request-worker hold time to capture-rs latency (including its
+retry budget), which starves bounded worker pools when capture-rs degrades. This
+buffer decouples the two: the view enqueues and returns immediately, a background
+sender thread batches events to ``capture_batch_internal``.
+
+CSP reporting is best-effort by contract: oversized events and events beyond a
+token's fair share of the buffer are dropped, on count or byte overflow the
+oldest queued events are evicted, events still unsent when a flush exceeds its
+wall-clock deadline are dropped, and buffered events are lost if the process
+dies before the final drain (all drops counted in ``csp_report_buffer_dropped``).
+Browsers never read report responses, so callers get no delivery guarantee
+either way.
+"""
+
+from __future__ import annotations
+
+import os
+import json
+import time
+import queue
+import atexit
+import threading
+from typing import Any
+
+import structlog
+from prometheus_client import Counter, Gauge
+
+from posthog.api.capture import capture_batch_internal
+from posthog.exceptions_capture import capture_exception
+from posthog.settings.ingestion import (
+ CSP_REPORT_BUFFER_FLUSH_INTERVAL_SECONDS,
+ CSP_REPORT_BUFFER_FLUSH_MAX_EVENTS,
+ CSP_REPORT_BUFFER_FLUSH_MAX_SECONDS,
+ CSP_REPORT_BUFFER_MAX_BYTES,
+ CSP_REPORT_BUFFER_MAX_EVENT_BYTES,
+ CSP_REPORT_BUFFER_MAX_EVENTS,
+ CSP_REPORT_BUFFER_MAX_TOKEN_SHARE,
+)
+
+logger = structlog.get_logger(__name__)
+
+CSP_BUFFER_ENQUEUED = Counter(
+ "csp_report_buffer_enqueued",
+ "CSP report events accepted into the forward buffer.",
+)
+CSP_BUFFER_DROPPED = Counter(
+ "csp_report_buffer_dropped",
+ "CSP report events dropped from the forward buffer.",
+ labelnames=["reason"],
+)
+CSP_BUFFER_SUBMITTED = Counter(
+ "csp_report_buffer_submitted",
+ "CSP report events successfully forwarded to capture.",
+)
+CSP_BUFFER_FAILED = Counter(
+ "csp_report_buffer_failed",
+ "CSP report events whose forward to capture failed.",
+)
+CSP_BUFFER_DEPTH = Gauge(
+ "csp_report_buffer_depth",
+ "Current number of events waiting in the forward buffer.",
+ multiprocess_mode="livesum",
+)
+
+
+class CspReportBuffer:
+ def __init__(
+ self,
+ maxsize: int = CSP_REPORT_BUFFER_MAX_EVENTS,
+ flush_interval: float = CSP_REPORT_BUFFER_FLUSH_INTERVAL_SECONDS,
+ flush_max_events: int = CSP_REPORT_BUFFER_FLUSH_MAX_EVENTS,
+ flush_max_seconds: float = CSP_REPORT_BUFFER_FLUSH_MAX_SECONDS,
+ max_token_share: float = CSP_REPORT_BUFFER_MAX_TOKEN_SHARE,
+ max_bytes: int = CSP_REPORT_BUFFER_MAX_BYTES,
+ max_event_bytes: int = CSP_REPORT_BUFFER_MAX_EVENT_BYTES,
+ ) -> None:
+ self.flush_interval = flush_interval
+ self.flush_max_events = flush_max_events
+ self.flush_max_seconds = flush_max_seconds
+ self.max_bytes = max_bytes
+ self.max_event_bytes = max_event_bytes
+ # maxsize=0 makes queue.Queue unbounded, which silently removes the count
+ # bound — the opposite of what zeroing the knob looks like it should do.
+ maxsize = max(1, maxsize)
+ self._queue: queue.Queue[tuple[str, dict[str, Any], int]] = queue.Queue(maxsize=maxsize)
+ self._lock = threading.Lock()
+ self._sender: threading.Thread | None = None
+ # Sender threads don't survive fork, so remember which process started ours.
+ self._sender_pid: int | None = None
+ # atexit doesn't deduplicate handlers, so register once per process even
+ # if the sender thread gets restarted.
+ self._atexit_pid: int | None = None
+ # Fairness: no single token may occupy more than its share of the buffer,
+ # so one team's report storm (or a bogus token — tokens are public and
+ # only capture-rs truly validates them) cannot evict other tokens'
+ # events on overflow.
+ self._token_cap = max(1, int(maxsize * max_token_share))
+ self._token_counts: dict[str, int] = {}
+ # Byte accounting: the count cap alone doesn't bound memory, events carry
+ # the raw report body. Guarded by _counts_lock like the token counts.
+ self._total_bytes = 0
+ self._counts_lock = threading.Lock()
+
+ def enqueue(self, events: list[dict[str, Any]], *, token: str) -> None:
+ """Add events to the buffer without ever blocking the caller.
+
+ Oversized events and a token over its share drop the incoming event; on
+ count or byte overflow the globally oldest events are evicted so fresh
+ reports win across tokens.
+ """
+ self._ensure_sender()
+ accepted = 0
+ for event in events:
+ # Serialized length bounds both the single event (request bodies can
+ # be far larger than any legitimate CSP report) and, summed, the
+ # buffer's total memory footprint.
+ size = len(json.dumps(event, default=str))
+ if size > self.max_event_bytes:
+ CSP_BUFFER_DROPPED.labels(reason="oversized").inc()
+ continue
+ if not self._reserve_slot(token):
+ CSP_BUFFER_DROPPED.labels(reason="token_share").inc()
+ continue
+ while True:
+ try:
+ self._queue.put_nowait((token, event, size))
+ break
+ except queue.Full:
+ self._evict_oldest("overflow")
+ with self._counts_lock:
+ self._total_bytes += size
+ accepted += 1
+ # _total_bytes is incremented after put and decremented after remove,
+ # matched per item, so the unlocked read below is safe under the GIL:
+ # it can only read a transiently stale total, never tear, and the count
+ # self-corrects. Worst case is one over- or under-eviction, tolerable
+ # for a best-effort buffer.
+ while self._total_bytes > self.max_bytes:
+ if not self._evict_oldest("bytes_overflow"):
+ break
+ CSP_BUFFER_ENQUEUED.inc(accepted)
+ CSP_BUFFER_DEPTH.set(self._queue.qsize())
+
+ def _reserve_slot(self, token: str) -> bool:
+ with self._counts_lock:
+ if self._token_counts.get(token, 0) >= self._token_cap:
+ return False
+ self._token_counts[token] = self._token_counts.get(token, 0) + 1
+ return True
+
+ def _release_slot(self, token: str) -> None:
+ with self._counts_lock:
+ remaining = self._token_counts.get(token, 0) - 1
+ if remaining > 0:
+ self._token_counts[token] = remaining
+ else:
+ self._token_counts.pop(token, None)
+
+ def _evict_oldest(self, reason: str) -> bool:
+ try:
+ token, _, size = self._queue.get_nowait()
+ except queue.Empty:
+ return False
+ self._release_slot(token)
+ with self._counts_lock:
+ self._total_bytes -= size
+ CSP_BUFFER_DROPPED.labels(reason=reason).inc()
+ return True
+
+ def _ensure_sender(self) -> None:
+ if self._sender is not None and self._sender.is_alive() and self._sender_pid == os.getpid():
+ return
+ with self._lock:
+ if self._sender is not None and self._sender.is_alive() and self._sender_pid == os.getpid():
+ return
+ self._sender_pid = os.getpid()
+ self._sender = threading.Thread(target=self._run, name="csp-report-buffer-sender", daemon=True)
+ self._sender.start()
+ if self._atexit_pid != os.getpid():
+ atexit.register(self._drain_on_exit)
+ self._atexit_pid = os.getpid()
+
+ def _run(self) -> None:
+ while True:
+ # A crashed sender would silently strand queued events until the next
+ # enqueue restarts it — never let an exception escape the loop.
+ try:
+ batch = self._collect()
+ if batch:
+ try:
+ self._flush(batch)
+ finally:
+ self._release_bytes(batch)
+ except Exception:
+ logger.exception("csp_report_buffer_sender_error")
+
+ def _collect(self) -> list[tuple[str, dict[str, Any], int]]:
+ """Wait up to ``flush_interval`` for work, then drain up to ``flush_max_events``."""
+ items: list[tuple[str, dict[str, Any], int]] = []
+ try:
+ items.append(self._queue.get(timeout=self.flush_interval))
+ except queue.Empty:
+ return items
+ while len(items) < self.flush_max_events:
+ try:
+ items.append(self._queue.get_nowait())
+ except queue.Empty:
+ break
+ for token, _, _ in items:
+ self._release_slot(token)
+ # Bytes stay reserved until the flush finishes (_release_bytes) — the
+ # in-flight batch still holds the memory, so releasing here would let
+ # the queue refill a full budget on top of it.
+ return items
+
+ def _release_bytes(self, items: list[tuple[str, dict[str, Any], int]]) -> None:
+ with self._counts_lock:
+ self._total_bytes -= sum(size for _, _, size in items)
+
+ def _flush(self, items: list[tuple[str, dict[str, Any], int]]) -> None:
+ CSP_BUFFER_DEPTH.set(self._queue.qsize())
+ by_token: dict[str, list[dict[str, Any]]] = {}
+ for token, event, _ in items:
+ by_token.setdefault(token, []).append(event)
+ # Token groups are submitted serially and tokens are attacker-controlled
+ # (only capture-rs validates them), so a flood of distinct tokens against
+ # a slow capture-rs would otherwise multiply the per-call transport
+ # budget by up to flush_max_events groups — stalling the sender while
+ # the queue evicts everything behind it. The deadline bounds the whole
+ # flush; only the last group started before it can overshoot (by one
+ # call's transport budget). Groups past the deadline are dropped and
+ # counted, matching the buffer's best-effort contract.
+ deadline = time.monotonic() + self.flush_max_seconds
+ groups = list(by_token.items())
+ for index, (token, events) in enumerate(groups):
+ if time.monotonic() > deadline:
+ remaining = sum(len(group_events) for _, group_events in groups[index:])
+ CSP_BUFFER_DROPPED.labels(reason="flush_deadline").inc(remaining)
+ logger.warning(
+ "csp_report_buffer_flush_deadline",
+ dropped=remaining,
+ groups_left=len(groups) - index,
+ flush_max_seconds=self.flush_max_seconds,
+ )
+ break
+ try:
+ # max_attempts=1: token groups are submitted serially, so a
+ # degraded capture-rs must not multiply its timeout by resubmit
+ # rounds across every group in the flush — drop and count
+ # instead of stalling the sender for minutes.
+ result = capture_batch_internal(
+ events=events,
+ token=token,
+ event_source="get_csp_report",
+ process_person_profile=False,
+ max_attempts=1,
+ )
+ except Exception as exc:
+ CSP_BUFFER_FAILED.inc(len(events))
+ capture_exception(exc, {"capture-pathway": "csp_report_buffer", "ph-team-token": token})
+ logger.warning("csp_report_buffer_flush_failed", batch_size=len(events), error=str(exc))
+ continue
+ # Count per-event outcomes: a partial failure must not mark events
+ # capture already accepted as lost — these counters are the only
+ # delivery visibility in a fire-and-forget design, so
+ # enqueued ≈ submitted + failed + dropped + depth has to hold.
+ accepted = len(result.ok) + len(result.warnings)
+ failed = len(result.dropped) + len(result.retried) + len(result.unaccounted)
+ CSP_BUFFER_SUBMITTED.inc(accepted)
+ if failed:
+ CSP_BUFFER_FAILED.inc(failed)
+ logger.warning(
+ "csp_report_buffer_flush_partial",
+ batch_size=len(events),
+ failed=failed,
+ error=result.error,
+ )
+
+ def _drain_on_exit(self) -> None:
+ # Best-effort final flush of at most one batch, bounded by the same flush
+ # deadline as regular flushes — flush_max_seconds (plus one call's
+ # transport budget of overshoot) has to fit inside the pod's termination
+ # grace.
+ items: list[tuple[str, dict[str, Any], int]] = []
+ while len(items) < self.flush_max_events:
+ try:
+ items.append(self._queue.get_nowait())
+ except queue.Empty:
+ break
+ for token, _, _ in items:
+ self._release_slot(token)
+ if items:
+ try:
+ self._flush(items)
+ finally:
+ self._release_bytes(items)
+
+
+csp_report_buffer = CspReportBuffer()
diff --git a/posthog/api/test/test_report_buffer.py b/posthog/api/test/test_report_buffer.py
new file mode 100644
index 000000000000..929df317a6ab
--- /dev/null
+++ b/posthog/api/test/test_report_buffer.py
@@ -0,0 +1,231 @@
+import json
+import queue
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase, override_settings
+from django.test.client import Client
+
+from rest_framework import status
+
+from posthog.api.report_buffer import CSP_BUFFER_DROPPED, CSP_BUFFER_FAILED, CSP_BUFFER_SUBMITTED, CspReportBuffer
+
+
+def _capture_result(ok=(), dropped=(), retried=(), unaccounted=(), warnings=()):
+ return MagicMock(
+ ok=list(ok),
+ dropped=list(dropped),
+ retried=list(retried),
+ unaccounted=list(unaccounted),
+ warnings=list(warnings),
+ error=None,
+ )
+
+
+CSP_PAYLOAD = {
+ "csp-report": {
+ "document-uri": "https://example.com/foo/bar",
+ "violated-directive": "default-src self",
+ "effective-directive": "img-src",
+ "original-policy": "default-src 'self'; img-src 'self' https://img.example.com",
+ "disposition": "enforce",
+ "blocked-uri": "https://evil.com/malicious-image.png",
+ }
+}
+
+
+class TestCspReportBufferedView(BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self):
+ super().setUp()
+ self.client = Client(enforce_csrf_checks=True)
+
+ @override_settings(CSP_REPORT_BUFFERED_FORWARD=True)
+ @patch("posthog.api.report.capture_internal")
+ @patch("posthog.api.report.csp_report_buffer")
+ def test_buffered_mode_enqueues_instead_of_calling_capture(self, mock_buffer, mock_capture) -> None:
+ resp = self.client.post(
+ f"/report/?token={self.team.api_token}",
+ data=json.dumps(CSP_PAYLOAD),
+ content_type="application/csp-report",
+ )
+ assert resp.status_code == status.HTTP_204_NO_CONTENT
+ assert mock_capture.call_count == 0
+ assert mock_buffer.enqueue.call_count == 1
+ events = mock_buffer.enqueue.call_args.args[0]
+ assert len(events) == 1
+ assert mock_buffer.enqueue.call_args.kwargs["token"] == self.team.api_token
+
+ @override_settings(CSP_REPORT_BUFFERED_FORWARD=True)
+ @patch("posthog.api.report.csp_report_buffer")
+ def test_buffered_mode_missing_token_returns_400_without_enqueue(self, mock_buffer) -> None:
+ resp = self.client.post(
+ "/report/",
+ data=json.dumps(CSP_PAYLOAD),
+ content_type="application/csp-report",
+ )
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+ assert mock_buffer.enqueue.call_count == 0
+
+ @patch("posthog.api.report.capture_internal")
+ @patch("posthog.api.report.csp_report_buffer")
+ def test_default_mode_stays_synchronous(self, mock_buffer, mock_capture) -> None:
+ mock_capture.return_value = MagicMock(raise_for_status=MagicMock())
+ resp = self.client.post(
+ f"/report/?token={self.team.api_token}",
+ data=json.dumps(CSP_PAYLOAD),
+ content_type="application/csp-report",
+ )
+ assert resp.status_code == status.HTTP_204_NO_CONTENT
+ assert mock_capture.call_count == 1
+ assert mock_buffer.enqueue.call_count == 0
+
+
+class TestCspReportBufferLogic(SimpleTestCase):
+ def _buffer(
+ self,
+ maxsize: int = 10,
+ max_token_share: float = 1.0,
+ max_bytes: int = 1_000_000,
+ max_event_bytes: int = 100_000,
+ flush_max_seconds: float = 5.0,
+ ) -> CspReportBuffer:
+ return CspReportBuffer(
+ maxsize=maxsize,
+ flush_interval=0.01,
+ flush_max_events=100,
+ flush_max_seconds=flush_max_seconds,
+ max_token_share=max_token_share,
+ max_bytes=max_bytes,
+ max_event_bytes=max_event_bytes,
+ )
+
+ # _ensure_sender is patched out so no sender thread runs — collect/flush are driven synchronously.
+ @patch.object(CspReportBuffer, "_ensure_sender")
+ @patch("posthog.api.report_buffer.capture_batch_internal")
+ def test_flush_groups_events_by_token(self, mock_capture, _mock_sender) -> None:
+ mock_capture.return_value = _capture_result(ok=["u1"])
+ buf = self._buffer()
+ buf.enqueue([{"event": "a"}, {"event": "b"}], token="token-1")
+ buf.enqueue([{"event": "c"}], token="token-2")
+
+ buf._flush(buf._collect())
+
+ assert mock_capture.call_count == 2
+ calls = {call.kwargs["token"]: call.kwargs["events"] for call in mock_capture.call_args_list}
+ assert [e["event"] for e in calls["token-1"]] == ["a", "b"]
+ assert [e["event"] for e in calls["token-2"]] == ["c"]
+
+ @patch.object(CspReportBuffer, "_ensure_sender")
+ def test_enqueue_on_full_buffer_drops_oldest_without_blocking(self, _mock_sender) -> None:
+ buf = self._buffer(maxsize=2)
+ buf.enqueue([{"event": "a"}, {"event": "b"}], token="token-1")
+ buf.enqueue([{"event": "c"}], token="token-2")
+
+ remaining = [(t, e["event"]) for t, e, _ in (buf._queue.get_nowait() for _ in range(2))]
+ assert remaining == [("token-1", "b"), ("token-2", "c")]
+ with self.assertRaises(queue.Empty):
+ buf._queue.get_nowait()
+
+ @patch.object(CspReportBuffer, "_ensure_sender")
+ def test_one_token_cannot_evict_other_tokens_events(self, _mock_sender) -> None:
+ buf = self._buffer(maxsize=4, max_token_share=0.5)
+ buf.enqueue([{"event": f"noisy-{i}"} for i in range(4)], token="token-noisy")
+ buf.enqueue([{"event": "quiet-1"}, {"event": "quiet-2"}], token="token-quiet")
+
+ contents = [buf._queue.get_nowait() for _ in range(4)]
+ assert [e["event"] for t, e, _ in contents if t == "token-noisy"] == ["noisy-0", "noisy-1"]
+ assert [e["event"] for t, e, _ in contents if t == "token-quiet"] == ["quiet-1", "quiet-2"]
+
+ @patch.object(CspReportBuffer, "_ensure_sender")
+ def test_collect_frees_token_share_for_new_events(self, _mock_sender) -> None:
+ buf = self._buffer(maxsize=4, max_token_share=0.5)
+ buf.enqueue([{"event": "a"}, {"event": "b"}, {"event": "c"}], token="token-1")
+ assert len(buf._collect()) == 2
+
+ buf.enqueue([{"event": "d"}], token="token-1")
+ assert [e["event"] for _, e, _s in buf._collect()] == ["d"]
+
+ @patch.object(CspReportBuffer, "_ensure_sender")
+ def test_oversized_event_is_dropped(self, _mock_sender) -> None:
+ buf = self._buffer(max_event_bytes=100)
+ buf.enqueue([{"event": "big", "raw": "x" * 500}, {"event": "small"}], token="token-1")
+
+ contents = [buf._queue.get_nowait() for _ in range(buf._queue.qsize())]
+ assert [e["event"] for _, e, _s in contents] == ["small"]
+
+ @patch.object(CspReportBuffer, "_ensure_sender")
+ def test_bytes_stay_reserved_while_batch_in_flight(self, _mock_sender) -> None:
+ buf = self._buffer(max_bytes=250, max_event_bytes=200)
+ buf.enqueue([{"event": "0", "raw": "x" * 100}], token="token-1")
+ in_flight = buf._collect()
+ assert len(in_flight) == 1
+
+ buf.enqueue([{"event": "1", "raw": "x" * 100}, {"event": "2", "raw": "x" * 100}], token="token-1")
+ assert buf._queue.qsize() == 1
+
+ buf._release_bytes(in_flight)
+ buf.enqueue([{"event": "3", "raw": "x" * 100}], token="token-1")
+ assert buf._queue.qsize() == 2
+
+ @patch.object(CspReportBuffer, "_ensure_sender")
+ @patch("posthog.api.report_buffer.capture_batch_internal")
+ def test_partial_batch_failure_splits_submitted_and_failed(self, mock_capture, _mock_sender) -> None:
+ mock_capture.return_value = _capture_result(ok=["u1"], dropped=["u2"])
+ buf = self._buffer()
+ submitted_before = CSP_BUFFER_SUBMITTED._value.get()
+ failed_before = CSP_BUFFER_FAILED._value.get()
+
+ buf._flush([("token-1", {"event": "a"}, 10), ("token-1", {"event": "b"}, 10)])
+
+ assert CSP_BUFFER_SUBMITTED._value.get() - submitted_before == 1
+ assert CSP_BUFFER_FAILED._value.get() - failed_before == 1
+
+ @patch.object(CspReportBuffer, "_ensure_sender")
+ def test_byte_budget_evicts_oldest(self, _mock_sender) -> None:
+ buf = self._buffer(max_bytes=250, max_event_bytes=200)
+ # Each event serializes to ~120 bytes, so the third pushes total over 250.
+ events = [{"event": str(i), "raw": "x" * 100} for i in range(3)]
+ buf.enqueue(events, token="token-1")
+
+ contents = [buf._queue.get_nowait() for _ in range(buf._queue.qsize())]
+ assert [e["event"] for _, e, _s in contents] == ["1", "2"]
+ assert buf._total_bytes <= 250
+
+ @patch("posthog.api.report_buffer.capture_exception")
+ @patch("posthog.api.report_buffer.capture_batch_internal", side_effect=Exception("capture down"))
+ def test_flush_failure_does_not_raise(self, mock_capture, mock_capture_exception) -> None:
+ buf = self._buffer()
+ buf._flush([("token-1", {"event": "a"}, 20)])
+ assert mock_capture.call_count == 1
+ assert mock_capture_exception.call_count == 1
+
+ # Regression: token groups are submitted serially, so a flood of distinct
+ # tokens against a slow capture-rs could stall the sender for the sum of
+ # every group's transport budget while the queue evicted everything behind
+ # it. The flush deadline must cut the loop and count unsent events.
+ @patch("posthog.api.report_buffer.time.monotonic")
+ @patch("posthog.api.report_buffer.capture_batch_internal")
+ def test_flush_stops_at_deadline_and_drops_remaining_groups(self, mock_capture, mock_monotonic) -> None:
+ mock_capture.return_value = _capture_result(ok=["u1"])
+ # monotonic calls: deadline anchor (0.0), group-1 check (0.5, within
+ # budget), group-2 check (10.0, past it) — groups 2 and 3 never submit.
+ mock_monotonic.side_effect = [0.0, 0.5, 10.0]
+ buf = self._buffer(flush_max_seconds=1.0)
+ dropped_before = CSP_BUFFER_DROPPED.labels(reason="flush_deadline")._value.get()
+
+ buf._flush(
+ [
+ ("token-1", {"event": "a"}, 10),
+ ("token-2", {"event": "b"}, 10),
+ ("token-2", {"event": "c"}, 10),
+ ("token-3", {"event": "d"}, 10),
+ ]
+ )
+
+ assert mock_capture.call_count == 1
+ assert mock_capture.call_args.kwargs["token"] == "token-1"
+ dropped = CSP_BUFFER_DROPPED.labels(reason="flush_deadline")._value.get() - dropped_before
+ assert dropped == 3
diff --git a/posthog/settings/ingestion.py b/posthog/settings/ingestion.py
index be3e1b218a03..6bff349d7563 100644
--- a/posthog/settings/ingestion.py
+++ b/posthog/settings/ingestion.py
@@ -71,6 +71,32 @@ CAPTURE_V1_INTERNAL_RETRY_AFTER_CAP_SECONDS = get_from_env(
)
# Chunk fan-out reuses CAPTURE_INTERNAL_MAX_WORKERS (above) for its thread pool.
CAPTURE_INTERNAL_BATCH_CHUNK_SIZE = get_from_env("CAPTURE_INTERNAL_BATCH_CHUNK_SIZE", type_cast=int, default=200)
+
+# Buffered CSP capture-forward: when enabled, /report/ enqueues accepted reports to a
+# bounded in-process buffer and returns 204 immediately; a background thread batches
+# them to capture-rs. Keeps request-worker hold time independent of capture-rs latency,
+# which is required for servers with bounded worker pools (WSGI). Off = legacy
+# synchronous forward.
+CSP_REPORT_BUFFERED_FORWARD = get_from_env("CSP_REPORT_BUFFERED_FORWARD", False, type_cast=str_to_bool)
+CSP_REPORT_BUFFER_MAX_EVENTS = get_from_env("CSP_REPORT_BUFFER_MAX_EVENTS", type_cast=int, default=10000)
+CSP_REPORT_BUFFER_FLUSH_INTERVAL_SECONDS = get_from_env(
+ "CSP_REPORT_BUFFER_FLUSH_INTERVAL_SECONDS", type_cast=float, default=0.5
+)
+CSP_REPORT_BUFFER_FLUSH_MAX_EVENTS = get_from_env("CSP_REPORT_BUFFER_FLUSH_MAX_EVENTS", type_cast=int, default=1000)
+# Wall-clock ceiling per flush: token groups are submitted serially, so many
+# distinct tokens against a slow capture-rs would otherwise stall the sender for
+# the sum of every group's transport budget. Events still unsent at the deadline
+# are dropped (reason="flush_deadline"). A healthy flush finishes well under a
+# second; the ceiling only bites while capture-rs degrades.
+CSP_REPORT_BUFFER_FLUSH_MAX_SECONDS = get_from_env("CSP_REPORT_BUFFER_FLUSH_MAX_SECONDS", type_cast=float, default=5.0)
+# Fairness: the largest share of the buffer any single token may hold, so one
+# token's report storm cannot evict every other token's events on overflow.
+CSP_REPORT_BUFFER_MAX_TOKEN_SHARE = get_from_env("CSP_REPORT_BUFFER_MAX_TOKEN_SHARE", type_cast=float, default=0.5)
+# Memory bounds: the count cap alone doesn't bound memory because events carry the
+# raw report body. Per-event cap rejects pathological payloads (legit CSP reports
+# are a few KB); the total cap evicts oldest when crossed.
+CSP_REPORT_BUFFER_MAX_EVENT_BYTES = get_from_env("CSP_REPORT_BUFFER_MAX_EVENT_BYTES", type_cast=int, default=64 * 1024)
+CSP_REPORT_BUFFER_MAX_BYTES = get_from_env("CSP_REPORT_BUFFER_MAX_BYTES", type_cast=int, default=64 * 1024 * 1024)
NEW_ANALYTICS_CAPTURE_EXCLUDED_TEAM_IDS = get_set(os.getenv("NEW_ANALYTICS_CAPTURE_EXCLUDED_TEAM_IDS", ""))
ELEMENT_CHAIN_AS_STRING_EXCLUDED_TEAMS = get_set(os.getenv("ELEMENT_CHAIN_AS_STRING_EXCLUDED_TEAMS", ""))