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(apm): add a service map tab to application observability (#123559)

Daniel Visca42657224e92d
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index fa61e0dfa6d2..17e5c6b0d713 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2677,6 +2677,15 @@ importers:
'@types/react':
specifier: 18.3.27
version: 18.3.27
+ '@xyflow/react':
+ specifier: '*'
+ clsx:
+ specifier: '*'
+ version: 2.1.1
+ elkjs:
+ specifier: '*'
+ version: 0.10.0
kea:
specifier: 'catalog:'
version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])
diff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.py
index 9c14ccf69aaa..2456f3ff77ed 100644
--- a/posthog/test/repo_invariants/test_pagination_contract.py
+++ b/posthog/test/repo_invariants/test_pagination_contract.py
@@ -32,6 +32,8 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {
"products.apm.backend.presentation.views.ServicesHealthViewSet",
# Returns one bounded object (capped at ENDPOINTS_LIMIT rows), not a page of rows.
"products.apm.backend.presentation.views.EndpointsHealthViewSet",
+ # Returns one bounded object (capped at MAP_EDGES_LIMIT edges over a bounded trace sample), not a page of rows.
+ "products.apm.backend.presentation.views.ServiceMapViewSet",
"ee.api.billing.BillingViewset",
"ee.api.quota_limits.QuotaLimitsViewSet",
"products.subscriptions.backend.presentation.views.SubscriptionDeliveryViewSet",
diff --git a/products/apm/backend/facade/api.py b/products/apm/backend/facade/api.py
index ea97f389b892..f5fb4f809b55 100644
--- a/products/apm/backend/facade/api.py
+++ b/products/apm/backend/facade/api.py
@@ -48,12 +48,15 @@ from products.apm.backend.logic.health.contract import (
EndpointHealth,
HealthRow,
HealthStatus,
+ ServiceEdge,
ServiceHealth,
rank_services,
status_of,
)
from products.apm.backend.logic.health.sources import (
+ ServiceMapResult,
ServicesHealthResult,
+ get_service_map as _get_service_map,
list_endpoints_health as _list_endpoints_health,
list_services_health as _list_services_health,
)
@@ -67,8 +70,11 @@ __all__ = [
"EndpointHealth",
"HealthRow",
"HealthStatus",
+ "ServiceEdge",
"ServiceHealth",
+ "ServiceMapResult",
"ServicesHealthResult",
+ "get_service_map",
"list_endpoints_health",
"list_services_health",
"rank_services",
@@ -120,3 +126,8 @@ def list_endpoints_health(
return _list_endpoints_health(
team=team, date_from=date_from, date_to=date_to, environment=environment, service=service
)
+
+
+def get_service_map(*, team: "Team", date_from: "datetime", date_to: "datetime", environment: str) -> ServiceMapResult:
+ """Service-to-service call edges in the environment and window, from a bounded sample of traces."""
+ return _get_service_map(team=team, date_from=date_from, date_to=date_to, environment=environment)
diff --git a/products/apm/backend/logic/health/contract.py b/products/apm/backend/logic/health/contract.py
index 3bfafc1c59f5..469019e24209 100644
--- a/products/apm/backend/logic/health/contract.py
+++ b/products/apm/backend/logic/health/contract.py
@@ -51,6 +51,17 @@ class EndpointHealth:
status: HealthStatus = HealthStatus.GOOD
+@dataclass(frozen=True)
+class ServiceEdge:
+ """Calls from one service into another, counted on the callee spans whose parent is in the caller."""
+
+ caller: str
+ callee: str
+ calls: int
+ error_count: int
+ p95_ms: float | None
+
+
def status_of(health: HealthRow) -> HealthStatus:
rate = health.error_rate or 0.0
if rate >= SERIOUS_ERROR_RATE:
diff --git a/products/apm/backend/logic/health/sources.py b/products/apm/backend/logic/health/sources.py
index 68e5128caabb..eebd7bad63f6 100644
--- a/products/apm/backend/logic/health/sources.py
+++ b/products/apm/backend/logic/health/sources.py
@@ -20,6 +20,7 @@ from posthog.models import Team
from products.apm.backend.logic.health.contract import (
EndpointHealth,
HealthRow,
+ ServiceEdge,
ServiceHealth,
rank_endpoints,
rank_services,
@@ -28,6 +29,11 @@ from products.apm.backend.logic.health.contract import (
SPARKLINE_POINTS = 24
SERVICES_LIMIT = 500
ENDPOINTS_LIMIT = 500
+# The map joins spans to their parents, so it reads a bounded sample of traces, not the whole window.
+MAP_TRACE_LIMIT = 2000
+MAP_EDGES_LIMIT = 1000
+# Caps the rows the self-join holds in memory, however many spans the sampled traces carry.
+MAP_SPAN_LIMIT = 200_000
DEFAULT_ENVIRONMENT = "default"
ENVIRONMENT_ATTRIBUTES = (
@@ -53,6 +59,12 @@ class ServicesHealthResult:
environments: list[str]
+@dataclass(frozen=True)
+class ServiceMapResult:
+ edges: list[ServiceEdge]
+ trace_count: int
+
+
def environment_expr() -> ast.Expr:
parts = ", ".join(f"nullIf(resource_attributes['{key}'], '')" for key in ENVIRONMENT_ATTRIBUTES)
return parse_expr(
@@ -137,6 +149,69 @@ def _endpoints_query(date_from: datetime, date_to: datetime, environment: str, s
return query
+def _sampled_traces_query(date_from: datetime, date_to: datetime, environment: str) -> ast.SelectQuery:
+ # DISTINCT with LIMIT stops reading once it has enough trace IDs, where GROUP BY would first
+ # aggregate every trace in the window.
+ query = parse_select(
+ """
+ SELECT DISTINCT trace_id
+ FROM posthog.trace_spans
+ WHERE {where} AND {env_expr} = {environment}
+ LIMIT {limit}
+ """,
+ placeholders={
+ "where": _window_where(date_from, date_to),
+ "env_expr": environment_expr(),
+ "environment": ast.Constant(value=environment),
+ "limit": ast.Constant(value=MAP_TRACE_LIMIT),
+ },
+ )
+ assert isinstance(query, ast.SelectQuery)
+ return query
+
+
+def _service_edges_query(
+ date_from: datetime, date_to: datetime, environment: str, trace_ids: list[str]
+) -> ast.SelectQuery:
+ # A call shows up as a callee span whose parent span belongs to another service, so each call
+ # counts once however many client spans the caller wraps around it. Both ends must be in the
+ # environment: a sampled trace can also hold spans from another environment. The CTE is read once
+ # per side of the join, so its span budget needs a stable order for both sides to see the same rows.
+ query = parse_select(
+ """
+ WITH spans AS (
+ SELECT trace_id, span_id, parent_span_id, service_name, status_code, duration_nano
+ FROM posthog.trace_spans
+ WHERE {where} AND {env_expr} = {environment} AND trace_id IN {trace_ids}
+ ORDER BY trace_id, span_id
+ LIMIT {span_limit}
+ )
+ SELECT
+ p.service_name AS caller,
+ s.service_name AS callee,
+ count() AS calls,
+ countIf(s.status_code = 2) AS error_count,
+ quantile(0.95)(s.duration_nano) / 1e6 AS p95_ms
+ FROM spans AS s
+ INNER JOIN spans AS p ON p.trace_id = s.trace_id AND p.span_id = s.parent_span_id
+ WHERE p.service_name != s.service_name
+ GROUP BY caller, callee
+ ORDER BY calls DESC, caller, callee
+ LIMIT {limit}
+ """,
+ placeholders={
+ "where": _window_where(date_from, date_to),
+ "env_expr": environment_expr(),
+ "environment": ast.Constant(value=environment),
+ "trace_ids": ast.Tuple(exprs=[ast.Constant(value=trace_id) for trace_id in trace_ids]),
+ "span_limit": ast.Constant(value=MAP_SPAN_LIMIT),
+ "limit": ast.Constant(value=MAP_EDGES_LIMIT),
+ },
+ )
+ assert isinstance(query, ast.SelectQuery)
+ return query
+
+
def _sparkline_query(date_from: datetime, date_to: datetime, environment: str) -> ast.SelectQuery:
# One bucket per point across the window; the client draws the counts in order.
query = parse_select(
@@ -241,3 +316,23 @@ def list_endpoints_health(
)
]
return rank_endpoints(endpoints)
+
+
+def get_service_map(*, team: Team, date_from: datetime, date_to: datetime, environment: str) -> ServiceMapResult:
+ # The sample runs once, so the edges and the reported trace count describe the same traces.
+ trace_ids = [row[0] for row in _run(team, _sampled_traces_query(date_from, date_to, environment))]
+ if not trace_ids:
+ return ServiceMapResult(edges=[], trace_count=0)
+ edges = [
+ ServiceEdge(
+ caller=caller,
+ callee=callee,
+ calls=int(calls),
+ error_count=int(error_count),
+ p95_ms=float(p95_ms) if p95_ms is not None else None,
+ )
+ for caller, callee, calls, error_count, p95_ms in _run(
+ team, _service_edges_query(date_from, date_to, environment, trace_ids)
+ )
+ ]
+ return ServiceMapResult(edges=edges, trace_count=len(trace_ids))
diff --git a/products/apm/backend/presentation/serializers.py b/products/apm/backend/presentation/serializers.py
index af9295ed4c61..38659b628330 100644
--- a/products/apm/backend/presentation/serializers.py
+++ b/products/apm/backend/presentation/serializers.py
@@ -67,3 +67,20 @@ class EndpointsHealthResponseSerializer(serializers.Serializer):
service = serializers.CharField(allow_null=True, help_text="The service filter applied, if any.")
date_from = serializers.DateTimeField(help_text="Start of the window used.")
date_to = serializers.DateTimeField(help_text="End of the window used.")
+
+
+class ServiceEdgeSerializer(serializers.Serializer):
+ caller = serializers.CharField(help_text="The calling service.")
+ callee = serializers.CharField(help_text="The called service.")
+ calls = serializers.IntegerField(help_text="Calls from the caller into the callee in the sampled traces.")
+ error_count = serializers.IntegerField(help_text="Calls with an error status on the callee span.")
+ p95_ms = serializers.FloatField(allow_null=True, help_text="95th percentile duration of the callee span, in ms.")
+
+
+@extend_schema_serializer(many=False)
+class ServiceMapResponseSerializer(serializers.Serializer):
+ edges = ServiceEdgeSerializer(many=True, help_text="One edge per calling and called service, most calls first.")
+ trace_count = serializers.IntegerField(help_text="Traces sampled to build the map.")
+ environment = serializers.CharField(help_text="The environment the map was built for.")
+ date_from = serializers.DateTimeField(help_text="Start of the window used.")
+ date_to = serializers.DateTimeField(help_text="End of the window used.")
diff --git a/products/apm/backend/presentation/views.py b/products/apm/backend/presentation/views.py
index 133758a36943..5357fb5db0f6 100644
--- a/products/apm/backend/presentation/views.py
+++ b/products/apm/backend/presentation/views.py
@@ -25,10 +25,11 @@ from posthog.dataclasses import frozen
from posthog.models import Team
from posthog.models.user import User
-from products.apm.backend.facade.api import is_apm_enabled, list_endpoints_health, list_services_health
+from products.apm.backend.facade.api import get_service_map, is_apm_enabled, list_endpoints_health, list_services_health
from products.apm.backend.presentation.serializers import (
EndpointsHealthRequestSerializer,
EndpointsHealthResponseSerializer,
+ ServiceMapResponseSerializer,
ServicesHealthRequestSerializer,
ServicesHealthResponseSerializer,
)
@@ -123,3 +124,27 @@ class EndpointsHealthViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
"date_to": window.date_to,
}
return Response(EndpointsHealthResponseSerializer(payload).data, status=status.HTTP_200_OK)
+
+
+class ServiceMapViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ """Service-to-service call edges in an environment and window. Same gate and window as services."""
+
+ scope_object = "tracing"
+
+ @extend_schema(parameters=[ServicesHealthRequestSerializer], responses={200: ServiceMapResponseSerializer})
+ def list(self, request: Request, *args, **kwargs) -> Response:
+ _check_flag(self.team, cast(User, request.user))
+ tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)
+ window = _window(ServicesHealthRequestSerializer(data=request.query_params))
+
+ result = get_service_map(
+ team=self.team, date_from=window.date_from, date_to=window.date_to, environment=window.environment
+ )
+ payload = {
+ "edges": [asdict(edge) for edge in result.edges],
+ "trace_count": result.trace_count,
+ "environment": window.environment,
+ "date_from": window.date_from,
+ "date_to": window.date_to,
+ }
+ return Response(ServiceMapResponseSerializer(payload).data, status=status.HTTP_200_OK)
diff --git a/products/apm/backend/routes.py b/products/apm/backend/routes.py
index 327d82a16583..4aa9a04489fd 100644
--- a/products/apm/backend/routes.py
+++ b/products/apm/backend/routes.py
@@ -1,8 +1,9 @@
from posthog.api.routing import RouterRegistry
-from products.apm.backend.presentation.views import EndpointsHealthViewSet, ServicesHealthViewSet
+from products.apm.backend.presentation.views import EndpointsHealthViewSet, ServiceMapViewSet, ServicesHealthViewSet
def register_routes(routers: RouterRegistry) -> None:
routers.projects.register(r"apm/services", ServicesHealthViewSet, "project_apm_services", ["team_id"])
routers.projects.register(r"apm/endpoints", EndpointsHealthViewSet, "project_apm_endpoints", ["team_id"])
+ routers.projects.register(r"apm/service_map", ServiceMapViewSet, "project_apm_service_map", ["team_id"])
diff --git a/products/apm/backend/tests/test_service_map_api.py b/products/apm/backend/tests/test_service_map_api.py
new file mode 100644
index 000000000000..9b8866eacb7c
--- /dev/null
+++ b/products/apm/backend/tests/test_service_map_api.py
@@ -0,0 +1,118 @@
+import datetime as dt
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from drf_spectacular.generators import SchemaGenerator
+
+from products.apm.backend.tests.span_fixtures import SpanWriter, recreate_trace_spans_tables, restore_trace_spans_tables
+
+DATE_FROM = "2026-06-02T07:00:00Z"
+DATE_TO = "2026-06-02T09:00:00Z"
+FLAG_PATCH = "products.apm.backend.presentation.views.is_apm_enabled"
+URL = "/api/projects/{}/apm/service_map/"
+
+
+class TestServiceMapAPI(ClickhouseTestMixin, APIBaseTest):
+ """Service-to-service edges from parent/child spans across services, over a bounded trace sample."""
+
+ CLASS_DATA_LEVEL_SETUP = True
+
+ @classmethod
+ def tearDownClass(cls):
+ restore_trace_spans_tables()
+ super().tearDownClass()
+
+ @classmethod
+ def setUpTestData(cls):
+ super().setUpTestData()
+ recreate_trace_spans_tables()
+ w = SpanWriter(team_id=cls.team.id, base=dt.datetime(2026, 6, 2, 8, 0, 0), uuid_prefix="019e8773")
+
+ # Three traces web -> api -> db-svc. The api -> db-svc call fails in the first trace.
+ for trace in range(1, 4):
+ web = w.span("web", name="GET /orders", env="prod", trace=trace)
+ call = w.span("web", name="GET api", kind=3, env="prod", trace=trace, parent=web)
+ api = w.span("api", name="GET /orders", env="prod", trace=trace, parent=call, ms=40)
+ # An internal child in the same service is not an edge.
+ w.span("api", name="serialize", kind=1, env="prod", trace=trace, parent=api)
+ w.span("db-svc", name="query", env="prod", trace=trace, parent=api, status_code=2 if trace == 1 else 0)
+ # A trace in another environment must not add an edge to the prod map.
+ root = w.span("eu-web", name="GET /", env="staging", trace=10)
+ w.span("eu-api", name="GET /", env="staging", trace=10, parent=root)
+ # A prod trace that calls into staging is sampled for prod, but its staging spans add no prod edges.
+ prod_root = w.span("web", name="GET /sync", env="prod", trace=20)
+ staging_child = w.span("eu-sync", name="POST /sync", env="staging", trace=20, parent=prod_root)
+ w.span("eu-store", name="write", env="staging", trace=20, parent=staging_child)
+ w.insert()
+
+ def _get(self, **params) -> dict:
+ query = {"date_from": DATE_FROM, "date_to": DATE_TO, "environment": "prod", **params}
+ with patch(FLAG_PATCH, return_value=True):
+ response = self.client.get(URL.format(self.team.id), query)
+ self.assertEqual(response.status_code, 200, response.content)
+ return response.json()
+
+ def test_edges_cross_services_only_with_call_and_error_counts(self) -> None:
+ data = self._get()
+ edges = {(e["caller"], e["callee"]): e for e in data["edges"]}
+ self.assertEqual(set(edges), {("web", "api"), ("api", "db-svc")})
+ self.assertEqual(edges[("web", "api")]["calls"], 3)
+ self.assertEqual(edges[("web", "api")]["error_count"], 0)
+ self.assertEqual(edges[("api", "db-svc")]["calls"], 3)
+ self.assertEqual(edges[("api", "db-svc")]["error_count"], 1)
+ self.assertGreaterEqual(edges[("web", "api")]["p95_ms"], 40)
+ self.assertEqual(data["trace_count"], 4)
+
+ def test_environment_filter(self) -> None:
+ data = self._get(environment="staging")
+ # The cross-environment trace adds its staging-only edge here, and not the prod -> staging call.
+ self.assertEqual(
+ sorted((e["caller"], e["callee"]) for e in data["edges"]), [("eu-sync", "eu-store"), ("eu-web", "eu-api")]
+ )
+ self.assertEqual(data["trace_count"], 2)
+
+ def test_trace_sample_is_capped(self) -> None:
+ with patch("products.apm.backend.logic.health.sources.MAP_TRACE_LIMIT", 1):
+ data = self._get()
+ self.assertEqual(data["trace_count"], 1)
+ self.assertEqual({e["calls"] for e in data["edges"]}, {1})
+
+ def test_span_input_to_the_join_is_capped(self) -> None:
+ # One span has no parent to join to, so a one-span budget leaves no edges over the same trace sample.
+ with patch("products.apm.backend.logic.health.sources.MAP_SPAN_LIMIT", 1):
+ data = self._get()
+ self.assertEqual(data["edges"], [])
+ self.assertEqual(data["trace_count"], 4)
+
+ def test_403_when_the_flag_is_off(self) -> None:
+ with patch(FLAG_PATCH, return_value=False):
+ response = self.client.get(URL.format(self.team.id))
+ self.assertEqual(response.status_code, 403)
+
+ def test_other_team_sees_nothing(self) -> None:
+ other = self.create_team_with_organization(organization=self.organization)
+ with patch(FLAG_PATCH, return_value=True):
+ response = self.client.get(
+ URL.format(other.id), {"date_from": DATE_FROM, "date_to": DATE_TO, "environment": "prod"}
+ )
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(response.json()["edges"], [])
+
+ def test_queries_are_tagged_for_the_request_path(self) -> None:
+ with (
+ patch(FLAG_PATCH, return_value=True),
+ patch("products.apm.backend.presentation.views.tag_queries") as tag,
+ ):
+ self.client.get(URL.format(self.team.id))
+ tag.assert_called_once()
+
+
+class TestServiceMapOpenApiSchema(SimpleTestCase):
+ def test_list_response_schema_is_a_single_object_not_an_array(self) -> None:
+ schema = SchemaGenerator().get_schema(request=None, public=True)
+ operation = schema["paths"]["/api/projects/{project_id}/apm/service_map/"]["get"]
+ response_schema = operation["responses"]["200"]["content"]["application/json"]["schema"]
+ self.assertNotEqual(response_schema.get("type"), "array")
diff --git a/products/apm/frontend/ApplicationObservabilityScene.tsx b/products/apm/frontend/ApplicationObservabilityScene.tsx
index 99283be0a707..abcaa1c4a745 100644
--- a/products/apm/frontend/ApplicationObservabilityScene.tsx
+++ b/products/apm/frontend/ApplicationObservabilityScene.tsx
@@ -14,6 +14,7 @@ import {
applicationObservabilityLogic,
} from './applicationObservabilityLogic'
import { EndpointsTab } from './EndpointsTab'
+import { ServiceMapTab } from './ServiceMapTab'
import { ServicesTab } from './ServicesTab'
export const scene: SceneExport = {
@@ -61,6 +62,7 @@ export function ApplicationObservabilityScene(): JSX.Element {
tabs={[
{ key: 'services', label: 'Services', content: <ServicesTab /> },
{ key: 'endpoints', label: 'Endpoints', content: <EndpointsTab /> },
+ { key: 'map', label: 'Map', content: <ServiceMapTab /> },
]}
data-attr="apm-tabs"
/>
diff --git a/products/apm/frontend/ServiceMapDetails.tsx b/products/apm/frontend/ServiceMapDetails.tsx
new file mode 100644
index 000000000000..3ffb2b5288bf
--- /dev/null
+++ b/products/apm/frontend/ServiceMapDetails.tsx
@@ -0,0 +1,96 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, Link } from '@posthog/lemon-ui'
+
+import { applicationObservabilityLogic } from './applicationObservabilityLogic'
+import type { ServiceEdgeApi } from './generated/api.schemas'
+import { formatMs, formatPercent, formatRate } from './healthDisplay'
+import { HealthStatusTag } from './HealthStatusTag'
+import { TelemetryLinks } from './TelemetryLinks'
+
+function CallList({
+ title,
+ edges,
+ peer,
+}: {
+ title: string
+ edges: ServiceEdgeApi[]
+ peer: 'caller' | 'callee'
+}): JSX.Element | null {
+ if (edges.length === 0) {
+ return null
+ }
+ return (
+ <div className="flex flex-col gap-1">
+ <span className="text-xs font-semibold text-secondary">{title}</span>
+ {edges.map((edge) => (
+ <div key={`${edge.caller}->${edge.callee}`} className="flex justify-between gap-2 text-xs">
+ <span className="truncate">{edge[peer]}</span>
+ <span className="font-mono text-secondary whitespace-nowrap">
+ {edge.calls} calls · {formatPercent(edge.calls ? edge.error_count / edge.calls : 0)}
+ </span>
+ </div>
+ ))}
+ </div>
+ )
+}
+
+export function ServiceMapDetails(): JSX.Element | null {
+ const { selectedMapServiceName, selectedMapService, serviceMap, timeRange } =
+ useValues(applicationObservabilityLogic)
+ const { setSelectedMapService, showServiceEndpoints } = useActions(applicationObservabilityLogic)
+
+ if (!selectedMapServiceName) {
+ return null
+ }
+ const edges = serviceMap?.edges ?? []
+ const health = selectedMapService?.health
+
+ return (
+ <div
+ className="flex max-h-[520px] w-72 flex-col gap-3 overflow-y-auto rounded border bg-surface-primary p-3 shadow"
+ data-attr="apm-map-details"
+ >
+ <div className="flex items-center justify-between gap-2">
+ <span className="truncate font-semibold">{selectedMapServiceName}</span>
+ <LemonButton size="xsmall" onClick={() => setSelectedMapService(null)}>
+ Close
+ </LemonButton>
+ </div>
+ {selectedMapService && health ? (
+ <div className="grid grid-cols-2 gap-1 text-xs">
+ <span className="text-secondary">Health</span>
+ <span>
+ <HealthStatusTag status={selectedMapService.status} />
+ </span>
+ <span className="text-secondary">Requests</span>
+ <span className="font-mono">{formatRate(health.request_rate)}</span>
+ <span className="text-secondary">Errors</span>
+ <span className="font-mono">{formatPercent(health.error_rate)}</span>
+ <span className="text-secondary">p95</span>
+ <span className="font-mono">{formatMs(health.p95_ms)}</span>
+ </div>
+ ) : (
+ <span className="text-xs text-secondary">
+ No health data for this service in this environment and time range.
+ </span>
+ )}
+ <CallList
+ title="Called by"
+ edges={edges.filter((edge) => edge.callee === selectedMapServiceName)}
+ peer="caller"
+ />
+ <CallList
+ title="Calls"
+ edges={edges.filter((edge) => edge.caller === selectedMapServiceName)}
+ peer="callee"
+ />
+ <div className="flex gap-2 text-xs">
+ <Link onClick={() => showServiceEndpoints(selectedMapServiceName)} data-attr="apm-map-endpoints">
+ Endpoints
+ </Link>
+ <TelemetryLinks serviceName={selectedMapServiceName} timeRange={timeRange} />
+ </div>
+ </div>
+ )
+}
diff --git a/products/apm/frontend/ServiceMapNode.tsx b/products/apm/frontend/ServiceMapNode.tsx
new file mode 100644
index 000000000000..bb6a82e9ced0
--- /dev/null
+++ b/products/apm/frontend/ServiceMapNode.tsx
@@ -0,0 +1,42 @@
+import { Handle, NodeProps, Position } from '@xyflow/react'
+import clsx from 'clsx'
+import { useActions, useValues } from 'kea'
+
+import { applicationObservabilityLogic } from './applicationObservabilityLogic'
+import { formatPercent, formatRate } from './healthDisplay'
+import type { ServiceMapNode as ServiceMapNodeType } from './serviceMap'
+
+export function ServiceMapNode({ data }: NodeProps<ServiceMapNodeType>): JSX.Element {
+ const { selectedMapServiceName, servicesHealthLoading } = useValues(applicationObservabilityLogic)
+ const { setSelectedMapService } = useActions(applicationObservabilityLogic)
+ const status = data.service?.status
+ const failing = status === 'serious' || status === 'critical'
+
+ return (
+ <>
+ <Handle type="target" position={Position.Left} isConnectable={false} className="opacity-0" />
+ <button
+ type="button"
+ onClick={() => setSelectedMapService(data.name)}
+ aria-pressed={selectedMapServiceName === data.name}
+ className={clsx(
+ 'flex h-16 w-[200px] cursor-pointer flex-col justify-center gap-0.5 rounded border bg-surface-primary px-3 text-left',
+ !data.service && 'border-dashed',
+ failing ? 'border-danger' : status === 'warning' ? 'border-warning' : 'border-primary',
+ selectedMapServiceName === data.name && 'ring-2 ring-accent'
+ )}
+ data-attr="apm-map-node"
+ >
+ <span className="truncate font-semibold">{data.name}</span>
+ <span className="font-mono text-xs text-secondary">
+ {data.service
+ ? `${formatRate(data.service.health.request_rate)} · ${formatPercent(data.service.health.error_rate)} errors`
+ : servicesHealthLoading
+ ? 'Loading health'
+ : 'No health data in this environment'}
+ </span>
+ </button>
+ <Handle type="source" position={Position.Right} isConnectable={false} className="opacity-0" />
+ </>
+ )
+}
diff --git a/products/apm/frontend/ServiceMapTab.tsx b/products/apm/frontend/ServiceMapTab.tsx
new file mode 100644
index 000000000000..184a6d9d1b6c
--- /dev/null
+++ b/products/apm/frontend/ServiceMapTab.tsx
@@ -0,0 +1,116 @@
+import '@xyflow/react/dist/style.css'
+
+import { Background, BackgroundVariant, Controls, Panel, ReactFlow, ReactFlowProvider } from '@xyflow/react'
+import { useActions, useValues } from 'kea'
+import { useMemo } from 'react'
+
+import { LemonBanner, Spinner } from '@posthog/lemon-ui'
+
+import { themeLogic } from '~/layout/navigation-3000/themeLogic'
+
+import type { ServiceMapWarning } from './applicationObservabilityLogic'
+import { applicationObservabilityLogic } from './applicationObservabilityLogic'
+import { ServiceMapDetails } from './ServiceMapDetails'
+import { ServiceMapNode } from './ServiceMapNode'
+
+const NODE_TYPES = { service: ServiceMapNode }
+// Calls into a callee that fails this often draw in the danger color, the same threshold as a failing status.
+const FAILING_EDGE_ERROR_RATE = 0.05
+
+function warningMessage(warning: Exclude<ServiceMapWarning, null>, hasMap: boolean): string {
+ switch (warning) {
+ case 'map':
+ return hasMap
+ ? "Couldn't refresh the map. Showing the last successful results."
+ : "Couldn't load the map. Check your connection and try again."
+ case 'layout':
+ return "Couldn't draw the map. Try again."
+ case 'health':
+ return "Couldn't load service health, so the map shows calls without health. Try again."
+ }
+}
+
+export function ServiceMapTab(): JSX.Element {
+ const { serviceMap, serviceMapLayout, serviceMapLoading, serviceMapWarning } =
+ useValues(applicationObservabilityLogic)
+ const { setSelectedMapService, layoutServiceMap, loadServiceMap, loadServicesHealth } =
+ useActions(applicationObservabilityLogic)
+ const { isDarkModeOn } = useValues(themeLogic)
+
+ const edges = useMemo(
+ () =>
+ (serviceMapLayout?.edges ?? []).map((edge) => ({
+ ...edge,
+ style: {
+ strokeWidth: edge.data?.width ?? 1,
+ stroke: (edge.data?.errorRate ?? 0) >= FAILING_EDGE_ERROR_RATE ? 'var(--danger)' : undefined,
+ },
+ })),
+ [serviceMapLayout]
+ )
+ const nodes = serviceMapLayout?.nodes ?? []
+
+ return (
+ <div className="flex flex-col gap-2">
+ {serviceMapWarning && (
+ <LemonBanner
+ type={serviceMapWarning === 'health' ? 'warning' : 'error'}
+ action={{
+ children: 'Try again',
+ onClick: () =>
+ serviceMapWarning === 'map'
+ ? loadServiceMap()
+ : serviceMapWarning === 'layout'
+ ? layoutServiceMap()
+ : loadServicesHealth(),
+ }}
+ >
+ {warningMessage(serviceMapWarning, !!serviceMapLayout?.nodes.length)}
+ </LemonBanner>
+ )}
+ {serviceMap && (
+ <span className="text-xs text-secondary">
+ Built from {serviceMap.trace_count.toLocaleString()} sampled traces. Line width shows the share of
+ calls. Select a service to see its health and calls.
+ </span>
+ )}
+ <div className="relative h-[560px] rounded border bg-surface-primary" data-attr="apm-service-map">
+ {nodes.length === 0 ? (
+ <div className="flex h-full items-center justify-center p-4 text-center text-secondary">
+ {serviceMapLoading || !serviceMap ? (
+ <Spinner />
+ ) : (
+ 'No services in this environment and time range. Send traces to see the map.'
+ )}
+ </div>
+ ) : (
+ <ReactFlowProvider>
+ <ReactFlow
+ colorMode={isDarkModeOn ? 'dark' : 'light'}
+ nodes={nodes}
+ edges={edges}
+ nodeTypes={NODE_TYPES}
+ onPaneClick={() => setSelectedMapService(null)}
+ nodesDraggable={false}
+ nodesConnectable={false}
+ // Each node renders its own button, which is the focus and keyboard target.
+ // Selectable elements keep pointer events on the node so the button gets clicks.
+ elementsSelectable
+ nodesFocusable={false}
+ fitView
+ minZoom={0.1}
+ maxZoom={2}
+ proOptions={{ hideAttribution: true }}
+ >
+ <Background variant={BackgroundVariant.Dots} gap={20} size={1} />
+ <Controls showInteractive={false} position="bottom-left" />
+ <Panel position="top-right">
+ <ServiceMapDetails />
+ </Panel>
+ </ReactFlow>
+ </ReactFlowProvider>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/products/apm/frontend/applicationObservabilityLogic.test.ts b/products/apm/frontend/applicationObservabilityLogic.test.ts
index 9f858d7e4ad0..ead9880f5586 100644
--- a/products/apm/frontend/applicationObservabilityLogic.test.ts
+++ b/products/apm/frontend/applicationObservabilityLogic.test.ts
@@ -11,7 +11,11 @@ import {
applicationObservabilityLogic,
drillDownParams,
} from './applicationObservabilityLogic'
-import type { EndpointsHealthResponseApi, ServicesHealthResponseApi } from './generated/api.schemas'
+import type {
+ EndpointsHealthResponseApi,
+ ServiceMapResponseApi,
+ ServicesHealthResponseApi,
+} from './generated/api.schemas'
const row = (service_name: string, status: 'good' | 'warning' | 'serious' | 'critical'): any => ({
service_name,
@@ -45,14 +49,24 @@ const ENDPOINTS_RESPONSE: EndpointsHealthResponseApi = {
date_to: '2026-06-02T08:00:00Z',
}
+const MAP_RESPONSE: ServiceMapResponseApi = {
+ edges: [{ caller: 'web', callee: 'queue', calls: 10, error_count: 1, p95_ms: 5 }],
+ trace_count: 10,
+ environment: 'prod',
+ date_from: '2026-06-02T07:00:00Z',
+ date_to: '2026-06-02T08:00:00Z',
+}
+
describe('applicationObservabilityLogic', () => {
let logic: ReturnType<typeof applicationObservabilityLogic.build>
let requests: string[]
let endpointRequests: string[]
+ let mapRequests: string[]
beforeEach(async () => {
requests = []
endpointRequests = []
+ mapRequests = []
useMocks({
get: {
'/api/projects/:team_id/apm/services/': ({ request }) => {
@@ -63,6 +77,10 @@ describe('applicationObservabilityLogic', () => {
endpointRequests.push(new URL(request.url).search)
return [200, ENDPOINTS_RESPONSE]
},
+ '/api/projects/:team_id/apm/service_map/': ({ request }) => {
+ mapRequests.push(new URL(request.url).search)
+ return [200, MAP_RESPONSE]
+ },
},
})
initKeaTests()
@@ -152,6 +170,7 @@ describe('applicationObservabilityLogic', () => {
await expectLogic(logic).toDispatchActions(['loadServicesHealthSuccess'])
expect(logic.values.tab).toBe('services')
expect(endpointRequests).toHaveLength(0)
+ expect(mapRequests).toHaveLength(0)
})
it('ignores an unknown tab in the URL', async () => {
@@ -197,5 +216,56 @@ describe('applicationObservabilityLogic', () => {
// The service filter only narrows endpoints, so service health must not reload with it.
expect(requests.length).toBe(servicesRequestsBefore)
})
+
+ it('loads the map for the environment and lays out every service node', async () => {
+ router.actions.push(APPLICATION_OBSERVABILITY_PATH, { tab: 'map', environment: 'staging' })
+ await expectLogic(logic).toDispatchActions(['loadServiceMapSuccess', 'layoutServiceMapSuccess'])
+ await expectLogic(logic).toFinishAllListeners()
+ expect(mapRequests).toHaveLength(1)
+ expect(mapRequests[0]).toContain('environment=staging')
+ expect(logic.values.serviceMap?.trace_count).toBe(10)
+ const nodes = logic.values.serviceMapLayout?.nodes ?? []
+ expect(nodes.map((node) => node.id).sort()).toEqual(['api', 'queue', 'web'])
+ for (const node of nodes) {
+ expect(Number.isFinite(node.position.x)).toBe(true)
+ expect(Number.isFinite(node.position.y)).toBe(true)
+ }
+ })
+
+ it('drops health from map nodes when the health refresh for a new environment fails', async () => {
+ router.actions.push(APPLICATION_OBSERVABILITY_PATH, { tab: 'map' })
+ await expectLogic(logic).toDispatchActions(['layoutServiceMapSuccess'])
+ await expectLogic(logic).toFinishAllListeners()
+ const nodeHealth = (): Record<string, string | null> =>
+ Object.fromEntries(
+ (logic.values.serviceMapLayout?.nodes ?? []).map((node) => [
+ node.id,
+ node.data.service?.status ?? null,
+ ])
+ )
+ expect(nodeHealth().queue).toBe('serious')
+
+ useMocks({
+ get: {
+ '/api/projects/:team_id/apm/services/': () => [500, { detail: 'boom' }],
+ '/api/projects/:team_id/apm/service_map/': () => [200, MAP_RESPONSE],
+ },
+ })
+ logic.actions.setEnvironment('staging')
+ await expectLogic(logic).toDispatchActions(['loadServicesHealthFailure'])
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(nodeHealth()).toEqual({ queue: null, web: null })
+ expect(logic.values.serviceMapWarning).toBe('health')
+ })
+
+ it('reports a layout failure instead of an empty map', async () => {
+ router.actions.push(APPLICATION_OBSERVABILITY_PATH, { tab: 'map' })
+ await expectLogic(logic).toDispatchActions(['layoutServiceMapSuccess'])
+ expect(logic.values.serviceMapWarning).toBeNull()
+
+ logic.actions.layoutServiceMapFailure('elk failed')
+ expect(logic.values.serviceMapWarning).toBe('layout')
+ })
})
})
diff --git a/products/apm/frontend/applicationObservabilityLogic.ts b/products/apm/frontend/applicationObservabilityLogic.ts
index 2d02529871f1..cc56b118ace2 100644
--- a/products/apm/frontend/applicationObservabilityLogic.ts
+++ b/products/apm/frontend/applicationObservabilityLogic.ts
@@ -4,21 +4,25 @@ import { actionToUrl, urlToAction } from 'kea-router'
import { teamLogic } from 'scenes/teamLogic'
-import { apmEndpointsList, apmServicesList } from './generated/api'
+import { apmEndpointsList, apmServiceMapList, apmServicesList } from './generated/api'
import type {
EndpointHealthApi,
EndpointsHealthResponseApi,
ServiceHealthApi,
+ ServiceMapResponseApi,
ServicesHealthResponseApi,
} from './generated/api.schemas'
+import { ServiceGraph, buildServiceGraph, layoutServiceGraph } from './serviceMap'
export const APPLICATION_OBSERVABILITY_PATH = '/application-observability'
export type TimeRange = '-1h' | '-6h' | '-24h' | '-7d'
-export type ApplicationObservabilityTab = 'services' | 'endpoints'
+export type ApplicationObservabilityTab = 'services' | 'endpoints' | 'map'
-export const TABS: ApplicationObservabilityTab[] = ['services', 'endpoints']
+export type ServiceMapWarning = 'map' | 'layout' | 'health' | null
+
+export const TABS: ApplicationObservabilityTab[] = ['services', 'endpoints', 'map']
export const TIME_RANGE_LABELS: Record<TimeRange, string> = {
'-1h': 'Last hour',
@@ -67,6 +71,15 @@ export interface applicationObservabilityLogicValues {
environments: string[]
hasLoadError: boolean
resolvedEnvironment: string
+ selectedMapService: ServiceHealthApi | null
+ selectedMapServiceName: string | null
+ serviceMap: ServiceMapResponseApi | null
+ serviceMapLayout: ServiceGraph | null
+ serviceMapLayoutError: boolean
+ serviceMapLayoutLoading: boolean
+ serviceMapLoadError: boolean
+ serviceMapLoading: boolean
+ serviceMapWarning: ServiceMapWarning
services: ServiceHealthApi[]
servicesHealth: ServicesHealthResponseApi | null
servicesHealthLoading: boolean
@@ -76,6 +89,21 @@ export interface applicationObservabilityLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface applicationObservabilityLogicActions {
+ layoutServiceMap: (_: void) => void
+ layoutServiceMapFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ layoutServiceMapSuccess: (
+ serviceMapLayout: ServiceGraph,
+ payload?: void
+ ) => {
+ serviceMapLayout: ServiceGraph
+ payload?: void
+ }
loadEndpointsHealth: (_: void) => void
loadEndpointsHealthFailure: (
error: string,
@@ -91,6 +119,21 @@ export interface applicationObservabilityLogicActions {
endpointsHealth: EndpointsHealthResponseApi
payload?: void
}
+ loadServiceMap: (_: void) => void
+ loadServiceMapFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadServiceMapSuccess: (
+ serviceMap: ServiceMapResponseApi,
+ payload?: void
+ ) => {
+ serviceMap: ServiceMapResponseApi
+ payload?: void
+ }
loadServicesHealth: (_: void) => void
loadServicesHealthFailure: (
error: string,
@@ -115,6 +158,9 @@ export interface applicationObservabilityLogicActions {
setEnvironment: (environment: string | null) => {
environment: string | null
}
+ setSelectedMapService: (service: string | null) => {
+ service: string | null
+ }
setTab: (tab: ApplicationObservabilityTab) => {
tab: ApplicationObservabilityTab
}
@@ -133,6 +179,15 @@ export interface applicationObservabilityLogicMeta {
environments: (servicesHealth: ServicesHealthResponseApi | null) => string[]
resolvedEnvironment: (environment: string | null, servicesHealth: ServicesHealthResponseApi | null) => string
endpoints: (endpointsHealth: EndpointsHealthResponseApi | null) => EndpointHealthApi[]
+ selectedMapService: (
+ serviceMapLayout: ServiceGraph | null,
+ selectedMapServiceName: string | null
+ ) => ServiceHealthApi | null
+ serviceMapWarning: (
+ serviceMapLoadError: boolean,
+ serviceMapLayoutError: boolean,
+ hasLoadError: boolean
+ ) => ServiceMapWarning
attentionCount: (services: ServiceHealthApi[]) => number
}
}
@@ -154,6 +209,7 @@ export const applicationObservabilityLogic = kea<applicationObservabilityLogicTy
setTab: (tab: ApplicationObservabilityTab) => ({ tab }),
setEndpointsService: (service: string | null) => ({ service }),
showServiceEndpoints: (service: string) => ({ service }),
+ setSelectedMapService: (service: string | null) => ({ service }),
// Internal: coalesces the picker actions and the initial URL sync into a single reload.
// `includeServices` is false for changes that only affect the active tab's own data.
requestReload: (includeServices: boolean = true) => ({ includeServices }),
@@ -179,6 +235,24 @@ export const applicationObservabilityLogic = kea<applicationObservabilityLogicTy
loadServicesHealthFailure: () => true,
},
],
+ selectedMapServiceName: [
+ null as string | null,
+ { setSelectedMapService: (_, { service }) => service, setEnvironment: () => null },
+ ],
+ serviceMapLoadError: [
+ false,
+ {
+ loadServiceMapSuccess: () => false,
+ loadServiceMapFailure: () => true,
+ },
+ ],
+ serviceMapLayoutError: [
+ false,
+ {
+ layoutServiceMapSuccess: () => false,
+ layoutServiceMapFailure: () => true,
+ },
+ ],
endpointsLoadError: [
false,
{
@@ -206,6 +280,42 @@ export const applicationObservabilityLogic = kea<applicationObservabilityLogicTy
},
},
],
+ serviceMap: [
+ null as ServiceMapResponseApi | null,
+ {
+ loadServiceMap: async (_: void, breakpoint): Promise<ServiceMapResponseApi> => {
+ const dateTo = new Date()
+ const dateFrom = new Date(dateTo.getTime() - TIME_RANGE_MS[values.timeRange])
+ const response = await apmServiceMapList(String(values.currentTeamId), {
+ date_from: dateFrom.toISOString(),
+ date_to: dateTo.toISOString(),
+ ...(values.environment ? { environment: values.environment } : {}),
+ })
+ breakpoint()
+ return response
+ },
+ },
+ ],
+ // ELK runs async, so the layout is a loader of its own over the services and the edges.
+ serviceMapLayout: [
+ null as ServiceGraph | null,
+ {
+ layoutServiceMap: async (_: void, breakpoint): Promise<ServiceGraph> => {
+ // Health joins the map by service name only, so attach it only when it is current
+ // and for the same environment. A failed or pending refresh would otherwise paint
+ // the previous environment's status onto the new map.
+ const healthMatchesMap =
+ !values.servicesHealthLoading &&
+ !values.hasLoadError &&
+ values.servicesHealth?.environment === values.serviceMap?.environment
+ const graph = await layoutServiceGraph(
+ buildServiceGraph(healthMatchesMap ? values.services : [], values.serviceMap?.edges ?? [])
+ )
+ breakpoint()
+ return graph
+ },
+ },
+ ],
servicesHealth: [
null as ServicesHealthResponseApi | null,
{
@@ -244,6 +354,16 @@ export const applicationObservabilityLogic = kea<applicationObservabilityLogicTy
(s) => [s.endpointsHealth],
(endpointsHealth: EndpointsHealthResponseApi | null): EndpointHealthApi[] => endpointsHealth?.results ?? [],
],
+ selectedMapService: [
+ (s) => [s.serviceMapLayout, s.selectedMapServiceName],
+ (serviceMapLayout: ServiceGraph | null, selectedMapServiceName: string | null): ServiceHealthApi | null =>
+ serviceMapLayout?.nodes.find((node) => node.id === selectedMapServiceName)?.data.service ?? null,
+ ],
+ serviceMapWarning: [
+ (s) => [s.serviceMapLoadError, s.serviceMapLayoutError, s.hasLoadError],
+ (serviceMapLoadError: boolean, serviceMapLayoutError: boolean, hasLoadError: boolean): ServiceMapWarning =>
+ serviceMapLoadError ? 'map' : serviceMapLayoutError ? 'layout' : hasLoadError ? 'health' : null,
+ ],
attentionCount: [
(s) => [s.services],
(services: ServiceHealthApi[]): number =>
@@ -301,6 +421,12 @@ export const applicationObservabilityLogic = kea<applicationObservabilityLogicTy
setTab: () => actions.requestReload(false),
setEndpointsService: () => actions.requestReload(false),
showServiceEndpoints: () => actions.requestReload(false),
+ loadServiceMapSuccess: () => actions.layoutServiceMap(),
+ loadServicesHealthSuccess: () => {
+ if (values.tab === 'map' && values.serviceMap) {
+ actions.layoutServiceMap()
+ }
+ },
// Debounced with a replaceable timer: several `requestReload` calls in the same tick
// (e.g. the initial URL sync setting both the environment and the range at once, or that
// sync landing in the same tick as the mount-time load) collapse into a single request.
@@ -315,6 +441,9 @@ export const applicationObservabilityLogic = kea<applicationObservabilityLogicTy
if (values.tab === 'endpoints') {
actions.loadEndpointsHealth()
}
+ if (values.tab === 'map') {
+ actions.loadServiceMap()
+ }
}, 0)
return () => clearTimeout(timerId)
}, 'reloadTimer')
diff --git a/products/apm/frontend/generated/api.schemas.ts b/products/apm/frontend/generated/api.schemas.ts
index b51f88c9a697..f2e9f2d212bc 100644
--- a/products/apm/frontend/generated/api.schemas.ts
+++ b/products/apm/frontend/generated/api.schemas.ts
@@ -78,6 +78,35 @@ export interface EndpointsHealthResponseApi {
date_to: string
}
+export interface ServiceEdgeApi {
+ /** The calling service. */
+ caller: string
+ /** The called service. */
+ callee: string
+ /** Calls from the caller into the callee in the sampled traces. */
+ calls: number
+ /** Calls with an error status on the callee span. */
+ error_count: number
+ /**
+ * 95th percentile duration of the callee span, in ms.
+ * @nullable
+ */
+ p95_ms: number | null
+}
+
+export interface ServiceMapResponseApi {
+ /** One edge per calling and called service, most calls first. */
+ edges: ServiceEdgeApi[]
+ /** Traces sampled to build the map. */
+ trace_count: number
+ /** The environment the map was built for. */
+ environment: string
+ /** Start of the window used. */
+ date_from: string
+ /** End of the window used. */
+ date_to: string
+}
+
export interface ServiceHealthApi {
/** The service.name resource attribute. */
service_name: string
@@ -132,6 +161,23 @@ export type ApmEndpointsListParams = {
service?: string
}
+export type ApmServiceMapListParams = {
+ /**
+ * Start of the window, ISO 8601. Defaults to one hour before date_to.
+ */
+ date_from?: string
+ /**
+ * End of the window, ISO 8601. Defaults to now.
+ */
+ date_to?: string
+ /**
+ * Environment to list, as resolved from span resource attributes. Defaults to 'default'.
+ * @minLength 1
+ * @maxLength 200
+ */
+ environment?: string
+}
+
export type ApmServicesListParams = {
/**
* Start of the window, ISO 8601. Defaults to one hour before date_to.
diff --git a/products/apm/frontend/generated/api.ts b/products/apm/frontend/generated/api.ts
index 1598a2e0a5c3..544456cc34de 100644
--- a/products/apm/frontend/generated/api.ts
+++ b/products/apm/frontend/generated/api.ts
@@ -10,8 +10,10 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
*/
import type {
ApmEndpointsListParams,
+ ApmServiceMapListParams,
ApmServicesListParams,
EndpointsHealthResponseApi,
+ ServiceMapResponseApi,
ServicesHealthResponseApi,
} from './api.schemas'
@@ -45,6 +47,36 @@ export const apmEndpointsList = async (
})
}
+export const getApmServiceMapListUrl = (projectId: string, params?: ApmServiceMapListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/apm/service_map/?${stringifiedParams}`
+ : `/api/projects/${projectId}/apm/service_map/`
+}
+
+/**
+ * Service-to-service call edges in an environment and window. Same gate and window as services.
+ */
+export const apmServiceMapList = async (
+ projectId: string,
+ params?: ApmServiceMapListParams,
+ options?: RequestInit
+): Promise<ServiceMapResponseApi> => {
+ return apiMutator<ServiceMapResponseApi>(getApmServiceMapListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getApmServicesListUrl = (projectId: string, params?: ApmServicesListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/apm/frontend/generated/api.zod.schemas.ts b/products/apm/frontend/generated/api.zod.schemas.ts
index 22be003ea0d6..223ae82309cc 100644
--- a/products/apm/frontend/generated/api.zod.schemas.ts
+++ b/products/apm/frontend/generated/api.zod.schemas.ts
@@ -87,6 +87,38 @@ export const EndpointsHealthResponseApi = zod.object({
export type EndpointsHealthResponseApi = zod.input<typeof EndpointsHealthResponseApi>
export type EndpointsHealthResponseApiOutput = zod.output<typeof EndpointsHealthResponseApi>
+export const ServiceEdgeApi = zod.object({
+ caller: zod.string().describe('The calling service.'),
+ callee: zod.string().describe('The called service.'),
+ calls: zod.number().describe('Calls from the caller into the callee in the sampled traces.'),
+ error_count: zod.number().describe('Calls with an error status on the callee span.'),
+ p95_ms: zod.number().nullable().describe('95th percentile duration of the callee span, in ms.'),
+})
+
+export type ServiceEdgeApi = zod.input<typeof ServiceEdgeApi>
+export type ServiceEdgeApiOutput = zod.output<typeof ServiceEdgeApi>
+
+export const ServiceMapResponseApi = zod.object({
+ edges: zod
+ .array(
+ zod.object({
+ caller: zod.string().describe('The calling service.'),
+ callee: zod.string().describe('The called service.'),
+ calls: zod.number().describe('Calls from the caller into the callee in the sampled traces.'),
+ error_count: zod.number().describe('Calls with an error status on the callee span.'),
+ p95_ms: zod.number().nullable().describe('95th percentile duration of the callee span, in ms.'),
+ })
+ )
+ .describe('One edge per calling and called service, most calls first.'),
+ trace_count: zod.number().describe('Traces sampled to build the map.'),
+ environment: zod.string().describe('The environment the map was built for.'),
+ date_from: zod.iso.datetime({ offset: true }).describe('Start of the window used.'),
+ date_to: zod.iso.datetime({ offset: true }).describe('End of the window used.'),
+})
+
+export type ServiceMapResponseApi = zod.input<typeof ServiceMapResponseApi>
+export type ServiceMapResponseApiOutput = zod.output<typeof ServiceMapResponseApi>
+
export const ServiceHealthApi = zod.object({
service_name: zod.string().describe('The service.name resource attribute.'),
environment: zod.string().describe('The environment the row was computed for.'),
diff --git a/products/apm/frontend/serviceMap.test.ts b/products/apm/frontend/serviceMap.test.ts
new file mode 100644
index 000000000000..6191f8994e20
--- /dev/null
+++ b/products/apm/frontend/serviceMap.test.ts
@@ -0,0 +1,45 @@
+import { buildServiceGraph } from './serviceMap'
+
+const service = (service_name: string, status: 'good' | 'serious'): any => ({
+ service_name,
+ environment: 'prod',
+ status,
+ health: { request_rate: 1, error_rate: status === 'good' ? 0 : 0.1, p95_ms: 10, span_count: 10, error_count: 0 },
+ sparkline: [],
+})
+
+const edge = (caller: string, callee: string, calls: number, error_count = 0): any => ({
+ caller,
+ callee,
+ calls,
+ error_count,
+ p95_ms: 5,
+})
+
+describe('buildServiceGraph', () => {
+ it('makes one node per service seen in the health rows or the edges, with health when known', () => {
+ const graph = buildServiceGraph(
+ [service('web', 'good'), service('api', 'serious'), service('lonely', 'good')],
+ [edge('web', 'api', 10), edge('api', 'db', 4)]
+ )
+ expect(graph.nodes.map((n) => n.id).sort()).toEqual(['api', 'db', 'lonely', 'web'])
+ const byId = Object.fromEntries(graph.nodes.map((n) => [n.id, n.data]))
+ expect(byId.api.service?.status).toBe('serious')
+ // A callee with no health row in this environment still gets a node, with no health.
+ expect(byId.db.service).toBeNull()
+ })
+
+ it('scales edge width by calls and carries the error rate', () => {
+ const graph = buildServiceGraph([], [edge('web', 'api', 10, 5), edge('api', 'db', 1)])
+ const byId = Object.fromEntries(graph.edges.map((e) => [e.id, e]))
+ expect(byId['web->api'].source).toBe('web')
+ expect(byId['web->api'].target).toBe('api')
+ expect(byId['web->api'].data?.errorRate).toBe(0.5)
+ expect(byId['web->api'].data!.width).toBeGreaterThan(byId['api->db'].data!.width)
+ expect(byId['api->db'].data!.width).toBeGreaterThanOrEqual(1)
+ })
+
+ it('returns an empty graph when there is nothing to draw', () => {
+ expect(buildServiceGraph([], [])).toEqual({ nodes: [], edges: [] })
+ })
+})
diff --git a/products/apm/frontend/serviceMap.ts b/products/apm/frontend/serviceMap.ts
new file mode 100644
index 000000000000..f30aceadc585
--- /dev/null
+++ b/products/apm/frontend/serviceMap.ts
@@ -0,0 +1,87 @@
+import type { Edge, Node } from '@xyflow/react'
+import type { ElkNode } from 'elkjs'
+
+import { getElk } from 'lib/elk'
+
+import type { ServiceEdgeApi, ServiceHealthApi } from './generated/api.schemas'
+
+export const SERVICE_NODE_WIDTH = 200
+export const SERVICE_NODE_HEIGHT = 64
+const MIN_EDGE_WIDTH = 1
+const MAX_EDGE_WIDTH = 6
+
+export type ServiceNodeData = {
+ name: string
+ service: ServiceHealthApi | null
+}
+
+export type ServiceEdgeData = {
+ calls: number
+ errorRate: number
+ p95Ms: number | null
+ width: number
+}
+
+export type ServiceMapNode = Node<ServiceNodeData, 'service'>
+export type ServiceMapEdge = Edge<ServiceEdgeData>
+
+export interface ServiceGraph {
+ nodes: ServiceMapNode[]
+ edges: ServiceMapEdge[]
+}
+
+export function buildServiceGraph(services: ServiceHealthApi[], edges: ServiceEdgeApi[]): ServiceGraph {
+ const health = new Map(services.map((row) => [row.service_name, row]))
+ const names = new Set(services.map((row) => row.service_name))
+ for (const edge of edges) {
+ names.add(edge.caller)
+ names.add(edge.callee)
+ }
+ const maxCalls = Math.max(1, ...edges.map((edge) => edge.calls))
+
+ return {
+ nodes: [...names].sort().map((name) => ({
+ id: name,
+ type: 'service',
+ position: { x: 0, y: 0 },
+ width: SERVICE_NODE_WIDTH,
+ height: SERVICE_NODE_HEIGHT,
+ data: { name, service: health.get(name) ?? null },
+ })),
+ edges: edges.map((edge) => ({
+ id: `${edge.caller}->${edge.callee}`,
+ source: edge.caller,
+ target: edge.callee,
+ data: {
+ calls: edge.calls,
+ errorRate: edge.calls > 0 ? edge.error_count / edge.calls : 0,
+ p95Ms: edge.p95_ms,
+ width: MIN_EDGE_WIDTH + ((MAX_EDGE_WIDTH - MIN_EDGE_WIDTH) * edge.calls) / maxCalls,
+ },
+ })),
+ }
+}
+
+export async function layoutServiceGraph(graph: ServiceGraph): Promise<ServiceGraph> {
+ if (graph.nodes.length === 0) {
+ return graph
+ }
+ const elk = await getElk()
+ const laidOut: ElkNode = await elk.layout({
+ id: 'root',
+ layoutOptions: {
+ 'elk.algorithm': 'layered',
+ 'elk.direction': 'RIGHT',
+ 'elk.layered.spacing.nodeNodeBetweenLayers': '80',
+ 'elk.spacing.nodeNode': '24',
+ 'elk.separateConnectedComponents': 'true',
+ },
+ children: graph.nodes.map((node) => ({ id: node.id, width: SERVICE_NODE_WIDTH, height: SERVICE_NODE_HEIGHT })),
+ edges: graph.edges.map((edge) => ({ id: edge.id, sources: [edge.source], targets: [edge.target] })),
+ })
+ const positions = new Map((laidOut.children ?? []).map((child) => [child.id, { x: child.x ?? 0, y: child.y ?? 0 }]))
+ return {
+ nodes: graph.nodes.map((node) => ({ ...node, position: positions.get(node.id) ?? node.position })),
+ edges: graph.edges,
+ }
+}
diff --git a/products/apm/package.json b/products/apm/package.json
index f4b1d38750a8..06ea81c03c73 100644
--- a/products/apm/package.json
+++ b/products/apm/package.json
@@ -14,6 +14,9 @@
"peerDependencies": {
"@posthog/icons": "catalog:",
"@types/react": "*",
+ "@xyflow/react": "*",
+ "clsx": "*",
+ "elkjs": "*",
"react": "*"
}
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a46413b052a1..5ca8a7eb45c5 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -109025,6 +109025,22 @@ export namespace Schemas {
policies?: ToolPolicyEntry[];
}
+ export interface ServiceEdge {
+ /** The calling service. */
+ caller: string;
+ /** The called service. */
+ callee: string;
+ /** Calls from the caller into the callee in the sampled traces. */
+ calls: number;
+ /** Calls with an error status on the callee span. */
+ error_count: number;
+ /**
+ * 95th percentile duration of the callee span, in ms.
+ * @nullable
+ */
+ p95_ms: number | null;
+ }
+
export interface ServiceHealth {
/** The service.name resource attribute. */
service_name: string;
@@ -109301,6 +109317,19 @@ export namespace Schemas {
notes: string[];
}
+ export interface ServiceMapResponse {
+ /** One edge per calling and called service, most calls first. */
+ edges: ServiceEdge[];
+ /** Traces sampled to build the map. */
+ trace_count: number;
+ /** The environment the map was built for. */
+ environment: string;
+ /** Start of the window used. */
+ date_from: string;
+ /** End of the window used. */
+ date_to: string;
+ }
+
export interface ServicesHealthResponse {
/** One row per service, worst status first. */
results: ServiceHealth[];
@@ -129182,6 +129211,23 @@ export namespace Schemas {
service?: string;
};
+ export type ApmServiceMapListParams = {
+ /**
+ * Start of the window, ISO 8601. Defaults to one hour before date_to.
+ */
+ date_from?: string;
+ /**
+ * End of the window, ISO 8601. Defaults to now.
+ */
+ date_to?: string;
+ /**
+ * Environment to list, as resolved from span resource attributes. Defaults to 'default'.
+ * @minLength 1
+ * @maxLength 200
+ */
+ environment?: string;
+ };
+
export type ApmServicesListParams = {
/**
* Start of the window, ISO 8601. Defaults to one hour before date_to.