Skip to main content

Rust execution paths

Spanway includes a compiled fast path for some provider calls. It is part of every container image, so nothing extra is installed, and you turn it on with SPANWAY_RUST. The extension does not replace the gateway. Authentication, routing, rate limits, guardrails, spend tracking and logging stay in Python. What it replaces, per route, is the provider call itself: building the upstream request, sending it, and decoding the response or the stream.

Whether a given request uses it is decided by an ordered rollout table built into the gateway, summarised in the table below. The first matching rule wins and anything unmatched stays on Python.

A real-world scenario​

A team serves Claude models through /v1/messages to a client library that depends on exact Anthropic streaming semantics, and runs OCR through /v1/ocr. The operator sets SPANWAY_RUST=1 on the gateway. Messages requests to Anthropic now carry x-spanway-rust: true, a request that uses a parameter the extension does not cover silently falls back to Python with no header, and OCR works because its implementation lives in the extension. During an incident the operator checks the header on a failing request first to know which path to read logs for.

The rollout table​

RouteProvidersRolloutWhat it means
Diagnostics redaction (log scrubbing)allOpt inUsed when SPANWAY_RUST is on, Python otherwise.
/v1/chat/completionsallPython onlyNever uses the extension, whatever SPANWAY_RUST says.
/v1/embeddingsallPython onlyNever uses the extension.
/v1/ocrallRequiredThere is no Python implementation. The extension must be present.
/v1/messagesanthropic, deepseek, vertex_ai (Claude models only)Opt inUsed when SPANWAY_RUST is on, with fallback to Python if the extension declines the request.
/v1/messagesevery other providerPython onlyPython translates the request through chat completions.
/v1/responsesallPython onlyNever uses the extension.
Token counting and tokenizersallPython onlyNever uses the extension.
Audio transcriptionbedrockRequiredThere is no Python implementation. The extension must be present.

"Opt in" rules read the switch below. "Python only" and "Required" rules ignore it: the first never leaves Python and the second never has a Python fallback.

Turning it on​

Set SPANWAY_RUST in the gateway's environment. The value is parsed as a boolean, so 1, true, yes and on enable it and 0, false, no and off disable it. An unparseable value is treated as unset.

docker run -p 4000:4000 -v "$PWD/config.yaml:/app/config.yaml" \
-e SPANWAY_MASTER_KEY -e SPANWAY_RUST=1 \
registry.spanway.ai/spanway/spanway-ai:2.0.0 --config /app/config.yaml

The switch is the SPANWAY_RUST environment variable on the gateway container. Set it in the container environment, the Helm values or the Terraform stack, then restart the gateway.

How a request is served​

When an opt in rule matches and the switch is on, the gateway projects the public call into a native request and hands it to the extension. Three things can happen.

The extension serves the request. The response carries the x-spanway-rust: true header, which is the only reliable way to confirm the path from the client side, and any cache key it computed comes back as x-spanway-cache-key.

The extension declines. Declines are deliberate: the request used a parameter the native implementation does not cover, or the request or model sets drop_params or modify_params, which rewrite requests in ways the extension does not reproduce. The call falls back to Python and the response has no x-spanway-rust header. Unknown parameters are the usual cause. The extension declines a request for one of these reasons:

  • drop_params or modify_params is set, because both rewrite the request in ways the native path does not reproduce.
  • The request sets a parameter that the route's native implementation does not take. Parameters left empty (null) and the cache or caching settings never cause a decline, and neither do the request context fields model, messages, input, api_key, api_base, base_url, custom_llm_provider, extra_headers, timeout, request_timeout, metadata and the logging callbacks.

To find the parameter, set SPANWAY_LOG=DEBUG on the gateway and send the request again. The gateway writes one DEBUG line with the reason, for example Rust messages bridge declined the request, serving it on Python: <reason>. The reason names the parameter, never its value. Turn DEBUG off again afterwards, because it is verbose.

The upstream provider fails. The error is mapped to the same APIError contract Python raises, with the provider's status code and a spanway rust <route>: prefix on the message, so retries, fallbacks and alerting behave the same way as on the Python path.

For "Required" routes there is no fallback. If the extension is missing, the request fails with HTTP 500 and the message Rust ocr bridge is unavailable (or Rust transcription bridge is unavailable). If the extension declines, the message is Rust ocr bridge declined the request: <reason>.

What to expect​

The extension changes the provider call, not the pipeline around it. On a gateway with a single worker the request pipeline (auth, routing, hooks, logging, spend) dominates the CPU per request, so turning SPANWAY_RUST on does not by itself change the gateway's added latency in a measurable way. The benchmarks page shows the measured overhead for both modes on the same machine against a zero latency mock upstream. Treat the extension as a correctness and provider coverage feature for the routes in the table above, and measure before expecting a throughput change for your workload.

Workers and forking​

The extension's runtime threads do not survive fork(). The gateway handles this itself, with the default server and with --run_gunicorn, so native routes only ever start inside workers. If a worker is ever forked after the runtime started, the next native call raises ForkedAfterNativeRuntimeStarted instead of hanging.

Checking the extension is loaded​

