Retrieved article excerpt
Open article · Retrieved 2026-11-13T15:22:15.288087+00:00
# AI Gateway service
A standalone Rust gateway for native provider APIs under two namespaces:
| Namespace | Endpoints | Generation ingested |
| --- | --- | --- |
| `/openai/v1` | `POST /responses`, `POST /responses/compact`, `POST /chat/completions`, `POST /decisions`, `POST /embeddings`, `GET /models` | Responses, compact, Chat Completions, Decisions and Embeddings |
| `/anthropic/v1` | `POST /messages`, `POST /messages/count_tokens`, `GET /models` | Messages |
Web resolves the gateway key to a trusted provider connection for the namespace's API
format; Rust relays native JSON or SSE without rewriting provider bytes, except that a
streamed Chat Completions request is asked for its usage (see below). Models listings
are GET proxies of the provider catalog and token counting returns the native count;
neither is ingested as a generation. A bounded capture layer captures request/response
facts and logs capture completeness at debug level. Each finalized generation is
uploaded as a Langfuse generation through OTLP, batched per project. Building and
testing need no real Web, database or provider credentials.
## Run locally
Alongside the repository's Node.js/pnpm setup, install [Rust via rustup](https://rust-lang.org/tools/install/)
and a native compiler/linker: Xcode Command Line Tools on macOS (`xcode-select --install`),
GCC/Clang on Linux (Ubuntu: `sudo apt install build-essential`), or MSVC C++ Build Tools on Windows.
Ensure `~/.cargo/bin` is on your PATH (reopen the terminal after installing rustup).
`rust-toolchain.toml` selects Rust 1.98.0 with Clippy and rustfmt automatically;
the first run needs network access to download the toolchain and Cargo dependencies.
No separate Rust watcher is needed.
After the usual repository `pnpm install`, run from the repository root:
```
pnpm dev
```
This starts the gateway alongside the other development services. Turbo Watch
restores the cached debug gateway binary when its inputs are unchanged, then
rebuilds and restarts it after Rust source changes; Web and worker keep their
built-in watchers. The gateway loads the root `.env` and listens on the first
available port starting at 8080. This lets multiple worktrees run their
development stacks at the same time. Add overrides from the table below to your
root `.env`; exported shell variables take precedence.
Without a Web URL, the process starts with liveness available; readiness and
inference return 503. To enable inference, configure the Web URL and shared service key.
To work on only the gateway, use `pnpm dev --filter=ai-gateway`.
Both commands watch Rust source changes; do not run both on the same port.
To start once without watching, run `pnpm dev` from `ai-gateway/`. Cargo also
works independently of Node/pnpm; it reads exported environment variables only,
without automatically loading `.env`. Direct Cargo and production starts fail
if the configured port is occupied unless port auto-increment is explicitly
enabled. Run it from this directory so rustup selects the pinned toolchain:
```
cd ai-gateway
cargo run --locked
```
In another terminal:
```
curl --fail http://localhost:8080/health
# {"status":"ok"}
curl http://localhost:8080/ready
# 503 without configuration; 200 {"status":"ready"} when configured
```
The binary reads configuration from the process environment. The pnpm development
script loads the root `.env` before starting it; production and direct Cargo runs
do not load dotenv files:
| Variable | Default | Validation |
| --- | --- | --- |
| `LANGFUSE_AI_GATEWAY_WEB_URL` | unset; inference disabled | Trusted Web base URL, including any deployment prefix |
| `LANGFUSE_AI_GATEWAY_SERVICE_KEY` | unset | Required with Web URL; same key configured in Web |
| `LANGFUSE_AI_GATEWAY_ALLOW_HTTP_WEB_URL` | `false` | `true`, `false`; `true` also accepts a plain `http://` Web URL on any host. Only for internal traffic, such as Web's in-cluster Kubernetes Service (`http://<release>-web.<namespace>.svc.cluster.local:3000`) or another private network; never for a URL that crosses the public internet, because resolve responses carry provider API keys and requests carry the service key and ingestion tokens unencrypted. Resolution, model catalogs and trace uploads all use this URL. The gateway logs a warning at startup when it is used |
| `LANGFUSE_AI_GATEWAY_ALLOW_MISSING_SERVICE_KEY` | `false` | `true`, `false`; `true` starts the gateway unconfigured (readiness and inference return 503, with a startup warning) when the Web URL is set but the service key is unset or blank, instead of failing startup. Docker Compose sets it so the gateway service can run before keys are configured |
| `LANGFUSE_LLM_CONNECTION_WHITELISTED_HOST` | unset | Comma-separated provider hostnames exempt from the private-address check, shared with Web's LLM connections |
| `LANGFUSE_LLM_CONNECTION_WHITELISTED_IPS` | unset | Comma-separated IP addresses exempt from the private-address check |
| `LANGFUSE_LLM_CONNECTION_WHITELISTED_IP_SEGMENTS` | unset | Comma-separated CIDR ranges exempt from the private-address check |
| `LANGFUSE_LLM_CONNECTION_ALLOWED_HOSTS` | unset | Comma-separated hostnames; when set, provider requests may only go to these hosts, including the official origins and Bedrock regional hosts |
| `LANGFUSE_OUTBOUND_BLOCKED_IP_SEGMENTS` | unset | Comma-separated CIDR ranges blocked in addition to the built-in private, loopback, link-local and metadata ranges |
| `NEXT_PUBLIC_LANGFUSE_CLOUD_REGION` | unset | Marks a Langfuse Cloud deployment, as in Web: provider URLs must be `https` and the `LANGFUSE_LLM_CONNECTION_*` exemptions are ignored |
| `LANGFUSE_AI_GATEWAY_LISTEN_ADDRESS` | `0.0.0.0:8080` | IP address and port; IPv6 uses `[::]:8080` |
| `LANGFUSE_AI_GATEWAY_AUTO_INCREMENT_LISTEN_PORT` | `false` | `true`, `false`; the pnpm dev task sets `true` |
| `LANGFUSE_LOG_FORMAT` | `text` | `text`, `json` |
| `LANGFUSE_LOG_LEVEL` | `info` | `debug`, `info`, `warn`, `error`, `fatal` |
| `LANGFUSE_AI_GATEWAY_CONNECTION_DRAIN_TIMEOUT_SECONDS` | `10` | Integer from 1 to 300; connection drain after the shutdown signal. Replaces the deprecated `LANGFUSE_AI_GATEWAY_SHUTDOWN_TIMEOUT_SECONDS`, which is still read when the new name is unset. On ECS behind an ALB, the deregistration delay drains streams before SIGTERM, so use `1`. On Kubernetes the gateway drains streams itself, so set it to the stream time to protect (for example `300`) |
| `LANGFUSE_AI_GATEWAY_TELEMETRY_SHUTDOWN_TIMEOUT_SECONDS` | `10` | Integer from 1 to 300; telemetry flush after the drain ends. On ECS use most of `stopTimeout` (max 120), for example `115`. On Kubernetes `30` is enough; set `terminationGracePeriodSeconds` above the `preStop` sleep plus both timeouts |
| `LANGFUSE_AI_GATEWAY_TELEMETRY_BUFFER_BYTES` | `67108864` (64 MiB) | Integer from 4194304 (4 MiB) to 4294967296 (4 GiB); span and credential bytes an instance holds for upload before dropping new records |
| `LANGFUSE_AI_GATEWAY_MAX_REQUEST_BYTES` | `16777216` (16 MiB) | Integer from 1048576 (1 MiB) to 4294967295; largest accepted request body |
| `LANGFUSE_AI_GATEWAY_MEMORY_BUDGET_BYTES` | 0.6 × cgroup limit − telemetry buffer; else `1073741824` (1 GiB) | Integer from the request limit plus the overhead up to Tokio's semaphore capacity; bytes all in-flight requests and model catalogs of an instance may reserve together. Unset, it is 60% of the cgroup v2 or v1 memory limit minus the telemetry buffer (at least one maximal request), or 1 GiB without a limit; the startup log reports it as `memory_budget_source` |
| `LANGFUSE_AI_GATEWAY_REQUEST_MEMORY_OVERHEAD_BYTES` | `1048576` (1 MiB) | Integer from 0 to 4294967295; fixed bytes each request reserves on top of its body for response capture and buffers |
| `LANGFUSE_AI_GATEWAY_MAX_EXECUTION_SECONDS` | `600` | Integer of at least 60; ceiling from execution admission until the response completes. Web ingestion tokens last 15 minutes, so traces of longer executions may be dropped |
| `LANGFUSE_AI_GATEWAY_STALL_TIMEOUT_SECONDS` | `120` | Integer from 1 to the execution ceiling; longest wait without progress |
The gateway shares `LANGFUSE_LOG_LEVEL` with Web and worker. Values are lowercase;
`fatal` maps to Rust's `error` level and therefore includes ordinary error logs.
Set `LANGFUSE_LOG_FORMAT=text` in the root `.env` for compact, readable logs
(the default). Use `LANGFUSE_LOG_FORMAT=json` for structured production logs.
Both formats use the same log level and preserve event fields. For example:
```
2026-09-10T13:20:00Z INFO gateway listening address=0.0.0.0:8080
```
Invalid values fail startup without echoing their contents. At the default `info`
level, logs contain service lifecycle events and HTTP response summaries.
Debug logging adds content-free phase and capture details. For direct
host-only development, set `LANGFUSE_AI_GATEWAY_LISTEN_ADDRESS=127.0.0.1:8080`.
## Operational observability
Logs and operational OpenTelemetry exports describe gateway health independently
of the inference generations sent to Langfuse. They do not include request/response
content, credentials, key metadata, or URL query strings. They do carry the
[resolution context](https://github.com/langfuse/langfuse/tree/main/ai-gateway#resolution-context), including the provider connection name
and the requested model. Health probes are excluded
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](https://github.com/langfuse/langfuse/tree/main/ai-gateway#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.
| Variable | Default | Purpose |
| --- | --- | --- |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | unset | Enables operational traces and metrics; HTTP/protobuf base URL, e.g. `http://localhost:4318` |
| `OTEL_SERVICE_NAME` | `ai-gateway` | Operational service name |
| `DD_ENV` | `development` | Deployment environment resource attribute |
| `BUILD_ID` | Cargo package version | Service version; set to the deployed image's commit SHA |
| `OTEL_TRACES_SAMPLER_ARG` | `1` | Sampling ratio from 0 to 1 for independent operational root traces |
Tower's `TraceLayer` keeps the server span alive through the response body.
The HTTP response log and `http.server.request.duration` measure time to response
headers, not full SSE duration; the `gateway response completed` log reports the
stream duration once the body reaches end of stream. Execution summaries and
`gateway.phase.duration` with `phase=execution` measure the provider relay through
completion, cancellation, timeout, or transport error. HTTP status and stream
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-reque