npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@pg-workflows/otel

v0.1.3

Published

OpenTelemetry tracing plugin for pg-workflows: one span per workflow execution and per step

Readme

@pg-workflows/otel

OpenTelemetry tracing for pg-workflows. otelPlugin emits one span per workflow execution and one per step. It's a separate package so the engine has no OpenTelemetry dependency.

Quickstart

This prints spans to the console. It assumes a Postgres at DATABASE_URL. The engine quickstart has a Docker command for one.

npm install pg-workflows pg @pg-workflows/otel @opentelemetry/api @opentelemetry/sdk-node
npm install -D tsx

Save as traced.ts:

import { NodeSDK, tracing } from '@opentelemetry/sdk-node'
import { otelPlugin } from '@pg-workflows/otel'
import { WorkflowEngine, WorkflowStatus, workflow } from 'pg-workflows'

const sdk = new NodeSDK({ traceExporter: new tracing.ConsoleSpanExporter() })
sdk.start()

const tracedWorkflow = workflow.use(otelPlugin())

const checkout = tracedWorkflow('checkout', async ({ step }) => {
  const charge = await step.run('charge', async () => ({ chargeId: 'ch_123' }))
  await step.run('send-receipt', async () => ({ sentFor: charge.chargeId }))
  return charge
})

async function main() {
  const engine = new WorkflowEngine({
    connectionString: process.env.DATABASE_URL ?? 'postgres://postgres:postgres@localhost:5432/postgres',
    workflows: [checkout],
  })
  await engine.start()

  const run = await engine.startWorkflow({ workflowId: 'checkout', input: {} })

  let result = await engine.getRun({ runId: run.id })
  while (result.status === WorkflowStatus.PENDING || result.status === WorkflowStatus.RUNNING) {
    await new Promise((resolve) => setTimeout(resolve, 200))
    result = await engine.getRun({ runId: run.id })
  }

  await engine.stop()
  await sdk.shutdown()
}

main()
npx tsx traced.ts

The output includes a pg_workflows.workflow.run span and two pg_workflows.step.run spans. In production, replace ConsoleSpanExporter with your exporter, for example OTLPTraceExporter from @opentelemetry/exporter-trace-otlp-http.

Spans

pg_workflows.workflow.run
├── pg_workflows.step.run
├── pg_workflows.step.waitFor
├── pg_workflows.step.delay
├── pg_workflows.step.waitUntil
├── pg_workflows.step.pause
├── pg_workflows.step.poll
└── pg_workflows.step.invokeChildWorkflow

step.sleep is an alias for step.delay and emits pg_workflows.step.delay.

One trace per execution. A run that pauses (waitFor, delay, pause, and so on) and later resumes produces a new trace for each execution. Correlate them with the workflow.id and workflow.run_id attributes.

Step spans are recorded when the step finishes. Each step span gets its start time from when the step began, but the span object is created only after the step returns or throws. Spans your code creates inside a step.run callback, including auto-instrumented HTTP or database calls, are therefore children of pg_workflows.workflow.run, not of the step span.

Attributes

| Span | Attributes | |------|------------| | pg_workflows.workflow.run | workflow.id, workflow.run_id, workflow.attempt (same as run.retryCount), workflow.resource_id (when set), and anything returned by the attributes option | | pg_workflows.step.<kind> | step.id, step.type (a StepType value) |

On success, a span's status is OK. On error, the plugin calls recordException(error) and sets the status to ERROR with the error message.

Replayed steps

When a run resumes, the handler runs from the top, and completed steps return their saved output. The plugin emits no span for these replays. It uses isStepCached(context.timeline, stepId) from pg-workflows. A step counts as cached when:

  • its output is in the timeline, or
  • it's a step.invokeChildWorkflow whose child run has already been created. This covers a parent that re-enters the step while the child is still running.

Two exceptions:

  • step.poll emits a span on every check, because each check is a real attempt.
  • step.run returning undefined emits no span. Return a value (for example { sent: true }) from steps you want traced.

Options

import { trace } from '@opentelemetry/api'
import { otelPlugin } from '@pg-workflows/otel'

otelPlugin({
  tracer: trace.getTracer('billing-worker'),
  spanNamePrefix: 'billing',
  attributes: (ctx) => ({ 'tenant.id': ctx.resourceId ?? 'none' }),
})

| Option | Type | Default | Description | |--------|------|---------|-------------| | tracer | Tracer | trace.getTracer('pg-workflows') | The tracer that creates spans. | | spanNamePrefix | string | 'pg_workflows' | Replaces pg_workflows in every span name. | | attributes | (ctx: WorkflowContext) => Record<string, AttributeValue> | none | Extra attributes for the workflow.run span. Receives the handler context, including input and resourceId. |

Errors

When a step or handler throws, the plugin records the exception, sets the span status to ERROR, and rethrows the original error. Retries and failure handling in the engine are unchanged.

A thrown non-Error value (throw 'msg') is wrapped in an Error for the span only. The original value is rethrown.

Composing plugins

otelPlugin uses the wrap(context, next) middleware hook that any plugin can implement. With several plugins, the first one passed to .use() is the outermost wrap:

import { otelPlugin } from '@pg-workflows/otel'
import { type WorkflowPlugin, workflow } from 'pg-workflows'

const timingPlugin: WorkflowPlugin = {
  name: 'timing',
  methods: () => ({}),
  wrap: async (ctx, next) => {
    const startedAt = Date.now()
    try {
      return await next()
    } finally {
      ctx.logger.log(`${ctx.workflowId} execution took ${Date.now() - startedAt}ms`)
    }
  },
}

// timingPlugin wraps the whole execution, including the workflow.run span
const instrumentedWorkflow = workflow.use(timingPlugin).use(otelPlugin())

Context propagation

Nested spans need a context manager that follows await. NodeSDK from @opentelemetry/sdk-node registers one. If you set up OpenTelemetry by hand, install @opentelemetry/context-async-hooks and register it:

import { context } from '@opentelemetry/api'
import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'

context.setGlobalContextManager(new AsyncHooksContextManager().enable())

Not supported yet

Most of these need the trace context stored with the run, and are expected to ship together.

  • Metrics. Only traces are emitted.
  • Linking executions. A resumed run starts a new root trace, not a continuation of the previous one.
  • Child workflow traces. A child run starts its own root trace.
  • Caller context. The trace of the request that called startWorkflow isn't propagated into the run.
  • Dead-letter failures. When retries run out, the run is marked failed outside the plugin chain, so that final transition has no span. The error is already on the last execution's span.
  • Sampling. The plugin uses your TracerProvider's sampler.

Migrating from pg-workflows 0.15 and earlier

otelPlugin used to be exported from pg-workflows. Install @pg-workflows/otel and change the import. Options and spans are unchanged.

-import { workflow, otelPlugin } from 'pg-workflows'
+import { otelPlugin } from '@pg-workflows/otel'
+import { workflow } from 'pg-workflows'

Requirements

  • pg-workflows >= 0.16.0 (peer dependency)
  • @opentelemetry/api ^1.9.0 (peer dependency)
  • An OpenTelemetry SDK with an async context manager. See Context propagation.