Every Spanway image ships with the extension built in, so there is nothing to install. To confirm it serves your traffic, follow the steps in the next section and look for the x-spanway-rust: true response header. If a route marked "Required" fails with HTTP 500 and the message Rust ocr bridge is unavailable or Rust transcription bridge is unavailable, the extension could not run on that gateway, so contact support@spanway.ai with the image tag.

Turn it on and confirm the path​

  1. Set SPANWAY_RUST=1 in the gateway's environment and restart it.

  2. Send an Anthropic Messages request to an Anthropic model and look at the headers:

    curl -sD - -o /dev/null http://localhost:4000/v1/messages \
    -H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \
    -d '{"model": "claude-sonnet-5-5", "max_tokens": 64, "messages": [{"role": "user", "content": "ping"}]}' | grep -i x-spanway-rust

    Expected result: x-spanway-rust: true. No header means the request fell back to Python.

  3. Send the same request with drop_params: true set in spanway_settings, or with a parameter the extension does not cover. Expected result: the answer is the same but the header is gone.

  4. Open Logs in the Admin UI. Both requests are logged, priced and attributed the same way, because logging and spend stay in Python.

  5. Replay logs produced by a separate data plane through the control plane route when you run one:

    curl -X POST http://localhost:4000/v1/rust_control_plane/logs \
    -H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \
    -d '{"records": [{"status": "success", "standard_logging_payload": {"id": "chatcmpl-8f2c1a7e", "call_type": "acompletion", "model": "gpt-5.5", "startTime": 1763712000.0, "endTime": 1763712001.2, "response_cost": 0.00042, "prompt_tokens": 120, "completion_tokens": 40}}]}'

    Expected result: {"processed": 1, "failed": 0, "failures": []}, and the request appears in Logs as if the gateway had served it.

MethodPathSummary
POST/v1/rust_control_plane/logsReplay finished request logs from the data plane

Errors​

SymptomMeaningFix
500 Rust ocr bridge is unavailable or Rust transcription bridge is unavailableA "Required" route ran on an image without the extension or with a mismatched Python ABI.Use a release image. Confirm the extension serves traffic with the x-spanway-rust header check in Turn it on and confirm the path. If the header never appears on a release image, contact support@spanway.ai with the image tag.
500 Rust ocr bridge declined the request: <reason> or Rust transcription bridge declined the request: <reason>A "Required" route received a parameter the extension does not take, and there is no Python path to fall back to.Remove the parameter the reason names and send the request again.
500 Max retries per request hit!The request already used up the retries that num_retries_per_request in spanway_settings allows, so the native call did not start.Find out in Logs why the earlier attempts failed, or raise num_retries_per_request.
The response has no x-spanway-rust header although the switch is onThe request did not match an opt in rule, or the extension declined it, for example because of drop_params, modify_params or an unknown parameter.Unset drop_params and modify_params, then remove optional request fields one at a time until the header comes back, as described in the decline reasons above.
APIError with a spanway rust <route>: prefixThe provider failed on the native path, the status code is the provider's.Treat it as the provider error it is, retries and fallbacks apply as usual.
ForkedAfterNativeRuntimeStartedA process forked after the extension's runtime started.Run the gateway from the release image with the default server or --run_gunicorn. If the error persists, report it to support@spanway.ai.
ProcessReservedForForkingA native route was called in the gunicorn master process, which is kept free of native threads so that it can fork workers. It does not happen on a release image started the documented way.Run the gateway with the default server or --run_gunicorn, and do not run custom code that calls a model in the master process.
NativeStateStartedBeforeFork, The Spanway Rust extension already ran a native route in <where>...Custom start-up code (a warm-up call, a health check, import-time setup) ran a native route before the server forked its workers. It does not happen on a release image started the documented way.Move that call into the worker, after the fork, then restart the gateway.
401 Authentication Error, No api key passed in., or Authentication Error, Invalid proxy server token passed. ...The replay route was called without a key, or with a key the gateway does not know. See the 401 rows of the error reference.Send a proxy admin key in the Authorization header.
403 /v1/rust_control_plane/logs is admin-only (proxy admin key required).The replay route was called with a non admin key.Use a proxy admin key.

Logs​

The extension writes its own log lines through the gateway's Spanway logger, so they reach the same output, redaction and log level as every other gateway line.

LevelLineMeaningAction
DEBUGRust <route> bridge declined the request, serving it on Python: <reason>An opt in route went back to Python. The reason names the parameter, never its value.Normal. Read it when you want to know why a request has no x-spanway-rust header.
DEBUGRust <route> bridge is unavailable, serving the request on PythonThe extension could not load, so an opt in route stayed on Python.Normal on a development checkout. On a release image, contact support@spanway.ai with the image tag.
WARNINGspanway_credential_name=<name> matched none of the <n> loaded credentials; the request runs without itA native request named a stored credential that the gateway has not loaded.Check the credential name on the LLM Credentials tab of Models + Endpoints.

Lines the extension itself produces carry two extra fields in JSON logs: rust_target, the part of the extension that wrote it, and rust_fields, its structured values after redaction. Every replay through /v1/rust_control_plane/logs also writes one row to the audit log, with the admin who sent it, the record counts and the key hashes the records charge.