How-to › Operate integrations in production

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.

Audience
Platform team
Level
intermediate
Topic
Instrument and meter API calls
Languages
TypeScript, Go and Python
Verified

A Book.list() call fails once with a 503 and succeeds on the retry. Your trace backend shows two spans called GET, in two separate traces, without the name of the operation your code called. On a busy service you cannot tell one retried call from two calls, so the latency chart for the operation counts the wrong thing.

What you get

You will end up with one span per SDK operation, named book.list, carrying the attempt count, with each HTTP attempt as a child span in the same trace. This is for you if you own the constructor of a generated SDK and run OpenTelemetry in the process.

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, 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

ApproachWhen it fitsWhat it costs youWhen to pick something else
Hand-written span around each callA few calls, any client, and you choose the span namesOne wrapper per call site, and it cannot see attempts, cache hits, or the generated operation nameThe SDK can open the span itself
ogen ogen/otel featureA Go client, and spans named for each operation out of the boxGo only, and retries live in whatever http.Client you pass itYour clients are TypeScript or Python
OpenTelemetry undici instrumentationEvery outbound request in a Node process, including calls that bypass your SDKSpans named by method, one trace per attempt, and no operation nameYou need operation names or attempt counts
orval mutatorA TypeScript client generated by orval, with one function you own on every callThe mutator receives a URL and request options, so operation names must come from a wrapperYou want the generator to name the span
sdkgen telemetry featureAn 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 belowYou 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 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:

  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.

  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:

  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:

  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:

node spans.mjs
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.

node --test spans.test.mjs
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 is on by default, and each generated method starts a span named for the operation before it sends:

	// 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. 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:

go run -C ogen-demo .
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 puts your function under every call, but the generated code passes it the URL and the request options only:

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:

node pitfall.mjs
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.

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.

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.

Footnotes

  1. The OpenTelemetry HTTP span conventions 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. ↩︎ Back to text

  2. The W3C 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 gives the default for idgen as sequential. The generated id opens with t, a letter hexadecimal does not have. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.