# Access Logs and Request Correlation

An AISIX gateway writes structured access logs and records identifiers that connect requests to callers, fronting infrastructure, and upstream providers. Together, these records let operators reconstruct what happened and find the corresponding entries in each system.

## Collect Access Logs[​](#collect-access-logs "Direct link to Collect Access Logs")

AISIX writes access logs through the process logger to standard error. Your container runtime, service manager, or host logging pipeline can collect that stream.

Set the process log level in the startup configuration. The default is `warn`, which writes `WARN` and above:

config.yaml

```
observability:

  log_level: "warn"
```

Raise it to `info` while diagnosing. That adds the lifecycle lines, such as `aisix listening` and `etcd connected`, the per-call lines, such as `provider call completed`, and guardrail diagnostics such as monitor-mode observations. At the default level none of these are written, so confirm that a gateway has started through [`/readyz`](https://docs.api7.ai/ai-gateway/deployment/health-checks.md#traffic-readiness), not from its log. The level is read at startup, so changing it takes a restart. A gateway at 1.9.0 or earlier defaults to `info`.

When set to a valid filter, the `RUST_LOG` environment variable overrides the configured log level.

Access logging is on by default and does not depend on the log level: while `access_log` is on, AISIX writes each access-log line whatever `log_level` or `RUST_LOG` says. A `RUST_LOG` that names the target, such as `info,aisix_obs::access_log=off`, does not stop it. To turn the access log off, set `access_log` to `false`:

config.yaml

```
observability:

  access_log: false
```

A gateway at 1.9.0 or earlier writes the access log at `info`, so it writes no line when the effective log filter is below `info`, and a `RUST_LOG` naming its target can turn it off.

With `access_log: false`, AISIX writes no access-log line, and every other log line is unaffected. The setting is read at startup. There is no separate access-log format or sink setting; collect the process's standard error stream.

An access log includes the request method, path, status, timing, provider, model, API key ID, request ID, token counts, routing outcome, the response-cache verdict, and the request and response [body sizes](#read-the-body-sizes) when those values are available.

For a failed request, `error_class` provides a stable failure category and `error` provides the underlying reason. A line with a status of `400` or above always has an `error`: when nothing more specific reached the line, such as on a refused `GET /mcp`, it reads `request failed with status <status>` and `error_class` can be empty. A gateway at 1.8.0 or earlier leaves `error` empty in that fallback case.

`error_class` uses the same class vocabulary as the usage event's `error_class`, which differs from the client-facing `error.type` for upstream failures. For example, an upstream HTTP error is `upstream_status` in the access log and `upstream_error` in the error envelope. See [Read the Error Class](https://docs.api7.ai/ai-gateway/observability/metrics-and-usage-events.md#read-the-error-class) for the full vocabulary.

The status, error class, addressed model, and caller wait are written as `status_code`, `error_class`, `requested_model`, and `downstream_latency_ms`. The usage event uses the same names for the same values, so a line and the usage events for the same `request_id` read the same way. A gateway at 1.7.1 or earlier writes them as `status`, `error_kind`, `model`, and `latency_ms`. Only one set of names is written.

MCP access logs add the JSON-RPC method, called tool, and tool-discovery counts. See [MCP Observability](https://docs.api7.ai/ai-gateway/mcp-gateway/observability.md#access-logs) to use these fields when diagnosing tool discovery and access.

### Absorb a Slow Log Consumer[​](#absorb-a-slow-log-consumer "Direct link to Absorb a Slow Log Consumer")

AISIX does not write log lines from the thread that produced them. Access-log and application-log lines go into an in-memory queue of 32,768 lines, and one dedicated writer thread drains it into standard error. A consumer that stops reading — a container runtime rotating the log file is the routine case — therefore fills a pipe buffer that the writer thread waits on, instead of stalling request handling.

If the stall lasts long enough to fill the queue, AISIX drops **new** lines rather than making requests wait for them. Each drop increments `aisix_log_lines_dropped_total`, and once the consumer catches up the gateway logs one `log sink fell behind; dropped log events` warning naming how many lines were lost. The counter is published on every scrape, so a healthy gateway reports `0`.

There is no configuration for this. The queue size is fixed, and a non-zero drop count is a signal to investigate the log collector rather than the gateway. A graceful shutdown waits up to five seconds for the queue to drain, so the final lines of a controlled stop reach the collector unless the collector is itself stuck.

### Know Which Requests Are Logged[​](#know-which-requests-are-logged "Direct link to Know Which Requests Are Logged")

Every request that the gateway's proxy listener answers writes one access-log line, including requests that never reach a model:

* Authentication denials: a `401` for a missing or rejected credential, and the `403` for a JWT that lacks a required scope. The line carries `status_code`, `error_class`, and `error`, but no `api_key_id`, because no key was resolved. It never contains any part of the presented credential. The separate `aisix::auth` log line for the same request carries the caller's address, and the key ID of a disabled or expired API key. That line is written at `debug` for a missing credential or an unknown API key.
* A path that matches no route, answered with `404`, and a known path called with a method it does not serve, answered with `405`.
* `GET /v1/models`, the A2A agent card at `/a2a/{agent}/.well-known/agent-card.json`, and the OAuth protected-resource discovery documents.

The `/livez` and `/readyz` probes write no access-log line.

Because unauthenticated requests are logged, an internet-facing gateway records scanner probes and other stray traffic in its access log. There is no setting that filters them out; `access_log` turns the whole access log on or off.

### Read the Two Timing Fields[​](#read-the-two-timing-fields "Direct link to Read the Two Timing Fields")

Every line carries two durations, and they answer different questions:

| Field                   | Measures                                                                                                                                   |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `downstream_latency_ms` | What the caller waited for. It ends when the response head was written, which for a streamed response is the first token or relayed frame. |
| `duration_ms`           | How long the request occupied the gateway, from receipt until the request ended.                                                           |

`downstream_latency_ms` is never greater than `duration_ms`, and the two coincide on a buffered response because nothing follows the head. Their difference is the length of the stream, so use `downstream_latency_ms` for the caller's experience and `duration_ms` for how long a connection was held.

Some route families measure differently by design:

* On `/a2a` and the audio transcription relays, `downstream_latency_ms` already covers the whole stream, which is the figure the usage event reports as the caller's wait. It therefore matches `duration_ms` rather than being shorter than it.
* `/v1/audio/speech` relays the generated audio to the caller after the upstream answers, and its `duration_ms` spans that relay to the last byte.
* On `/v1/videos/{id}/content`, a video the gateway proxies from the provider likewise has a `duration_ms` that spans the relay. A redirect to the provider's own URL, or an error, ends `duration_ms` when the gateway produces the response.

### Read the Token Counts[​](#read-the-token-counts "Direct link to Read the Token Counts")

The line carries `prompt_tokens`, `completion_tokens`, and `total_tokens` whenever the request produced token usage. This covers chat completions, streamed responses, and non-streamed requests to `/v1/messages`, `/v1/embeddings`, `/v1/responses`, `/v1/completions`, `/v1/rerank`, `/v1/images/*`, `/v1/audio/*`, `/v1/systemone`, `/v1/decisions`, and `/a2a`. These lines report the same counts as the request's terminal usage event. A `/v1/realtime` line carries the session's input and output totals.

When a request produces no token usage, its line omits the token fields rather than writing zeros. The fields are also absent from `/v1/messages/count_tokens`; Files, Batches, and Fine-tuning management calls; `/v1/videos`; and `/mcp`. AISIX also omits them for authentication and routing refusals, the `499` line for a caller that left before the response head, and a Realtime session that failed before it opened.

A gateway at 1.7.1 or earlier writes token fields only on chat completions, passthrough routes, and streamed responses. Its non-streamed lines on the other endpoints above, and its Realtime lines, carry none.

`total_tokens` on the line is the gateway's cache-inclusive sum: prompt, completion, cache-creation, and cache-read tokens. Cache tokens that an upstream such as Anthropic reports separately from input are added, while cache reads that an upstream such as OpenAI already counts inside its prompt tokens are not counted twice. This is the figure rate limits and the token metrics use. The `total_tokens` of a usage event, as the SLS, object storage, and Datadog exporters deliver it, is instead the total the upstream reported, and is absent when the upstream reported none.

### Read the Body Sizes[​](#read-the-body-sizes "Direct link to Read the Body Sizes")

The line reports how many body bytes crossed the gateway in each direction. Both fields are unsigned byte counts:

| Field                 | Measures                                                                                                                                                                                                                                      |
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `request_body_bytes`  | Request body bytes the gateway read from the caller. The gateway does not decompress a request body, so this is the size on the wire.                                                                                                         |
| `response_body_bytes` | Response body bytes the gateway handed to its HTTP server for the caller, including SSE framing such as `data:` and `event:` lines and `[DONE]`, and keep-alive heartbeat frames. Headers, chunked transfer framing, and TLS are not counted. |

A size that is unknown is omitted from the line rather than written as `0`, because `0` is a real size.

`request_body_bytes` is present only when the gateway read the body to its end. That includes a request refused after its body was read, such as one with malformed JSON, and a `499` line whose body had been read before the caller left. It is omitted when:

* the gateway refused the request from its `Content-Length` before reading the body, which is the `413` from `proxy.request_body_limit_bytes`;
* the route never reads a body, as on most `GET` requests and an `/a2a` call to an unknown agent;
* the caller disconnected before or during the upload;
* the request opened a `/v1/realtime` session.

`response_body_bytes` is omitted only on the `499` line of a caller that left before the response head was written, and on `/v1/realtime`, whose WebSocket session has no HTTP response body. A response whose body the server never read, such as the answer to a `HEAD` request, reports `0`. When the caller disconnects mid-response, the field counts what had been handed to the server until then, which can exceed what the caller received.

### Read the Semantic Routing Decision[​](#read-the-semantic-routing-decision "Direct link to Read the Semantic Routing Decision")

A request addressed to a [semantic router](https://docs.api7.ai/ai-gateway/routing/semantic-routing.md) records how the router decided, whether it uses an embedding model or a classifier. Once the router has decided, the fields appear on the request's line however the request then ends. Lines of requests to other models never carry them:

| Field               | When present                                                                                                                                                                  | Value                                                                                                                                                                                     |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `semantic_route`    | A route's target served the request.                                                                                                                                          | The name of the route. The `x-aisix-route` response header reports the same name when `proxy.expose_debug_headers` is `true`.                                                             |
| `semantic_score`    | The router computed a decision.                                                                                                                                               | For an embedding router, the cosine similarity of the winning route, or of the closest route when none matched. For a classifier, the decision model's confidence in the route it picked. |
| `semantic_fallback` | No route served the request.                                                                                                                                                  | Why the default model or the failure policy handled it, as listed below.                                                                                                                  |
| `semantic_pinned`   | The request went to the route its session is [pinned](https://docs.api7.ai/ai-gateway/routing/semantic-routing.md#pin-a-session-to-its-route) to instead of being classified. | Always `true`. The field is absent on every other line.                                                                                                                                   |

`semantic_fallback` takes one of these values:

| Value                | Meaning                                                                                                                                                                                                                       |
| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `no_match`           | Embedding router: no route reached its threshold.                                                                                                                                                                             |
| `low_confidence`     | The classifier picked a route with confidence below `min_confidence`.                                                                                                                                                         |
| `empty_prompt`       | The request carried no user text to decide on, so it went to the default model without a decision call.                                                                                                                       |
| `decision_failed`    | The embedding or classifier call failed or timed out, and the router's failure policy applied. That includes a `503` when the policy is `fail`, whose line carries `error_class="semantic_decision_failed"`.                  |
| `target_unavailable` | A route was picked, but its target could not serve this caller, because the target's client-IP allowlist excluded the caller or the target was unavailable while the default model was not. The default model served instead. |

`semantic_score` is also present on a `no_match`, `low_confidence`, or `target_unavailable` line, which makes it the value to compare with a threshold or `min_confidence` when tuning a router. It is absent when no decision was computed, as with `empty_prompt`, `decision_failed`, and every line with `semantic_pinned`. A pinned request whose target was unavailable carries `semantic_pinned=true` and `semantic_fallback="target_unavailable"`, and no `semantic_route`. A gateway before 1.10.0 does not write `semantic_pinned`.

### Identify the Target That Served the Request[​](#identify-the-target-that-served-the-request "Direct link to Identify the Target That Served the Request")

Once the gateway selects a target, the line carries `upstream_model` and `provider_key_id` beside `requested_model`. `requested_model` keeps its meaning — the entry the caller addressed, which is the group name for a routing request — while the new pair names the target actually dispatched to and the provider key it used. Both are omitted from the line when no target was selected, such as a request refused before dispatch or abandoned before routing resolved.

A request addressed to a Model Group also carries `served_by_model`, the name of the target that served it. This is the value the `x-aisix-served-by` response header reports, and the line records it even when the gateway does not send that header. The gateway sends it only when [`proxy.expose_debug_headers`](https://docs.api7.ai/ai-gateway/reference/configuration-files.md#expose-debug-response-headers) is `true`.

A response served from the response cache also dispatched to nothing, and what the pair reports then depends on the kind of entry the caller addressed. See [Read the Cache Verdict](#read-the-cache-verdict).

### Read the Cache Verdict[​](#read-the-cache-verdict "Direct link to Read the Cache Verdict")

On `/v1/chat/completions`, the line reports how the response cache answered the request:

| Field             | Values                                       |
| ----------------- | -------------------------------------------- |
| `cache_status`    | `disabled`, `miss`, `hit`, or `bypass`       |
| `cache_hit_layer` | `exact` or `semantic`. Present only on a hit |

Both fields are spelled as the usage event spells them, so a line and the usage events for the same `request_id` read the same way. They are omitted on every line that had no cache decision to report: the other routes, which do not cache, and a line written before the request produced a response. A streamed or cancelled line takes both values from the request's terminal usage event, so the two can never disagree; because streaming responses are never cached, such a line reports `cache_status="disabled"` even where the environment has a cache policy enabled.

A cache hit contacts no upstream, so the target-shaped fields on its line report only what the addressed entry can claim without a dispatch:

| Field on a cache hit                     | Direct model                                                                                                                                                        | Model Group (routing or semantic)                                                                                                                                                                     |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `upstream_model`, `provider_key_id`      | The entry's own static mapping. These are properties of the model, true whether a request ever left the gateway — not evidence that this request reached a provider | Omitted. A group has no mapping of its own, and which of its targets produced the stored response is not recorded anywhere                                                                            |
| `provider`                               | The entry's own provider                                                                                                                                            | `unknown`. Unlike the pair above, it keeps the sentinel instead of being omitted, because it is the same string the Prometheus `provider` label carries for the request, and a label cannot be absent |
| `served_by_model`, `provider_request_id` | Omitted                                                                                                                                                             | Omitted                                                                                                                                                                                               |

`cache_status` is what tells a cache-served response apart from a request that never reached a provider; the absence of target fields alone does not. A cache hit that an output guardrail then blocks follows every rule above and still reports `cache_status="hit"`, even though the line ends as a `422`.

The request's usage event reports the same verdict and adds what the stored response itself records; see [What the Usage Log Records](https://docs.api7.ai/ai-gateway/observability/metrics-and-usage-events.md#what-the-usage-log-records).

## Understand Log Timing and Coverage[​](#understand-log-timing-and-coverage "Direct link to Understand Log Timing and Coverage")

AISIX writes exactly one access-log line per request, whatever the outcome. When it is written determines which details the line can carry:

| Signal                                                                                                       | Written                                                                                  | What it provides                                                                                                                                                                                                                             |
| ------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Access log for a non-streamed request                                                                        | When the response body has been handed to the server, or dropped because the caller left | The request outcome and all fields the gateway resolved, including token counts and the provider response ID when available.                                                                                                                 |
| Access log for a streamed request                                                                            | When the stream ends                                                                     | The final status and token counts. Modeled proxy streams can also record `provider_request_id`, `served_by_model`, and routing counts, which passthrough streams leave empty. Both carry the same error details as the terminal usage event. |
| Access log for a Realtime session                                                                            | After the WebSocket session closes                                                       | The session outcome, resolved request fields, and the session's token totals.                                                                                                                                                                |
| Access log for a cancelled request                                                                           | When the caller hangs up before the response head                                        | Status `499` and the identities the request had resolved by then, including the dispatched target. Token counts, `provider_request_id`, and the routing counts stay empty, because the request never produced them.                          |
| `provider call completed` log, written at `info`                                                             | Once for each provider call that records a `provider_request_id`                         | `request_id`, `attempt_index`, `is_final_attempt`, `attempt_kind`, and `provider_request_id` for that upstream attempt.                                                                                                                      |
| [Usage event](https://docs.api7.ai/ai-gateway/observability/metrics-and-usage-events.md#export-usage-events) | Once per request attempt on supported proxy paths                                        | Attempt outcome, consumption, latency, and provider response ID when available.                                                                                                                                                              |

A streamed request writes its line when the stream ends, so the line carries the final status, such as `499` for a stream the caller abandoned, and the token counts.

Every line that has a response body is written once that body is finished with, because only then are both [body sizes](#read-the-body-sizes) final. What the line reports does not change, and there is still one line per request: a streamed line uses the terminal request status and token counts. Writing every line at the end has two visible effects:

* The access-log line comes after the request's `provider call completed` lines.
* If the deployment platform stops the process while a slow caller is still reading a response body, for example when `terminationGracePeriodSeconds` runs out, that request's line is never written. This applies to streamed and buffered responses alike. See [Size the Platform Deadline](https://docs.api7.ai/ai-gateway/deployment/graceful-shutdown.md#size-the-platform-deadline) for sizing that limit.

### Trace Provider Attempts[​](#trace-provider-attempts "Direct link to Trace Provider Attempts")

`provider_request_id` is the ID the provider gave the call. Use it to find the call in the provider's console or support records. AISIX takes it from the response object when there is one, such as an OpenAI `chat.completion.id`, an Anthropic message `id`, a Responses API `resp_…`, or a Gemini `responseId`. Otherwise it takes the provider's request-ID response header, the first present of `x-amzn-requestid`, `x-request-id`, `request-id`, `x-ms-request-id`, `apim-request-id`, `x-goog-request-id`, and `cf-ray`. The header covers the calls whose response has no ID of its own: every failed upstream attempt, including a stream that fails before its first token, `/v1/messages/count_tokens`, and successful embeddings, audio, image, rerank, and Bedrock calls. A retried request's events each carry the ID of the response that answered that attempt.

The field is omitted rather than left blank when no ID is available, including for guardrail blocks, cache hits, requests refused before dispatch, and calls whose provider sent neither a response ID nor one of those headers. `/v1/realtime` records no header ID. On modeled proxy routes, a streamed response carries the ID when it arrives in the first frame because the line is written at the stream's end, unless the caller leaves before that frame.

A failed request's line names the provider of the target it attempted, as the request metrics do. A request that failed before dispatch names no provider.

The access log reports the ID of the attempt that served the request. To see the other attempts of a retried or failed-over request, read the `provider call completed` entries: join them to the access log by `request_id`, and use `attempt_index` to distinguish retries from failovers. These entries are written at `info`, so they need `log_level: "info"`.

A failed upstream attempt during retries or failover also writes a `WARN` line with the message `routing target attempt failed`. The line carries `request_id` as its own field, beside `target_model`, `target_attempt`, `error`, and `retryable`, so it joins to the request at every log level. A gateway at 1.9.0 or earlier does not write the request span that prefixes other lines with the request ID when the level is below `info`, which leaves this field as the only link.

## Correlate a Request Across Systems[​](#correlate-a-request-across-systems "Direct link to Correlate a Request Across Systems")

The `x-aisix-request-id` response header is the main join key for request records, and AISIX sends it on every proxy response. Other response headers report retry timing and, when the gateway enables [`proxy.expose_debug_headers`](https://docs.api7.ai/ai-gateway/reference/configuration-files.md#expose-debug-response-headers), cache outcomes and selected targets; see [Headers and Error Codes](https://docs.api7.ai/ai-gateway/reference/headers-and-error-codes.md#proxy-response-headers) for their route coverage.

A request can involve three kinds of identifiers, and none substitutes for another:

| Identifier              | Assigned by                                                                                                                                                                                                  | Use it to                                                                                                                |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ |
| `request_id`            | AISIX, or the caller when AISIX adopts a supplied value. Returned as `x-aisix-request-id`.                                                                                                                   | Find the request's access log and usage events, including exported records and entries on the dashboard's **Logs** page. |
| `downstream_request_id` | Fronting infrastructure through the `x-request-id` request header. Recorded in gateway logs but not returned as a separate downstream ID. If AISIX adopts the value, it is returned as `x-aisix-request-id`. | Find the same HTTP request in an ingress controller, reverse proxy, service mesh, or CDN.                                |
| `provider_request_id`   | The provider, one for each upstream attempt whose response includes an ID or a request-ID header.                                                                                                            | Find the attempt in the provider's console or quote its ID to provider support.                                          |

To investigate a completed response:

1. Start with the `x-aisix-request-id` value returned to the caller.
2. Find the matching access log and usage events by `request_id`. Use `attempt_index` to order retries or failovers. The row with `is_final_attempt: true` is the last one.
3. Read `provider_request_id` from the relevant attempt when you need to investigate the call with the provider.

For a disconnect before response headers, start with `downstream_request_id` from the fronting infrastructure when available.

### Match Fronting Infrastructure[​](#match-fronting-infrastructure "Direct link to Match Fronting Infrastructure")

AISIX records separate values for the network connection, forwarded request, and resolved caller address:

| Value                   | Identifies                                                                                                                                                                                                                                                                                                                                                   | Match it with                                                                                                                    |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- |
| `peer`                  | The remote end of the accepted TCP connection, including its source port. When a trusted layer-4 load balancer opens the connection with a PROXY protocol header, it is the client address and port from that header instead. See [Client IP Resolution](https://docs.api7.ai/ai-gateway/deployment/client-ip-resolution.md#behind-a-layer-4-load-balancer). | A fronting proxy's connection record, or the client's own connection when a layer-4 load balancer sends a PROXY protocol header. |
| `downstream_request_id` | The HTTP request ID received in `x-request-id`.                                                                                                                                                                                                                                                                                                              | The fronting proxy's or ingress controller's request log.                                                                        |
| Resolved caller address | The caller IP selected through `proxy.real_ip`, without a port. It starts from `peer` and follows a trusted `X-Forwarded-For` header.                                                                                                                                                                                                                        | Access-control decisions and usage records.                                                                                      |

When present, `peer` and `downstream_request_id` follow the request through its access log, `provider call completed` entries, and intermediate diagnostic lines. Missing values are omitted rather than logged as empty fields.

AISIX screens an incoming `x-request-id` before logging it. Recording the value does not make it the gateway's `request_id`; adopting it is controlled separately by [`proxy.request_id.accept_headers`](#choose-the-accepted-headers).

## Diagnose Incomplete or Refused Requests[​](#diagnose-incomplete-or-refused-requests "Direct link to Diagnose Incomplete or Refused Requests")

The access log and related signals distinguish where a request stopped:

| Scenario                                                                        | What AISIX records                                                                                                                                                                                                                                       | Additional signal                                                                                                                                                                                                                                         |
| ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Caller disconnects before response headers                                      | An access log with status `499`, `error_class="client_disconnected"`, and `error="client closed the request before the response head was written"`. It includes the resolved model, provider, and dispatched target when available, but no token fields. | A usage event with the same status, class, and message, zero tokens, and zero cost. [`aisix_proxy_client_cancelled_requests_total`](https://docs.api7.ai/ai-gateway/reference/metrics.md#request-metrics) counts the request.                             |
| Caller disconnects after the response head but before reading any of the stream | The same `499` line, with `error="client closed the request before the response body was streamed"`.                                                                                                                                                     | A usage event with the same values and zero delivered tokens. Because the upstream had already answered, the event names the target that served it. The cancel counter also records this case.                                                            |
| Caller disconnects during a streamed response                                   | A `499` line written when the stream ends, with `error_class="client_disconnected"` and `error="client closed the request while the response was streaming"`.                                                                                            | A usage event with status `499`, `error_class="client_disconnected"`, the disconnect message, and any token counts received before the disconnect. This case does not raise the cancel counter, which records only what the request-level guard observed. |
| Upstream fails during a streamed response                                       | A line written at the point the stream ended, with the failure's status, such as `502` for a dropped connection or `504` for a read timeout. The line also records the failure as `error_class` and `error`. The caller received a `200`.                | A usage event with the same status and the failure class and message. See [Streams That Fail After the Response Head](https://docs.api7.ai/ai-gateway/observability/metrics-and-usage-events.md#streams-that-fail-after-the-response-head).               |
| Oversized request body is fully drained                                         | An `aisix::body_limit` entry with `drain_outcome="completed"`, logged at `info`, so it needs `log_level: "info"`. The caller can receive `413 Content Too Large`.                                                                                        | [`aisix_proxy_request_body_limit_rejections_total`](https://docs.api7.ai/ai-gateway/reference/metrics.md#request-metrics) counts the rejection.                                                                                                           |
| Oversized body cannot be fully drained                                          | The diagnostic uses `cap_reached`, `timeout`, or `client_read_error`, and the caller usually sees a closed connection. These `warn` entries are limited to one per outcome per second.                                                                   | The rejection metric counts every occurrence, including diagnostics suppressed by the log limiter.                                                                                                                                                        |

Body-limit diagnostic entries also carry `request_id`, `declared_content_length`, `configured_limit_bytes`, and `drained_bytes`. Join them to the access log by `request_id`.

If the caller disconnects before model resolution, the access log contains neither a model nor a provider. Its usage event carries an empty `model_id` when the entry the caller addressed was a routing group, because a group's own name is never written there; a direct model records its own identifier.

A cancelled request is recorded only when it authenticated. Authentication failures emit authentication metrics, diagnostic logging, and an unattributed access-log entry, but no usage event. Body-size rejection can also emit an access log and request metrics before credentials are read. A body that cannot be parsed produces rejection logging and metrics without a usage event. See [What the Usage Log Records](https://docs.api7.ai/ai-gateway/observability/metrics-and-usage-events.md#what-the-usage-log-records) for the full boundary.

## Reuse Your Own Request ID[​](#reuse-your-own-request-id "Direct link to Reuse Your Own Request ID")

If your service already generates a request ID for the business call, send it to AISIX. The adopted value then appears in the response header, access log, every usage event, the control plane's [Request Logs](https://docs.api7.ai/ai-gateway/cloud/logging-and-auditing.md#request-logs), and the `x-aisix-request-id` header sent upstream.

```
# AISIX_PROXY is the gateway origin; omit a trailing slash and endpoint path

# The local quickstarts use http://127.0.0.1:3000

export AISIX_PROXY="YOUR_AISIX_GATEWAY_URL"

export AISIX_API_KEY="YOUR_CALLER_API_KEY"

export MODEL_ALIAS="YOUR_MODEL_ALIAS"



curl -i "$AISIX_PROXY/v1/chat/completions" \

  -H "Authorization: Bearer $AISIX_API_KEY" \

  -H "Content-Type: application/json" \

  -H "x-aisix-request-id: req_abc123-orders-svc" \

  -d '{

    "model": "'"$MODEL_ALIAS"'",

    "messages": [

      {

        "role": "user",

        "content": "Hello"

      }

    ]

  }'
```

The response echoes the same value:

```
HTTP/1.1 200 OK

x-aisix-request-id: req_abc123-orders-svc
```

Retries and failovers reuse the adopted ID on every usage event, so filtering by that value returns the complete attempt chain.

### Accepted Values[​](#accepted-values "Direct link to Accepted Values")

AISIX handles supplied values as follows:

| Supplied value                                                            | Result                                                                                                                        |
| ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| 1–256 bytes containing only visible ASCII characters (`!` through `~`)    | AISIX adopts the value. UUIDs, ULIDs, prefixed IDs such as `req_abc123`, and the hexadecimal nginx `$request_id` all qualify. |
| Empty, oversized, non-ASCII, space-containing, or control-character value | AISIX ignores the value, generates a UUID, and continues the request.                                                         |
| A value reused for separate requests                                      | AISIX accepts it because uniqueness is not enforced, but the requests become indistinguishable in logs and event trails.      |

Generate a fresh ID for each request.

### Choose the Accepted Headers[​](#choose-the-accepted-headers "Direct link to Choose the Accepted Headers")

By default, AISIX adopts a caller-supplied ID only from `x-aisix-request-id`. The following configuration also accepts an infrastructure-assigned `x-request-id`, while keeping the default header as a fallback:

config.yaml

```
proxy:

  request_id:

    # Default: accept only the AISIX request ID header.

    # accept_headers: ["x-aisix-request-id"]



    # Headers are checked from left to right; the first acceptable value wins.

    accept_headers: ["x-request-id", "x-aisix-request-id"]



    # To ignore all caller-supplied IDs and always generate a UUID, use:

    # accept_headers: []
```

Use this option when AISIX is the first hop or when the ID assigned by a reverse proxy or ingress controller should become the request's identity everywhere. AISIX records an acceptable `x-request-id` as `downstream_request_id` regardless of this setting; when it also adopts that value, `request_id` and `downstream_request_id` are identical.

If you configure AISIX with environment variables, set the priority list as a comma-separated `AISIX_PROXY__REQUEST_ID__ACCEPT_HEADERS` value.

Use only valid, non-reserved HTTP header names. Startup fails if the list contains a malformed name or a reserved header, including credential-bearing headers, `host`, `cookie`, `traceparent`, and `tracestate`. AISIX blocks these headers because an adopted value is logged, returned to the caller, and sent upstream.

## Next Steps[​](#next-steps "Direct link to Next Steps")

Use [Metrics and Usage Events](https://docs.api7.ai/ai-gateway/observability/metrics-and-usage-events.md) to monitor aggregate traffic and compare request-level metrics with per-attempt usage events. Configure [Observability Exporters](https://docs.api7.ai/ai-gateway/observability/exporters.md) to send usage events to an external destination.
