# How to emit OpenTelemetry spans from a generated SDK

> Give every SDK operation one OpenTelemetry span named for the operation, with each HTTP attempt as a child, and keep a second layer from doubling the spans.

Source: https://voxgig.com/howto/emit-opentelemetry-spans-from-a-generated-sdk

- Audience: platform-team
- Level: intermediate
- Languages: typescript, go, python
- Verified: 2026-11-20
- Published: 2026-11-20

## Short answer

Turn on the sdkgen telemetry feature in the constructor and pass it an idgen that starts an OpenTelemetry span, an exporter that ends it, and a system.fetch that runs each attempt inside that span. With undici instrumentation on, one retried call gives a book.list span with one GET child per attempt. ogen generates operation spans itself, and orval needs a hand-written span around each call.

---
## You will need

Node 22 or later, a generated SDK whose constructor you control, and an OpenTelemetry tracer
provider. The sample uses an in-memory exporter from
[`@opentelemetry/sdk-trace`](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/sdk-trace),
so no collector runs. The SDK was generated from `api.json`, a five-operation Bookshelf
document, with `--feature telemetry,retry`; `generate.sh` in the sample records the commands.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Hand-written span around each call](https://opentelemetry.io/docs/languages/js/instrumentation/) | A few calls, any client, and you choose the span names | One wrapper per call site, and it cannot see attempts, cache hits, or the generated operation name | The SDK can open the span itself |
| [`ogen` `ogen/otel` feature](https://ogen.dev/docs/config/) | A Go client, and spans named for each operation out of the box | Go only, and retries live in whatever `http.Client` you pass it | Your clients are TypeScript or Python |
| [OpenTelemetry undici instrumentation](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-undici) | Every outbound request in a Node process, including calls that bypass your SDK | Spans named by method, one trace per attempt, and no operation name | You need operation names or attempt counts |
| [orval mutator](https://orval.dev/docs/guides/custom-client/) | A TypeScript client generated by orval, with one function you own on every call | The mutator receives a URL and request options, so operation names must come from a wrapper | You want the generator to name the span |
| [sdkgen telemetry feature](https://github.com/voxgig/sdkgen/blob/main/docs/reference/features.md) | An sdkgen SDK, and one span per operation, named `<entity>.<op>` | Its spans are plain records with a name and ids, so OpenTelemetry needs the bridge below | You have no control over the SDK constructor |

Voxgig maintains sdkgen. It is the subject of this page, and its row says when to pick something
else.

Auto-instrumentation has the widest reach and the least knowledge: it catches every request in
the process and names none of them. The SDK-side layers know the operation and the attempt, but
they cover only calls that go through that SDK. `ogen` gives you the operation span without
writing anything; sdkgen and orval each need some code from you.

## Bridge the telemetry feature into OpenTelemetry

The [telemetry feature](https://github.com/voxgig/sdkgen/blob/main/docs/reference/features.md#telemetry)
opens one span per operation at `PrePoint`, adds `traceparent`, `X-Trace-Id`, and `X-Span-Id`
headers at `PreRequest`, and closes the span at `PreDone`, or at `PreUnexpected` on a failure. Its spans are plain objects handed to an `exporter` callback, not
OpenTelemetry spans. The bridge makes them live ones:

```js title="bridge.mjs"
  function idgen(kind) {
    if ('trace' === kind) {
      pending = tracer.startSpan('sdk.operation', { kind: SpanKind.CLIENT })
      return pending.spanContext().traceId
    }
    const span = pending
    pending = undefined
    if (null == span) throw new Error('telemetry asked for a span id before a trace id')
    const id = span.spanContext().spanId
    open.set(id, { span, attempts: 0 })
    return id
  }
```

`idgen` is the feature's injectable id source. The generated `PrePoint` asks for a trace id and
then a span id in one synchronous step, so the bridge starts an OpenTelemetry span there and hands
out its ids. The span starts when the operation does, under whatever span the caller had active.

```js title="bridge.mjs"
  function exporter(record) {
    const entry = open.get(record.spanId)
    if (null == entry) return
    open.delete(record.spanId)
    const [entity, op] = record.name.split('.')
    entry.span.updateName(record.name)
    entry.span.setAttributes({ 'sdk.entity': entity, 'sdk.operation': op, 'sdk.attempts': entry.attempts })
    if (!record.ok) entry.span.setStatus({ code: SpanStatusCode.ERROR })
    entry.span.end()
  }
```

The feature's record is `{ traceId, spanId, name, start, end, durationMs, ok }`, with `name` set to
`<entity>.<op>`. It has no entity, operation, or attempt fields, so the bridge splits the name and
counts the attempts itself.

The third piece runs once per HTTP attempt. The `retry` feature wraps the transport, so it calls
`system.fetch` again for each attempt, with the same headers:

```js title="bridge.mjs"
  function tracedFetch(url, init = {}) {
    const headers = { ...init.headers }
    const name = Object.keys(headers).find((h) => 'traceparent' === h.toLowerCase())
    const spanId = name ? String(headers[name]).split('-')[2] : undefined
    const entry = null == spanId ? undefined : open.get(spanId)
    if (null == entry) return fetch(url, init)
    entry.attempts++
    // The HTTP instrumentation injects the attempt's own traceparent; a
    // second copy of the operation's would reach the server beside it.
    delete headers[name]
    const ctx = trace.setSpan(context.active(), entry.span)
    return context.with(ctx, () => fetch(url, { ...init, headers }))
  }
```

Each attempt runs inside the operation span's context, so the undici instrumentation makes its
`GET` span a child. Pass all three in the constructor:

```js title="spans.mjs"
  if (has('sdkgen')) {
    const bridge = otelTelemetry(tracing.tracer)
    feature.telemetry = { active: true, idgen: bridge.idgen, exporter: bridge.exporter }
    options.system = { fetch: bridge.fetch }
  }
```

## Compare the three layers on one retried call

`spans.mjs` makes one `Book.list()` call against a stand-in that answers 503 once, with retry on,
under three setups:

```bash
node spans.mjs
```

```text output
undici auto-instrumentation alone
  GET         root   status=503
  GET         root   status=200
  spans: 2, traces: 2, requests whose traceparent names an exported span: 2 of 2
a hand-written span around the call, plus undici
  Book.list   root   no attributes
    GET       child  status=503
    GET       child  status=200
  spans: 3, traces: 1, requests whose traceparent names an exported span: 2 of 2
the sdkgen telemetry feature through the bridge, plus undici
  book.list   root   entity=book op=list attempts=2
    GET       child  status=503
    GET       child  status=200
  spans: 3, traces: 1, requests whose traceparent names an exported span: 2 of 2
```

Alone, undici gives each attempt its own trace and names it by method.[^1] Neither `GET` span
carries `http.request.resend_count`, because each attempt reaches undici as a separate request.
The hand-written span joins the attempts but knows nothing the call site did not tell it. The
bridge gives the same tree plus the entity, the operation, and the attempt count.

## Check it worked

The tests make the retried call and assert one `book.list` span with two `GET` children in one
trace. They also check one `traceparent` per request, an error status on a 404, and three
concurrent calls whose children stay under their own operation.

```bash
node --test spans.test.mjs
```

```text output
1..7
# tests 7
# suites 0
# pass 7
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 208.674417
```

## Get operation spans in Go and from orval

`ogen` generates the operation span. The [`ogen/otel` feature](https://ogen.dev/docs/config/) is on
by default, and each generated method starts a span named for the operation before it sends:

```go title="ogen-demo/bookshelf/oas_client_gen.go"
	// Start a span for this request.
	ctx, span := c.cfg.Tracer.Start(ctx, ListBooksOperation,
		trace.WithAttributes(otelAttrs...),
		clientSpanKind,
	)
```

Pass `WithTracerProvider` to `NewClient`, and wrap the transport of the `http.Client` you give
`WithClient` with [`otelhttp.NewTransport`](https://pkg.go.dev/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp).
The generated client has no retry, so the demo wraps `otelhttp` in a one-retry transport. Run the
demo against its own `httptest` stand-in:

```bash
go run -C ogen-demo .
```

```text output
books: 1
  ListBooks  root               oas.operation=listBooks http.request.method=GET
  HTTP GET   child of ListBooks http.request.method=GET http.response.status_code=503
  HTTP GET   child of ListBooks http.request.method=GET http.response.status_code=200
```

orval generates no tracing. Its [`override.mutator`](https://orval.dev/docs/guides/custom-client/)
puts your function under every call, but the generated code passes it the URL and the request
options only:

```ts title="orval/client/bookshelf.ts"
export const listBooks = async ( options?: Parameters<typeof tracedFetch>[1]): Promise<listBooksResponse> => {

  return tracedFetch<listBooksResponse>(getListBooksUrl(),
  {
    ...options,
    method: 'GET'
```

So with orval, wrap each exported function in `startActiveSpan`, named for the function, and let
undici make the children. That is the hand-written row, as `spans.mjs` runs it.

## When it goes wrong

The server receives two `traceparent` headers. Telemetry is on with its default ids and undici
instrumentation adds its own header beside the SDK's:

```bash
node pitfall.mjs
```

```text output
telemetry on with its defaults, plus undici
  GET         root   status=503
  GET         root   status=200
  spans: 2, traces: 2, requests whose traceparent names an exported span: 0 of 2
  request: 2 traceparent headers, the SDK's is 00-t0001000000000000-s0002000000000000-01, valid W3C: false
  request: 2 traceparent headers, the SDK's is 00-t0001000000000000-s0002000000000000-01, valid W3C: false
a hand-written span on top of the bridge, plus undici
  Book.list   root   no attributes
    book.list child  entity=book op=list attempts=2
      GET     child  status=503
      GET     child  status=200
  spans: 4, traces: 1, requests whose traceparent names an exported span: 2 of 2
```

The default ids are sequential and fail the W3C format,[^2] and with no `exporter` the SDK's span
never reaches OpenTelemetry. Pass the bridge's `idgen` and `fetch`, which replace both.

The operation appears twice. A team added a wrapper span while the bridge was already on, so every
call carries `Book.list` and `book.list`. Pick one layer per client for the operation span, and
write the choice down beside the tracer setup.

The bridge throws `telemetry asked for a span id before a trace id`. A regenerated `PrePoint`
changed the order of its `idgen` calls; the first test fails on the same change.

## When not to do this

Do not add the sdkgen bridge for an SDK you call twice a day. Auto-instrumentation already gives
you the HTTP spans, and the bridge depends on the order in which the generated code asks for ids.

Do not expect the SDK layer to cover calls that skip it. A `fetch` written by hand, or another
library in the process, still needs undici instrumentation, so keep it on for those. In Python the
same layer is
[`HTTPXClientInstrumentor`](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/httpx/httpx.html).

Do not adopt a generator for its tracing. If your clients are Go, `ogen` emits operation spans with
nothing to write, which beats both sdkgen and orval for that reader. If you already generate with
orval, a wrapper around the exported functions costs less than a second generator.

## Related how-tos

- [Choose the layer that instruments outbound API calls](/howto/choose-a-layer-to-instrument-outbound-calls)

- [Export outbound call spans from a serverless function](/howto/flush-spans-from-a-serverless-function)

- [Generate your first SDK with sdkgen](/howto/first-sdk-with-sdkgen)

- [Attribute API cost per operation and per caller in an SDK](/howto/attribute-api-cost-per-operation-and-caller)

## Last verified

Verified 2026-11-20 against Node 22.23.5, `@voxgig/create-sdkgen` 0.31.9, `@voxgig/sdkgen` 4.44.3,
`@opentelemetry/sdk-trace` 3.1.1, `@opentelemetry/instrumentation-undici` 0.35.1, orval 8.48.0
and `ogen` v1.25.0. Every output block is what the command preceding it printed. The generated
SDK is committed under `generated/`. `ogen` and orval were run once on the same document and their
output committed. The Go demo's module needs Go 1.26, which the Go command fetches for an older
install.

[^1]: The OpenTelemetry [HTTP span conventions](https://opentelemetry.io/docs/specs/semconv/http/http-spans/)
say a client span SHOULD be named `{method} {target}` when a low-cardinality target is available,
and `{method}` when it is not. The undici instrumentation sees a URL rather than a route template, and
uses the second form, so every call this page makes is called `GET`.

[^2]: The [W3C Trace Context](https://www.w3.org/TR/trace-context/) Recommendation of 23 November
2021 defines a trace id as 32 lowercase hexadecimal digits and a parent id as 16, with all zeroes
forbidden. sdkgen's [feature reference](https://github.com/voxgig/sdkgen/blob/main/docs/reference/features.md#telemetry)
gives the default for `idgen` as sequential. The generated id opens with `t`, a letter hexadecimal
does not have.