Tracing Async Workflows: Queues, Schedulers, and Background Jobs

Philip Rehberger Nov 24, 2026 8 min read

Connect spans across queues and schedulers so async work appears in your traces.

Synchronous tracing is mostly solved. An HTTP request comes in, the framework attaches a span, downstream calls carry the context, the trace appears in the backend as a single tree. Async tracing is where things fall apart.

A job enqueued during a request runs minutes later in a separate worker process. A scheduled task starts from nothing every five minutes. A retry pulls a message off a queue with context that may or may not still be valid. Each of these breaks the assumption — implicit in most tracing libraries — that one process owns a trace from start to finish.

The consequence is that traces tell a smaller story than they should. The customer-visible work that happens "later" — billing, notifications, document generation, data exports — is invisible to the tracing UI, even though that work is often where failures hide.

This guide is about closing that gap.

Why It Is Hard

The core problem: distributed tracing depends on context propagation, but the standard propagation channel is the HTTP request. Queue messages are not HTTP requests. Scheduled jobs are not triggered by HTTP at all. The library has no obvious place to put the trace context.

The answer is to manually attach the context — into the message body, the job arguments, the scheduler invocation — and manually extract it on the consumer side. Most modern tracing SDKs have helpers for this, but the helpers need to be used. The work doesn't happen by default.

Pattern 1: Queue Messages

The most common async boundary. A producer enqueues a job; a worker consumes it later. The trace context lives in the producer's process and must be serialized into the message.

In Laravel:

use OpenTelemetry\API\Globals;
use OpenTelemetry\API\Trace\Propagation\TraceContextPropagator;
use OpenTelemetry\Context\Context;

class SendInvoiceEmail implements ShouldQueue
{
    public array $traceContext;

    public function __construct(public int $invoiceId)
    {
        $this->traceContext = [];
        TraceContextPropagator::getInstance()->inject(
            $this->traceContext,
            Context::getCurrent()
        );
    }

    public function handle(): void
    {
        $context = TraceContextPropagator::getInstance()->extract($this->traceContext);
        $scope = Context::storage()->attach($context);

        try {
            $tracer = Globals::tracerProvider()->getTracer('billing');
            $span = $tracer->spanBuilder('invoice.email.send')->startSpan();
            $span->setAttribute('invoice.id', $this->invoiceId);

            try {
                $this->doWork();
            } finally {
                $span->end();
            }
        } finally {
            $scope->detach();
        }
    }
}

The job carries a traceContext field. The constructor (running in the producer) populates it. The handler (running in the worker) extracts it and attaches the context for the duration of the work. The result: spans created inside handle attach to the original request's trace.

Wrap this pattern in a base class or trait so every job class inherits the behavior. Repeating it per-job is the kind of boilerplate that gets skipped.

Pattern 2: Message Queues with Native Tracing

Some message queue systems support trace context as a first-class concept. Kafka, NATS, RabbitMQ all have header support; SQS supports message attributes. Tracing libraries that integrate with these queues often inject and extract automatically.

The OpenTelemetry instrumentation for Kafka producers injects traceparent into message headers. The consumer-side instrumentation extracts and creates child spans. Once configured, no per-message code is needed.

This is the cleanest pattern but only works with queue systems and instrumentation libraries that support it. For systems without native tracing support, the manual-propagation pattern is the answer.

Pattern 3: Scheduled Jobs

A scheduled job has no parent trace. The right pattern is to start a new root span for the scheduled run:

from opentelemetry import trace

tracer = trace.get_tracer(__name__)

def run_nightly_export():
    with tracer.start_as_current_span("nightly_export") as span:
        span.set_attribute("scheduled.run_at", datetime.utcnow().isoformat())
        process_records()

Everything inside the with block creates child spans. The scheduled job appears in the tracing UI as a single trace per run.

Attribute hygiene matters here. Include the schedule name, the cron expression, and the run timestamp as span attributes. They make the trace findable later ("show me the nightly export from three days ago").

Pattern 4: Retries

Retries muddy the trace model. If a job fails and is retried, is the retry a new trace, a child span of the original, or a continuation of the original?

