Skip to Content

Telemetry

Add observability to your job queue with OpenTelemetry tracing

Duron provides built-in OpenTelemetry support for tracing job and step execution. Duron depends only on @opentelemetry/api. Your application owns the OpenTelemetry SDK: it creates the tracer provider, with its own Resource, span processors and exporters, and passes it to Duron.

This follows the OpenTelemetry guidance for libraries. You choose the SDK version, and Duron never brings a second copy of the SDK into your application.

Configuration

Create a tracer provider in your application and pass it as telemetry.tracerProvider:

import { resourceFromAttributes } from '@opentelemetry/resources'
import { BatchSpanProcessor, TracerProvider } from '@opentelemetry/sdk-trace'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'
import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions'
import { duron } from 'duron'
import { postgresAdapter } from 'duron/adapters/postgres'

const tracerProvider = new TracerProvider({
  resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: 'my-service' }),
  spanProcessors: [
    new BatchSpanProcessor({
      exporter: new OTLPTraceExporter({ url: 'http://localhost:4318/v1/traces' }),
    }),
  ],
})

const client = duron({
  database: postgresAdapter({
    connection: process.env.DATABASE_URL,
  }),
  actions: {/* your actions */},
  telemetry: { tracerProvider },
})

Configuration Options

OptionTypeDescription
tracerProviderTracerProviderThe provider Duron gets its tracer from (tracerProvider.getTracer('duron')). Required in telemetry.

TracerProvider is the interface from @opentelemetry/api. Any provider works: TracerProvider from @opentelemetry/sdk-trace (SDK 3), NodeTracerProvider from @opentelemetry/sdk-trace-node (SDK 2), or the provider that NodeSDK registers globally.

Without the telemetry option, telemetry is disabled. Duron uses a no-op tracer and does not fall back to the global tracer provider. To use a global provider, pass it explicitly:

import { trace } from '@opentelemetry/api'
import { NodeSDK } from '@opentelemetry/sdk-node'

const sdk = new NodeSDK({/* serviceName, traceExporter, ... */})
sdk.start()

const client = duron({
  // ...
  telemetry: { tracerProvider: trace.getTracerProvider() },
})

Service name and Resource

Duron does not create a Resource. The spans carry the Resource of the provider that you pass, so set service.name and any other resource attributes on your provider. Duron's spans use the instrumentation scope duron.

Exporters, batching and shutdown

Exporters, span processors and batching options (scheduledDelayMillis, and others) are part of your provider. To send spans to several backends, add one span processor per exporter. Duron does not flush or shut down the provider: call tracerProvider.shutdown() when your application stops, so that buffered spans are exported.

Multiple clients

Each Duron client uses only the provider passed to it. Two clients with different providers export their spans separately, with their own Resources.

Context propagation

Duron links its job, step and custom spans explicitly, so its trace hierarchy is correct without a global context manager. Libraries that read context.active() (for example, HTTP or database instrumentations) need a context manager registered by your application, for example AsyncLocalStorageContextManager from @opentelemetry/context-async-hooks, or NodeSDK.

Migration from traceExporter

The options traceExporter, serviceName and batchDelayMs are removed. Duron no longer creates a tracer provider. Create the provider in your application and pass it as tracerProvider.

An un-migrated config does not silently disable tracing: if telemetry is set without a tracerProvider (an object with getTracer()), or contains one of the removed options, the Client constructor throws a TypeError that links to this section.

Before:

const client = duron({
  database,
  actions,
  telemetry: {
    traceExporter: new OTLPTraceExporter(),
    serviceName: 'my-service',
    batchDelayMs: 1000,
  },
})

After:

import { resourceFromAttributes } from '@opentelemetry/resources'
import { BatchSpanProcessor, TracerProvider } from '@opentelemetry/sdk-trace'
import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions'

const tracerProvider = new TracerProvider({
  resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: 'my-service' }),
  spanProcessors: [
    new BatchSpanProcessor({ exporter: new OTLPTraceExporter(), scheduledDelayMillis: 1000 }),
  ],
})

const client = duron({ database, actions, telemetry: { tracerProvider } })

// On shutdown
await client.stop()
await tracerProvider.shutdown()

Differences:

  • The default service name was duron. Now the service name comes from your provider's Resource. Without one, the SDK default applies (unknown_service:<process>).
  • An array of exporters becomes one span processor per exporter.
  • Without the telemetry option, Duron does not use a globally registered provider.

Telemetry Context

Both action and step handlers have access to ctx.telemetry which provides OpenTelemetry APIs:

interface TelemetryContext {
  // Get the active span for the current job/step (undefined if no span is active)
  getActiveSpan(): Span | undefined

  // Get a tracer for creating custom spans
  getTracer(name: string): Tracer

  // Start a new span as a child of the current job/step span
  startSpan(name: string, options?: { attributes?: Record<string, any> }): Span

  // Record a metric as a span event
  recordMetric(name: string, value: number, attributes?: Record<string, any>): void
}

Recording Metrics

Use recordMetric() to record numeric metrics as span events:

const processOrder = defineAction()({
  name: 'process-order',
  input: z.object({ orderId: z.string() }),
  handler: async (ctx) => {
    const startTime = Date.now()

    const result = await ctx.step('process', async ({ telemetry }) => {
      // Record step-specific metrics
      telemetry.recordMetric('items.count', 5)
      telemetry.recordMetric('order.value', 99.99, { currency: 'USD' })

      return { success: true }
    })

    // Record action-level metrics
    ctx.telemetry.recordMetric('processing.duration_ms', Date.now() - startTime)

    return result
  },
})

