HTTP Latency Fields
Learn where the latency field in TraceLayer logs comes from, what unit it uses, and how to change it with LatencyUnit
The latency field is the number on the finished line that says how long a request took. It looks small, latency=0 ms or latency=151 ms, but it carries the answer to the first question anyone asks when a server feels slow: how long did the request take, and where did the time go. This page explains what the number measures, what unit it is printed in, how to change that unit, and how it differs from the other duration on the log lines, the stream duration.
Where This Fits
Every request that TraceLayer logs produces a finished line, and every finished line ends with two fields, a latency and a status. The latency is the duration of the request itself, from arrival to response. The status says what the response was. The two fields sit side by side because they answer the two halves of the same question: how long, and with what result. This page takes the first half apart.
The Smallest Working Version
Here is the smallest server that makes the latency field visible. It has two routes: a fast one and a slow one that waits 150 milliseconds before answering. The wait is deliberate. It makes the latency grow by a known amount, so you can see the field change.
[package]
name = "latency_demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tower-http = { version = "=0.7.1", features = ["trace"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
use axum::{routing::get, Router};
use std::time::Duration;
use tower_http::trace::TraceLayer;
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();
let app = Router::new()
.route("/", get(hello))
.route("/slow", get(slow))
.layer(TraceLayer::new_for_http());
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("server listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
async fn hello() -> &'static str {
tracing::info!("hello handler was reached");
"Hello, world!"
}
async fn slow() -> &'static str {
tokio::time::sleep(Duration::from_millis(150)).await;
"Slow response"
}
Run the server with cargo run, then request both routes.
curl http://127.0.0.1:3000/
curl http://127.0.0.1:3000/slow
The finished lines look like this, verified by running the program. Timestamps and colour codes are left out here for readability.
DEBUG request{method=GET uri=/ version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=200
DEBUG request{method=GET uri=/slow version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=151 ms status=200
The fast route shows latency=0 ms. The slow route shows latency=151 ms. The handler waited 150 milliseconds, and the measured latency is 151 milliseconds, which is the wait plus about a millisecond of work around it. The number is doing what it promises. It measures the request, and a slower handler makes it grow.
A growing latency means the measurement works:
If the slow route shows a latency near 150 milliseconds while the fast route shows 0 ms, the latency field is working. The exact number varies by a millisecond or two from run to run, because real timing is never exact. What matters is the size of the number, not its last digit.
What the Number Measures
The latency is measured from the moment the request reaches TraceLayer until the moment the handler has produced a response. In the layer source, the clock starts when the layer receives the request, and the elapsed time is read when the response future completes. That interval includes everything the request passes through inside the layer: the routing, the handler, and any middleware that sits inside TraceLayer. It does not include the time the client spent sending the request, and it does not include the time the response body spends travelling to the client after the response was produced.
That last point is the one beginners get wrong most often. The finished line appears when the response exists, not when the client has finished reading it. A handler that returns a large streamed body can show a small latency, because producing the response was fast, while the body keeps flowing for much longer afterwards. The time the body spends flowing is measured separately, by the stream_duration field on the end of stream line. The two numbers answer two different questions, and the streamed example below shows them side by side.
Think of the latency as the time the kitchen takes to put the plate together, and the stream duration as the time the waiter takes to carry it to the table and back. Both matter, but they measure different work, and a slow waiter does not mean a slow kitchen.
The Default Unit Is Milliseconds
The default latency unit is milliseconds, and the value is printed as a whole number of milliseconds. That has a consequence that surprises beginners: anything faster than one millisecond prints as 0 ms. A fast handler that takes 334 microseconds shows latency=0 ms, which looks like the request took no time at all. It did not. It took less than a millisecond, and the default unit is too coarse to show it. The value is truncated, not rounded. A latency of 1.9 milliseconds prints as 1 ms, not 2 ms.
The unit and the truncation both come from the way the layer formats the duration. The default DefaultOnResponse uses LatencyUnit::Millis, and the millisecond form prints the duration as a whole count of milliseconds. The other units have their own formats, and the next section shows each one with real output from the same slow handler, so you can see the same duration printed four ways.
Changing the Unit with LatencyUnit
LatencyUnit is an enum with four variants: Seconds, Millis, Micros, and Nanos. It lives at the top of the tower_http crate, not inside the trace module, so the import path is tower_http::LatencyUnit. You set it on DefaultOnResponse with the latency_unit method. The default is Millis.
| Unit | Variant | How the same 151 millisecond request prints |
|---|---|---|
| Seconds | LatencyUnit::Seconds | latency=0.151091765 s |
| Milliseconds | LatencyUnit::Millis | latency=151 ms |
| Microseconds | LatencyUnit::Micros | latency=151089 us |
| Nanoseconds | LatencyUnit::Nanos | latency=151010672 ns |
All four rows were verified by running the same slow handler with each unit in turn. The numbers differ slightly between runs, because real timing varies, but the shape of each unit is exact. Seconds print as a decimal number with an s after it. Milliseconds print as a whole number with ms. Microseconds print as a whole number with us after it. Nanoseconds print as a whole number with ns.
The pages write us where your terminal prints a Greek letter:
On a real terminal, microseconds print with the Greek letter mu before the s. These pages write us instead, so the text stays plain ASCII. When you run the examples yourself, expect to see the mu symbol where the page shows us. The number is the same either way.
Here is the microseconds version, with the level raised to INFO so the finished line is visible even with a plain subscriber. Drop this layer into the basic example in place of the plain TraceLayer::new_for_http() line.
use tower_http::{
trace::{DefaultOnResponse, TraceLayer},
LatencyUnit,
};
use tracing::Level;
let trace_layer = TraceLayer::new_for_http().on_response(
DefaultOnResponse::new()
.level(Level::INFO)
.latency_unit(LatencyUnit::Micros),
);
Request / and /slow with this layer, and the finished lines read like this, verified by running the program.
INFO request{method=GET uri=/ version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=334 us status=200
INFO request{method=GET uri=/slow version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=151089 us status=200
The fast request, which printed as 0 ms in the default unit, now prints as 334 us. The duration did not change. Only the ruler changed. That is the whole point of the unit setting. Milliseconds hide fast requests behind a zero, and microseconds show them.
The seconds version makes the opposite trade. It prints the slow request as 0.151091765 s, a decimal with nine digits after the point. That is precise, but it is hard to scan by eye, and a fast request prints as a small decimal like 0.000334 s, which is harder to read than 334 us. Seconds suit a system where most requests take seconds, not one where most take milliseconds.
A practical rule follows from the four shapes. Use milliseconds for ordinary web handlers, where most requests take a few milliseconds and the numbers stay short. Use microseconds when you are hunting a fast-path problem and the millisecond zero hides what you need. Use nanoseconds only for short experiments, because the numbers get long and hard to compare. Use seconds when the work genuinely takes seconds, such as a handler that waits on a slow external service. Pick the unit that makes the numbers you actually see easy to read, not the unit that sounds most precise.
The unit changes the printing, not the measurement:
Changing the latency unit does not change how long the request takes or how the duration is measured. The layer still measures the same interval with the same clock. Only the printed form changes. A request that took 151 milliseconds still took 151 milliseconds when it is printed as 151089 us.
The Response Unit and the Stream Unit Are Separate
Changing the unit on DefaultOnResponse changes only the latency field on the finished line. It does not change the stream_duration field on the end of stream line. That field has its own setting, on DefaultOnEos, and its own default of milliseconds. This was verified by running a server with the response unit set to microseconds: the finished line printed latency=151089 us while the end of stream line still printed stream_duration=0 ms.
To change the stream duration unit as well, set it on DefaultOnEos.
use tower_http::{
trace::{DefaultOnEos, TraceLayer},
LatencyUnit,
};
let trace_layer = TraceLayer::new_for_http()
.on_eos(DefaultOnEos::new().latency_unit(LatencyUnit::Micros));
With this layer, a streamed response that takes about 300 milliseconds to deliver its body prints an end of stream line like this, verified by running the program.
DEBUG request{method=GET uri=/stream version=HTTP/1.1}: tower_http::trace::on_eos: end of stream stream_duration=304490 us
The finished line for the same request still prints latency=0 ms, because its unit was not changed. The two units are independent settings on two independent callbacks, and changing one never changes the other. If both lines show the unit you want, both settings were changed. If only one line changed, the other setting is still at its default.
Latency and Stream Duration Side by Side
The clearest way to see the two durations apart is a streamed response. The handler returns at once, so the latency is near zero, and the body arrives in pieces over time, so the stream duration grows. Here is a handler that sends three chunks, with a 100 millisecond pause before each one. It uses tokio-stream, which needs its own dependency entry.
use axum::{
body::Body,
response::IntoResponse,
routing::get,
Router,
};
use std::time::Duration;
use tower_http::trace::TraceLayer;
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();
let app = Router::new()
.route("/stream", get(stream))
.layer(TraceLayer::new_for_http());
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn stream() -> impl IntoResponse {
use tokio_stream::StreamExt;
let chunks = vec!["chunk-one-", "chunk-two-", "chunk-three"];
let s = tokio_stream::iter(chunks).then(|chunk| async move {
tokio::time::sleep(Duration::from_millis(100)).await;
Ok::<_, std::io::Error>(axum::body::Bytes::from(chunk))
});
Body::from_stream(s)
}
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tokio-stream = "0.1"
tower-http = { version = "=0.7.1", features = ["trace"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
Request /stream with curl, which reads the whole body, and the two lines for that request look like this, verified by running the program.
DEBUG request{method=GET uri=/stream version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=200
DEBUG request{method=GET uri=/stream version=HTTP/1.1}: tower_http::trace::on_eos: end of stream stream_duration=302 ms
The latency is 0 ms, because the handler produced the response immediately. The stream duration is 302 ms, because the three chunks took about 100 milliseconds each to arrive. If you only watched the latency, you would think the request was instant. If you only watched the stream duration, you would think the handler was slow. Both numbers are correct, and they measure different intervals. A slow finished line points at the handler. A fast finished line with a slow end of stream line points at the body, the network, or a client that reads slowly.
There is one more thing to know about the end of stream line. It is driven by the body being read to its end. In a live run, responses with an empty body, such as a handler that returns only a status code with no body text, produced no end of stream line at all even after waiting several seconds. The body was never read through the layer, so the end of the stream was never observed. A response with a real body always produced the line.
Reading the Latency Inside a Custom on_response
The default on_response prints the latency in the unit you chose. A custom on_response closure receives the same duration as a plain std::time::Duration, and you can print it however you like. The closure form is the right choice when the message itself needs to change, for example when you want to log different levels for success and failure. For latency, the closure is useful when you want the full precision of the duration instead of the rounded unit form.
use axum::{routing::get, Router};
use std::time::Duration;
use tower_http::trace::TraceLayer;
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();
let trace_layer = TraceLayer::new_for_http().on_response(
|response: &axum::response::Response,
latency: Duration,
_span: &tracing::Span| {
tracing::info!(
"completed with status {} in {:?}",
response.status(),
latency
);
},
);
let app = Router::new()
.route("/", get(hello))
.route("/slow", get(slow))
.layer(trace_layer);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn hello() -> &'static str {
tracing::info!("hello handler was reached");
"Hello, world!"
}
async fn slow() -> &'static str {
tokio::time::sleep(Duration::from_millis(150)).await;
"Slow response"
}
Request /slow and the custom line reads like this, verified by running the program.
INFO request{method=GET uri=/slow version=HTTP/1.1}: completed with status 200 OK in 151.925756ms
The {:?} formatting is the Debug form of Duration, and it prints the duration with its natural unit and full precision, 151.925756ms for the slow request and 245.408us for the fast one. Compare that with the default millisecond form, which printed the same fast request as 0 ms. The Debug form never hides a fast request behind a zero, which makes it a good choice for a custom log line, and a bad choice for a dashboard, where a fixed unit is easier to graph.
One warning applies to every custom on_response closure. Replacing on_response replaces the default finished line entirely. The closure above prints its own line instead, so nothing is lost, but a closure that only records a value and prints nothing will make the finished line disappear. If the finished line vanishes after you add a custom callback, the callback replaced the default instead of adding to it.
Per-Chunk Latency with on_body_chunk
The on_body_chunk callback fires each time a piece of the response body is sent, and it receives the time since the response was sent or since the last chunk. Its default does nothing, so a normal response produces no per-chunk lines unless you add a callback yourself. The example below adds one, using the same streamed handler as above.
use axum::{
body::Body,
response::IntoResponse,
routing::get,
Router,
};
use std::time::Duration;
use tower_http::trace::TraceLayer;
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();
let trace_layer = TraceLayer::new_for_http().on_body_chunk(
|chunk: &bytes::Bytes, latency: Duration, _span: &tracing::Span| {
tracing::info!("sent a body chunk of {} bytes after {:?}", chunk.len(), latency);
},
);
let app = Router::new()
.route("/stream", get(stream))
.layer(trace_layer);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn stream() -> impl IntoResponse {
use tokio_stream::StreamExt;
let chunks = vec!["chunk-one-", "chunk-two-", "chunk-three"];
let s = tokio_stream::iter(chunks).then(|chunk| async move {
tokio::time::sleep(Duration::from_millis(100)).await;
Ok::<_, std::io::Error>(axum::body::Bytes::from(chunk))
});
Body::from_stream(s)
}
The stream handler and the Cargo.toml are the same as in the streamed example above, with tokio-stream as a dependency. Request /stream and the terminal shows one line per chunk, verified by running the program.
INFO request{method=GET uri=/stream version=HTTP/1.1}: sent a body chunk of 10 bytes after 101.956907ms
INFO request{method=GET uri=/stream version=HTTP/1.1}: sent a body chunk of 10 bytes after 101.762054ms
INFO request{method=GET uri=/stream version=HTTP/1.1}: sent a body chunk of 11 bytes after 101.828074ms
DEBUG request{method=GET uri=/stream version=HTTP/1.1}: tower_http::trace::on_eos: end of stream stream_duration=305 ms
Each chunk line shows about 101 milliseconds, not a growing total. The latency passed to on_body_chunk is the time since the last chunk, or since the response was sent for the first chunk. Three chunks at 100 millisecond intervals produce three lines near 100 milliseconds each, and the stream duration at the end is the sum, about 305 milliseconds. That per-chunk timing is what makes this callback useful for finding a stall in the middle of a stream. If one chunk line shows a much larger gap than the others, the pause happened between those two chunks.
Per-chunk lines multiply quickly:
A streamed response with many chunks produces one log line per chunk. A file download split into thousands of chunks would produce thousands of lines, which can flood the logs and hide everything else. Use a per-chunk callback only while debugging a specific stream, and remove it or raise its level before the code reaches production.
How the Two Durations Flow
The full timing picture for one streamed request looks like this, in order.
Request arrives, clock starts for latency
|
v
Handler runs, latency keeps counting
|
v
Handler returns a response, latency stops, finished line prints
|
v
Response body streams, stream clock starts, on_body_chunk fires per chunk
|
v
Body stream ends, stream_duration stops, end of stream line prints
The latency clock and the stream clock are separate timers with separate start points. The latency clock starts when the layer receives the request and stops when the response is produced. The stream clock starts when the response is sent and stops when the body ends. A request with a fast handler and a slow body shows a small latency and a large stream duration. A request with a slow handler and a fast body shows the reverse. Reading the two numbers together tells you which half of the request was slow.
Testing It
Testing latency means testing that the routes answer correctly with the layer applied, including the slow route. Log text itself is not asserted, because log lines depend on timing, and asserting on a timing value makes tests flaky. The test below sends mock requests directly through the router, with no network connection, using tower::ServiceExt::oneshot. It needs tower as a dev dependency with the util feature.
use axum::{
body::Body,
http::{Request, StatusCode},
routing::get,
Router,
};
use std::time::Duration;
use tower::ServiceExt;
use tower_http::trace::TraceLayer;
fn app() -> Router {
Router::new()
.route("/", get(|| async { "Hello, world!" }))
.route("/slow", get(slow))
.layer(TraceLayer::new_for_http())
}
async fn slow() -> &'static str {
tokio::time::sleep(Duration::from_millis(150)).await;
"Slow response"
}
#[tokio::test]
async fn home_returns_ok() {
let response = app()
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn slow_route_returns_ok() {
let response = app()
.oneshot(
Request::builder()
.uri("/slow")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Run the tests with cargo test. The equivalent tests passed in the scratch project used to verify this page. The tests prove the layer does not change what the routes return. The latency values themselves are checked by eye, by running the server and curling it, which is how every output block on this page was produced. If you want a test that checks timing, assert on the handler behaviour, such as the sleep, rather than on the log line, because the log line format is owned by the layer and can change between versions.
Common Beginner Mistakes
Reading 0 ms as instant
A fast request prints latency=0 ms in the default unit, and beginners often read that as proof the request took no time. It took less than a millisecond. Switch the unit to microseconds to see the real value, or use a custom on_response closure with {:?} formatting. The zero is a property of the ruler, not of the request.
Changing one unit and expecting both to change
The response unit and the end of stream unit are separate settings. Setting latency_unit on DefaultOnResponse leaves stream_duration in milliseconds, and setting it on DefaultOnEos leaves latency in milliseconds. If one line changed and the other did not, the unchanged line still has its default setting. Change both when you want both in the same unit.
Measuring latency by hand in the handler
It is tempting to start a timer at the top of the handler and log the elapsed time at the bottom. That measures the handler only, and it misses the routing and any middleware inside the layer. It also duplicates what the layer already measures. Use the layer latency for the request, and use a hand timer only for a specific piece of work inside the handler, such as a database call, where the layer cannot see the boundary.
Using seconds for fast endpoints
Seconds print as a decimal with many digits, such as 0.000334 s for a fast request. That is precise, but it is hard to scan, and comparing two such numbers by eye is slow work. Pick the unit that makes the numbers you actually see easy to read. For most web handlers that is milliseconds, and for fast-path work it is microseconds.
Leaving a per-chunk callback in production
A per-chunk callback that logs at INFO level turns every streamed response into a flood of lines. That flood can hide the lines that matter, and it can fill log storage quickly. Keep per-chunk logging at DEBUG level, or remove the callback once the stream problem is understood.
A custom on_response replaces the finished line:
Replacing on_response with a closure removes the default finished line, including its latency and status fields. A closure that only records a value and prints nothing leaves no finished line at all. If the finished line disappears after you add a custom callback, add a log call inside the closure, or delegate to DefaultOnResponse after doing your own work.
Final Complete Example
Here is everything from this page put together. One server, a slow route, a streamed route, microseconds on the finished line, and microseconds on the end of stream line.
use axum::{
body::Body,
response::IntoResponse,
routing::get,
Router,
};
use std::time::Duration;
use tower_http::{
trace::{DefaultOnEos, DefaultOnResponse, TraceLayer},
LatencyUnit,
};
use tracing::Level;
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();
let trace_layer = TraceLayer::new_for_http()
.on_response(
DefaultOnResponse::new()
.level(Level::INFO)
.latency_unit(LatencyUnit::Micros),
)
.on_eos(DefaultOnEos::new().latency_unit(LatencyUnit::Micros));
let app = Router::new()
.route("/", get(hello))
.route("/slow", get(slow))
.route("/stream", get(stream))
.layer(trace_layer);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("server listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
async fn hello() -> &'static str {
tracing::info!("hello handler was reached");
"Hello, world!"
}
async fn slow() -> &'static str {
tokio::time::sleep(Duration::from_millis(150)).await;
"Slow response"
}
async fn stream() -> impl IntoResponse {
use tokio_stream::StreamExt;
let chunks = vec!["chunk-one-", "chunk-two-", "chunk-three"];
let s = tokio_stream::iter(chunks).then(|chunk| async move {
tokio::time::sleep(Duration::from_millis(100)).await;
Ok::<_, std::io::Error>(axum::body::Bytes::from(chunk))
});
Body::from_stream(s)
}
[package]
name = "latency_demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tokio-stream = "0.1"
tower-http = { version = "=0.7.1", features = ["trace"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
Run it with cargo run, then request the routes.
curl http://127.0.0.1:3000/
curl http://127.0.0.1:3000/slow
curl http://127.0.0.1:3000/stream
The fast route shows a finished line in microseconds, so it no longer hides behind 0 ms. The slow route shows a latency near 151000 microseconds. The streamed route shows a small latency and a stream duration near 300000 microseconds. Each number now uses the same ruler, and the two clocks can be compared directly.
Summary
The latency field answers one question, how long the request took, and the decision framework for reading it has three parts. First, know which clock produced the number. The finished line latency runs from arrival to response, and the end of stream duration runs from response to the end of the body. Second, pick the unit that fits the numbers you see. Milliseconds hide fast requests behind a zero, microseconds show them, and seconds suit work that genuinely takes seconds. Third, remember that the two durations have separate settings. Changing the response unit never changes the stream unit, and a custom callback that replaces the finished line takes the latency field with it unless the callback prints its own line. Read the two numbers together, in a unit that fits, and a slow request tells you which half of its life was slow.