Skip to content

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 in jobs.duration.

This one is given four jobs, and stops once it has done them.

examples/worker.rs
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(())
}
Cargo.toml
[dependencies]
oxtel = "0.4"
metrics = "0.24"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync", "time"] }
tracing = "0.1"

From a checkout of the repository:

Terminal window
cargo run -p oxtel-examples --example worker
OTEL_METRICS_EXPORTER=console cargo run -p oxtel-examples --example worker # and the metrics, at exit
Standard error
{"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"}

Every 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.

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.

MetricWhat it records
jobs.processedA counter: each job, with outcome set to ok, failed or panicked
jobs.durationA 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.

  • 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 sends SIGTERM rather 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 from oxtel::propagation::extract_parent is 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.