The pragmatic answer: each attempt is a separate span, with a retry.count attribute, all attached to the same trace as the original work.

public function handle(): void
{
    $tracer = Globals::tracerProvider()->getTracer('billing');
    $span = $tracer->spanBuilder('invoice.email.send')
        ->setAttribute('retry.count', $this->attempts())
        ->setAttribute('retry.max', $this->tries)
        ->startSpan();

    // ... rest of handler
}

The trace then shows N spans for N attempts, with an obvious story about how many retries it took. Backends with span filtering can show only failed retries; users can spot consistent retry patterns.

Pattern 5: Long-Running Workflows

Some async work runs for hours. A data migration. A bulk import. A long-running report generation. A single span for the whole run is too coarse — when something fails, you cannot see where.

Use nested spans for sub-stages:

with tracer.start_as_current_span("data_migration") as outer:
    outer.set_attribute("records.total", total_count)

    with tracer.start_as_current_span("extract"):
        records = fetch_records()

    with tracer.start_as_current_span("transform") as t:
        transformed = transform(records)
        t.set_attribute("records.transformed", len(transformed))

    with tracer.start_as_current_span("load"):
        load(transformed)

The trace tree mirrors the workflow stages. A failure in the transform stage is immediately visible.

The size of the trace matters. Backends have limits on trace duration and span count per trace. A workflow that creates 10,000 spans will be rejected or truncated. Split very long workflows into multiple traces with a shared correlation ID instead.

Trace Linking for Many-to-Many

Sometimes one piece of work fans out into many. A request creates ten jobs; each runs independently. Or many requests aggregate into one batch job.

The OpenTelemetry concept of span links handles this. A child span can link to multiple parents, or one parent can spawn many children that all link back. The trace UI in Tempo, Jaeger, and similar backends renders links explicitly.

Not every backend supports linking well. Where it works, use it for fan-out and fan-in. Where it doesn't, fall back to logging correlation IDs that let you reconstruct the relationship in queries.

Avoiding Pitfalls

A few patterns that bite in production.

Stale context. A job enqueued today, run a week later, carries a traceparent whose original trace has long since been deleted from the backend. The trace structure is meaningless. Decide whether jobs older than a certain age start a new root instead of attaching to an expired trace.

Context across process restarts. A long-running workflow that hands off between processes (writes intermediate state to a database, picks up from another worker) needs the trace context persisted alongside the state. Forgetting this produces orphan spans.

Sampling decisions. Head-based sampling at the producer means the consumer sees the sampling decision. If the producer sampled out, the consumer's spans are dropped — even when the consumer has the only useful data (the error). Tail-based sampling at a gateway fixes this; head-based at 100% for queue-driven flows is a pragmatic workaround.

Cardinality from job IDs. Adding job_id as a span attribute is fine. Adding job_id as a trace-wide attribute or metric label inflates cardinality unbounded. Be careful which path the value takes.

Verification

Unit tests rarely catch async tracing bugs. Verification needs production-shape traffic.

A verification routine for any service with async work:

  1. Trigger a real request that spawns a known set of background jobs.
  2. Find the trace in the backend.
  3. Confirm the span tree includes each job as a child of the expected parent.
  4. Confirm no orphan traces appear for the same time window.

Do this once per service deployment for the first few weeks. After confidence is established, occasional audits catch drift.

A Starting Checklist

For a service with async work and broken or missing tracing today:

  • Every job class serializes trace context in the constructor and restores in the handler.
  • A trait or base class enforces the pattern.
  • Scheduled jobs start a new root span.
  • Span attributes include schedule name, retry count, and any natural correlation IDs.
  • Long-running workflows are split into nested spans by stage.
  • A monthly audit confirms async traces are connecting correctly.

This is a one-week investment for a service of moderate complexity, and it adds the entire async surface to a trace tool that previously stopped at the request boundary.


Losing visibility once work goes async? We help teams design tracing pipelines that follow the work across every boundary. scopeforged.com

Share this article

Related Articles

Need help with your project?

Let's discuss how we can help you build reliable software.