skip to content

In a Rust service using tracing, a handler holds `span.enter()`'s guard across an `.await`, and unrelated heartbeat events land inside its `charge` span; why, and how do you fix it?

level: seniorimportance: should knowfreq 40%

answer

  1. yielding is not dropping
  2. current span is per thread
  3. the guard outlives the poll
  4. enter on poll, exit on yield

basics

~20 s

At an .await the future yields but its locals, including the Entered guard, are not dropped, so the span stays entered on that thread while other futures run there. Use Instrument::instrument or #[instrument] on the async fn, and Span::in_scope for synchronous sections.

solid answer

~50 s

`span.enter()` returns an `Entered` guard that exits the span when dropped. In an `async fn`, an `.await` that returns `Pending` suspends the future without dropping its locals, so the guard keeps the span entered on the worker thread, and whatever that thread polls next, such as a heartbeat future joined with the handler, is recorded inside `charge`. On a multi-threaded runtime the future can resume on another worker, so the exit lands on a thread that never entered the span. The fix is to attach the span to the future: `fut.instrument(span)` (from `tracing::Instrument`) enters the span on every poll and exits it whenever the future yields, and `#[instrument]` on an `async fn` generates exactly that. For a synchronous block inside an async function use `span.in_scope(|| ...)`. The bug compiles silently, because `Entered` is `Send`; the owned guard from `.entered()` is `!Send`, so `tokio::spawn` rejects it.

code

rust · 31 lines
rust
use std::time::Duration;
use tracing::{info, info_span, Instrument};

async fn charge_wrong(order_id: u64) {
    let span = info_span!("charge", order_id);
    let _guard = span.enter(); // held across the .await below
    tokio::time::sleep(Duration::from_millis(20)).await;
    info!("charge done");
}

async fn charge_right(order_id: u64) {
    async {
        tokio::time::sleep(Duration::from_millis(20)).await;
        info!("charge done");
    }
    .instrument(info_span!("charge", order_id))
    .await
}

async fn heartbeat() {
    tokio::time::sleep(Duration::from_millis(5)).await;
    info!("heartbeat");
}

#[tokio::main(flavor = "current_thread")]
async fn main() {
    tracing_subscriber::fmt().with_ansi(false).without_time().with_target(false).init();
    tokio::join!(charge_wrong(1), heartbeat());
    info!("--- with Instrument");
    tokio::join!(charge_right(2), heartbeat());
}

go deeper

for a junior

Remember that in async code you attach a span to a future with .instrument or #[instrument], never by holding span.enter() in a local.

for a middle

Explain why: an .await suspends the future without dropping the guard, and the current span is tracked per thread, so other futures run inside it.

for a senior

Diagnose misattributed events from a trace, explain why rustc accepts Entered across .await but rejects EnteredSpan under tokio::spawn, and fix spawned tasks with .instrument(Span::current()).

for a principal

Make span hygiene a review rule for async crates, since neither the compiler nor the subscriber flags this mistake and it quietly corrupts every trace the team relies on.

