# Gateway · OpenTelemetry integration (/docs/gateway/otel)



`@pleach/gateway` emits two kinds of OpenTelemetry signal:

* **Spans.** One `llm.invocation` span per routed call, from
  `GatewayClient.route()` and from a transport-served
  `GatewayRuntime.routeChatCompletion()`.
* **Counters.** The cost-event adapter records a cost counter and a
  token counter per `CostEvent`.

## Cost counters [#cost-counters]

The cost-event adapter at `@pleach/gateway/cost` emits two counters per
`CostEvent`:

```
pleach_gateway_cost_usd        # Counter, double, USD
pleach_gateway_tokens_total    # Counter, long,   {token}
```

`pleach_gateway_tokens_total` carries a `token.kind = "prompt" |
"completion"` dimension, so the breakdown isn't collapsed into one sum.

### Wiring [#wiring]

`routeChatCompletion`'s output lacks `tenantId`, `family`, `callClass`,
`byokActive`, and the full `routingDecision`. Merge those from the
request and your routing context, then build the event in
`computeCost`. The full mapper and an example are in
[Cost events](/docs/gateway/cost-events#costmiddleware-factory). Pass
`createOtelCostEmitter({ meter })` as the middleware's `emitter`.

### Attributes recorded on every measurement [#attributes-recorded-on-every-measurement]

| Attribute         | Source                           |
| ----------------- | -------------------------------- |
| `tenant.id`       | `event.tenantId`                 |
| `provider.family` | `event.family`                   |
| `call.class`      | `event.callClass`                |
| `model.invoked`   | `event.modelInvoked`             |
| `byok.active`     | `event.byokActive`               |
| `cost.event.type` | `"domain.gateway.cost.recorded"` |

`token.kind` (`"prompt"` / `"completion"`) is added to
`pleach_gateway_tokens_total` measurements only.

### The OTel SDK is an optional peer [#the-otel-sdk-is-an-optional-peer]

`createOtelCostEmitter` accepts any `meter` shaped like
`@opentelemetry/api`'s `Meter`, such as a test stub or an in-house
facade. It throws a `TypeError` if `meter` lacks
`createCounter(name, options?)`.

### Override counter names [#override-counter-names]

```typescript
const emitter = createOtelCostEmitter({
  meter,
  costCounterName: "myco.pleach.gateway.cost.usd",
  tokensCounterName: "myco.pleach.gateway.tokens.total",
})
```

### Soft-fail semantics [#soft-fail-semantics]

`emit()` swallows internal exceptions, so a metric backend failure
never propagates up the gateway call.

## `llm.invocation` spans [#llminvocation-spans]

The gateway emits one span named `llm.invocation` per routed call, the
same span name core's seams emit:

* `GatewayClient.route()` emits one span per call that reaches a
  transport.
* `GatewayRuntime.routeChatCompletion()` emits one span per
  transport-served call. The stub path, with no transport wired, emits
  none because no provider was invoked.

Cascade and failover hops are attributes on that one span. The gateway
emits no `llm.attempt` children; those come only from core's seams (see
[OTel spans](/docs/otel-observability#the-span-types)). Spans the
transport opens, such as HTTP client instrumentation, nest under it.

### Choosing a tracer [#choosing-a-tracer]

```typescript
import { trace } from "@opentelemetry/api"
import { GatewayClient } from "@pleach/gateway"

const client = new GatewayClient({
  tenantId,
  transports,
  tracer: trace.getTracer("my-app"), // or null to turn spans off
})
```

* A `tracer` you pass wins. It's typed structurally, so any
  `@opentelemetry/api` `Tracer` fits.
* `tracer: null` disables span emission.
* With no `tracer`, the gateway lazily imports `@opentelemetry/api`
  (an optional peer, `^1.0.0`) on the first routed call and uses
  `trace.getTracer("@pleach/gateway")`. If the package isn't installed,
  emission is a silent no-op.

`GatewayRuntimeConfig.tracer` takes the same values. A throwing tracer
never fails a routed call; it degrades to no span.

Webpack may print a "Critical dependency" warning for the lazy import.
Pass `tracer` explicitly, or `null`, to avoid it.

### Attributes [#attributes]

The tenant, call-class, family, and token keys come from
`@pleach/core/otel`, so gateway and core traces filter on the same
keys. `pleach.model_id` uses the same spelling core's seam spans use.

| Attribute                                      | `route()`                                      | `routeChatCompletion()`                          |
| ---------------------------------------------- | ---------------------------------------------- | ------------------------------------------------ |
| `pleach.tenant_id`                             | yes                                            | yes                                              |
| `pleach.sub_tenant_id`                         | —                                              | when `input.subTenantId` is set                  |
| `pleach.call_class`                            | yes (the class that served, after any cascade) | yes (`input.callClass`, default `"converse"`)    |
| `pleach.family`                                | yes                                            | yes                                              |
| `pleach.model_id`                              | model that served                              | model that served                                |
| `pleach.tokens.input` · `pleach.tokens.output` | yes                                            | when the transport reports `usage`               |
| `pleach.cost.usd`                              | yes                                            | yes                                              |
| `pleach.cost.incomplete`                       | yes (`true` when no price was known)           | —                                                |
| `pleach.gateway.requested_model`               | yes                                            | yes                                              |
| `pleach.gateway.provider`                      | —                                              | provider that served                             |
| `pleach.gateway.region`                        | —                                              | when a region was resolved                       |
| `pleach.gateway.byok_active`                   | yes                                            | —                                                |
| `pleach.gateway.fallback_hops`                 | yes                                            | yes                                              |
| `pleach.gateway.fallback_chain`                | models attempted before the one that served    | providers that failed before the one that served |
| `pleach.gateway.family_exhausted`              | yes                                            | —                                                |
| `pleach.gateway.routing_decision_id`           | —                                              | yes                                              |

`GATEWAY_SPAN_ATTRIBUTE_KEYS` and `LLM_INVOCATION_SPAN_NAME` are
exported from the package root, along with the `GatewayTracerLike` and
`GatewaySpanLike` types.

Token, cost, and served-model attributes are set when the call
succeeds. If the transport result has no `usage`, the token attributes
are omitted, never set to `0`.

### Errors [#errors]

A failed call ends the span with status `ERROR`. It records only:

* `error.type`: the error class name, when it's a plain identifier
  (otherwise `"Error"`), never the message.
* `http.response.status_code`: when the error carries a numeric HTTP
  status.

The status message and recorded exception use the fixed text
`llm invocation failed`. Transport error messages can embed the
upstream response body, so the raw message is never copied onto the
span.

For `route()`, the span ends after the cost event is emitted, so a
cost-sink failure shows as an `ERROR` span.

### `callClass` on `routeChatCompletion()` [#callclass-on-routechatcompletion]

`RouteChatCompletionInput.callClass` is optional and defaults to
`"converse"`; a value outside core's `ALL_CALL_CLASSES` throws
`TypeError`. It feeds `pleach.call_class` and the provenance row. It's
attribution only: `GatewayRuntime` selects by `family` and `model`.

## Public surface [#public-surface]

* `OtelMeter` / `OtelCounter` duck-typed interfaces and the
  `createOtelCostEmitter` factory, from
  `@pleach/gateway/cost/adapters/otel`.
* `CostMiddleware`, which composes the OTel adapter with any route
  response shape, from `@pleach/gateway/cost`.
* The LLM invocation span (`LLM_INVOCATION_SPAN_NAME`,
  `GATEWAY_SPAN_ATTRIBUTE_KEYS`), from `@pleach/gateway`.

## Where to go next [#where-to-go-next]

<Cards>
  <Card title="Cost events" href="/docs/gateway/cost-events" description="The CostEmitter contract and the Postgres, Datadog and Honeycomb adapters." />

  <Card title="OTel observability" href="/docs/otel-observability" description="Platform-wide OTel posture, span conventions, and the `runtime.otel` facet." />

  <Card title="`@pleach/gateway` overview" href="/docs/gateway" description="GatewayClient, cost events, family-strict cascade, transport seam." />
</Cards>
