RequestId Correlation Layer in Axum
Learn how to give every request a correlation id with tower-http SetRequestIdLayer and PropagateRequestIdLayer, read it in a handler, generate custom ids, and avoid the ordering trap that silently drops generated ids
What a request id is
A request id is a short unique label attached to one single request. The server gives the label to the request when it arrives, carries it through everything that happens while handling that request, and sends it back to the client on the response. The label itself means nothing. It is not a user id, not a timestamp, and not a secret. Its only job is to connect things that belong together.
The problem it solves shows up the moment a server handles more than one request at a time. Logs from hundreds of requests mix together in one stream. A client reports an error and pastes a line from its own log. Without a shared label, there is no way to find the matching lines in the server log, because nothing in the two logs is the same. With a request id, the client log line, the server log lines, and the log lines of any service further down the chain all carry the same string. Finding the full story of one request becomes a search for one string.
Think of the id as a luggage tag. A bag passes through check-in, loading, and delivery, and the tag stays on it at every step. Nobody needs to know what is inside the bag to follow it. A request id works the same way. It stays attached to the request from arrival to response, and every log line written along the way can carry it.
This page follows one id on its whole journey. A layer generates the id and puts it on the request. The handler reads it. Another layer copies it onto the response. The client receives it and can quote it back when something goes wrong.
There is no RequestIdLayer:
There is no type called RequestIdLayer in tower-http 0.7. If you write that name, the compiler reports that it does not exist. The work is split across two layers, SetRequestIdLayer and PropagateRequestIdLayer, and the value they pass around is called RequestId. This page uses those exact names throughout.
The journey of one id
One request, four steps. The order matters, and the rest of this page is an explanation of each step.
client sends a request
-> SetRequestIdLayer makes sure an id exists, and puts it on the request
-> the handler runs, and can read the id
-> PropagateRequestIdLayer copies the id onto the response
client receives the response, with the id in a header
The first layer is the setter. It looks at the incoming request. If the request already carries an id in its header, the setter keeps it. If it does not, the setter generates a fresh one. Either way, after the setter runs, the request has an id, and the id is stored in two places: in a request header, so it can travel over the network, and in the request extensions, so Rust code inside the server can read it as a typed value.
The handler sits in the middle. It does its normal work, and whenever it writes a log line it can include the id. It can also pass the id onward when it calls another service, so the chain continues past this server instead of ending here.
The last layer is the propagator. It runs after the handler, on the way out. It reads the id from the request and writes it into a response header with the same name. The client then sees the id and can store it in its own logs.
A beginner mistake is to think of these as two names for one job. They are not. The setter guarantees an id exists. The propagator makes the id visible to the client. A server with only the setter has ids in its own logs but never tells the client what they are. A server with only the propagator echoes ids the client sent, but generates nothing when the client sends none, so most responses carry no id at all. The pair together is what makes the system work.
The two layers and the value type
Three names carry the whole feature. Each one has a single job.
SetRequestIdLayer makes sure the request has an id. It generates one when the request arrived without one, keeps the one the client sent when there is one, writes the id into a request header, and stores a RequestId value in the request extensions for handlers to read. It is the layer that guarantees an id exists.
PropagateRequestIdLayer copies the id from the request header onto the response header. It runs after the handler, so it sees the id the setter produced. It never invents an id. If the request had no id when the propagator ran, the response gets no id either.
RequestId is the value type both layers pass around. It is a thin wrapper around a header value, which is the http crate's type for the value of one HTTP header. It has three useful methods. RequestId::new(value) builds one from a header value. .header_value() borrows the header value inside it. .into_header_value() consumes it and returns the header value. A handler that wants the id as a string calls .header_value().to_str(), which turns the header value into a string slice.
The generator is a separate piece. MakeRequestUuid is the built-in generator, and it produces a random version 4 UUID, a 36-character string such as 5e3d27d8-226d-4c72-b105-f1dd69900ba8. A UUID is a standard format for random identifiers, and a version 4 UUID is made almost entirely of random bits, so two requests practically never receive the same one. Anything else is a custom generator, which this page builds later.
All of this lives in the tower_http::request_id module. It is behind a feature flag, a named switch in a crate that turns a piece of functionality on or off. The flag here is called request-id. Without it, the module does not exist and the import fails. The next section shows the project setup that turns it on.
Without the request-id feature the module does not exist:
If the import tower_http::request_id::... fails with an unresolved import error, the cause is almost always a missing feature flag, not a typo. Add "request-id" to the tower-http features in Cargo.toml. The same rule applies to every tower-http module: each one needs its own feature flag.
Setting up the project
Every example on this page runs in the same small project. Create it with cargo new request-id-demo and replace the generated Cargo.toml with this one.
[package]
name = "request-id-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower = { version = "0.5", features = ["util"] }
tower-http = { version = "0.7", features = ["request-id", "trace", "util"] }
tracing = "0.1"
tracing-subscriber = "0.3"
The versions here are axum 0.8.9, tokio 1.54.1, tower 0.5.3, and tower-http 0.7.1. The version strings in the file are ranges, so Cargo picks the newest release inside each range. The tower feature util turns on ServiceBuilder, the helper used to stack layers in the examples below. The tower-http feature request-id turns on the request id module, and util turns on the one-line builder methods shown near the end of the page. The trace feature and the tracing and tracing-subscriber dependencies are only needed for the logging section near the end of the page, where the id is shown in the server logs.
Run the server with cargo run and keep it running in a terminal while you send requests with curl from another terminal. curl is a command line tool for sending HTTP requests. The -i flag tells it to print the response headers as well as the body, which is what you want here, because the id travels in a header.
The smallest working example
This is the whole feature in its simplest form. Two layers, one handler, one route. The handler answers with the id it saw, so a single curl request shows the id in three places at once: the response header, the response body, and, if the handler logged it, the server log.
use axum::{extract::Extension, routing::get, Router};
use tower::ServiceBuilder;
use tower_http::request_id::{
MakeRequestUuid, PropagateRequestIdLayer, RequestId, SetRequestIdLayer,
};
async fn echo_id(Extension(id): Extension<RequestId>) -> String {
id.header_value().to_str().unwrap().to_string()
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(echo_id))
.layer(
ServiceBuilder::new()
.layer(SetRequestIdLayer::x_request_id(MakeRequestUuid))
.layer(PropagateRequestIdLayer::x_request_id()),
);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The handler takes Extension<RequestId> as its argument. Extension is an axum extractor, a type a handler declares as a parameter so axum pulls a value out of the request for it. Here it pulls the RequestId the setter stored in the request extensions. The handler turns the id into a string and returns it as the response body.
The router stacks the two layers with ServiceBuilder. In a builder, the first layer listed runs first, so the setter runs before the propagator. That order is not a style choice. It is the rule the whole feature depends on, and a later section shows what breaks when it is reversed.
The two constructors with x_request_id in their names are shortcuts for the header x-request-id. That header name is a widely used convention for request ids, and using it means clients, proxies, and other services already know where to look. For any other header name, the general constructors take the name as an argument, as shown in the custom header section below.
Start the server and send a request with no id header:
$ curl -i http://localhost:3000/
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
x-request-id: 91c29727-b13b-4c89-870c-98441c3cf92f
content-length: 36
date: Fri, 13 Nov 2026 03:32:01 GMT
91c29727-b13b-4c89-870c-98441c3cf92f
The response header x-request-id and the response body carry the same string. The client sent no id, so the setter generated one, the handler read it and returned it, and the propagator copied it onto the response. Run the request again and the id is different, because the generator produces a fresh random UUID for every request.
How to tell the pair is working:
Send a request with no x-request-id header. If the response comes back with an x-request-id header, and the body contains the same string as that header, the setter and the propagator are both running, in the right order. If the header is missing but the body still contains an id, the setter works and the propagator is either absent or running in the wrong order.
Reading the id in a handler
The handler in the smallest example reads the id with Extension<RequestId>. That is the intended way to read it, and it works because the setter stores the RequestId in the request extensions before the handler runs. Extensions are a map on the request where middleware can store typed values for later code to pick up by type. Extension<RequestId> asks for the value stored under the type RequestId, and there is exactly one such value per request.
The id is also present in the request headers, so a handler could read it from there instead, with a header map lookup. Prefer the typed value. A header lookup returns a raw header value and can be confused with another header if the name ever changes. The typed value keeps working if the header name changes, because the setter stores the same RequestId no matter which header name it writes.
If no setter ran for a route, the extension is absent, and Extension<RequestId> rejects the request with a 500 status. A 500 here means the server failed to handle the request because of its own setup, not because of anything the client did. That failure is loud, which is good: it points straight at a route that is missing the layer. When the id is genuinely optional for a route, use Option<Extension<RequestId>> instead. The Option form gives None when the extension is absent, and the handler can carry on without an id.
async fn maybe_id(maybe: Option<Extension<RequestId>>) -> String {
match maybe {
Some(Extension(id)) => id.header_value().to_str().unwrap().to_string(),
None => "no request id".to_string(),
}
}
This handler answers with the id when one exists and with the words no request id when none does. In practice, when the setter is attached to the whole router, every route has an id and the plain Extension<RequestId> form is the right one. Reach for the Option form only for routes that deliberately run without the setter.
One more detail about the value itself. RequestId::new takes a header value, and RequestId also implements From<HeaderValue>, so a plain header value converts into a RequestId with .into(). Handlers rarely need either constructor, because the setter builds the value. They matter when writing a custom generator, which is where they appear next.
When the client already sends an id
Neither layer ever overwrites an id that is already there. Send a request with your own id and the server keeps it end to end.
$ curl -i -H "x-request-id: client-123" http://localhost:3000/
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
x-request-id: client-123
content-length: 10
date: Fri, 13 Nov 2026 03:32:01 GMT
client-123
The handler saw client-123 and the response carried client-123. No UUID was generated, because none was needed. The rule holds on both sides. The setter does not replace a request header that already exists, and the propagator does not replace a response header that already exists. The layers fill gaps. They do not take over.
This matters because in real systems your server is rarely the first to touch a request. A gateway or a load balancer upstream often assigns an id before the request reaches your code. A load balancer is a service that spreads incoming requests across several servers. When it assigns the id, your server joins the existing chain instead of starting a new one. Every service the request visits after yours sees the same id, and the logs line up across all of them.
The same idea applies in the other direction. When your handler calls another service, it should send the same id on the outgoing request. Read the id from Extension<RequestId>, turn it into a header value, and set it as the x-request-id header on the call you make. A chain that stops at the first service cannot explain a failure in the second one, and the fix is one header on the outgoing request.
Do not put meaningful data in the id:
The id is an opaque correlator, a label with no meaning of its own. Do not encode a user id, a timestamp, or a sequence number into it. Anything meaningful belongs in its own header or in the handler logs. A client that can read meaning out of your ids can also guess other requests' ids, and an id that carries meaning stops being a safe label to print in every log line.
Using a different header name
The x-request-id name is a convention, not a rule. Some teams use x-trace-id, x-correlation-id, or a name their gateway already uses. The general constructors take the header name as an argument, so any name works. A header name is the HeaderName type, and HeaderName::from_static builds one from a string written directly in the code.
use axum::http::HeaderName;
use tower_http::request_id::{PropagateRequestIdLayer, SetRequestIdLayer};
use tower_http::request_id::MakeRequestUuid;
let x_trace = HeaderName::from_static("x-trace-id");
let app = Router::new()
.route("/", get(echo_id))
.layer(
ServiceBuilder::new()
.layer(SetRequestIdLayer::new(x_trace.clone(), MakeRequestUuid))
.layer(PropagateRequestIdLayer::new(x_trace)),
);
This is the same stack as the smallest example, with only the name changed. The setter writes x-trace-id on the request, the handler still reads the id from Extension<RequestId>, and the propagator copies x-trace-id onto the response. The handler code does not change at all, because the typed value it reads is the same no matter which header carries it. That is the practical payoff of reading the typed value instead of the header: renaming the header is a one-line change in the layer setup, not a hunt through every handler.
The name is cloned when it is passed to the setter, because the propagator needs the same name and each layer owns its copy. HeaderName is cheap to clone, and cloning it here is the normal pattern. A header name written with capital letters, spaces, or other characters that are not allowed in a header name makes from_static panic at startup. That failure is loud and early, which is what you want: a typo in a header name should break the program before it serves its first request, not silently produce a header nobody recognises.
Your own generator
The built-in generator produces random UUIDs. That is the right default for production, but sometimes a different id is more useful. In tests and local development, readable ids such as req-1 and req-2 are easier to follow than random strings. A gateway might require ids in a particular format. In each case, write your own generator by implementing the MakeRequestId trait, an interface with one method that turns a request into an id.
use axum::extract::Request;
pub trait MakeRequestId {
fn make_request_id<B>(&mut self, request: &Request<B>) -> Option<RequestId>;
}
The method receives the whole request, so the id can be derived from anything on it: a header, a path, a counter. It returns Option<RequestId>, a value that is either Some(id) or None. Returning None means do not set an id for this request at all. The setter then leaves the request untouched.
Here is a counter generator. It hands out req-1, req-2, req-3, and so on, in the order requests arrive.
use axum::{extract::Request, routing::get, Router};
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
use tower::ServiceBuilder;
use tower_http::request_id::{
MakeRequestId, PropagateRequestIdLayer, RequestId, SetRequestIdLayer,
};
#[derive(Clone, Default)]
struct Counter {
n: Arc<AtomicUsize>,
}
impl MakeRequestId for Counter {
fn make_request_id<B>(&mut self, _request: &Request<B>) -> Option<RequestId> {
let n = self.n.fetch_add(1, Ordering::SeqCst) + 1;
Some(RequestId::new(format!("req-{n}").parse().unwrap()))
}
}
Arc is a shared pointer that lets several owners share one value, and AtomicUsize is a counter that can be safely incremented from several threads at once. The counter lives inside the Arc, so every copy of the generator shares the same count. That sharing is what makes the numbers keep increasing across requests instead of restarting at one each time. The generator is cloned whenever the layer is applied, and a plain number field would be copied with it, resetting the count. The Arc is the part that survives.
Pair the counter with the custom header name from the previous section:
use axum::http::HeaderName;
let x_trace = HeaderName::from_static("x-trace-id");
let app = Router::new()
.route("/", get(echo_id))
.layer(
ServiceBuilder::new()
.layer(SetRequestIdLayer::new(x_trace.clone(), Counter::default()))
.layer(PropagateRequestIdLayer::new(x_trace)),
);
Two requests in a row return x-trace-id: req-1 and then x-trace-id: req-2, with the same values in the response bodies. The count survives across requests because the shared counter lives in the layer, behind the Arc, and the layer is what axum keeps and reuses. A counter stored anywhere else would reset.
The method receives the request, so the id does not have to be blind. It can read a header the gateway sets and use that as the id, hash the path, or combine a prefix that is unique to this process with a counter, giving ids that are both readable and unique across restarts. The one responsibility the generator owns is uniqueness. A counter that resets when the process restarts repeats ids across restarts, and two requests with the same id in the logs are worse than no ids at all, because they join two unrelated stories into one. In production, use MakeRequestUuid, or mix something generated once at startup into the id. Save the plain counter for tests and local development, where restarts are frequent and the log is short.
A generator must be Clone:
SetRequestIdLayer requires its generator to be Clone, because the layer clones the generator each time it is applied. A generator that holds a plain counter or a plain socket will fail to compile when the layer tries to clone it. Put shared state behind an Arc, as the counter example does, and derive Clone on the struct. The compiler error for a missing Clone points at the .layer() call, not at the generator, which is why this mistake takes a while to track down.
The ordering trap
This is the one mistake that costs people an afternoon, because it fails silently. The propagator captures the id from the request headers at the moment it runs. If it runs before the setter has generated the id, there is nothing to capture, and the generated id never reaches the response. No error, no warning. The response simply has no x-request-id header.
In a ServiceBuilder, the first layer listed runs first, so the setter is listed first, exactly as in the smallest example:
ServiceBuilder::new()
.layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)) // runs first
.layer(PropagateRequestIdLayer::x_request_id()) // runs second
With chained .layer() calls, the same stack is written in reverse, because the last call is outermost and outermost runs first:
Router::new()
.route("/", get(echo_id))
.layer(PropagateRequestIdLayer::x_request_id()) // inner, runs second
.layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)); // outer, runs first
Writing .layer(Set).layer(Propagate) reads naturally and is wrong. It puts the propagator outermost, so the propagator runs first and drops every generated id. The trap is hard to spot because client-supplied ids still work in the wrong order. They were already on the request when the propagator ran, so they propagate fine. Everything looks correct until a client arrives that does not send an id, and that is exactly the client the feature exists for.
Here is the wrong order running live. A request with no id gets a body containing the generated id, because the setter did run and the handler did see it, but the response has no x-request-id header:
$ curl -i http://localhost:3000/
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
content-length: 36
date: Fri, 13 Nov 2026 03:32:04 GMT
6b1c384e-bc3b-4c47-8647-0f8beb9f10f4
The same server, given a client-supplied id, propagates it without any problem:
$ curl -i -H "x-request-id: client-123" http://localhost:3000/
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
x-request-id: client-123
content-length: 10
date: Fri, 13 Nov 2026 03:32:04 GMT
client-123
That split behaviour is the fingerprint of this bug. If responses are missing the id only for clients that do not send one, check the layer order first. If no response ever carries an id, the propagator is probably absent entirely. The fix in a builder is to list the setter first. The fix in a chain is to add the propagator first and the setter last, so the setter ends up outermost.
Wrong order fails silently and only for generated ids:
A propagator running before the setter drops every generated id with no error and no log line, while client-supplied ids keep working. That combination hides the bug in every test that sends its own id. Always test with a request that sends no id at all. That single request is the test that catches this mistake.
Seeing the id in logs
An id that only travels in headers is half the feature. Its value shows up when it appears in the server logs, next to the log lines for the same request. That takes a third layer, the tracing layer that logs each request and response, placed between the setter and the propagator.
use tower::ServiceBuilder;
use tower_http::{
request_id::{MakeRequestUuid, PropagateRequestIdLayer, SetRequestIdLayer},
trace::{DefaultMakeSpan, DefaultOnResponse, TraceLayer},
};
let app = Router::new()
.route("/", get(echo_id))
.layer(
ServiceBuilder::new()
.layer(SetRequestIdLayer::x_request_id(MakeRequestUuid))
.layer(
TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().include_headers(true))
.on_response(DefaultOnResponse::new().include_headers(true)),
)
.layer(PropagateRequestIdLayer::x_request_id()),
);
The order is setter, tracing layer, propagator, listed in that order in the builder. The setter runs first so the id exists before anything else touches the request. The tracing layer runs second, and it creates a span, a named unit of work in the tracing system that groups the log lines of one request together. With include_headers(true), the span records the request headers, so the id is in the log. The propagator runs last on the request, and on the way back the order reverses, so the propagator adds the header to the response before the tracing layer logs the response. That is why the response log line shows the id too.
The tracing layer logs at DEBUG level by default, and the standard log setup only shows INFO level and above, so the request lines would be invisible without one more line in the setup. The subscriber, the piece that receives log events and prints them, needs its maximum level raised to DEBUG:
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();
That call needs tracing-subscriber as a dependency. With it in place, a request carrying x-request-id: trace-test-1 produces log lines whose span carries the id in its headers, and whose response line carries it in the response headers:
DEBUG request{method=GET uri=/ version=HTTP/1.1 headers={"host": "127.0.0.1:3000", "user-agent": "curl/8.5.0", "accept": "*/*", "x-request-id": "trace-test-1"}}: tower_http::trace::on_request: started processing request
DEBUG request{method=GET uri=/ version=HTTP/1.1 headers={"host": "127.0.0.1:3000", "user-agent": "curl/8.5.0", "accept": "*/*", "x-request-id": "trace-test-1"}}: tower_http::trace::on_response: finished processing request latency=0 ms status=200 response_headers={"content-type": "text/plain; charset=utf-8", "x-request-id": "trace-test-1"}
The two lines share the same span, so they share the same x-request-id value in the headers. A reader searching the log for trace-test-1 finds both lines, and any line the handler writes inside that span joins them. Without include_headers(true), the span records the method and the path but no headers, and the id is nowhere in the log even though the feature is working. Without the DEBUG level, there are no request lines at all. Both settings are required for the id to show up.
Two settings hide the id from logs:
The tracing layer logs at DEBUG level, and its span records no headers unless include_headers(true) is set. Miss either one and the logs look exactly as if the request id feature were not installed, while the headers on the wire are fine. When the id is missing from the logs, check those two settings before touching the request id layers.
The one-line form
When the x-request-id header and the UUID generator are what you want, the two layers collapse into two method calls on the builder. They come from the ServiceBuilderExt trait, an extension that adds tower-http methods to ServiceBuilder, and they need the util feature flag, which is already in the project setup above.
use tower_http::{request_id::MakeRequestUuid, ServiceBuilderExt};
let app = Router::new()
.route("/", get(echo_id))
.layer(
ServiceBuilder::new()
.set_x_request_id(MakeRequestUuid)
.propagate_x_request_id(),
);
These two calls are exactly SetRequestIdLayer::x_request_id and PropagateRequestIdLayer::x_request_id: same behaviour, less typing. The order rule is the same. The setter call comes first, the propagator call second, because in a builder the first call runs first. The general forms take a header name, .set_request_id(header_name, generator) and .propagate_request_id(header_name), for the custom header case. Use the explicit layers when you need a custom generator that is not the UUID one, or when the code reads better with the layer names visible. Use the one-liners when the standard setup is all you need.
Echoing an id is not the same as guaranteeing one
A related layer, PropagateHeaderLayer from the tower_http::propagate_header module, copies a header from the request to the response without generating anything. It takes the header the client sent and echoes it, and does nothing at all when the client sent nothing. That is the right tool when the requirement is only to echo what the client sent. It is the wrong tool when the requirement is that every response carries an id, whether or not the client sent one. That requirement needs the setter plus the propagator from this page, because only the setter creates an id when none arrived. The difference is one sentence, and it decides which layer to reach for: echo what arrived, or guarantee one exists.
Common mistakes
Wrong order, propagator before setter. Generated ids vanish silently while client-supplied ids keep working. The setter runs first in a builder listing, and last in a chained .layer() sequence. Test with a request that sends no id.
Using the name RequestIdLayer. It does not exist in tower-http 0.7. The pair is SetRequestIdLayer plus PropagateRequestIdLayer, and RequestId is the value type.
Expecting the id on every response when the layers only wrap some routes. Layers attached to one route run only for that route. A request to another route, including one that matches nothing, never passes through them and gets no id. Attach the pair to the whole router when every response must carry an id.
A generator that is not unique. A counter that resets on every restart, a timestamp with second resolution, or a constant string all defeat the purpose. Two requests sharing an id join two unrelated stories in the logs. Use MakeRequestUuid in production.
Forgetting the request-id feature. Without it, the tower_http::request_id module does not exist and the import fails. The one-line builder methods additionally need the util feature.
Reading the id from the header instead of the extension. It works, until the header name changes and every handler needs editing. Extension<RequestId> is typed, it cannot be confused with another header, and it keeps working when the name changes.
Summary
The decision this page leaves behind is a short one. If the client sends an id, keep it. If it does not, generate one. Tell the client what it is, and write it in the logs. That is the whole contract, and the two layers split it cleanly: the setter guarantees the id exists, the propagator makes it visible, and the handler reads the typed value in between. The one rule that decides whether the system works or silently does nothing is the order the two layers run in, with the setter first. Everything else is a variation on that shape. A custom header renames the label. A custom generator changes how the label is made. A tracing layer in the middle puts the label in the logs. None of them changes the journey: generate, set, read, propagate, and the same string in the client log, the server log, and the response header.