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(github): trace outbound request latency (#102627)

Paul D'Ambrabe5476c4b999
diff --git a/posthog/egress/README.md b/posthog/egress/README.md
index 4d735a080ac6..7ad135283468 100644
--- a/posthog/egress/README.md
+++ b/posthog/egress/README.md
@@ -125,6 +125,12 @@ Each domain keeps its own metric names, so existing dashboards stay valid.
The `source` label (e.g. `integration`, `visual_review`, `warehouse`) carries per-subsystem attribution.
Endpoint labels are normalized to bound cardinality: numeric ids are templated out by default, and a domain with structured paths passes its own normalizer, so raw-URL callers don't mint one label per id.
+The base transports also emit an experimental OpenTelemetry client span for every outbound request.
+The span uses the shared `egress.*` attributes and the domain adds only API-specific attributes.
+It records the final response host after redirects, marks HTTP error responses, and records only the
+exception type when a request fails so credentials cannot enter trace attributes.
+A gated call records the limiter's decision as `egress.admission.granted`, so a denied `CRITICAL` call that proceeds shows `false`; an identity-blind call has no admission attribute.
+
Harmonic also records `harmonic_api_request_duration_seconds` from the start of an HTTP request through response headers, and `harmonic_api_admission_wait_seconds` for waits in the bulk client's pacing loop, including time queued for the pacing lock.
The request duration excludes the local admission wait and response-body parsing.
Both are one-offs, marked as such in `harmonic/observability.py`, and request duration moves into the base clients once a second domain needs it.
diff --git a/posthog/egress/browserless/transport.py b/posthog/egress/browserless/transport.py
index cb45a79da152..55d0bc5d1395 100644
--- a/posthog/egress/browserless/transport.py
+++ b/posthog/egress/browserless/transport.py
@@ -35,6 +35,7 @@ def fleet_scope(url: str, token: str) -> str:
class BrowserlessClient(EgressClient):
observability = browserless_egress
+ egress_domain = "browserless"
def _standard_headers(self) -> dict[str, str]:
return {"Content-Type": "application/json"}
diff --git a/posthog/egress/firecrawl/transport.py b/posthog/egress/firecrawl/transport.py
index b45c7dc7387c..0280b5fb9fd0 100644
--- a/posthog/egress/firecrawl/transport.py
+++ b/posthog/egress/firecrawl/transport.py
@@ -26,6 +26,7 @@ class FirecrawlClient(EgressClient):
every caller; wire it through :func:`firecrawl_request`."""
observability = firecrawl_egress
+ egress_domain = "firecrawl"
def _standard_headers(self) -> dict[str, str]:
return {"Accept": "application/json", "Content-Type": "application/json"}
diff --git a/posthog/egress/github/transport.py b/posthog/egress/github/transport.py
index 76bc97119270..aa44d554c053 100644
--- a/posthog/egress/github/transport.py
+++ b/posthog/egress/github/transport.py
@@ -96,6 +96,23 @@ class GitHubClient(EgressClient):
instance serves every caller; wire it through :func:`github_request`."""
observability = github_egress
+ egress_domain = "github"
+ span_name = "github.http.request"
+
+ def _span_attributes(
+ self,
+ method: str,
+ url: str,
+ *,
+ source: str,
+ scope: str | None,
+ priority: Priority,
+ endpoint: str | None,
+ ) -> dict[str, str | bool]:
+ return {
+ **super()._span_attributes(method, url, source=source, scope=scope, priority=priority, endpoint=endpoint),
+ "github.resource": classify_github_resource(url).value,
+ }
def _standard_headers(self) -> dict[str, str]:
return {"Accept": "application/vnd.github+json", "X-GitHub-Api-Version": GITHUB_API_VERSION}
diff --git a/posthog/egress/google_workspace/transport.py b/posthog/egress/google_workspace/transport.py
index b9515234f1a6..9df74ad041b2 100644
--- a/posthog/egress/google_workspace/transport.py
+++ b/posthog/egress/google_workspace/transport.py
@@ -14,6 +14,7 @@ class GoogleWorkspaceEgressBudgetExhausted(EgressBudgetExhausted):
class GoogleWorkspaceClient(EgressClient):
observability = google_workspace_egress
+ egress_domain = "google_workspace"
def _standard_headers(self) -> dict[str, str]:
return {"Accept": "application/json"}
diff --git a/posthog/egress/harmonic/transport.py b/posthog/egress/harmonic/transport.py
index a4d31083b4a9..68eb406e9b98 100644
--- a/posthog/egress/harmonic/transport.py
+++ b/posthog/egress/harmonic/transport.py
@@ -34,6 +34,7 @@ class HarmonicClient(AsyncEgressClient):
matching aiohttp's recommended session-reuse pattern rather than one session per call)."""
observability = harmonic_egress
+ egress_domain = "harmonic"
def _standard_headers(self) -> dict[str, str]:
return {"Content-Type": "application/json"}
diff --git a/posthog/egress/logodev/transport.py b/posthog/egress/logodev/transport.py
index e6263283e332..6c6dc1d906ff 100644
--- a/posthog/egress/logodev/transport.py
+++ b/posthog/egress/logodev/transport.py
@@ -26,6 +26,7 @@ class LogoDevClient(EgressClient):
every caller; wire it through :func:`logodev_request`."""
observability = logodev_egress
+ egress_domain = "logodev"
def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:
return consume_logodev_sync(priority=priority, source=source)
diff --git a/posthog/egress/observability/observability.py b/posthog/egress/observability/observability.py
index 136e9ba497b2..fb9cafda05be 100644
--- a/posthog/egress/observability/observability.py
+++ b/posthog/egress/observability/observability.py
@@ -149,6 +149,9 @@ class EgressObservability:
if gauge is not None and value is not None:
gauge.labels(scope, snapshot.resource).set(value)
+ def normalize_endpoint(self, url: str | None) -> str:
+ return self._normalize_endpoint(url)
+
def record_requests_response(
self,
response: requests.Response,
diff --git a/posthog/egress/openai_auth/transport.py b/posthog/egress/openai_auth/transport.py
index b93871245ee5..29e775f54ce2 100644
--- a/posthog/egress/openai_auth/transport.py
+++ b/posthog/egress/openai_auth/transport.py
@@ -18,6 +18,7 @@ OPENAI_OAUTH_REVOKE_URL = "https://auth.openai.com/oauth/revoke"
class OpenAIAuthClient(RecordedEgressClient):
observability = openai_auth_egress
+ egress_domain = "openai_auth"
def _standard_headers(self) -> dict[str, str]:
return {"Accept": "application/json"}
diff --git a/posthog/egress/slack/transport.py b/posthog/egress/slack/transport.py
index f223fef099b7..e5e9f2cac167 100644
--- a/posthog/egress/slack/transport.py
+++ b/posthog/egress/slack/transport.py
@@ -11,6 +11,7 @@ class SlackClient(RecordedEgressClient):
remaining-budget headers, so there is no single budget to draw from. Callers own reactive retries."""
observability = slack_egress
+ egress_domain = "slack"
def __init__(self, app_id: str) -> None:
self._app_id = app_id
diff --git a/posthog/egress/test/test_async_egress_client.py b/posthog/egress/test/test_async_egress_client.py
index 66cc6a100fcb..691ee85e08e6 100644
--- a/posthog/egress/test/test_async_egress_client.py
+++ b/posthog/egress/test/test_async_egress_client.py
@@ -1,8 +1,17 @@
-from unittest.mock import AsyncMock
+from collections.abc import Iterator
+from contextlib import contextmanager
+
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
import aiohttp
+from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.sdk.trace.export import SimpleSpanProcessor
+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
+from yarl import URL
from posthog.egress.limiter.policies import Priority
+from posthog.egress.observability.observability import EgressObservability
from posthog.egress.transport.transport import AsyncEgressClient, EgressBudgetExhausted
@@ -11,6 +20,9 @@ class _StubBudgetExhausted(EgressBudgetExhausted):
class _StubAsyncEgressClient(AsyncEgressClient):
+ observability = MagicMock(spec=EgressObservability, **{"normalize_endpoint.return_value": "/"})
+ egress_domain = "stub"
+
def __init__(self, granted: bool) -> None:
self._granted = granted
self.recorded_exceptions: list[str] = []
@@ -33,6 +45,15 @@ class _StubAsyncEgressClient(AsyncEgressClient):
return _StubBudgetExhausted("denied")
+@contextmanager
+def _captured_spans() -> Iterator[InMemorySpanExporter]:
+ exporter = InMemorySpanExporter()
+ provider = TracerProvider()
+ provider.add_span_processor(SimpleSpanProcessor(exporter))
+ with patch("posthog.egress.transport.transport.tracer", provider.get_tracer("test")):
+ yield exporter
+
+
def _fake_session(status: int = 200) -> AsyncMock:
response = AsyncMock()
response.status = status
@@ -84,3 +105,45 @@ async def test_async_base_records_a_total_deadline_timeout() -> None:
assert raised
assert client.recorded_exceptions == ["https://example.com"]
+
+
+async def test_async_base_span_records_the_final_response_host() -> None:
+ client = _StubAsyncEgressClient(granted=True)
+ session = _fake_session(status=503)
+ session.request.return_value.url = URL("https://redirected.example.com/final")
+
+ with _captured_spans() as exporter:
+ await client.request(session, "GET", "https://example.com/start", source="test", scope="scope")
+
+ span = exporter.get_finished_spans()[0]
+ assert span.attributes is not None
+ assert span.attributes["server.address"] == "redirected.example.com"
+ assert span.attributes["http.response.status_code"] == 503
+ assert span.status.status_code.name == "ERROR"
+
+
[email protected]("granted", [True, False])
+async def test_async_base_span_records_the_admission_decision(granted: bool) -> None:
+ client = _StubAsyncEgressClient(granted=granted)
+
+ with _captured_spans() as exporter:
+ await client.request(_fake_session(), "GET", "https://example.com", source="test", scope="scope")
+
+ attributes = exporter.get_finished_spans()[0].attributes
+ assert attributes is not None
+ assert attributes["egress.admission.granted"] is granted
+
+
+async def test_async_base_span_marks_a_gate_error() -> None:
+ client = _StubAsyncEgressClient(granted=True)
+ session = _fake_session()
+
+ with _captured_spans() as exporter, patch.object(client, "_consume", AsyncMock(side_effect=RuntimeError)):
+ with pytest.raises(RuntimeError):
+ await client.request(session, "GET", "https://example.com", source="test", scope="scope")
+
+ session.request.assert_not_called()
+ span = exporter.get_finished_spans()[0]
+ assert span.attributes is not None
+ assert span.attributes["error.type"] == "RuntimeError"
+ assert span.status.status_code.name == "ERROR"
diff --git a/posthog/egress/test/test_domains.py b/posthog/egress/test/test_domains.py
index f49b2765934f..a72f626d4da9 100644
--- a/posthog/egress/test/test_domains.py
+++ b/posthog/egress/test/test_domains.py
@@ -1,8 +1,10 @@
+import inspect
import importlib
from pathlib import Path
import posthog.egress
from posthog.egress.limiter.policies import _REGISTRY, Priority, resolve_policy
+from posthog.egress.transport.transport import AsyncEgressClient, RecordedEgressClient
_EGRESS_ROOT = Path(posthog.egress.__file__).parent
@@ -25,6 +27,18 @@ def test_every_domain_documents_itself_in_a_readme_with_sources() -> None:
assert missing == []
+def test_every_domain_client_names_its_domain_on_spans() -> None:
+ mislabeled = []
+ for domain in _domain_dirs():
+ module = importlib.import_module(f"posthog.egress.{domain.name}.transport")
+ for name, cls in inspect.getmembers(module, inspect.isclass):
+ if cls.__module__ != module.__name__ or not issubclass(cls, (RecordedEgressClient, AsyncEgressClient)):
+ continue
+ if vars(cls).get("egress_domain") != domain.name:
+ mislabeled.append(name)
+ assert mislabeled == []
+
+
def test_only_reviewed_domains_run_a_flat_policy() -> None:
domain_names = {domain.name for domain in _domain_dirs()}
for domain in _domain_dirs():
diff --git a/posthog/egress/test/test_github_transport.py b/posthog/egress/test/test_github_transport.py
index a6e7fb80d356..59538f8b5509 100644
--- a/posthog/egress/test/test_github_transport.py
+++ b/posthog/egress/test/test_github_transport.py
@@ -3,6 +3,9 @@ from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase
import requests
+from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.sdk.trace.export import SimpleSpanProcessor
+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from parameterized import parameterized
from requests.structures import CaseInsensitiveDict
@@ -22,6 +25,50 @@ def _response(status: int = 200) -> requests.Response:
class TestGitHubTransport(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("success", 200, True, "UNSET"),
+ ("http_error", 429, True, "ERROR"),
+ ("denied_critical_call_proceeds", 200, False, "UNSET"),
+ ]
+ )
+ def test_request_records_normalized_client_span(
+ self, _name: str, status_code: int, granted: bool, span_status: str
+ ) -> None:
+ exporter = InMemorySpanExporter()
+ provider = TracerProvider()
+ provider.add_span_processor(SimpleSpanProcessor(exporter))
+
+ with (
+ patch("posthog.egress.transport.transport.tracer", provider.get_tracer("test")),
+ patch("posthog.egress.github.transport.consume_github_installation_sync", return_value=granted),
+ patch("requests.request", return_value=_response(status_code)),
+ ):
+ github_request(
+ "GET",
+ "https://api.github.com/repos/example/repo/branches?page=1",
+ source="integration",
+ installation_id="42",
+ endpoint="/repos/{owner}/{repo}/branches",
+ )
+
+ span = exporter.get_finished_spans()[0]
+ assert span.name == "github.http.request"
+ assert span.kind.name == "CLIENT"
+ assert span.attributes == {
+ "http.request.method": "GET",
+ "server.address": "api.github.com",
+ "egress.domain": "github",
+ "egress.source": "integration",
+ "egress.priority": "critical",
+ "egress.endpoint": "/repos/{owner}/{repo}/branches",
+ "egress.scoped": True,
+ "egress.admission.granted": granted,
+ "github.resource": "core",
+ "http.response.status_code": status_code,
+ }
+ assert span.status.status_code.name == span_status
+
@parameterized.expand(
[
("code_search", "https://api.github.com/search/code?q=x", GitHubRateResource.CODE_SEARCH),
@@ -45,3 +92,94 @@ class TestGitHubTransport(SimpleTestCase):
):
github_request("GET", "https://api.github.com/search/code?q=x", source="test", installation_id=None)
consume.assert_not_called()
+
+ def test_span_marks_a_gate_error(self) -> None:
+ exporter = InMemorySpanExporter()
+ provider = TracerProvider()
+ provider.add_span_processor(SimpleSpanProcessor(exporter))
+
+ with (
+ patch("posthog.egress.transport.transport.tracer", provider.get_tracer("test")),
+ patch("posthog.egress.github.transport.consume_github_installation_sync", side_effect=RuntimeError),
+ patch("requests.request") as send,
+ self.assertRaises(RuntimeError),
+ ):
+ github_request("GET", "https://api.github.com/repos/example/repo", source="test", installation_id="42")
+
+ send.assert_not_called()
+ span = exporter.get_finished_spans()[0]
+ assert span.attributes is not None
+ assert span.attributes["error.type"] == "RuntimeError"
+ assert span.status.status_code.name == "ERROR"
+
+ def test_span_uses_the_request_host_for_raw_github_urls(self) -> None:
+ exporter = InMemorySpanExporter()
+ provider = TracerProvider()
+ provider.add_span_processor(SimpleSpanProcessor(exporter))
+
+ with (
+ patch("posthog.egress.transport.transport.tracer", provider.get_tracer("test")),
+ patch("requests.request", return_value=_response()),
+ ):
+ github_request("GET", "https://raw.githubusercontent.com/PostHog/posthog/main/README.md", source="test")
+
+ attributes = exporter.get_finished_spans()[0].attributes
+ assert attributes is not None
+ assert attributes["server.address"] == "raw.githubusercontent.com"
+
+ def test_span_uses_the_final_response_host_after_redirects(self) -> None:
+ exporter = InMemorySpanExporter()
+ provider = TracerProvider()
+ provider.add_span_processor(SimpleSpanProcessor(exporter))
+ response = _response()
+ response.url = "https://uploads.github.com/repos/example/repo/archive.zip"
+
+ with (
+ patch("posthog.egress.transport.transport.tracer", provider.get_tracer("test")),
+ patch("requests.request", return_value=response),
+ ):
+ github_request("GET", "https://api.github.com/repos/example/repo/archive", source="test")
+
+ attributes = exporter.get_finished_spans()[0].attributes
+ assert attributes is not None
+ assert attributes["server.address"] == "uploads.github.com"
+
+ def test_span_handles_response_without_url(self) -> None:
+ exporter = InMemorySpanExporter()
+ provider = TracerProvider()
+ provider.add_span_processor(SimpleSpanProcessor(exporter))
+ response = MagicMock(spec=["status_code", "headers"])
+ response.status_code = 200
+ response.headers = CaseInsensitiveDict()
+
+ with (
+ patch("posthog.egress.transport.transport.tracer", provider.get_tracer("test")),
+ patch("requests.request", return_value=response),
+ ):
+ assert github_request("GET", "https://api.github.com/repos/example/repo", source="test") is response
+
+ attributes = exporter.get_finished_spans()[0].attributes
+ assert attributes is not None
+ assert attributes["server.address"] == "api.github.com"
+
+ def test_span_matches_identity_blind_request_without_explicit_endpoint(self) -> None:
+ exporter = InMemorySpanExporter()
+ provider = TracerProvider()
+ provider.add_span_processor(SimpleSpanProcessor(exporter))
+
+ with (
+ patch("posthog.egress.transport.transport.tracer", provider.get_tracer("test")),
+ patch("requests.request", return_value=_response()),
+ ):
+ github_request(
+ "GET",
+ "https://api.github.com/repos/example/repo/branches?page=1",
+ source="test",
+ installation_id="",
+ )
+
+ attributes = exporter.get_finished_spans()[0].attributes
+ assert attributes is not None
+ assert attributes["egress.endpoint"] == "/repos/{owner}/{repo}/branches"
+ assert attributes["egress.scoped"] is False
+ assert "egress.admission.granted" not in attributes
diff --git a/posthog/egress/transport/transport.py b/posthog/egress/transport/transport.py
index 6c89c82da65a..729f73ac3084 100644
--- a/posthog/egress/transport/transport.py
+++ b/posthog/egress/transport/transport.py
@@ -21,17 +21,23 @@ from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Callable
from typing import TYPE_CHECKING, Any
+from urllib.parse import urlparse
import requests
+from opentelemetry import trace
+from opentelemetry.trace import Status, StatusCode
# aiohttp is only needed by AsyncEgressClient, and the sync domains import this module during
# django.setup(). A module-level import would put aiohttp on the startup path of every process.
if TYPE_CHECKING:
import aiohttp
+ from yarl import URL
from posthog.egress.limiter.policies import Priority
from posthog.egress.observability.observability import EgressObservability
+tracer = trace.get_tracer(__name__)
+
class EgressBudgetExhausted(Exception):
"""A *sheddable* (non-CRITICAL) outbound call was denied by the egress limiter before it was sent.
@@ -57,6 +63,7 @@ def _raise_if_denied(granted: bool, priority: Priority, make_error: Callable[[],
# regardless, so a user-facing call is never shed by us — the API's own 429 is the backstop.
# Sheddable lanes back off so their headroom is left for higher-priority traffic. Shared by both
# the sync and async gate so the rule can't drift between the two.
+ trace.get_current_span().set_attribute("egress.admission.granted", granted)
if not granted and priority is not Priority.CRITICAL:
raise make_error()
@@ -65,6 +72,8 @@ class _EgressHooks:
"""The hooks every transport shares, sync or async. Subclasses set ``observability``."""
observability: EgressObservability
+ egress_domain: str
+ span_name = "egress.http.request"
def _standard_headers(self) -> dict[str, str]:
"""Default headers merged under the caller's (the caller's win) — e.g. Accept, API version."""
@@ -74,6 +83,43 @@ class _EgressHooks:
"""Record a request that raised before returning a response (timeout, connection error)."""
self.observability.record_exception(source=source, scope=scope, method=method, endpoint=endpoint, url=url)
+ def _span_attributes(
+ self,
+ method: str,
+ url: str,
+ *,
+ source: str,
+ scope: str | None,
+ priority: Priority,
+ endpoint: str | None,
+ ) -> dict[str, str | bool]:
+ return {
+ "http.request.method": method.upper(),
+ "server.address": urlparse(url).hostname or "unknown",
+ "egress.domain": self.egress_domain,
+ "egress.source": source,
+ "egress.priority": priority.value,
+ "egress.endpoint": endpoint or self.observability.normalize_endpoint(url),
+ "egress.scoped": bool(scope),
+ }
+
+ @staticmethod
+ def _mark_span_exception(span: trace.Span, error: Exception) -> None:
+ span.set_attribute("error.type", type(error).__name__)
+ span.set_status(Status(StatusCode.ERROR))
+
+ @staticmethod
+ def _set_span_response_metadata(span: trace.Span, response_url: str | URL | None, status_code: int | None) -> None:
+ """Record response URL (after redirects) and status code to the span."""
+ if response_url is not None:
+ response_hostname = urlparse(str(response_url)).hostname
+ if response_hostname:
+ span.set_attribute("server.address", response_hostname)
+ if isinstance(status_code, int):
+ span.set_attribute("http.response.status_code", status_code)
+ if status_code >= 400:
+ span.set_status(Status(StatusCode.ERROR))
+
class RecordedEgressClient(_EgressHooks):
"""One outbound API's transport without a budget: request → record.
@@ -91,21 +137,45 @@ class RecordedEgressClient(_EgressHooks):
headers: dict[str, str] | None = None,
scope: str | None = None,
endpoint: str | None = None,
+ priority: Priority = Priority.CRITICAL,
timeout: float | tuple[float, float] | None = None,
session: requests.Session | None = None,
**kwargs: Any,
) -> requests.Response:
request_headers = {**self._standard_headers(), **(headers or {})}
sender = session or requests
- try:
- response = sender.request(method, url, headers=request_headers, timeout=timeout, **kwargs)
- except requests.RequestException:
- # Best-effort telemetry must never mask the real transport error — record and re-raise it.
- self._record_exception(source=source, scope=scope, method=method, url=url, endpoint=endpoint)
- raise
-
- self._record_response(response, source=source, scope=scope, method=method, endpoint=endpoint)
- return response
+ with tracer.start_as_current_span(
+ self.span_name,
+ kind=trace.SpanKind.CLIENT,
+ attributes=self._span_attributes(
+ method, url, source=source, scope=scope, priority=priority, endpoint=endpoint
+ ),
+ record_exception=False,
+ set_status_on_exception=False,
+ ) as span:
+ try:
+ self._before_request(scope, source, priority, url)
+ response = sender.request(method, url, headers=request_headers, timeout=timeout, **kwargs)
+ except EgressBudgetExhausted:
+ # A shed call is the limiter working as designed, not a failed request.
+ raise
+ except requests.RequestException as error:
+ self._mark_span_exception(span, error)
+ # Best-effort telemetry must never mask the real transport error.
+ self._record_exception(source=source, scope=scope, method=method, url=url, endpoint=endpoint)
+ raise
+ except Exception as error:
+ self._mark_span_exception(span, error)
+ raise
+
+ self._record_response(response, source=source, scope=scope, method=method, endpoint=endpoint)
+ self._set_span_response_metadata(
+ span, getattr(response, "url", None), getattr(response, "status_code", None)
+ )
+ return response
+
+ def _before_request(self, scope: str | None, source: str, priority: Priority, url: str) -> None:
+ pass
def _record_response(
self, response: requests.Response, *, source: str, scope: str | None, method: str, endpoint: str | None
@@ -139,7 +209,6 @@ class EgressClient(RecordedEgressClient, ABC):
session: requests.Session | None = None,
**kwargs: Any,
) -> requests.Response:
- self._gate(scope, source, priority, url)
return super().request(
method,
url,
@@ -147,11 +216,15 @@ class EgressClient(RecordedEgressClient, ABC):
headers=headers,
scope=scope,
endpoint=endpoint,
+ priority=priority,
timeout=timeout,
session=session,
**kwargs,
)
+ def _before_request(self, scope: str | None, source: str, priority: Priority, url: str) -> None:
+ self._gate(scope, source, priority, url)
+
def _gate(self, scope: str | None, source: str, priority: Priority, url: str) -> None:
# Identity-blind callers have no shared budget to draw on — record volume only, never gate.
# An empty scope is no identity either: gating on it would key a phantom budget/metric series.
@@ -195,21 +268,37 @@ class AsyncEgressClient(_EgressHooks, ABC):
) -> aiohttp.ClientResponse:
import aiohttp # noqa: PLC0415
- await self._gate(scope, source, priority, url)
-
request_headers = {**self._standard_headers(), **(headers or {})}
- try:
- response = await session.request(method, url, headers=request_headers, **kwargs)
- except (aiohttp.ClientError, TimeoutError):
- # aiohttp raises a bare TimeoutError when ClientTimeout.total expires; only the connect
- # phase gets wrapped into a ClientError. Catching just ClientError would drop the most
- # likely outage from the metric.
- # Best-effort telemetry must never mask the real transport error — record and re-raise it.
- self._record_exception(source=source, scope=scope, method=method, url=url, endpoint=endpoint)
- raise
-
- self._record_response(response, source=source, scope=scope, method=method, endpoint=endpoint)
- return response
+ with tracer.start_as_current_span(
+ self.span_name,
+ kind=trace.SpanKind.CLIENT,
+ attributes=self._span_attributes(
+ method, url, source=source, scope=scope, priority=priority, endpoint=endpoint
+ ),
+ record_exception=False,
+ set_status_on_exception=False,
+ ) as span:
+ try:
+ await self._gate(scope, source, priority, url)
+ response = await session.request(method, url, headers=request_headers, **kwargs)
+ except EgressBudgetExhausted:
+ # A shed call is the limiter working as designed, not a failed request.
+ raise
+ except (aiohttp.ClientError, TimeoutError) as error:
+ self._mark_span_exception(span, error)
+ # aiohttp raises a bare TimeoutError when ClientTimeout.total expires; only the connect
+ # phase gets wrapped into a ClientError. Catching just ClientError would drop the most
+ # likely outage from the metric.
+ # Best-effort telemetry must never mask the real transport error.
+ self._record_exception(source=source, scope=scope, method=method, url=url, endpoint=endpoint)
+ raise
+ except Exception as error:
+ self._mark_span_exception(span, error)
+ raise
+
+ self._set_span_response_metadata(span, response.url, response.status)
+ self._record_response(response, source=source, scope=scope, method=method, endpoint=endpoint)
+ return response
async def _gate(self, scope: str | None, source: str, priority: Priority, url: str) -> None:
# Identity-blind callers have no shared budget to draw on — record volume only, never gate.
diff --git a/posthog/egress/typesafe/transport.py b/posthog/egress/typesafe/transport.py
index 1376662867e2..47ccdbd6d755 100644
--- a/posthog/egress/typesafe/transport.py
+++ b/posthog/egress/typesafe/transport.py
@@ -28,6 +28,7 @@ class TypeSafeClient(EgressClient):
every caller; wire it through :func:`typesafe_request`."""
observability = typesafe_egress
+ egress_domain = "typesafe"
def _gate(self, scope: str | None, source: str, priority: Priority, url: str) -> None:
if not typesafe_allowed():