Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(ai-gateway): correlate requests with a gateway request ID (#18052)

Hassieb Pakzad808032c0e5c8
diff --git a/ai-gateway/Cargo.lock b/ai-gateway/Cargo.lock
index 2fe11c7cdf..4e6c5e5eb0 100644
--- a/ai-gateway/Cargo.lock
+++ b/ai-gateway/Cargo.lock
@@ -47,6 +47,7 @@ dependencies = [
"tracing",
"tracing-opentelemetry",
"tracing-subscriber",
+ "uuid",
]
[[package]]
@@ -1911,6 +1912,17 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
+[[package]]
+name = "uuid"
+version = "1.26.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce"
+dependencies = [
+ "getrandom 0.4.3",
+ "js-sys",
+ "wasm-bindgen",
+]
+
[[package]]
name = "valuable"
version = "0.1.1"
diff --git a/ai-gateway/Cargo.toml b/ai-gateway/Cargo.toml
index de02744035..3a8edbc883 100644
--- a/ai-gateway/Cargo.toml
+++ b/ai-gateway/Cargo.toml
@@ -28,6 +28,7 @@ tower-http = { version = "0.7", features = ["trace"] }
tracing = "0.1.44"
tracing-opentelemetry = { version = "0.34", default-features = false }
tracing-subscriber = { version = "0.3.23", default-features = false, features = ["env-filter", "fmt", "json"] }
+uuid = { version = "1.26.1", default-features = false, features = ["v7", "std"] }
[dev-dependencies]
http-body = "1"
diff --git a/ai-gateway/README.md b/ai-gateway/README.md
index 5ad29a91e4..ac2b37ed81 100644
--- a/ai-gateway/README.md
+++ b/ai-gateway/README.md
@@ -107,6 +107,8 @@ from request logs and spans.
Use `LANGFUSE_LOG_FORMAT=text` locally and `json` for log collectors. Built-in `tracing-subscriber` formatters handle both modes. JSON event fields
are top-level attributes; span fields are nested. HTTP response and execution
summaries include top-level `trace_id` and `span_id` for Datadog correlation.
+Every JSON log line emitted while serving an inference request also carries a
+top-level `request_id`; see [Request IDs](#request-ids).
`info` emits lifecycle, HTTP response, and execution summaries; `debug` adds
sanitized capture details. Other log events do not automatically include trace IDs. Dependency logs stay at `warn`. Log severity does not control
trace sampling. `trace` is not an accepted gateway log level.
@@ -129,6 +131,40 @@ outcome are separate: a 200 response can still fail while streaming. The server
span carries `http.request.body.size`, `gateway.outcome`, and
`gateway.first_byte_ms` once they are known.
+### Request IDs
+
+Every inference request gets a fresh UUIDv7 gateway request ID (time-ordered, no prefix) at ingress, before
+authentication, so it exists for every response, including rejections before
+resolution, 4xx/5xx gateway errors and streams. It appears in:
+
+| Where | Field |
+| --- | --- |
+| Every response | `langfuse-request-id` header, sent with the initial headers of a stream |
+| Gateway JSON error bodies | Top-level `request_id` in both native envelopes |
+| Gateway JSON log lines for the request | Top-level `request_id` |
+| Operational server span | `gateway.request.id` |
+| Web resolution call | `langfuse-gateway-request-id` header; Web adds it to its log context |
+| Langfuse generation | `langfuse.gateway.request.id` metadata |
+
+A caller's `x-request-id` never becomes the gateway request ID. A single printable
+value of at most 256 bytes is recorded separately as the server span's
+`gateway.client.request.id` and as `langfuse.gateway.client.request.id` generation
+metadata; it is not forwarded to Web or the provider. The provider's own request ID
+(OpenAI `x-request-id`, Anthropic `request-id`) is recorded as the server span's
+`provider_request_id` on every route and as `langfuse.gateway.upstream.request.id`
+generation metadata, and its response header is still relayed unchanged.
+
+When the request will produce a Langfuse generation (`/openai/v1/responses`,
+`/openai/v1/responses/compact` and `/anthropic/v1/messages` with inference telemetry
+configured), the response also carries `langfuse-trace-id` and
+`langfuse-observation-id`: the uploaded generation's trace ID, after `traceparent`
+and agent turn grouping, and its OpenTelemetry span ID, which Langfuse stores as the
+observation ID. They are also set on 502/504 responses for provider failures before
+response headers, which still upload a generation. Requests rejected earlier, such
+as authentication failures, and model or token-count routes omit them. Upload is
+best-effort, so a dropped generation can leave these IDs unresolved. The gateway
+does not set CORS headers, so no `Access-Control-Expose-Headers` is involved.
+
Each inference request phase has a child span of the server span so a waterfall
has no unattributed wall time:
@@ -273,8 +309,9 @@ only; Web still selects the provider connection. Compact `encrypted_content` is
unchanged. Inference routes drop request query strings: the Anthropic SDK's
`?beta=true` carries nothing beyond the `anthropic-beta` header. Provider errors retain
their status and body. Gateway errors use the namespace's native envelope:
-`{"error":{"message":"...","type":"...","param":null,"code":"..."}}` for OpenAI and
-`{"type":"error","error":{"type":"...","message":"..."}}` for Anthropic, where the
+`{"error":{"message":"...","type":"...","param":null,"code":"..."},"request_id":"..."}`
+for OpenAI and `{"type":"error","error":{"type":"...","message":"..."},"request_id":"..."}`
+for Anthropic, where `request_id` is the gateway request ID and the
error type follows the status (`authentication_error`, `permission_error`,
`not_found_error`, `request_too_large`, `invalid_request_error`, `overloaded_error`,
`api_error`).
@@ -369,10 +406,11 @@ each field describes:
| `request.metadata`, `request.prompt_cache_key`, `request.safety_identifier`, `request.user` | Native caller-supplied fields, captured only in full mode |
| `response.id` | Native response object's ID |
| `response.status_code` | HTTP status returned to the caller |
+| `request.id` | Gateway request ID, also returned as the `langfuse-request-id` response header |
+| `client.request.id` | Caller's `x-request-id`, when valid |
| `upstream.request.id` | Provider request ID from the upstream `x-request-id` (OpenAI) or `request-id` (Anthropic) header |
-`request.id` is reserved for a future gateway-generated request ID and is not
-emitted. The upstream request ID is separate and is omitted when unavailable.
+The client and upstream request IDs are omitted when unavailable.
API-key attribution entries appear both as top-level metadata and under
`langfuse.gateway.api_key.metadata.*`.
Gateway, agent and OpenTelemetry fields win collisions; the namespaced attribution
diff --git a/ai-gateway/src/capture/anthropic_messages/tests.rs b/ai-gateway/src/capture/anthropic_messages/tests.rs
index 70ef8c5abd..cd6017d354 100644
--- a/ai-gateway/src/capture/anthropic_messages/tests.rs
+++ b/ai-gateway/src/capture/anthropic_messages/tests.rs
@@ -560,6 +560,7 @@ async fn streamed_messages_upload_one_generation_with_native_usage() {
Bytes::from_static(REQUEST),
Route::AnthropicMessages,
None,
+ &mut crate::correlation::RequestCorrelation::default(),
)
.await
.unwrap();
diff --git a/ai-gateway/src/capture/mod.rs b/ai-gateway/src/capture/mod.rs
index 854affaefb..2f4c02f95a 100644
--- a/ai-gateway/src/capture/mod.rs
+++ b/ai-gateway/src/capture/mod.rs
@@ -11,6 +11,7 @@ use serde_json::{Map, Value, json};
use tokio::time::Instant;
use crate::{
+ correlation::RequestCorrelation,
resolution::{ApiFormat, IngestionMode, MetadataValue, ResolvedRequestContext},
telemetry,
};
@@ -169,15 +170,19 @@ impl ExecutionCapture {
telemetry: telemetry::Telemetry,
context: &ResolvedRequestContext,
headers: &HeaderMap,
+ correlation: &mut RequestCorrelation,
) {
let client_metadata = self
.protocol
.as_ref()
.and_then(ProtocolCapture::client_metadata);
- self.delivery = Some((
- telemetry,
- telemetry::DeliveryContext::from_resolved(context, headers, client_metadata),
- ));
+ let delivery = telemetry::DeliveryContext::from_resolved(context, headers, client_metadata);
+ correlation.record_generation(delivery.generation_ids());
+ self.metadata["request_id"] = json!(correlation.id());
+ if let Some(client_id) = correlation.client_id() {
+ self.metadata["client_request_id"] = json!(client_id);
+ }
+ self.delivery = Some((telemetry, delivery));
}
pub fn record_response(&mut self, status: u16, headers: &HeaderMap) {
diff --git a/ai-gateway/src/correlation.rs b/ai-gateway/src/correlation.rs
new file mode 100644
index 0000000000..62542dbbd0
--- /dev/null
+++ b/ai-gateway/src/correlation.rs
@@ -0,0 +1,136 @@
+//! One gateway request ID per inference request, shared by the caller's response,
+//! logs, operational spans, the Web resolution call and the Langfuse generation.
+use axum::{
+ extract::Request,
+ http::{HeaderMap, HeaderName, HeaderValue},
+ middleware::Next,
+ response::Response,
+};
+
+pub(crate) const REQUEST_ID_HEADER: HeaderName = HeaderName::from_static("langfuse-request-id");
+const TRACE_ID_HEADER: HeaderName = HeaderName::from_static("langfuse-trace-id");
+const OBSERVATION_ID_HEADER: HeaderName = HeaderName::from_static("langfuse-observation-id");
+const CLIENT_REQUEST_ID_HEADER: &str = "x-request-id";
+const MAX_CLIENT_REQUEST_ID_BYTES: usize = 256;
+
+/// The Langfuse generation the gateway uploads for a request: its trace ID and
+/// its OpenTelemetry span ID, which becomes the observation ID.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct GenerationIds {
+ pub trace_id: String,
+ pub observation_id: String,
+}
+
+#[derive(Clone, Debug)]
+pub(crate) struct RequestCorrelation {
+ id: String,
+ client_id: Option<String>,
+ generation: Option<GenerationIds>,
+}
+
+impl Default for RequestCorrelation {
+ fn default() -> Self {
+ Self {
+ id: uuid::Uuid::now_v7().hyphenated().to_string(),
+ client_id: None,
+ generation: None,
+ }
+ }
+}
+
+impl RequestCorrelation {
+ /// Always a fresh ID; a caller's `x-request-id` is kept only as a separate value.
+ pub fn from_headers(headers: &HeaderMap) -> Self {
+ let mut values = headers.get_all(CLIENT_REQUEST_ID_HEADER).iter();
+ let client_id = match (values.next(), values.next()) {
+ (Some(value), None) => value
+ .to_str()
+ .ok()
+ .map(str::trim)
+ .filter(|value| {
+ !value.is_empty()
+ && value.len() <= MAX_CLIENT_REQUEST_ID_BYTES
+ && value
+ .bytes()
+ .all(|byte| byte == b' ' || byte.is_ascii_graphic())
+ })
+ .map(str::to_owned),
+ _ => None,
+ };
+ Self {
+ client_id,
+ ..Self::default()
+ }
+ }
+
+ pub fn id(&self) -> &str {
+ &self.id
+ }
+
+ pub fn client_id(&self) -> Option<&str> {
+ self.client_id.as_deref()
+ }
+
+ pub fn record_generation(&mut self, ids: GenerationIds) {
+ self.generation = Some(ids);
+ }
+
+ /// Only a request that will produce a Langfuse generation advertises its IDs.
+ pub fn apply_generation_headers(&self, headers: &mut HeaderMap) {
+ let Some(generation) = &self.generation else {
+ return;
+ };
+ for (name, value) in [
+ (TRACE_ID_HEADER, &generation.trace_id),
+ (OBSERVATION_ID_HEADER, &generation.observation_id),
+ ] {
+ if let Ok(value) = HeaderValue::from_str(value) {
+ headers.insert(name, value);
+ }
+ }
+ }
+}
+
+/// Runs inside the server span before any rejection, so every response, log line
+/// and phase span of the request can carry the ID.
+pub(crate) async fn assign_request_id(mut request: Request, next: Next) -> Response {
+ let correlation = RequestCorrelation::from_headers(request.headers());
+ let span = tracing::Span::current();
+ span.record("gateway.request.id", correlation.id());
+ if let Some(client_id) = correlation.client_id() {
+ span.record("gateway.client.request.id", client_id);
+ }
+ let value = HeaderValue::from_str(correlation.id()).expect("a UUID is a valid header value");
+ request.extensions_mut().insert(correlation);
+ let mut response = next.run(request).await;
+ response.headers_mut().insert(REQUEST_ID_HEADER, value);
+ response
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn client_request_ids_are_bounded_single_printable_values() {
+ let client_id = |values: &[&str]| {
+ let mut headers = HeaderMap::new();
+ for value in values {
+ headers.append(CLIENT_REQUEST_ID_HEADER, value.parse().unwrap());
+ }
+ RequestCorrelation::from_headers(&headers)
+ .client_id()
+ .map(str::to_owned)
+ };
+ assert_eq!(client_id(&[" req 1 "]).as_deref(), Some("req 1"));
+ assert_eq!(client_id(&[]), None);
+ assert_eq!(client_id(&[" "]), None);
+ assert_eq!(client_id(&["one", "two"]), None);
+ assert_eq!(
+ client_id(&[&"x".repeat(MAX_CLIENT_REQUEST_ID_BYTES + 1)]),
+ None
+ );
+ let correlation = RequestCorrelation::from_headers(&HeaderMap::new());
+ assert_ne!(correlation.id(), RequestCorrelation::default().id());
+ }
+}
diff --git a/ai-gateway/src/http.rs b/ai-gateway/src/http.rs
index 10e05f4c5f..9087ad117e 100644
--- a/ai-gateway/src/http.rs
+++ b/ai-gateway/src/http.rs
@@ -12,6 +12,7 @@ use serde::Serialize;
use tracing::Instrument;
use crate::{
+ correlation::{RequestCorrelation, assign_request_id},
inference::{InferenceService, RequestPreparationError},
providers::{ProviderError, Route, forwarded_query},
resolution::{ApiFormat, ResolutionError},
@@ -47,6 +48,7 @@ pub fn router(inference: Option<InferenceService>, lifecycle: GatewayLifecycleSt
inference: inference.map(Arc::new),
lifecycle,
})
+ .layer(axum::middleware::from_fn(assign_request_id))
}
async fn handle_responses(State(state): State<InferenceRouteState>, request: Request) -> Response {
@@ -85,16 +87,24 @@ async fn handle_anthropic_models(
handle(state, request, Route::AnthropicModels).await
}
-async fn handle(state: InferenceRouteState, request: Request, route: Route) -> Response {
- relay(state, request, route)
- .await
- .unwrap_or_else(|error| error.into_native_response(route.api_format()))
+async fn handle(state: InferenceRouteState, mut request: Request, route: Route) -> Response {
+ let mut correlation = request
+ .extensions_mut()
+ .remove::<RequestCorrelation>()
+ .unwrap_or_default();
+ let mut response = match relay(state, request, route, &mut correlation).await {
+ Ok(response) => response,
+ Err(error) => error.into_native_response(route.api_format(), correlation.id()),
+ };
+ correlation.apply_generation_headers(response.headers_mut());
+ response
}
async fn relay(
state: InferenceRouteState,
request: Request,
route: Route,
+ correlation: &mut RequestCorrelation,
) -> Result<Response, InferenceHttpError> {
let inference = state
.inference
@@ -103,7 +113,7 @@ async fn relay(
.ok_or(InferenceHttpError::Unavailable)?;
let gateway_key = gateway_key(request.headers(), route.api_format())?.to_owned();
let (permit, context) = inference
- .resolve_and_admit(&gateway_key, route.api_format())
+ .resolve_and_admit(&gateway_key, route.api_format(), correlation.id())
.await
.map_err(|error| match error {
RequestPreparationError::Resolution(error) => InferenceHttpError::Resolution(error),
@@ -124,6 +134,7 @@ async fn relay(
bytes,
route,
query.as_deref(),
+ correlation,
)
.await
.map_err(InferenceHttpError::Provider)
@@ -226,8 +237,9 @@ enum InferenceHttpError {
}
#[derive(Serialize)]
-struct OpenAiErrorResponse {
+struct OpenAiErrorResponse<'a> {
error: OpenAiErrorDetail,
+ request_id: &'a str,
}
#[derive(Serialize)]
struct OpenAiErrorDetail {
@@ -239,10 +251,11 @@ struct OpenAiErrorDetail {
}
#[derive(Serialize)]
-struct AnthropicErrorResponse {
+struct AnthropicErrorResponse<'a> {
#[serde(rename = "type")]
kind: &'static str,
error: AnthropicErrorDetail,
+ request_id: &'a str,
}
#[derive(Serialize)]
struct AnthropicErrorDetail {
@@ -356,7 +369,7 @@ impl InferenceHttpError {
}
}
- fn into_native_response(self, api_format: ApiFormat) -> Response {
+ fn into_native_response(self, api_format: ApiFormat, request_id: &str) -> Response {
let (phase, reason) = self.category();
let (status, message, kind, code) = self.classify();
if status.is_server_error() {
@@ -384,6 +397,7 @@ impl InferenceHttpError {
param: None,
code,
},
+ request_id,
}),
)
.into_response(),
@@ -395,6 +409,7 @@ impl InferenceHttpError {
kind: anthropic_error_type(status),
message,
},
+ request_id,
}),
)
.into_response(),
diff --git a/ai-gateway/src/http/tests.rs b/ai-gateway/src/http/tests.rs
index 1aae02545a..533f15353c 100644
--- a/ai-gateway/src/http/tests.rs
+++ b/ai-gateway/src/http/tests.rs
@@ -184,6 +184,100 @@ impl Gateway {
fn models(&self) -> reqwest::RequestBuilder {
reqwest::Client::new().get(format!("{}/openai/v1/models", self.url))
}
+
+ fn messages(&self) -> reqwest::RequestBuilder {
+ reqwest::Client::new().post(format!("{}/anthropic/v1/messages", self.url))
+ }
+}
+
+/// Returns the response's `langfuse-request-id` after checking it is a canonical `UUIDv7`.
+fn request_id(response: &reqwest::Response) -> String {
+ let id = response.headers()["langfuse-request-id"]
+ .to_str()
+ .unwrap()
+ .to_owned();
+ assert_eq!(id.len(), 36, "{id}");
+ for (index, byte) in id.bytes().enumerate() {
+ if [8, 13, 18, 23].contains(&index) {
+ assert_eq!(byte, b'-', "{id}");
+ } else {
+ assert!(matches!(byte, b'0'..=b'9' | b'a'..=b'f'), "{id}");
+ }
+ }
+ assert_eq!(id.as_bytes()[14], b'7', "{id}");
+ assert!(
+ matches!(id.as_bytes()[19], b'8' | b'9' | b'a' | b'b'),
+ "{id}"
+ );
+ id
+}
+
+#[tokio::test]
+async fn every_error_carries_a_fresh_request_id_in_its_header_and_native_body() {
+ let web = FakeServer::start(|request| async move {
+ if request.headers().get(header::AUTHORIZATION)
+ == Some(&header::HeaderValue::from_static("Bearer valid"))
+ {
+ return resolution_response("provider-secret");
+ }
+ Response::builder()
+ .status(StatusCode::UNAUTHORIZED)
+ .body(Body::empty())
+ .unwrap()
+ })
+ .await;
+ let provider = FakeServer::start(|_| async { Response::new(Body::empty()) }).await;
+ let unconfigured = Gateway::start(None).await;
+ let configured = Gateway::start(Some(inference(&web, &provider))).await;
+ let mut seen = std::collections::HashSet::new();
+ for (request, status, anthropic) in [
+ (unconfigured.post(), StatusCode::SERVICE_UNAVAILABLE, false),
+ (
+ unconfigured.messages(),
+ StatusCode::SERVICE_UNAVAILABLE,
+ true,
+ ),
+ (configured.post(), StatusCode::UNAUTHORIZED, false),
+ (
+ configured.post().bearer_auth("rejected"),
+ StatusCode::UNAUTHORIZED,
+ false,
+ ),
+ (
+ configured.messages().header("x-api-key", "rejected"),
+ StatusCode::UNAUTHORIZED,
+ true,
+ ),
+ (
+ configured
+ .post()
+ .bearer_auth("valid")
+ .body(vec![b'x'; MAX_REQUEST_BYTES + 1]),
+ StatusCode::PAYLOAD_TOO_LARGE,
+ false,
+ ),
+ ] {
+ let response = request
+ .header("x-request-id", "client-request")
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(response.status(), status);
+ let id = request_id(&response);
+ assert!(!response.headers().contains_key("langfuse-trace-id"));
+ assert!(!response.headers().contains_key("langfuse-observation-id"));
+ let body: serde_json::Value =
+ serde_json::from_slice(&response.bytes().await.unwrap()).unwrap();
+ assert_eq!(body["request_id"], id.as_str());
+ if anthropic {
+ assert_eq!(body["type"], "error");
+ assert!(body["error"]["type"].is_string());
+ } else {
+ assert!(body["error"]["code"].is_string());
+ }
+ assert!(seen.insert(id), "request IDs must be unique");
+ }
+ assert_eq!(provider.calls(), 0);
}
impl Drop for Gateway {
@@ -549,13 +643,23 @@ async fn pre_header_provider_failures_export_the_status_returned_to_the_caller()
.await
.unwrap();
assert_eq!(response.status(), expected);
+ let id = request_id(&response);
+ let header = |name: &str| response.headers()[name].to_str().unwrap().to_owned();
+ let (trace_id, observation_id) = (
+ header("langfuse-trace-id"),
+ header("langfuse-observation-id"),
+ );
+ let status = response.status();
+ let body: Value = serde_json::from_slice(&response.bytes().await.unwrap()).unwrap();
+ assert_eq!(body["request_id"], id.as_str());
let payload = tokio::time::timeout(Duration::from_secs(2), received.recv())
.await
.unwrap()
.unwrap();
- let attrs = payload["resourceSpans"][0]["scopeSpans"][0]["spans"][0]["attributes"]
- .as_array()
- .unwrap();
+ let span = &payload["resourceSpans"][0]["scopeSpans"][0]["spans"][0];
+ assert_eq!(span["traceId"], trace_id.as_str());
+ assert_eq!(span["spanId"], observation_id.as_str());
+ let attrs = span["attributes"].as_array().unwrap();
let metadata: Value = serde_json::from_str(
attrs
.iter()
@@ -567,8 +671,9 @@ async fn pre_header_provider_failures_export_the_status_returned_to_the_caller()
.unwrap();
assert_eq!(
metadata["langfuse.gateway.response.status_code"],
- response.status().as_u16()
+ status.as_u16()
);
+ assert_eq!(metadata["langfuse.gateway.request.id"], id.as_str());
assert!(
metadata
.get("langfuse.gateway.upstream.request.id")
@@ -653,6 +758,8 @@ async fn active_admission_is_held_through_stream_and_shutdown_drains_it() {
.send()
.await
.unwrap();
+ // The stream is still open, so the ID was sent with the initial headers.
+ request_id(&response);
assert_eq!(response.chunk().await.unwrap().unwrap(), "data: first\n\n");
assert_eq!(
gateway
diff --git a/ai-gateway/src/inference.rs b/ai-gateway/src/inference.rs
index c4eda64ffc..0a963c9054 100644
--- a/ai-gateway/src/inference.rs
+++ b/ai-gateway/src/inference.rs
@@ -7,6 +7,7 @@ use tokio::sync::Semaphore;
use tracing::Instrument;
use crate::{
+ correlation::RequestCorrelation,
providers::{ProviderError, ProviderTransport, RequestPermit, Route},
resolution::{
ApiFormat, ControlPlaneClient, ControlPlaneConfig, ResolutionError, ResolvedRequestContext,
@@ -60,6 +61,7 @@ impl InferenceService {
&self,
gateway_key: &str,
api_format: ApiFormat,
+ request_id: &str,
) -> Result<(RequestPermit, ResolvedRequestContext), RequestPreparationError> {
let span = tracing::info_span!(
"resolution",
@@ -67,7 +69,7 @@ impl InferenceService {
gateway.outcome = tracing::field::Empty
);
async {
- let prepared = self.prepare(gateway_key, api_format).await;
+ let prepared = self.prepare(gateway_key, api_format, request_id).await;
tracing::Span::current().record(
"gateway.outcome",
match &prepared {
@@ -86,6 +88,7 @@ impl InferenceService {
&self,
gateway_key: &str,
api_format: ApiFormat,
+ request_id: &str,
) -> Result<(RequestPermit, ResolvedRequestContext), RequestPreparationError> {
let context = {
let _permit = self.resolution_capacity.try_acquire().map_err(|_| {
@@ -94,7 +97,7 @@ impl InferenceService {
})?;
let _active = crate::observability::Active::new("resolution");
self.control_plane
- .resolve(gateway_key, api_format)
+ .resolve(gateway_key, api_format, request_id)
.await
.map_err(RequestPreparationError::Resolution)?
};
@@ -105,6 +108,10 @@ impl InferenceService {
Ok((permit, context))
}
+ #[expect(
+ clippy::too_many_arguments,
+ reason = "each argument is a distinct per-request input passed straight through"
+ )]
pub(crate) async fn forward(
&self,
permit: RequestPermit,
@@ -113,9 +120,10 @@ impl InferenceService {
body: Bytes,
route: Route,
query: Option<&str>,
+ correlation: &mut RequestCorrelation,
) -> Result<Response<Body>, ProviderError> {
self.provider
- .forward_route(permit, context, headers, body, route, query)
+ .forward_route(permit, context, headers, body, route, query, correlation)
.await
}
diff --git a/ai-gateway/src/lib.rs b/ai-gateway/src/lib.rs
index 0b9caa6ed0..bb51633433 100644
--- a/ai-gateway/src/lib.rs
+++ b/ai-gateway/src/lib.rs
@@ -1,5 +1,6 @@
mod capture;
pub mod config;
+mod correlation;
pub mod http;
pub mod inference;
pub mod observability;
diff --git a/ai-gateway/src/observability/http.rs b/ai-gateway/src/observability/http.rs
index 31049e277b..e379e6e09e 100644
--- a/ai-gateway/src/observability/http.rs
+++ b/ai-gateway/src/observability/http.rs
@@ -21,7 +21,7 @@ pub fn instrument(router: Router) -> Router {
TraceLayer::new_for_http()
.make_span_with(|request: &Request<Body>| {
let (method, route) = request_labels(request);
- let span = tracing::info_span!(parent: None, "http.server", otel.name = %format_args!("{method} {route}"), otel.kind = "server", http.request.method = method, http.route = route, http.request.body.size = tracing::field::Empty, http.response.status_code = tracing::field::Empty, otel.status_code = tracing::field::Empty, provider_request_id = tracing::field::Empty, gateway.outcome = tracing::field::Empty, gateway.first_byte_ms = tracing::field::Empty);
+ let span = tracing::info_span!(parent: None, "http.server", otel.name = %format_args!("{method} {route}"), otel.kind = "server", http.request.method = method, http.route = route, http.request.body.size = tracing::field::Empty, http.response.status_code = tracing::field::Empty, otel.status_code = tracing::field::Empty, gateway.request.id = tracing::field::Empty, gateway.client.request.id = tracing::field::Empty, provider_request_id = tracing::field::Empty, gateway.outcome = tracing::field::Empty, gateway.first_byte_ms = tracing::field::Empty);
// Operational tracing has no caller or ambient trace context.
let _ = span.set_parent(Context::new());
span
diff --git a/ai-gateway/src/observability/http/tests.rs b/ai-gateway/src/observability/http/tests.rs
index fb8e534a1d..fb90de8281 100644
--- a/ai-gateway/src/observability/http/tests.rs
+++ b/ai-gateway/src/observability/http/tests.rs
@@ -57,9 +57,11 @@ impl Recording {
tracing_subscriber::fmt::layer()
.json()
.flatten_event(true)
+ .map_event_format(crate::observability::logs::WithRequestId)
.with_writer(move || buffer.clone()),
)
- .with(tracing_opentelemetry::layer().with_tracer(provider.tracer("test")));
+ .with(tracing_opentelemetry::layer().with_tracer(provider.tracer("test")))
+ .with(crate::observability::logs::RequestIdSpans);
Self {
_guard: tracing::subscriber::set_default(subscriber),
_provider: provider,
@@ -67,11 +69,16 @@ impl Recording {
output,
}
}
- fn summaries(&self) -> Vec<Value> {
+ fn events(&self) -> Vec<Value> {
String::from_utf8(self.output.0.lock().unwrap().clone())
.unwrap()
.lines()
.map(|line| serde_json::from_str::<Value>(line).unwrap())
+ .collect()
+ }
+ fn summaries(&self) -> Vec<Value> {
+ self.events()
+ .into_iter()
.filter(|event| event["message"] == "gateway response started")
.collect()
}
@@ -271,6 +278,7 @@ async fn generation_context_is_isolated_from_operational_spans_and_outbound_head
async {
Response::builder()
.header("content-type", "application/json")
+ .header("x-request-id", "req_upstream")
.body(Body::from(PROVIDER_RESPONSE))
.unwrap()
}
@@ -301,6 +309,7 @@ async fn generation_context_is_isolated_from_operational_spans_and_outbound_head
assert!(futures_util::poll!(serving.as_mut()).is_pending());
let response = app.oneshot(generation_request()).await.unwrap();
assert_eq!(response.status(), 200);
+ let response_headers = response.headers().clone();
axum::body::to_bytes(response.into_body(), 4096)
.await
.unwrap();
@@ -327,6 +336,7 @@ async fn generation_context_is_isolated_from_operational_spans_and_outbound_head
assert_generation_context(payload);
}
}
+ assert_request_correlation(&response_headers, &recording, server, &observed);
}
type SpanData = opentelemetry_sdk::trace::SpanData;
@@ -441,6 +451,7 @@ fn generation_request() -> HttpRequest<Body> {
.header("langfuse-environment", "production")
.header("langfuse-tags", "one,two")
.header("langfuse-metadata", "team:search")
+ .header("x-request-id", "client-request-canary")
.body(Body::from(GENERATION_REQUEST))
.unwrap()
}
@@ -472,6 +483,7 @@ fn assert_outbound_context(headers: &HeaderMap, span: Option<&opentelemetry_sdk:
"langfuse-environment",
"langfuse-tags",
"langfuse-metadata",
+ "x-request-id",
] {
assert!(
!headers.contains_key(name),
@@ -480,7 +492,67 @@ fn assert_outbound_context(headers: &HeaderMap, span: Option<&opentelemetry_sdk:
}
}
-fn assert_generation_context(payload: &Value) {
+/// One gateway request ID links the caller's response, every request log line, the
+/// server span, the Web resolution call and the uploaded generation, whose trace
+/// and observation IDs the response also advertises.
+fn assert_request_correlation(
+ response: &HeaderMap,
+ recording: &Recording,
+ server: &SpanData,
+ observed: &[(&str, HeaderMap, Value)],
+) {
+ let header = |name: &str| response[name].to_str().unwrap();
+ let request_id = header("langfuse-request-id");
+ assert_eq!(
+ header("langfuse-trace-id"),
+ "4bf92f3577b34da6a3ce929d0e0e4736"
+ );
+ assert_attribute(server, "gateway.request.id", request_id.to_owned());
+ assert_attribute(server, "gateway.client.request.id", "client-request-canary");
+ assert_attribute(server, "provider_request_id", "req_upstream");
+ let events: Vec<_> = recording
+ .events()
+ .into_iter()
+ .filter(|event| {
+ event["spans"]
+ .as_array()
+ .is_some_and(|spans| spans.iter().any(|span| span["name"] == "http.server"))
+ })
+ .collect();
+ let messages: Vec<_> = events.iter().map(|event| &event["message"]).collect();
+ for message in ["gateway response started", "gateway execution finished"] {
+ assert!(messages.contains(&&Value::from(message)), "{messages:?}");
+ }
+ for event in &events {
+ assert_eq!(event["request_id"], request_id, "{event}");
+ }
+ for (name, headers, payload) in observed {
+ assert_eq!(
+ headers
+ .get("langfuse-gateway-request-id")
+ .map(|value| value.to_str().unwrap()),
+ (*name == "resolver").then_some(request_id),
+ "{name}"
+ );
+ if *name == "ingestion" {
+ let generation = &payload["resourceSpans"][0]["scopeSpans"][0]["spans"][0];
+ assert_eq!(generation["traceId"], header("langfuse-trace-id"));
+ assert_eq!(generation["spanId"], header("langfuse-observation-id"));
+ let metadata = assert_generation_context(payload);
+ assert_eq!(metadata["langfuse.gateway.request.id"], request_id);
+ assert_eq!(
+ metadata["langfuse.gateway.client.request.id"],
+ "client-request-canary"
+ );
+ assert_eq!(
+ metadata["langfuse.gateway.upstream.request.id"],
+ "req_upstream"
+ );
+ }
+ }
+}
+
+fn assert_generation_context(payload: &Value) -> Value {
let span = &payload["resourceSpans"][0]["scopeSpans"][0]["spans"][0];
assert_eq!(span["traceId"], "4bf92f3577b34da6a3ce929d0e0e4736");
assert_eq!(span["parentSpanId"], "00f067aa0ba902b7");
@@ -510,4 +582,5 @@ fn assert_generation_context(payload: &Value) {
serde_json::from_str(attributes["langfuse.observation.metadata"]).unwrap();
assert_eq!(metadata["team"], "search");
assert_eq!(metadata["source"], "python");
+ metadata
}
diff --git a/ai-gateway/src/observability/logs.rs b/ai-gateway/src/observability/logs.rs
new file mode 100644
index 0000000000..195da09237
--- /dev/null
+++ b/ai-gateway/src/observability/logs.rs
@@ -0,0 +1,98 @@
+//! JSON span fields are nested, so the request ID is repeated as a top-level
+//! `request_id` on every event emitted inside a request, for log search.
+use std::fmt;
+
+use tracing::{
+ Event, Subscriber,
+ field::{Field, Visit},
+ span,
+};
+use tracing_subscriber::{
+ fmt::{FmtContext, FormatEvent, FormatFields, format::Writer},
+ layer::{Context, Layer},
+ registry::LookupSpan,
+};
+
+const REQUEST_ID_FIELD: &str = "gateway.request.id";
+
+struct LoggedRequestId(String);
+
+/// Keeps each span's `gateway.request.id` where [`WithRequestId`] can find it.
+pub(crate) struct RequestIdSpans;
+
+impl<S> Layer<S> for RequestIdSpans
+where
+ S: Subscriber + for<'a> LookupSpan<'a>,
+{
+ fn on_new_span(&self, attributes: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
+ let mut visitor = RequestIdVisitor(None);
+ attributes.record(&mut visitor);
+ store(id, &ctx, visitor.0);
+ }
+
+ fn on_record(&self, id: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
+ let mut visitor = RequestIdVisitor(None);
+ values.record(&mut visitor);
+ store(id, &ctx, visitor.0);
+ }
+}
+
+fn store<S>(id: &span::Id, ctx: &Context<'_, S>, request_id: Option<String>)
+where
+ S: Subscriber + for<'a> LookupSpan<'a>,
+{
+ if let (Some(request_id), Some(span)) = (request_id, ctx.span(id)) {
+ span.extensions_mut().replace(LoggedRequestId(request_id));
+ }
+}
+
+struct RequestIdVisitor(Option<String>);
+
+impl Visit for RequestIdVisitor {
+ fn record_str(&mut self, field: &Field, value: &str) {
+ if field.name() == REQUEST_ID_FIELD {
+ self.0 = Some(value.to_owned());
+ }
+ }
+
+ fn record_debug(&mut self, _: &Field, _: &dyn fmt::Debug) {}
+}
+
+/// Wraps a JSON event formatter and prepends the innermost span's request ID.
+pub(crate) struct WithRequestId<F>(pub F);
+
+impl<S, N, F> FormatEvent<S, N> for WithRequestId<F>
+where
+ S: Subscriber + for<'a> LookupSpan<'a>,
+ N: for<'a> FormatFields<'a> + 'static,
+ F: FormatEvent<S, N>,
+{
+ fn format_event(
+ &self,
+ ctx: &FmtContext<'_, S, N>,
+ mut writer: Writer<'_>,
+ event: &Event<'_>,
+ ) -> fmt::Result {
+ let request_id = ctx.event_scope().and_then(|scope| {
+ scope.into_iter().find_map(|span| {
+ span.extensions()
+ .get::<LoggedRequestId>()
+ .map(|id| id.0.clone())
+ })
+ });
+ let Some(request_id) = request_id else {
+ return self.0.format_event(ctx, writer, event);
+ };
+ let mut line = String::new();
+ self.0.format_event(ctx, Writer::new(&mut line), event)?;
+ let Some(rest) = line.strip_prefix('{') else {
+ return writer.write_str(&line);
+ };
+ let request_id = serde_json::to_string(&request_id).map_err(|_| fmt::Error)?;
+ write!(writer, "{{\"request_id\":{request_id}")?;
+ if !rest.starts_with('}') {
+ writer.write_char(',')?;
+ }
+ writer.write_str(rest)
+ }
+}
diff --git a/ai-gateway/src/observability/metrics.rs b/ai-gateway/src/observability/metrics.rs
index a68fd9e729..f8762b5b10 100644
--- a/ai-gateway/src/observability/metrics.rs
+++ b/ai-gateway/src/observability/metrics.rs
@@ -94,9 +94,6 @@ pub(crate) fn delivery(outcome: &'static str, reason: &'static str, records: u64
}
pub(crate) fn execution_finished(facts: &crate::capture::InferenceFacts) {
- if let Some(request_id) = &facts.inference.provider_request_id {
- tracing::Span::current().record("provider_request_id", request_id.as_str());
- }
let outcome = match facts.outcome {
RelayOutcome::Eof => "complete",
RelayOutcome::Cancelled => "cancelled",
diff --git a/ai-gateway/src/observability/mod.rs b/ai-gateway/src/observability/mod.rs
index 02641e3371..1372de5436 100644
--- a/ai-gateway/src/observability/mod.rs
+++ b/ai-gateway/src/observability/mod.rs
@@ -1,5 +1,6 @@
mod client;
mod http;
+mod logs;
mod metrics;
pub(crate) use client::instrument_client;
@@ -102,6 +103,7 @@ pub fn init(config: &GatewayConfig) -> Result<Observability, Box<dyn Error>> {
LogFormat::Json => tracing_subscriber::fmt::layer()
.json()
.flatten_event(true)
+ .map_event_format(logs::WithRequestId)
.with_filter(log_filter)
.boxed(),
LogFormat::Text => tracing_subscriber::fmt::layer()
@@ -122,6 +124,7 @@ pub fn init(config: &GatewayConfig) -> Result<Observability, Box<dyn Error>> {
tracing_subscriber::registry()
.with(logger)
.with(spans)
+ .with(logs::RequestIdSpans)
.try_init()
.map_err(|_| "failed to initialize gateway logging")?;
Ok(Observability { traces, metrics })
diff --git a/ai-gateway/src/providers/mod.rs b/ai-gateway/src/providers/mod.rs
index 496fa5a523..ace07407e4 100644
--- a/ai-gateway/src/providers/mod.rs
+++ b/ai-gateway/src/providers/mod.rs
@@ -15,6 +15,7 @@ use tokio::{
pub use crate::transport::ProviderError;
use crate::{
capture::{ExecutionCapture, RelayOutcome},
+ correlation::RequestCorrelation,
resolution::{ApiFormat, Provider, ProviderCredential, ResolvedRequestContext},
transport,
};
@@ -176,10 +177,22 @@ impl ProviderTransport {
headers: &HeaderMap,
body: Bytes,
) -> Result<Response<Body>, ProviderError> {
- self.forward_route(permit, context, headers, body, Route::OpenAiResponses, None)
- .await
+ self.forward_route(
+ permit,
+ context,
+ headers,
+ body,
+ Route::OpenAiResponses,
+ None,
+ &mut RequestCorrelation::from_headers(headers),
+ )
+ .await
}
+ #[expect(
+ clippy::too_many_arguments,
+ reason = "each argument is a distinct per-request input of the relay"
+ )]
pub(crate) async fn forward_route(
&self,
permit: RequestPermit,
@@ -188,6 +201,7 @@ impl ProviderTransport {
body: Bytes,
route: Route,
query: Option<&str>,
+ correlation: &mut RequestCorrelation,
) -> Result<Response<Body>, ProviderError> {
let api_format = route.api_format();
let (credential_name, mut credential) = provider_credential(&context)?;
@@ -195,7 +209,7 @@ impl ProviderTransport {
let mut capture = if route.captures_generation() {
let mut capture = ExecutionCapture::for_request(api_format, &context, headers, &body);
if let Some(telemetry) = &self.telemetry {
- capture.deliver_to(telemetry.clone(), &context, headers);
+ capture.deliver_to(telemetry.clone(), &context, headers, correlation);
}
capture
} else {
@@ -239,6 +253,9 @@ impl ProviderTransport {
return Err(error);
}
};
+ if let Some(request_id) = transport::provider_request_id(response.headers(), api_format) {
+ tracing::Span::current().record("provider_request_id", request_id);
+ }
capture.record_response(response.status().as_u16(), response.headers());
let mut downstream = Response::new(Body::empty());
*downstream.status_mut() = response.status();
diff --git a/ai-gateway/src/providers/tests.rs b/ai-gateway/src/providers/tests.rs
index 13ba944669..2f7382672a 100644
--- a/ai-gateway/src/providers/tests.rs
+++ b/ai-gateway/src/providers/tests.rs
@@ -609,6 +609,7 @@ async fn compact_posts_compact_path_and_models_get_skips_ingestion() {
Bytes::from_static(COMPACT),
Route::OpenAiResponsesCompact,
None,
+ &mut crate::correlation::RequestCorrelation::default(),
)
.await
.unwrap();
@@ -632,6 +633,7 @@ async fn compact_posts_compact_path_and_models_get_skips_ingestion() {
Bytes::new(),
Route::OpenAiModels,
None,
+ &mut crate::correlation::RequestCorrelation::default(),
)
.await
.unwrap();
@@ -696,7 +698,8 @@ fn assert_completed_upload(payload: &serde_json::Value, streaming: bool) {
assert!(metadata.get("native_usage").is_none());
assert_eq!(metadata["langfuse.gateway.response.id"], "resp-1");
assert_eq!(metadata["langfuse.gateway.upstream.request.id"], "req-1");
- assert!(metadata.get("langfuse.gateway.request.id").is_none());
+ assert!(metadata["langfuse.gateway.request.id"].is_string());
+ assert!(metadata.get("langfuse.gateway.client.request.id").is_none());
let usage: Value = serde_json::from_str(
attrs
.iter()
@@ -821,6 +824,7 @@ async fn sends_the_x_api_key_credential_and_forwards_the_open_anthropic_header_f
Bytes::from_static(REQUEST),
Route::AnthropicMessages,
None,
+ &mut crate::correlation::RequestCorrelation::default(),
)
.await
.unwrap();
@@ -905,6 +909,7 @@ async fn count_tokens_relays_the_body_and_models_forwards_only_pagination() {
Bytes::from(body),
route,
query.as_deref(),
+ &mut crate::correlation::RequestCorrelation::default(),
)
.await
.unwrap();
diff --git a/ai-gateway/src/resolution/mod.rs b/ai-gateway/src/resolution/mod.rs
index 23bae11f23..98993a867d 100644
--- a/ai-gateway/src/resolution/mod.rs
+++ b/ai-gateway/src/resolution/mod.rs
@@ -18,6 +18,7 @@ use std::{
};
const RESOLVE_PATH: &str = "/api/internal/ai-gateway/v1/resolve";
+const REQUEST_ID_HEADER: &str = "langfuse-gateway-request-id";
// Web sits behind load balancers that drop idle connections after 60s by default
// (AWS ALB). Evicting pooled connections first keeps the resolver from sending on a
// socket the balancer is closing, which would fail without a retry.
@@ -114,6 +115,7 @@ impl ControlPlaneClient {
}
/// Resolve a gateway credential and API format into a validated execution contract.
+ /// `request_id` is the gateway request ID, sent so Web logs carry it.
///
/// # Errors
/// Returns a sanitized [`ResolutionError`] for invalid credentials, authentication or
@@ -123,11 +125,13 @@ impl ControlPlaneClient {
&self,
gateway_key: &str,
api_format: ApiFormat,
+ request_id: &str,
) -> Result<ResolvedRequestContext, ResolutionError> {
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|_| ResolutionError::Unavailable)?;
- self.resolve_at(gateway_key, api_format, timestamp).await
+ self.resolve_at(gateway_key, api_format, timestamp, request_id)
+ .await
}
async fn resolve_at(
@@ -135,6 +139,7 @@ impl ControlPlaneClient {
gateway_key: &str,
api_format: ApiFormat,
timestamp: Duration,
+ request_id: &str,
) -> Result<ResolvedRequestContext, ResolutionError> {
if gateway_key.len() > 8192 || !valid_token(gateway_key) {
return Err(ResolutionError::InvalidCredential);
@@ -142,7 +147,7 @@ impl ControlPlaneClient {
let started = Instant::now();
let body = tokio::time::timeout(
self.config.limits.timeout,
- self.fetch(gateway_key, api_format, timestamp.as_secs()),
+ self.fetch(gateway_key, api_format, timestamp.as_secs(), request_id),
)
.await
.map_err(|_| ResolutionError::Timeout)??;
@@ -158,6 +163,7 @@ impl ControlPlaneClient {
gateway_key: &str,
api_format: ApiFormat,
timestamp: u64,
+ request_id: &str,
) -> Result<Vec<u8>, ResolutionError> {
let mut credential = HeaderValue::from_str(&format!("Bearer {gateway_key}"))
.map_err(|_| ResolutionError::InvalidCredential)?;
@@ -176,6 +182,7 @@ impl ControlPlaneClient {
.post(self.config.endpoint(RESOLVE_PATH))
.header(AUTHORIZATION, credential)
.header("langfuse-gateway-authorization", signature)
+ .header(REQUEST_ID_HEADER, request_id)
.header(CONTENT_TYPE, "application/json")
.body(body)
.send()
diff --git a/ai-gateway/src/resolution/tests.rs b/ai-gateway/src/resolution/tests.rs
index 2959de4301..45dd611884 100644
--- a/ai-gateway/src/resolution/tests.rs
+++ b/ai-gateway/src/resolution/tests.rs
@@ -23,6 +23,7 @@ const NOW: u64 = 1_800_000_000;
const NOW_TIME: Duration = Duration::from_secs(NOW);
const SERVICE_KEY: &str = "gateway-web-test-secret-not-for-production";
const GATEWAY_KEY: &str = "gw_test_alice";
+const REQUEST_ID: &str = "0b0c3b5e-6d7a-4f1e-9c2d-8a1b2c3d4e5f";
struct FakeWeb {
url: String,
@@ -118,6 +119,7 @@ async fn signs_the_exact_key_and_sends_only_the_api_format() {
assert_eq!(request.uri(), "/api/internal/ai-gateway/v1/resolve");
assert_eq!(request.headers()[header::AUTHORIZATION], "Bearer gw_test_alice");
assert_eq!(request.headers()[header::CONTENT_TYPE], "application/json");
+ assert_eq!(request.headers()["langfuse-gateway-request-id"], REQUEST_ID);
assert_eq!(request.headers()["langfuse-gateway-authorization"],
"HMAC timestamp=1800000000,signature=e104b6baa50d9b766b036e27876683aa1f4bff7f31bb6af66dce6b636a53b2bd");
assert_eq!(to_bytes(request.into_body(), 1024).await.unwrap(),
@@ -127,7 +129,12 @@ async fn signs_the_exact_key_and_sends_only_the_api_format() {
let context = web
.control_plane()
- .resolve_at(GATEWAY_KEY, ApiFormat::OpenAiResponses, NOW_TIME)
+ .resolve_at(
+ GATEWAY_KEY,
+ ApiFormat::OpenAiResponses,
+ NOW_TIME,
+ REQUEST_ID,
+ )
.await
.unwrap();
assert_eq!(context.connection().id(), "connection-1");
@@ -173,7 +180,12 @@ async fn denied_and_failed_resolutions_are_classified_without_retries_or_body_le
.await;
let error = web
.control_plane()
- .resolve_at(GATEWAY_KEY, ApiFormat::OpenAiResponses, NOW_TIME)
+ .resolve_at(
+ GATEWAY_KEY,
+ ApiFormat::OpenAiResponses,
+ NOW_TIME,
+ REQUEST_ID,
+ )
.await
.unwrap_err();
assert!(match status {
@@ -205,7 +217,12 @@ async fn never_follows_redirects_with_credentials() {
.await;
assert!(
web.control_plane()
- .resolve_at(GATEWAY_KEY, ApiFormat::OpenAiResponses, NOW_TIME)
+ .resolve_at(
+ GATEWAY_KEY,
+ ApiFormat::OpenAiResponses,
+ NOW_TIME,
+ REQUEST_ID
+ )
.await
.is_err()
);
@@ -231,7 +248,12 @@ async fn rejects_oversized_declared_and_chunked_responses() {
.await;
let result = web
.control_plane_with_limits(Duration::from_secs(2), 128)
- .resolve_at(GATEWAY_KEY, ApiFormat::OpenAiResponses, NOW_TIME)
+ .resolve_at(
+ GATEWAY_KEY,
+ ApiFormat::OpenAiResponses,
+ NOW_TIME,
+ REQUEST_ID,
+ )
.await;
assert!(matches!(result, Err(ResolutionError::ResponseTooLarge)));
assert_eq!(web.calls(), 1);
@@ -258,7 +280,12 @@ async fn deadline_covers_response_headers_and_body() {
let result = tokio::time::timeout(
Duration::from_millis(500),
web.control_plane_with_limits(Duration::from_millis(30), 256 * 1024)
- .resolve_at(GATEWAY_KEY, ApiFormat::OpenAiResponses, NOW_TIME),
+ .resolve_at(
+ GATEWAY_KEY,
+ ApiFormat::OpenAiResponses,
+ NOW_TIME,
+ REQUEST_ID,
+ ),
)
.await
.expect("resolver must enforce its deadline");
@@ -273,7 +300,7 @@ async fn malformed_credentials_never_reach_web() {
for key in ["", "has space", "has\r\nheader", "has\ttab"] {
let result = web
.control_plane()
- .resolve_at(key, ApiFormat::OpenAiResponses, NOW_TIME)
+ .resolve_at(key, ApiFormat::OpenAiResponses, NOW_TIME, REQUEST_ID)
.await;
assert!(matches!(result, Err(ResolutionError::InvalidCredential)));
}
@@ -295,6 +322,7 @@ async fn rejects_a_grant_that_expires_while_resolving_across_a_second_boundary()
GATEWAY_KEY,
ApiFormat::OpenAiResponses,
NOW_TIME + Duration::from_millis(900),
+ REQUEST_ID,
)
.await;
assert!(matches!(result, Err(ResolutionError::InvalidResponse)));
@@ -316,8 +344,18 @@ async fn concurrent_resolutions_keep_credentials_and_contexts_isolated() {
.await;
let control_plane = web.control_plane();
let (alice, bob) = tokio::join!(
- control_plane.resolve_at("gw_test_alice", ApiFormat::OpenAiResponses, NOW_TIME),
- control_plane.resolve_at("gw_test_bob", ApiFormat::OpenAiResponses, NOW_TIME),
+ control_plane.resolve_at(
+ "gw_test_alice",
+ ApiFormat::OpenAiResponses,
+ NOW_TIME,
+ REQUEST_ID
+ ),
+ control_plane.resolve_at(
+ "gw_test_bob",
+ ApiFormat::OpenAiResponses,
+ NOW_TIME,
+ REQUEST_ID
+ ),
);
let alice = alice.unwrap();
let bob = bob.unwrap();
@@ -360,7 +398,12 @@ async fn resolves_anthropic_messages_with_the_native_credential_scheme() {
let context = web
.control_plane()
- .resolve_at(GATEWAY_KEY, ApiFormat::AnthropicMessages, NOW_TIME)
+ .resolve_at(
+ GATEWAY_KEY,
+ ApiFormat::AnthropicMessages,
+ NOW_TIME,
+ REQUEST_ID,
+ )
.await
.unwrap();
assert_eq!(context.connection().id(), "connection-anthropic");
@@ -540,7 +583,12 @@ async fn rejects_ingestion_tokens_that_authorize_a_different_tenant() {
.await;
assert!(
web.control_plane()
- .resolve_at(GATEWAY_KEY, ApiFormat::OpenAiResponses, NOW_TIME)
+ .resolve_at(
+ GATEWAY_KEY,
+ ApiFormat::OpenAiResponses,
+ NOW_TIME,
+ REQUEST_ID
+ )
.await
.is_ok()
);
@@ -558,7 +606,7 @@ async fn assert_invalid_context_for(body: Value, api_format: ApiFormat) {
.await;
let result = web
.control_plane()
- .resolve_at(GATEWAY_KEY, api_format, NOW_TIME)
+ .resolve_at(GATEWAY_KEY, api_format, NOW_TIME, REQUEST_ID)
.await;
assert!(matches!(result, Err(ResolutionError::InvalidResponse)));
assert_eq!(web.calls(), 1);
@@ -572,7 +620,12 @@ async fn rejects_malformed_json_without_exposing_response_contents() {
.await;
let error = web
.control_plane()
- .resolve_at(GATEWAY_KEY, ApiFormat::OpenAiResponses, NOW_TIME)
+ .resolve_at(
+ GATEWAY_KEY,
+ ApiFormat::OpenAiResponses,
+ NOW_TIME,
+ REQUEST_ID,
+ )
.await
.unwrap_err();
assert!(matches!(error, ResolutionError::InvalidResponse));
diff --git a/ai-gateway/src/telemetry/mapping.rs b/ai-gateway/src/telemetry/mapping.rs
index 89c184bf59..27515a20c3 100644
--- a/ai-gateway/src/telemetry/mapping.rs
+++ b/ai-gateway/src/telemetry/mapping.rs
@@ -190,6 +190,15 @@ fn generation_metadata(facts: &InferenceFacts) -> Map<String, Value> {
for (key, value) in &facts.inference.request_metadata {
metadata.insert(format!("langfuse.gateway.request.{key}"), value.clone());
}
+ // Inserted after caller request metadata so the gateway's own ID always wins.
+ for (source, target) in [
+ ("request_id", "request.id"),
+ ("client_request_id", "client.request.id"),
+ ] {
+ if let Some(value) = facts.metadata.get(source) {
+ metadata.insert(format!("langfuse.gateway.{target}"), value.clone());
+ }
+ }
if let Some(omission) = facts.inference.input_omission {
metadata.insert(
"langfuse.gateway.request.input_omitted".into(),
diff --git a/ai-gateway/src/telemetry/mod.rs b/ai-gateway/src/telemetry/mod.rs
index bc26140d65..e0442de8c8 100644
--- a/ai-gateway/src/telemetry/mod.rs
+++ b/ai-gateway/src/telemetry/mod.rs
@@ -81,6 +81,13 @@ impl DeliveryContext {
generation: GenerationContext::from_request(headers, client_metadata),
}
}
+
+ pub fn generation_ids(&self) -> crate::correlation::GenerationIds {
+ crate::correlation::GenerationIds {
+ trace_id: self.generation.trace_id.clone(),
+ observation_id: self.generation.observation_id.clone(),
+ }
+ }
}
#[derive(Default)]
diff --git a/ai-gateway/src/test_support.rs b/ai-gateway/src/test_support.rs
index b389a4b454..a078ce8837 100644
--- a/ai-gateway/src/test_support.rs
+++ b/ai-gateway/src/test_support.rs
@@ -165,7 +165,7 @@ pub(crate) async fn resolved_request_context_for(
})
.await;
web.control_plane()
- .resolve("gateway-secret", api_format)
+ .resolve("gateway-secret", api_format, "test-request-id")
.await
.unwrap()
}
diff --git a/ai-gateway/src/transport/mod.rs b/ai-gateway/src/transport/mod.rs
index 8665f71a20..c543695363 100644
--- a/ai-gateway/src/transport/mod.rs
+++ b/ai-gateway/src/transport/mod.rs
@@ -122,6 +122,19 @@ pub(crate) fn response_headers(source: &HeaderMap, api_format: ApiFormat) -> Hea
}
}
+/// The provider's own request ID, bounded like other captured provider facts.
+pub(crate) fn provider_request_id(headers: &HeaderMap, api_format: ApiFormat) -> Option<&str> {
+ let name = match api_format {
+ ApiFormat::OpenAiResponses => "x-request-id",
+ ApiFormat::AnthropicMessages => "request-id",
+ };
+ headers
+ .get(name)?
+ .to_str()
+ .ok()
+ .filter(|value| value.len() <= 512)
+}
+
pub(crate) fn relay<T: Send + 'static>(
upstream: reqwest::Response,
deadline: Instant,
diff --git a/ai-gateway/tests/observability.rs b/ai-gateway/tests/observability.rs
index 1dff2eff4e..5ad2723f76 100644
--- a/ai-gateway/tests/observability.rs
+++ b/ai-gateway/tests/observability.rs
@@ -69,7 +69,7 @@ impl Gateway {
}
}
- async fn request(&self, sampled: bool) {
+ async fn request(&self, sampled: bool) -> String {
let response = reqwest::Client::new()
.post(format!(
"{}/openai/v1/responses?secret=query-canary",
@@ -87,13 +87,20 @@ impl Gateway {
.header("tracestate", "caller=state-canary")
.header("baggage", "langfuse_user_id=baggage-canary")
.header("langfuse-session-id", "session-canary")
+ .header("x-request-id", "client-request-canary")
.header("authorization", "Bearer secret-auth-token")
.body(r#"{"input":"secret-prompt-content"}"#)
.send()
.await
.unwrap();
assert_eq!(response.status(), 503);
- let _ = response.bytes().await.unwrap();
+ let id = response.headers()["langfuse-request-id"]
+ .to_str()
+ .unwrap()
+ .to_owned();
+ let body: Value = serde_json::from_slice(&response.bytes().await.unwrap()).unwrap();
+ assert_eq!(body["request_id"], id.as_str());
+ id
}
async fn stop(&mut self) {
@@ -148,8 +155,8 @@ async fn exports_otlp_traces_metrics_and_correlated_content_free_logs() {
let endpoint = format!("http://{}", listener.local_addr().unwrap());
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let mut gateway = Gateway::start(&endpoint, "5", "debug");
- gateway.request(true).await;
- gateway.request(false).await;
+ let request_ids = [gateway.request(true).await, gateway.request(false).await];
+ assert_ne!(request_ids[0], request_ids[1]);
assert_eq!(
reqwest::get(format!("{}/health", gateway.url))
.await
@@ -182,6 +189,7 @@ async fn exports_otlp_traces_metrics_and_correlated_content_free_logs() {
assert!(!metrics.is_empty(), "metrics must flush on shutdown");
let logs = gateway.logs.lock().unwrap();
assert_operational_traces(&traces, &logs);
+ assert_request_correlation(&traces, &logs, &request_ids);
let serialized = serde_json::to_string(&*logs).unwrap();
let exported = format!("{traces:?}{metrics:?}");
for secret in [
@@ -243,6 +251,55 @@ fn assert_operational_traces(traces: &[ResourceSpans], logs: &[Value]) {
}
}
+/// Every log line emitted while serving a request repeats its gateway request ID at
+/// the top level, and the operational server span carries it as an attribute.
+fn assert_request_correlation(traces: &[ResourceSpans], logs: &[Value], request_ids: &[String]) {
+ let spans: Vec<_> = traces
+ .iter()
+ .flat_map(|resource| &resource.scope_spans)
+ .flat_map(|scope| &scope.spans)
+ .collect();
+ let attribute = |span: &opentelemetry_proto::tonic::trace::v1::Span, key: &str| {
+ span.attributes
+ .iter()
+ .find(|attribute| attribute.key == key)
+ .and_then(|attribute| attribute.value.as_ref()?.value.clone())
+ };
+ let mut span_ids: Vec<_> = spans
+ .iter()
+ .map(|span| {
+ assert_eq!(
+ attribute(span, "gateway.client.request.id"),
+ Some(AttributeValue::StringValue("client-request-canary".into()))
+ );
+ match attribute(span, "gateway.request.id") {
+ Some(AttributeValue::StringValue(id)) => id,
+ other => panic!("server span lacks gateway.request.id: {other:?}"),
+ }
+ })
+ .collect();
+ span_ids.sort();
+ let mut expected = request_ids.to_vec();
+ expected.sort();
+ assert_eq!(span_ids, expected);
+ let request_logs: Vec<_> = logs
+ .iter()
+ .filter(|log| {
+ log["spans"]
+ .as_array()
+ .is_some_and(|spans| spans.iter().any(|span| span["name"] == "http.server"))
+ })
+ .collect();
+ assert!(request_logs.len() >= 4, "{request_logs:?}");
+ for log in request_logs {
+ let id = log["request_id"]
+ .as_str()
+ .unwrap_or_else(|| panic!("{log}"));
+ assert!(request_ids.iter().any(|expected| expected == id), "{log}");
+ assert_eq!(log["spans"][0]["gateway.request.id"], id, "{log}");
+ }
+}
+
fn assert_http_metrics(metrics: &[ResourceMetrics]) {
let http_duration = metrics
.iter()
diff --git a/packages/shared/src/server/otel/OtelIngestionProcessor.metadataDropped.test.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.metadataDropped.test.ts
index 0ee33c84ae..2c82dd4d64 100644
--- a/packages/shared/src/server/otel/OtelIngestionProcessor.metadataDropped.test.ts
+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.metadataDropped.test.ts
@@ -139,6 +139,13 @@ const expectDropTags = (
expect(tags?.sdkVersion).toBe("3.8.1");
};
+// The gateway links a generation to its logs and provider call through these keys.
+const gatewayRequestIds = {
+ request: "0192b6f4-6c1e-7a3b-8c4d-5e6f7a8b9c0d",
+ client: "client-request",
+ upstream: "req_upstream",
+};
+
describe("gateway metadata", () => {
it.each([
["v3", "langfuse-ai-gateway"],
@@ -178,6 +185,9 @@ describe("gateway metadata", () => {
"langfuse.observation.output": '[{"type":"message","content":[]}]',
"langfuse.observation.metadata": JSON.stringify({
"langfuse.gateway.provider.request.id": "req-test",
+ "langfuse.gateway.request.id": gatewayRequestIds.request,
+ "langfuse.gateway.client.request.id": gatewayRequestIds.client,
+ "langfuse.gateway.upstream.request.id": gatewayRequestIds.upstream,
}),
"langfuse.observation.metadata.langfuse.gateway.api-key.id":
"key-test",
@@ -225,6 +235,9 @@ describe("gateway metadata", () => {
});
expect(observation?.metadata).toEqual({
"langfuse.gateway.provider.request.id": "req-test",
+ "langfuse.gateway.request.id": gatewayRequestIds.request,
+ "langfuse.gateway.client.request.id": gatewayRequestIds.client,
+ "langfuse.gateway.upstream.request.id": gatewayRequestIds.upstream,
"langfuse.gateway.api-key.id": "key-test",
attributes: {
...(scope === "langfuse-ai-gateway" ? {} : canonicalAttributes),
diff --git a/web/src/features/ai-gateway/server/auth/gatewayRequestSignatureVerifier.servertest.ts b/web/src/features/ai-gateway/server/auth/gatewayRequestSignatureVerifier.servertest.ts
index fb0b3a00dd..69e6b83e6d 100644
--- a/web/src/features/ai-gateway/server/auth/gatewayRequestSignatureVerifier.servertest.ts
+++ b/web/src/features/ai-gateway/server/auth/gatewayRequestSignatureVerifier.servertest.ts
@@ -1,6 +1,7 @@
import { createHash } from "node:crypto";
import { Readable } from "node:stream";
+import { propagation, ROOT_CONTEXT } from "@opentelemetry/api";
import type { NextApiRequest, NextApiResponse } from "next";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -8,6 +9,7 @@ import { signHmacSha256 } from "@/src/server/utils/hmac";
import { createShaHash } from "@langfuse/shared/src/server/auth/apiKeys";
import {
+ contextWithGatewayRequestId,
withGatewayModelsSignatureVerification,
withGatewayResolveSignatureVerification,
} from "./gatewayRequestSignatureVerifier";
@@ -211,3 +213,30 @@ describe("withGatewayResolveSignatureVerification", () => {
}
});
});
+
+describe("contextWithGatewayRequestId", () => {
+ const requestId = "0192b6f4-6c1e-7a3b-8c4d-5e6f7a8b9c0d";
+ const loggedRequestId = (headers: NextApiRequest["headers"]) =>
+ propagation
+ .getBaggage(
+ contextWithGatewayRequestId(
+ { headers } as NextApiRequest,
+ ROOT_CONTEXT,
+ ),
+ )
+ ?.getEntry("langfuse.gateway.request.id")?.value;
+
+ it("adds the gateway request ID to the log context", () => {
+ expect(loggedRequestId({ "langfuse-gateway-request-id": requestId })).toBe(
+ requestId,
+ );
+ });
+
+ it.each([
+ ["missing", {}],
+ ["not a UUID", { "langfuse-gateway-request-id": "req\ninjected" }],
+ ["repeated", { "langfuse-gateway-request-id": [requestId, requestId] }],
+ ])("ignores a %s request ID", (_, headers) => {
+ expect(loggedRequestId(headers)).toBeUndefined();
+ });
+});
diff --git a/web/src/features/ai-gateway/server/auth/gatewayRequestSignatureVerifier.ts b/web/src/features/ai-gateway/server/auth/gatewayRequestSignatureVerifier.ts
index 4ea8498121..92fbaf9fd6 100644
--- a/web/src/features/ai-gateway/server/auth/gatewayRequestSignatureVerifier.ts
+++ b/web/src/features/ai-gateway/server/auth/gatewayRequestSignatureVerifier.ts
@@ -1,5 +1,6 @@
import { createHash } from "node:crypto";
+import { context, propagation, trace, type Context } from "@opentelemetry/api";
import type { NextApiRequest, NextApiResponse } from "next";
import { z } from "zod/v4";
@@ -23,6 +24,8 @@ const resolveBodySchema = z
const modelsQuerySchema = z
.object({ api_format: GatewayApiFormatSchema })
.strict();
+const GATEWAY_REQUEST_ID_HEADER = "langfuse-gateway-request-id";
+const GATEWAY_REQUEST_ID_KEY = "langfuse.gateway.request.id";
const gatewayAuthorizationSchema =
/^HMAC timestamp=(\d+),signature=([0-9a-f]{64})$/;
@@ -76,6 +79,27 @@ function verifyGatewayRequestSignatureAndHashApiKey(input: {
return createShaHash(input.virtualSecretKey, env.SALT);
}
+/**
+ * Adds the gateway's request ID to the active span and to the baggage the logger
+ * copies onto every line, so Web resolution logs join the gateway's. Call it
+ * only after the gateway signature is verified; the header itself is unsigned,
+ * so only a single UUID is accepted.
+ */
+export function contextWithGatewayRequestId(
+ req: Pick<NextApiRequest, "headers">,
+ parent: Context = context.active(),
+): Context {
+ const requestId = singleHeader(req.headers[GATEWAY_REQUEST_ID_HEADER]);
+ if (!requestId || !z.uuid().safeParse(requestId).success) return parent;
+
+ trace.getSpan(parent)?.setAttribute(GATEWAY_REQUEST_ID_KEY, requestId);
+ const baggage = (
+ propagation.getBaggage(parent) ?? propagation.createBaggage()
+ ).setEntry(GATEWAY_REQUEST_ID_KEY, { value: requestId });
+
+ return propagation.setBaggage(parent, baggage);
+}
+
export function withGatewayResolveSignatureVerification(
handler: GatewayResolveHandler,
) {
@@ -170,12 +194,14 @@ function withGatewayControlPlaneAuth<
),
});
- return await handler({
- req,
- res,
- fastHashedSecretKey,
- body: body.data,
- });
+ return await context.with(contextWithGatewayRequestId(req), () =>
+ handler({
+ req,
+ res,
+ fastHashedSecretKey,
+ body: body.data,
+ }),
+ );
} catch (error) {
if (error instanceof GatewayControlPlaneError) {
return res.status(error.status).json({ error: error.message });