A background worker
A program that works through jobs in the background: a queue consumer, a mailer, a thumbnail maker. Each job gets:
- a span,
job, with the job’s id and kind, on the tokio task that runs it; - those fields and a trace id of its own on every log line it writes;
- a count in
jobs.processed, by outcome, and its duration injobs.duration.
This one is given four jobs, and stops once it has done them.
The code
Section titled “The code”use std::time::{Duration, Instant};
use tokio::sync::mpsc;use tracing::Instrument;
/// A unit of work, as it might arrive from a message queue.struct Job { id: u64, kind: &'static str,}
#[tokio::main]async fn main() -> Result<(), Box<dyn std::error::Error>> { // First, so the metrics below find oxtel's recorder. Keep the guard // until main returns. let _telemetry = oxtel::init()?; metrics::describe_counter!("jobs.processed", "Jobs processed, by outcome."); metrics::describe_histogram!( "jobs.duration", metrics::Unit::Seconds, "How long each job took." );
let (queue, jobs) = mpsc::channel(16); let worker = tokio::spawn(work(jobs)); for (id, kind) in [ (1, "resize"), (2, "resize"), (3, "transcode"), (4, "resize"), ] { queue.send(Job { id, kind }).await?; } // Closing the queue lets the worker finish what's left, then stop. drop(queue); worker.await?; Ok(())}
/// Takes jobs off the queue, one at a time, until it's closed.async fn work(mut jobs: mpsc::Receiver<Job>) { while let Some(job) = jobs.recv().await { let span = tracing::info_span!("job", job.id = job.id, job.kind = job.kind); let started = Instant::now(); // Each job runs on a task of its own, so a panic fails that job and // not the worker. A new task doesn't start inside the current span: // `instrument` carries the job's span onto it. let outcome = match tokio::spawn(run(job).instrument(span)).await { Ok(Ok(())) => "ok", Ok(Err(_)) => "failed", Err(_) => "panicked", }; metrics::counter!("jobs.processed", "outcome" => outcome).increment(1); metrics::histogram!("jobs.duration").record(started.elapsed().as_secs_f64()); }}
/// One job's work. It runs inside the job's span, so its log lines carry/// the job's fields and trace id.async fn run(job: Job) -> Result<(), String> { tracing::info!("started"); // Stands in for the real work. tokio::time::sleep(Duration::from_millis(20)).await; if job.kind == "transcode" { let error = "no encoder for this format"; tracing::warn!(error, "failed"); return Err(error.into()); } tracing::info!("done"); Ok(())}Dependencies
Section titled “Dependencies”[dependencies]oxtel = "0.4"metrics = "0.24"tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync", "time"] }tracing = "0.1"Run it
Section titled “Run it”From a checkout of the repository:
cargo run -p oxtel-examples --example workerOTEL_METRICS_EXPORTER=console cargo run -p oxtel-examples --example worker # and the metrics, at exitWhat it prints
Section titled “What it prints”{"timestamp":"2026-11-20T21:07:34.023206Z","level":"INFO","target":"oxtel","message":"log lines: standard error, as JSON; traces, metrics and logs: not exported (set OTEL_EXPORTER_OTLP_ENDPOINT to send them to a collector)"}{"timestamp":"2026-11-20T21:07:34.023361Z","level":"INFO","target":"worker","message":"started","trace_id":"b685e8367755fb99bac001cc771fb074","span_id":"efebf55b5e3f9936","job.id":1,"job.kind":"resize"}{"timestamp":"2026-11-20T21:07:34.045485Z","level":"INFO","target":"worker","message":"done","trace_id":"b685e8367755fb99bac001cc771fb074","span_id":"efebf55b5e3f9936","job.id":1,"job.kind":"resize"}{"timestamp":"2026-11-20T21:07:34.045553Z","level":"INFO","target":"worker","message":"started","trace_id":"9de12a939a1aa32683a5ae73a4663fcb","span_id":"7c94dd1c2ea27874","job.id":2,"job.kind":"resize"}{"timestamp":"2026-11-20T21:07:34.066699Z","level":"INFO","target":"worker","message":"done","trace_id":"9de12a939a1aa32683a5ae73a4663fcb","span_id":"7c94dd1c2ea27874","job.id":2,"job.kind":"resize"}{"timestamp":"2026-11-20T21:07:34.066823Z","level":"INFO","target":"worker","message":"started","trace_id":"579eeb766be8edcb1dec9db611a17503","span_id":"ea1952c382b3f7c2","job.id":3,"job.kind":"transcode"}{"timestamp":"2026-11-20T21:07:34.087906Z","level":"WARN","target":"worker","message":"failed","trace_id":"579eeb766be8edcb1dec9db611a17503","span_id":"ea1952c382b3f7c2","job.id":3,"job.kind":"transcode","error":"no encoder for this format"}{"timestamp":"2026-11-20T21:07:34.087968Z","level":"INFO","target":"worker","message":"started","trace_id":"02966f44711fea6a9a1f9bcdff35a700","span_id":"af9299489ac0b8db","job.id":4,"job.kind":"resize"}{"timestamp":"2026-11-20T21:07:34.109458Z","level":"INFO","target":"worker","message":"done","trace_id":"02966f44711fea6a9a1f9bcdff35a700","span_id":"af9299489ac0b8db","job.id":4,"job.kind":"resize"}2026-11-20T21:07:34.411293Z INFO oxtel: log lines: standard error, as text; traces, metrics and logs: not exported (set OTEL_EXPORTER_OTLP_ENDPOINT to send them to a collector)2026-11-20T21:07:34.411465Z INFO job{job.id=1 job.kind=resize}: worker: started trace_id=73220e51b60cdff18592c122765555a1 span_id=9c6ec98e79e6b0312026-11-20T21:07:34.433151Z INFO job{job.id=1 job.kind=resize}: worker: done trace_id=73220e51b60cdff18592c122765555a1 span_id=9c6ec98e79e6b0312026-11-20T21:07:34.433221Z INFO job{job.id=2 job.kind=resize}: worker: started trace_id=90f31a0decdaa8e95d4e7932f91f549f span_id=a0fd6bec251a27752026-11-20T21:07:34.454311Z INFO job{job.id=2 job.kind=resize}: worker: done trace_id=90f31a0decdaa8e95d4e7932f91f549f span_id=a0fd6bec251a27752026-11-20T21:07:34.454374Z INFO job{job.id=3 job.kind=transcode}: worker: started trace_id=e559a532eae06a9284264a2d4d697375 span_id=4f39130d6db0b2342026-11-20T21:07:34.474731Z WARN job{job.id=3 job.kind=transcode}: worker: failed error="no encoder for this format" trace_id=e559a532eae06a9284264a2d4d697375 span_id=4f39130d6db0b2342026-11-20T21:07:34.474786Z INFO job{job.id=4 job.kind=resize}: worker: started trace_id=8b168b952e38acbc350512514581ec2c span_id=34a4812d823e21052026-11-20T21:07:34.496846Z INFO job{job.id=4 job.kind=resize}: worker: done trace_id=8b168b952e38acbc350512514581ec2c span_id=34a4812d823e2105Every line a job writes carries its id and kind, and its own trace id, so everything one job did can be found together. The third job fails, and says why. CI runs the example and checks it still prints these lines.
Spans and tasks
Section titled “Spans and tasks”tokio::spawn starts a task outside any span. Without .instrument(span), the job’s lines would carry no job fields and no trace id. instrument enters the span each time the task runs, and leaves it each time the task waits, so the span follows the job and nothing else.
That’s also why async code uses instrument rather than span.enter(): a span entered before an .await stays entered while the task waits, and other tasks running on the same thread meanwhile would be logged as part of it.
The metrics
Section titled “The metrics”| Metric | What it records |
|---|---|
jobs.processed | A counter: each job, with outcome set to ok, failed or panicked |
jobs.duration | A histogram: each job’s duration, in seconds |
With nothing configured, metrics aren’t kept. OTEL_METRICS_EXPORTER=console, as in the second command above, prints them on standard output when the worker exits. Once OTEL_EXPORTER_OTLP_ENDPOINT is set, they’re sent with the traces and logs, every 60 seconds and once more at exit. A Prometheus scrape names them jobs_processed_total and jobs_duration_seconds.
Because the histogram is described in seconds, it gets the OpenTelemetry conventions’ buckets for durations, from 5 ms to 10 s.
For production
Section titled “For production”- Run jobs side by side. This worker runs one at a time, to keep its output in order. To run several at once, spawn them into a
tokio::task::JoinSet; each still needs.instrument(span). - Stop gracefully. On a signal, stop taking jobs, finish the ones in flight, and return from
main, so oxtel sends what’s pending. In a container, the platform sendsSIGTERMrather than Ctrl-C: wait for both. - Keep ids off metrics. A job id on a metric makes a new series for every job. Put ids on spans and log lines, and give metrics a few values each, such as the outcome.
- Continue the sender’s trace. When another service queues the job, the message can carry its trace. The sender writes it into the message’s headers with
oxtel::propagation::inject_current; the worker creates the job’s span while the guard fromoxtel::propagation::extract_parentis alive, and the job joins the sender’s trace. - Say what kind of span it is. The OpenTelemetry conventions call a span that handles a message from a queue a consumer span: add
otel.kind = "consumer"to the span’s fields.