## Entering a span is a thread-local fact A **span** in `tracing` is a period of work with a name and fields, such as `charge{order_id=1}`. A subscriber tracks which span is **current**, so every event can be attached to it. `Span::enter()` makes a span current and returns an **`Entered` guard**; dropping the guard exits the span. In synchronous code this matches lexical scope exactly. `tracing-subscriber`'s `Registry` keeps the stack of current spans **per thread**. Entering pushes the span's id onto the calling thread's stack; exiting pops it from the calling thread's stack. ## What an `.await` does to the guard An `async fn` compiles to a state machine. When it reaches an `.await` on a future that is not ready, it returns `Poll::Pending` to the executor and keeps its local variables stored inside the future. **Yielding is not dropping**: the `Entered` guard is still alive, so the span is never exited. The tracing documentation spells it out: another task begins executing while remaining in the entered span, which produces an incorrect trace. ```rust async fn charge_wrong(order_id: u64) { let span = info_span!("charge", order_id); let _guard = span.enter(); // held across the .await below tokio::time::sleep(Duration::from_millis(20)).await; info!("charge done"); } ``` Joined with a heartbeat future on a current-thread runtime, the heartbeat's event is reported inside `charge`: ```plaintext INFO charge{order_id=1}: heartbeat INFO charge{order_id=1}: charge done ``` On a **multi-threaded** runtime it gets worse. The handler can resume on a different worker, and the guard's exit then runs on a thread whose span stack does not contain that span. The registry finds nothing to pop there, while the first worker still has the span marked as entered, so later work on that worker is attributed to it as well. ## The three correct tools | Situation | Use | Why it is correct | |---|---|---| | A whole async function | `#[instrument]` on the `async fn` | generates `Instrument::instrument` around the body | | An async block or a call site | `fut.instrument(span).await` | enters on every poll, exits on every yield | | A synchronous section inside async code | `span.in_scope(\|\| ...)` | the closure returns before the next `.await` | `Instrument` is a trait in `tracing` (`use tracing::Instrument;`) implemented for every type, so any future gains `.instrument(span)`. The wrapper, an `Instrumented<T>` future, owns the span and does three things on every poll: - it calls `span.enter()` before polling the inner future; - it polls the inner future once; - it drops the guard before returning, whether the result is `Ready` or `Pending`. The span is therefore current exactly while this future's code runs, on whichever thread polls it, and never while the executor runs something else. Rewritten that way, the heartbeat is no longer inside the span: ```plaintext INFO heartbeat INFO charge{order_id=2}: charge done ``` ## Why the compiler does not stop you `Entered<'a>` only borrows the `Span`, and `Span` is `Send` and `Sync`, so a future holding `Entered` across `.await` is still `Send` and `tokio::spawn` accepts it. The bug is a **silent tracing error**, not a build failure. The owned variant, `span.entered()`, returns an `EnteredSpan` that the crate deliberately makes `!Send`, so the same code with `.entered()` fails at `tokio::spawn` with "future cannot be sent between threads safely". Why a non-`Send` value held across `.await` makes the future non-`Send` is covered with Send futures and spawning. ## Finding it in a codebase 1. Search async code for `.enter()` and `.entered()` bound to a local that lives past an `.await`. 2. Replace the pattern with `#[instrument]`, `.instrument(span)` or `in_scope`. 3. Read a trace where two requests run concurrently on one worker: a request's span should contain only its own events. 4. Make the rule a review item, because neither rustc nor the subscriber reports the mistake. ## Common mistakes - Believing the span is exited automatically at each `.await`; only `Instrument` does that. - Using `.entered()` to work around it; the guard still lives across the `.await`, and now the future is not `Send`. - Instrumenting only the outer handler while inner spawned tasks lose their context: `tokio::spawn(fut.instrument(Span::current()))` carries it across.

  • A request handler spawns a background task with `tokio::spawn`, and the task's events lose the request's span. How do you carry it over?
    A spawned task is polled independently, so it does not inherit whatever span was current where it was spawned. Attach one explicitly: `tokio::spawn(work().instrument(tracing::Span::current()))`, or create a child span with `info_span!(...)` inside the handler and pass it to `.instrument`. The task then enters that span on every poll, wherever it runs.
  • Is `span.in_scope(|| ...)` safe inside an `async fn`, and when would you use it instead of `.instrument`?
    Yes, as long as the closure is synchronous. `in_scope` enters the span, runs the closure and exits before returning, so the span can never be held across an `.await`. Use it for a CPU-bound step inside an async handler, such as building a signature, when you want that step in its own span without wrapping a future.

Holding the guard across an .await is like leaving your name badge on a shared desk when you step out: whoever sits down next works under your name until you come back for it.

  • An .await drops the Entered guard, so the span exits on its own.
  • Holding span.enter() across .await fails to compile under tokio::spawn.
  • Switching to span.entered() fixes the problem in async code.
  • Wrong spans in async traces mean the subscriber is buggy.
  • Instrument::instrument enters the span once and keeps it until the future is dropped.