Creating Custom Spans

Use getTracer() to create custom spans. The tracer automatically links new spans to the current job/step trace:

const result = await ctx.step('with-custom-span', async ({ telemetry }) => {
  const tracer = telemetry.getTracer('my-service')

  return tracer.startActiveSpan('custom-operation', (span) => {
    try {
      span.setAttribute('custom.input', 'value')
      // Do work...
      span.setAttribute('custom.output', 'result')
      return { success: true }
    } finally {
      span.end()
    }
  })
})

Working with the Active Span

Use getActiveSpan() to add attributes or events to the current span. It returns undefined if no span is active (e.g., when telemetry is not configured):

const result = await ctx.step('annotated', async ({ telemetry }) => {
  const span = telemetry.getActiveSpan()

  if (span) {
    span.setAttribute('user.id', 'user-123')
    span.addEvent('processing.started')

    // Do work...

    span.addEvent('processing.completed', { items: 5 })
  }

  return { success: true }
})

Integration with External Libraries

Use getTracer() to get an OpenTelemetry tracer for external library integration. The tracer automatically links spans to the current job/step trace:

import { openai } from '@ai-sdk/openai'
import { OpenTelemetry } from '@ai-sdk/otel'
import { generateText } from 'ai'

const aiAction = defineAction()({
  name: 'ai-generation',
  input: z.object({ prompt: z.string() }),
  handler: async (ctx) => {
    const response = await ctx.step('generate', async ({ telemetry }) => {
      // Pass the tracer to the AI SDK's OpenTelemetry integration - spans are automatically linked
      const result = await generateText({
        prompt: ctx.input.prompt,
        model: openai('gpt-4o-mini'),
        telemetry: {
          integrations: [new OpenTelemetry({ tracer: telemetry.getTracer('ai') })],
        },
      })

      return result.text
    })

    return { response }
  },
})

The tracer returned by getTracer(name) is context-aware and automatically injects the parent span, so external libraries don't need to manually handle context propagation. It is your provider's tracer name (tracerProvider.getTracer(name)), so its spans carry that instrumentation scope; startSpan() uses Duron's tracer (scope duron).

Using startSpan

Use startSpan() as a shorthand to create a child span linked to the current job/step trace:

const result = await ctx.step('with-child-span', async ({ telemetry }) => {
  const span = telemetry.startSpan('custom-operation', {
    attributes: { 'custom.input': 'value' },
  })

  try {
    // Do work...
    span.addEvent('operation.complete')
    return { success: true }
  } catch (error) {
    span.recordException(error)
    throw error
  } finally {
    span.end()
  }
})

Automatic Tracing

Duron automatically creates spans for:

Span TypeName FormatAttributes
Jobjob:{actionName}duron.job.id, duron.action.name, duron.group.key
Stepstep:{stepName}duron.job.id, duron.step.id, duron.step.name, duron.step.parent_id

Spans include:

  • Start and end timestamps
  • Duration
  • Status (ok, error)
  • Error details when applicable
  • Parent-child relationships for nested steps

Best Practices

Use Descriptive Metric Names

// Good: Namespaced and descriptive
telemetry.recordMetric('order.processing.duration_ms', duration)
telemetry.recordMetric('ai.tokens.total', tokens)

// Bad: Generic and unclear
telemetry.recordMetric('time', duration)
telemetry.recordMetric('count', tokens)

Add Context with Attributes

telemetry.recordMetric('api.request.duration_ms', 250, {
  endpoint: '/users',
  method: 'GET',
  statusCode: 200,
})

Track Costs and Resources

// AI token usage
telemetry.recordMetric('ai.tokens.input', inputTokens)
telemetry.recordMetric('ai.tokens.output', outputTokens)
telemetry.recordMetric('ai.cost.usd', cost, { model: 'gpt-4o' })

Always End Custom Spans

const tracer = telemetry.getTracer('my-service')
const span = tracer.startSpan('operation')
try {
  // Do work...
} finally {
  span.end() // Always end the span
}

Installation

@opentelemetry/api is a peer dependency of Duron (^1.9.0). Your application installs it once, so Duron and your SDK share the same API instance. Install the SDK and the exporter that you want:

bun add @opentelemetry/api @opentelemetry/sdk-trace @opentelemetry/resources @opentelemetry/semantic-conventions

# For OTLP export
bun add @opentelemetry/exporter-trace-otlp-http

Duron is tested with @opentelemetry/api 1.10 and @opentelemetry/sdk-trace 3. SDK 2 (@opentelemetry/sdk-trace-node, which requires @opentelemetry/api lower than 1.10) also works.

Architecture Notes

Duron's telemetry implementation:

  • Depends only on @opentelemetry/api: the application owns the SDK, the Resource and the exporters
  • Does not globally register a tracer provider and does not read the global one: each client uses only the provider passed to it
  • Uses a context-aware tracer wrapper that automatically links spans to the correct trace hierarchy
  • Exports spans with duron.job.id attribute for job association. Spans created with ctx.telemetry.startSpan() or the tracer from getTracer() (startSpan and startActiveSpan) also get duron.job.id, and duron.step.id inside a step. Duron sets these from its own state and does not read SDK-specific span properties, so they work with any provider that implements the @opentelemetry/api interfaces

On this page