Skip to the content.

Configuration Reference

Conduit is configured with a single file in JSON or YAML format. Both are fully equivalent — YAML is recommended because it supports comments.

conduit -c conduit.yaml          # explicit path
conduit -c conduit.json          # JSON is fine too
conduit                          # auto-discover: conduit.json → conduit.yaml → conduit.yml
conduit validate -c conduit.yaml # validate without starting

Fields accept environment variable references — "$MY_VAR" is replaced at startup. This keeps secrets out of config files. The reference works wherever a value stands, a number included (port: $PORT in YAML), and the value arrives unchanged: in JSON and in a YAML "..." it is written as a JSON string, in a YAML '...' a quote is doubled, in an unquoted YAML value it is written as it is. A value that an unquoted YAML value cannot carry without changing it (a line break of any kind, a space at the start or end, a start such as *, &, !, |, - , a : or ` # inside it, a # right after a space, a comma or bracket inside [ ], an empty value or one that YAML reads as null: null, ~) makes the load fail with a message that names the variable and never shows the value: put the reference in double quotes (“$MY_VAR”). A variable that is not set leaves $MY_VAR` as written. A reference in a YAML comment is not replaced.

Warning, credentials: a password, API key, JWT secret or Admin API token whose whole value is a reference to a variable that is not set keeps the text of the reference, and that text is then the credential: anyone who has seen the configuration, an example or this page can present $MY_VAR. conduit validate, the start-up log and POST /reload warn about every such credential (the warning names the place and the variable, never a value). Treat the warning as an error in a deployment: set the variable in the environment of the process (for the systemd unit: /etc/conduit/conduit.env). A real credential must not be written as a bare $Word (for example $Hunter2): it cannot be told from a reference to an unset variable, so the warning would print it as a variable name.

Optional build features

Conduit is compiled from Cargo features: a feature that is not compiled in is not in the binary, so it cannot be attacked, and the binary is smaller. There are three kinds, and every name below is described in the tables that follow:

  1. Baseline features, on by default: proxy, compression, static, hotreload, mimalloc.
  2. Optional features, off unless you ask for them: jwt, consumers, forward-auth, rhai, wasm, ext-proc, tcp, upload, redis, cache, disk-cache, acme, fault-injection, otlp, tokio-metrics, kubernetes, jemalloc.
  3. Bundles, which are only a short name for a set of the above: standard, gateway, static-server, full. A bundle adds no code of its own.

The published downloads and images are full (the plain file names and tags), standard, gateway and static-server (names ending in -standard, -gateway, -static); npx installs full; cargo install lopatnov-conduit is the default build. See docs/cli.md: Build features and Building for sizes and build commands.

If your config uses something your binary lacks, Conduit does not fail: the section is parsed, ignored, and a warning is printed at start-up and by conduit validate. That matters most for the security features and for middleware that can reject a request, where “ignored” means the check is not applied (jwtAuth without jwt, consumers without consumers, forwardAuth without forward-auth, a rhai or wasm entry that was a gate: every request goes through unchecked). The one exception is an ext_proc entry that is not failOpen: a build without ext-proc refuses to start with it, because skipping it would switch the check off silently. To see what a config needs, and whether the binary you run has it:

conduit features -c conduit.yaml   # lists the features the config needs; exit 1 if this binary lacks one, 2 if the config cannot be loaded
conduit validate -c conduit.yaml   # prints a warning for every ignored section

Baseline features (on by default)

Feature What it gives you Config If it is compiled out
proxy Reverse proxying: upstream targets, load balancing, upstream groups, health checks, retry, circuit breaker, traffic mirroring. proxy, routes[].proxy, groups Those sections are ignored; a request that would have gone to an upstream gets the site’s fallback response. See Building without proxy.
compression Response compression (brotli, gzip, deflate, zstd), negotiated with Accept-Encoding, for static files, fallback responses and the metrics page. Proxied responses are not compressed by Conduit (the upstream can do it). compression Responses are sent uncompressed.
static Static file serving and the fallback responses (404 page, single-page-app shell). static, fallback static and fallback are ignored: every unmatched request gets a plain 404 Not Found.
hotreload Browser live reload: a Server-Sent Events stream and a file watcher that tells open pages to refresh when a served file changes. hotReload hotReload is ignored and /__hot-reload__ is an ordinary unmatched path.
mimalloc The mimalloc memory allocator, in its hardened secure mode, in the conduit binary instead of the system one: about 4 % less CPU per proxied request in our measurement (see building). A build-time choice; nothing to configure. no config key The system allocator is used (--no-default-features); everything works, a little slower.

Without these (--no-default-features) little is left: TLS, the always-on guards (IP filter, rate limits, CORS, security headers), redirects, the health endpoint, metrics and the Admin API.

Optional features

Feature What it gives you Config If it is compiled out
jwt Validates JWT bearer tokens: HS256 with a shared secret, RS256/ES256 through a JWKS URL (fetched and refreshed in the background). Claims are available as `` in header templates. jwtAuth, claim templates jwtAuth is ignored: requests are not authenticated by JWT. JWT credentials of consumers are not recognised either.
consumers Named API clients: each with its own API keys, Basic or JWT credentials, its own rate limit and headers added to the proxied request. consumers consumers is ignored: API-key, Basic and JWT consumer authentication is not applied, every request bypasses it.
forward-auth Asks an external HTTP service whether each request may pass (like nginx auth_request or Traefik ForwardAuth) and copies chosen headers from its answer. forwardAuth forwardAuth is ignored: the external check does not run.
rhai Small scripts as middleware: read or change headers, reject a request, answer it directly. middleware[].type: "script" The entry is ignored: a script that was a gate no longer runs.
wasm WebAssembly plugins (any language that compiles to WASM) run in a Wasmtime sandbox as middleware; a plugin that fails lets the request through (fail-open). Adds the Wasmtime runtime to the binary. middleware[].type: "wasm" The entry is ignored: a plugin that was a gate no longer runs.
ext-proc Sends the request headers to an external processor over gRPC (Envoy’s ext_proc protocol), which can change them or answer the request itself, and fails closed when the processor does not answer. Adds the gRPC client (tonic, prost) to the binary. middleware[].type: "ext_proc" A fail-closed entry (the default) is refused at validation: the binary will not start with it. A failOpen: true entry is ignored with a warning: requests are not sent to the processor.
tcp A raw TCP proxy site, for protocols that are not HTTP (databases, message brokers, anything else on a TCP port). type: "tcp" site The site is ignored.
upload An endpoint that accepts multipart file uploads and writes them to a directory. upload upload is ignored.
redis Keeps rate-limit counters and cached responses in Redis, so several Conduit instances share them. global.redis, rateLimit.store: redis, cache.store: redis A rate limit falls back to the in-memory store, per instance: with three instances each limit effectively triples. A route with a Redis cache store is not cached.
cache HTTP response cache for proxied responses (memory store). Implies proxy. proxy.*.cache Responses are not cached.
disk-cache The on-disk cache store, cache.store: "disk:/path": the code that writes cache files under a directory. Implies cache. A cache build without it is a memory (and, with redis, Redis) cache. cache.store: "disk:/path" The route is not cached and nothing is written under the directory; the start-up log and conduit validate say so.
acme Obtains and renews certificates from Let’s Encrypt on its own. tls.acme tls.acme is ignored: no certificate is requested.
fault-injection Adds delays or errors to a share of the requests, to test how clients and upstreams behave under failure. faultInjection faultInjection is ignored (nothing is broken on purpose).
otlp Exports traces to an OpenTelemetry collector over OTLP. global.otlp global.otlp is ignored: no traces are exported.
tokio-metrics One more Prometheus gauge: conduit_eventloop_lag_ms, the scheduling delay of the admin runtime. no config key The gauge is absent.
kubernetes Reads the sites from ConduitSite resources in a cluster instead of a file. --kubernetes-namespace (a command-line flag, not a config field) The flag does not exist.
jemalloc The jemalloc memory allocator in the conduit binary, instead of mimalloc. Not in any bundle: mimalloc measured faster and smaller (building); jemalloc is for those who prefer its tuning and profiling. With both on, jemalloc is used. no config key mimalloc (the default) or the system allocator is used.

Bundles

A bundle is a name for several features. ✓ means the bundle includes the feature.

Feature standard gateway static-server full
proxy ✓ ✓   ✓
compression ✓ ✓ ✓ ✓
static ✓   ✓ ✓
hotreload ✓   ✓ ✓
mimalloc ✓ ✓ ✓ ✓
jwt, consumers, forward-auth, cache, disk-cache, acme ✓ ✓   ✓
rhai, wasm, ext-proc, tcp, upload, redis, fault-injection, otlp, tokio-metrics, kubernetes       ✓

Which one to pick:

You want Build
A reverse proxy with auth, caching and automatic HTTPS standard (the -standard download, :latest-standard)
Everything, including scripting, WASM, TCP, uploads, Redis full
The smallest proxy the default build, or --no-default-features --features proxy
A static site server with no upstream at all --no-default-features --features static-server
A gateway without static files --no-default-features --features gateway
A few extra features on top of the default build --features "jwt,rhai"

Download the plain-named (full) binary, or one ending in -standard, -gateway or -static, from GitHub Releases or build from source: cargo build --release --features full.


Table of Contents

Background

Essentials

Routing

Reliability

Caching

Authentication

Rate Limiting & Load Shedding

Transforms

Observability

Security

Middleware

Advanced


Concepts

These sections explain how Conduit behaves — not config fields you set, but background knowledge that helps understand the rest of the reference.

Request pipeline

The order in which configured features are applied for every incoming request:

Incoming request
  │
  ├─ 1. X-Request-ID injection        — auto-generate UUID v4 if absent
  ├─ 2. IP filter                     — 403 if blocked (before any auth)
  ├─ 3. CORS preflight                — OPTIONS short-circuit
  ├─ 4. Health / ACME bypass          — skip all guards for /__health__ etc.
  ├─ 5. Inflight limit                — 503 if maxInflightRequests exceeded
  ├─ 6. Site-level rate limit         — 429 if over limit
  ├─ 7. Consumers                     — identify named client (V1/V2/V3)
  ├─ 8. Basic Auth                    — 401 if credentials missing/wrong
  ├─ 9. API Key                       — 401 if key missing/wrong
  ├─ 10. JWT Auth                     — 401 if token invalid
  ├─ 11. Forward Auth                 — delegate to external service
  ├─ 12. Redirects                    — 301/308 if path matches
  ├─ 13. Fault injection              — abort/delay (testing only)
  ├─ 14. Rhai / WASM middleware       — custom scripts in order
  │
  ├─ Route matching + per-route rate limit
  ├─ Circuit breaker check
  │
  └─ Upstream request
       ├─ X-Forwarded-For / -Proto / -Host injection
       ├─ requestTransform (setHeaders / removeHeaders)
       ├─ Path rewrite (stripPrefix / rewrite rules)
       └─ Traffic mirror (fire-and-forget)

Upstream response
  ├─ CRLF header protection
  ├─ CORS / security / custom headers injection
  ├─ responseTransform
  ├─ X-Response-Time header
  ├─ Retry-on-error decision
  └─ Error masking (5xx body replacement)

Steps 7–11 are mutually exclusive in practice — only one auth method identifies the client, but multiple may be configured as fallbacks. The consumers guard runs before basicAuth and apiKey, so a consumer match takes priority.

Forwarded headers

Conduit automatically injects these headers into every proxied upstream request. No configuration is needed — they are always present.

Header Value Notes
X-Forwarded-For Client IP Appended to existing value if already present
X-Forwarded-Proto http or https Derived from whether the site has TLS configured
X-Forwarded-Host Original Host header Lets upstreams reconstruct full URLs
X-Request-ID UUID v4 Auto-generated if absent; forwarded as-is if client sends it
Via 1.1 conduit RFC 7230 §5.7 — identifies the proxy hop; appended to existing value

To remove any of these before forwarding, use requestTransform.removeHeaders:

# conduit.yaml
requestTransform:
  removeHeaders: [X-Forwarded-For, X-Forwarded-Host]
// conduit.json
{
  "requestTransform": {
    "removeHeaders": ["X-Forwarded-For", "X-Forwarded-Host"]
  }
}

skipPaths glob syntax

Many config sections accept a skipPaths list — requests whose path matches are bypassed by that feature entirely. It is not a top-level field; it appears inside basicAuth, apiKey, jwtAuth, forwardAuth, consumers, rateLimit, and logging.

Two pattern forms are supported:

Pattern Matches
/exact/path Only that exact path
/prefix/** The prefix itself, /prefix/, and any sub-path
# conduit.yaml — example inside jwtAuth
jwtAuth:
  secret: "$JWT_SECRET"
  skipPaths:
    - /__health__ # exact match — health check bypasses JWT
    - /public/** # /public, /public/, /public/assets/logo.png, …
// conduit.json
{
  "jwtAuth": {
    "secret": "$JWT_SECRET",
    "skipPaths": ["/__health__", "/public/**"]
  }
}

Note: only /** at the end is supported as a wildcard. Patterns like /api/*/details or /**.json are treated as exact matches (no mid-path or extension wildcards).


Port and Host

# YAML
port: 8080
host: api.example.com # optional — virtual hosting
// JSON
{ "port": 8080, "host": "api.example.com" }
Field Type Default Description
port number 80 / 443 ¹ TCP port to listen on
host string — Virtual hostname. Omit to match all Host headers (catch-all)

¹ Default port is 443 when tls is configured, 80 otherwise. When no sites are configured at all, Conduit listens on 8080 as a fallback.

Use host when running multiple sites on the same process.


TLS / HTTPS

Manual certificates

# YAML
port: 443
tls:
  cert: /etc/tls/server.crt
  key: /etc/tls/server.key
  httpRedirectPort: 80
// JSON
{
  "port": 443,
  "tls": {
    "cert": "/etc/tls/server.crt",
    "key": "/etc/tls/server.key",
    "httpRedirectPort": 80
  }
}

Auto-TLS via Let’s Encrypt

Requires cargo build --features acme

# YAML
host: example.com      # required: the certificate is ordered for this name
port: 443
tls:
  acme:
    email: admin@example.com
    storage: ./certs
    challenge: http-01
// JSON
{
  "host": "example.com",
  "port": 443,
  "tls": {
    "acme": {
      "email": "admin@example.com",
      "storage": "./certs",
      "challenge": "http-01"
    }
  }
}

The certificate is ordered for the site’s host, and the files are stored as <storage>/<host>.crt.pem and <storage>/<host>.key.pem. Because the host becomes part of a file name, conduit validate rejects a host that is not a plain DNS name: labels of ASCII letters, digits and hyphens separated by dots (international names in punycode, xn--…), with no /, \, .., empty label or other character. A leading *. is accepted, but a CA validating over HTTP-01, the only challenge Conduit implements, normally refuses wildcards.

A background task renews the certificate on disk when no more than a third of its lifetime is left, and never later than 30 days before expiry (30 days for a 90-day certificate, 21 for a 64-day one, 15 for a 45-day one), or earlier when the CA’s ACME Renewal Information (RFC 9773) asks for it; the running process keeps serving the one it loaded, so restart Conduit within that window (with profile: shortlived, a certificate of about 6 days, that window is 2 days: restart at least every day or two, or the process serves an expired certificate). Details: acme in the CLI reference.

The account with the CA is kept in <storage>/acme_account.json, which records the directory URL it was created for. When you point directory at another CA (staging to production, say), the old account is not tried against the new CA: a second file, acme_account.<readable part of the URL>.<hash of the whole URL>.json, holds the account for it, and a file that records another directory than the one asked for is refused. A private key that you placed at <storage>/<host>.key.pem is read only as PKCS#8 (-----BEGIN PRIVATE KEY-----); a PKCS#1 (RSA PRIVATE KEY), SEC1 (EC PRIVATE KEY) or encrypted key is named in the log and then replaced by a newly ordered key, so convert it first (openssl pkcs8 -topk8 -nocrypt -in old.key -out <host>.key.pem).

TLS field reference

Field Type Default Description
cert path — PEM certificate file
key path — PEM private key file
ca path — CA bundle for upstream verification
httpRedirectPort number — Port that redirects HTTP to HTTPS. Only Host values of sites using this port are redirected (a site without host, or with "*", allows any valid host); other hosts get 421 Misdirected Request, an invalid Host gets 400
acme.email string — Contact email for ACME account
acme.storage path — Directory for certificate persistence

versions/ciphers are not currently enforced (issue #189). The fields still parse, but the way Conduit builds its TLS listeners (through Pingora’s TlsSettings) gives no way to restrict protocol versions or cipher suites — TLS 1.2 and 1.3 are always both enabled with the default rustls cipher suite set, regardless of config. (Pingora 0.9 still exposes no way to set versions or ciphers on a listener: TlsSettings::build() hard-codes TLS 1.2 and 1.3.) Setting either field is a hard validation error (fails startup with an explanation) rather than a silent no-op, so a misconfigured expectation of TLS restriction can’t go unnoticed. | acme.challenge | string | — | "http-01" (the only challenge implemented; other values are rejected) | | acme.profile | string | — | Certificate profile to ask the CA for (Let’s Encrypt: classic, tlsserver, shortlived); absent = the CA’s default. An empty value is rejected; a profile the CA does not offer fails the order | | acme.orderTimeoutSecs | integer | 60 | Seconds one request of an order (account setup, new order, finalize, certificate download) may take. 1 to 86400 | | acme.validationTimeoutSecs | integer | 180 | Seconds the whole challenge validation may take. 1 to 86400 | | acme.ariTimeoutSecs | integer | 30 | Seconds the whole renewal-information (ARI) probe may take; one request of it gets half. 1 to 86400 | | acme.retryAfterMinSecs | integer | 300 | The CA’s Retry-After is never taken as shorter than this. Must not exceed retryAfterMaxSecs. 60 to 86400 | | acme.retryAfterMaxSecs | integer | 86400 | The CA’s Retry-After is never taken as longer than this. 1 to 86400 | | acme.checkIntervalSecs | integer | 43200 | Seconds between two renewal checks of a certificate. With several ACME sites the shortest value counts. 300 to 86400 | | acme.directory | string | — | Custom ACME directory URL. Use "https://acme-staging-v02.api.letsencrypt.org/directory" for Let’s Encrypt staging (rate-limit-free testing) | | clientAuth | object | — | mTLS client cert verification |

Note — single cert per port: Conduit does not support per-SNI certificate selection yet. When multiple HTTPS sites share the same port, the first registered cert is used for all. Use separate ports for different certificates. (Pingora 0.9’s rustls backend can pick a certificate per SNI hostname through a custom resolver; Conduit does not install one yet.)


HTTP/2

# YAML
port: 443
tls:
  cert: ./certs/cert.pem
  key: ./certs/key.pem
http2: {} # enable HTTP/2 with defaults
// JSON
{
  "port": 443,
  "tls": { "cert": "./certs/cert.pem", "key": "./certs/key.pem" },
  "http2": {}
}

Full config with all fields:

http2:
  maxConcurrentStreams: 100
  initialWindowSize: 65535
  h2c: false   # HTTP/2 cleartext (internal gRPC without TLS)
// JSON
{
  "http2": {
    "maxConcurrentStreams": 100,
    "initialWindowSize": 65535,
    "h2c": false
  }
}
Field Type Default Description
maxConcurrentStreams number 100 Max parallel streams per connection
initialWindowSize number 65535 Flow-control window in bytes
h2c bool false Serve HTTP/2 on plaintext connections (h2c): a client that starts with the HTTP/2 preface, as gRPC clients do (prior knowledge), works (tested in scripts/e2e/grpc.sh); the HTTP/1.1 Upgrade: h2c handshake is not covered by a test. For TLS ports HTTP/2 is negotiated via ALPN regardless. See gRPC.

Compression

Add Content-Encoding: br / zstd / gzip / deflate to responses. Applies to static files, the metrics endpoint, and fallback responses (JSON/text body or file) — each negotiated independently against the same minBytes/types thresholds, so a small metrics scrape or error body may stay uncompressed even with compression enabled.

# YAML — shorthand (enable with defaults)
compression: true

# YAML — fine-grained
compression:
  algorithms: [br, zstd, gzip]  # Brotli first, then Zstd, then gzip
  level: 6                       # 1 = fastest, 9 = smallest
  minBytes: 1024                 # skip responses smaller than 1 KB
// JSON — shorthand
{ "compression": true }

// JSON — fine-grained
{
  "compression": {
    "algorithms": ["br", "zstd", "gzip"],
    "level": 6,
    "minBytes": 1024
  }
}

The types field filters which response Content-Types are compressed:

compression:
  algorithms: [br, gzip]
  types:
    - "text/"
    - "application/json"
    - "application/xml"
    - "application/javascript"
    - "image/svg"
Field Type Default Description
algorithms string[] ["br", "zstd", "gzip"] Compression algorithms to offer. Supported: "br" (Brotli), "zstd" (Zstandard), "gzip", "deflate"
level number 6 Compression level (1–9)
minBytes number 1024 Minimum response size to compress (bytes)
types string[] ["text/", "application/json", "application/xml", "application/javascript", "application/xhtml", "image/svg"] Content-Type prefixes to compress. Use ["*"] to compress all types (not recommended for binary content)

Response Time Header

Inject X-Response-Time: <ms> into every response.

# YAML
responseTime: true

# With custom precision
responseTime:
  digits: 3   # decimal places in the millisecond value
// JSON
{ "responseTime": true }
// JSON
{ "responseTime": { "digits": 3 } }

Server-Timing Header

Add a W3C Server-Timing header to proxied responses so that browser DevTools (Network → Timing) can show where the time went.

# YAML
serverTiming: true
// JSON
{ "serverTiming": true }
server-timing: total;dur=12.4, upstream;dur=11.8

The header is added to responses that come back from an upstream. A response Conduit produces itself (a static file, a redirect, a rejection by a guard) does not carry it. The header is visible to every client, so leave it off if you do not want to expose timings.


Proxy

The proxy object maps URL path prefixes to upstream targets. Each key is a path and starts with / (an empty key means /); a key that does not can never match a request, and conduit validate warns about it. In particular proxy: { targets: [...] } is one route named targets, not “these are the targets”: to send every request to one upstream write proxy: "http://host:port" or proxy: { "/": [...] }. (targets is a field of a route’s object, as in proxy: { "/api": { targets: [...] } }.)

Single upstream (shorthand)

# YAML
proxy:
  /api: "http://backend:4000"
// JSON
{ "proxy": { "/api": "http://backend:4000" } }

Multiple targets

# YAML
proxy:
  /api:
    targets:
      - "http://backend-1:4000"
      - "http://backend-2:4000"
    strategy: round-robin
    stripPrefix: true
// JSON
{
  "proxy": {
    "/api": {
      "targets": ["http://backend-1:4000", "http://backend-2:4000"],
      "strategy": "round-robin",
      "stripPrefix": true
    }
  }
}

URL rewriting

Rewrite rules are evaluated in order. The first matching rule is applied.

# YAML
proxy:
  /api:
    targets: ["http://backend:4000"]
    stripPrefix: true
    rewrite:
      - from: "^/v[0-9]+/(.+)$" # strip version prefix
        to: "/$1"
      - from: "^/users/([0-9]+)$" # migrate legacy paths
        to: "/members/$1"
// JSON
{
  "proxy": {
    "/api": {
      "targets": ["http://backend:4000"],
      "stripPrefix": true,
      "rewrite": [
        { "from": "^/v[0-9]+/(.+)$", "to": "/$1" },
        { "from": "^/users/([0-9]+)$", "to": "/members/$1" }
      ]
    }
  }
}

Proxy route field reference

Field Type Default Description
targets string[] or object[] — Upstream URLs (plain strings or {url, weight}); http://, https://, and ws:///wss:// as the same two (a WebSocket handshake is an HTTP request)
strategy string round-robin Load balancing — see Load balancing
stripPrefix bool false Remove matched path prefix before forwarding
rewriteDestination bool false WebDAV: apply stripPrefix and rewrite to the paths in the Destination and If request headers too — see WebDAV
hashKey string — Key for hash-based strategies: "ip", "url", "header:X-Name"
rewrite object[] — URL rewrite rules: [{from, to}] — first match wins
http2 bool or "h2c" false HTTP/2 to the upstream: true negotiates it through ALPN (TLS upstreams); "h2c" also speaks it to a plaintext upstream (gRPC without TLS) — see gRPC
timeout.connectMs number 3000 TCP connect timeout
timeout.sendMs number — Request send timeout
timeout.readMs number 30000 Response read timeout
timeout.firstByteMs number — Max ms to wait for first upstream response byte (overrides readMs)
timeout.perTryMs number — Per-retry timeout
websocket bool false Allow WebSocket upgrades (101 Switching Protocols) — rejected with 502 by default
retry.attempts number 0 Number of retry attempts (0 = disabled)
retry.conditions string[] — connection_error, 5xx, timeout
retry.backoffMs number 0 Wait between retries (ms)
retry.backoffJitter bool false ±50% random spread on backoffMs to avoid thundering herd
retry.budgetPercent number — Soft cap: max % of in-flight requests that may be retries
healthCheck object — Active health probes — see Health checks
backup string — Fallback URL when all primaries are unhealthy
cache object — Response cache — see Proxy cache
pool object — Connection pool — see Connection pool
rateLimit object — Per-route rate limit — see Rate limiting
upstreamTls object — TLS for HTTPS upstreams — see Upstream TLS
mirror string — Shadow URL — see Traffic mirroring
sticky.cookie string — Cookie name for sticky sessions
sticky.secret string — HMAC-SHA256 secret — Conduit signs + verifies the cookie (prevents forgery)
sticky.strict boolean false Return 503 when the pinned upstream is down (instead of routing elsewhere)
sticky.secure boolean when tls Secure attribute of the cookie Conduit sets (needs secret)
sticky.maxAgeSecs integer session Max-Age of the cookie Conduit sets (needs secret)
groups object[] — Two-level LB groups: [{name, targets, strategy}]
groupStrategy string round-robin Outer strategy when groups is set
priority number (0–100) 50 Request priority for load shedding — see Priority routing

Routes

The routes array matches requests before proxy / static. First match wins.

# YAML
routes:
  # Route to dedicated API v2 server — checked first
  - match:
      path: /api/v2/**
      method: [GET, POST]
      headers:
        X-Version: "2"
    proxy:
      targets: ["http://v2-backend:4000"]

  # Write operations go to write cluster
  - match:
      path: /api/**
      method: [POST, PUT, PATCH, DELETE]
    proxy:
      targets: ["http://write-api:4001", "http://write-api:4002"]
      strategy: least-conn

  # Beta users via cookie → canary backend
  - match:
      cookies:
        beta: "1" # exact: cookie beta=1
        experiment: "blue|green" # regex: blue or green
    proxy:
      targets: ["http://canary:4000"]

  # Everything else → SPA static files
  - match:
      path: /**
    static: ./dist
// JSON
{
  "routes": [
    {
      "match": {
        "path": "/api/v2/**",
        "method": ["GET", "POST"],
        "headers": { "X-Version": "2" }
      },
      "proxy": { "targets": ["http://v2-backend:4000"] }
    },
    {
      "match": {
        "path": "/api/**",
        "method": ["POST", "PUT", "PATCH", "DELETE"]
      },
      "proxy": {
        "targets": ["http://write-api:4001", "http://write-api:4002"],
        "strategy": "least-conn"
      }
    },
    {
      "match": { "path": "/**" },
      "static": "./dist"
    }
  ]
}

Each route entry has exactly three top-level fields: match, proxy, and static. Auth, rate limiting, and other policies come from the site-level config and apply to all routes uniformly.

A proxy action takes the same route options as an entry of the proxy: {} map (see Proxy route field reference): groups, strategy, hashKey, sticky, backup, retry, rewrite, mirror, upstreamTls, healthCheck and the rest behave identically in both forms. Two things differ because a routes[] entry has no path-prefix key:

match field Type Description
path glob Path glob — see skipPaths glob syntax
method string[] HTTP methods to match (case-insensitive)
headers object Request headers that must match (exact or regex)
query object Query parameters that must match (exact or regex)
cookies object Cookies that must match (exact or regex)

All headers, query, and cookies values are matched as full-string regex (anchored ^…$). Plain strings like "v2" or "1" match exactly; regex patterns like "blue|green" or "Bearer .+" use regex semantics. An invalid regex falls back to exact-string comparison.


Load Balancing

Set strategy inside a proxy route. All strategies skip upstreams that are currently unhealthy (failed health probes) or ejected (outlier detection).

proxy:
  /api:
    targets: ["http://a:4000", "http://b:4000"]
    strategy: least-conn # pick a strategy

Choosing a strategy

The algorithm matters less than it looks — every strategy here already skips unhealthy/ejected upstreams (health checks, not the algorithm, are what keeps traffic off a broken backend). Pick based on your actual traffic shape:

Strategy Family Picks based on Session affinity Pool change impact Best for Weak point
round-robin (default) Static Rotation order ✗ none Homogeneous upstreams, simplest default Ignores load — a slow request still gets the next slot
weighted-round-robin Static Rotation + fixed weight ✗ none Heterogeneous capacity (big primary + small standby, canary %) Weights are static — doesn’t adapt to real-time load
random Static Uniform random pick ✗ none Very large pools where a counter is unnecessary overhead Worse uniformity than round-robin at small N
least-conn Load-aware Fewest active connections per unit of weight ✗ none Variable response times (mixed fast reads / slow writes), with or without unequal capacity O(N) scan of the pool on every request
least-response-time Load-aware Lowest probed latency ✗ none Upstreams with different hardware/geography Needs healthCheck configured, or it’s just round-robin
p2c Load- and latency-aware 2 random samples, lower EWMA latency × (in-flight + 1) ÷ weight wins ✗ none Large pools (10+) where least-conn’s full scan is too slow Marginally less precise than true least-conn
least-bandwidth Load-aware √((bytes per second + 1) × (in-flight + 1)) ÷ weight, two random samples ✗ none Mixed large and small responses, where equal connection counts hide very unequal network load Counts bytes, not CPU or memory; a route’s meters start at zero and update every 250 ms
ip-hash Affinity rendezvous hash of the client IP by IP only the clients on a peer that leaves (or joins) move; the rest stay put Soft per-IP affinity without a cookie Behind a proxy or CDN every request has the proxy’s address and goes to one upstream; clients behind one NAT share an upstream
consistent-hash Affinity rendezvous hash of the configured key by key same as ip-hash — only the keys on a peer that leaves (or joins) move Per-tenant/per-user routing, cache locality by URL path Spreads keys, not requests: one very busy key loads one upstream; the header comes from the client

Rule of thumb: start with round-robin. Move to least-conn or p2c once request cost varies noticeably. Reach for ip-hash/consistent-hash only for affinity, not performance — and prefer sticky.cookie over ip-hash when you control the client, since cookie-based affinity survives the client’s own IP changing, which ip-hash does not.

                         ┌─────────────┐
   client ──requests──▶  │   Conduit   │
                         │  (strategy) │
                         └──────┬──────┘
             ┌───────────────────┼───────────────────┐
             ▼                   ▼                    ▼
        upstream A          upstream B           upstream C
       (healthy)            (healthy)            (ejected ✗ — skipped
                                                   by every strategy)

   round-robin / weighted-rr / random  → pick by rotation or chance
   least-conn / least-response-time / p2c → pick by current load/latency
   ip-hash / consistent-hash          → pick by rendezvous hash of the key over the healthy set

round-robin (default)

Cycles through the target list in order, one request at a time. A per-route atomic counter is incremented on each request and taken modulo the number of healthy upstreams.

Request 1 → a  Request 2 → b  Request 3 → a  …

Use when: all upstreams are homogeneous (same hardware, same capacity). Simple, predictable, zero overhead.

proxy:
  /api:
    targets: ["http://a:4000", "http://b:4000", "http://c:4000"]
    strategy: round-robin # or omit — this is the default

weighted-round-robin

Like round-robin, but each upstream gets a number of slots proportional to its weight. If A has weight 3 and B has weight 1, the pattern is A, A, A, B per four requests (exact interleaving may differ, but ratios are preserved over time).

Use when: upstreams have different capacities — e.g. a beefy primary and a smaller standby, or a canary deployment receiving a fraction of traffic.

Targets must be { url, weight } objects — plain strings use weight 1.

proxy:
  /api:
    targets:
      - { url: "http://primary:4000", weight: 9 } # 90% of traffic
      - { url: "http://canary:4000", weight: 1 } # 10% canary
    strategy: weighted-round-robin
// JSON
{
  "proxy": {
    "/api": {
      "targets": [
        { "url": "http://primary:4000", "weight": 9 },
        { "url": "http://canary:4000", "weight": 1 }
      ],
      "strategy": "weighted-round-robin"
    }
  }
}

Note: conduit upstreams weight can change weights at runtime without reloading the config.


least-conn

Routes each new request to the upstream with the fewest active in-flight connections at that instant. The connection counter is incremented before the request is forwarded and decremented when the response completes (including retries and errors).

Use when: requests have highly variable response times — e.g. a mix of fast reads and slow writes. Under uniform load it behaves like round-robin; its advantage emerges when some requests stall.

Ties. When several upstreams have the same count (all of them, whenever the requests are short enough that none is still in flight when the next arrives), one of them is chosen at random, in proportion to its weight. Earlier releases always picked the first target in the list for such a tie, so a lightly loaded pool sent every request to its first target.

Weights. The comparison is active connections divided by weight, as in nginx least_conn: an upstream with weight 3 carries three times the in-flight requests of a weight-1 upstream before the next request goes elsewhere. Plain string targets have weight 1, so a pool without weights behaves exactly as plain least-connections. An upstream with weight 0 receives nothing while any other upstream has a weight above 0. conduit upstreams weight changes the weight at runtime.

proxy:
  /api:
    targets: ["http://a:4000", "http://b:4000", "http://c:4000"]
    strategy: least-conn
proxy:
  /api:
    targets:
      - { url: "http://big:4000", weight: 3 } # up to 3x the in-flight requests of "small"
      - { url: "http://small:4000", weight: 1 }
    strategy: least-conn

Tip: combine with healthCheck.maxConnectionsPerUpstream for a circuit breaker that activates when all upstreams are saturated.


least-response-time

Routes each request to the upstream with the lowest measured latency from the most recent active health probe. Falls back to round-robin during the warm-up phase before any probe has completed.

Latency is measured by the health-check prober (a HEAD request to healthCheck.path for a plaintext upstream, the TCP connect time for a TLS one: https://, wss://). Upstreams without probe data are ranked last (u64::MAX).

Use when: upstreams have meaningfully different hardware or geographic proximity and you want to bias traffic toward the fastest one. Requires healthCheck to be configured on the route — without probes, this strategy falls back to round-robin permanently.

proxy:
  /api:
    targets:
      - "http://us-east:4000"
      - "http://eu-west:4000"
    strategy: least-response-time
    healthCheck:
      path: /health
      intervalSecs: 10
// JSON
{
  "proxy": {
    "/api": {
      "targets": ["http://us-east:4000", "http://eu-west:4000"],
      "strategy": "least-response-time",
      "healthCheck": { "path": "/health", "intervalSecs": 10 }
    }
  }
}

ip-hash

Sends every request from the same client address to the same upstream, without any cookie. Conduit hashes the address of the TCP peer that connected to it (FNV-1a) and maps the hash to an upstream by rendezvous (highest-random-weight) hashing: every healthy upstream is scored against the hash and the highest score wins. The same address lands on the same upstream for as long as the set of healthy upstreams is unchanged. An upstream listed twice is scored once, so a duplicate entry is not a weight: use weighted-round-robin when the capacities differ.

Field Meaning Default
strategy: ip-hash Turns the behaviour on. round-robin
hashKey What is hashed. The default ip is what this strategy is for; url and header:<Name> make ip-hash behave exactly like consistent-hash, which is the clearer name for them. ip

Use when:

Do not use it when:

When the pool changes. Removing an upstream, or ejecting it as unhealthy, moves only the clients that were on it, each to its next-best upstream; everyone else stays where they are. When it comes back, those clients return. Adding an upstream takes over about 1/N of the clients. A plain “hash modulo the number of upstreams” scheme would instead reshuffle nearly everyone on every change.

Spread. With few clients the split is uneven by chance (two clients can hash to the same upstream); it evens out as the number of distinct addresses grows. If you need an exact split, use weighted-round-robin; affinity and exact shares do not go together.

proxy:
  /auth:
    targets: ["http://auth1:5000", "http://auth2:5000"]
    strategy: ip-hash
    hashKey: ip # default for ip-hash; can be omitted
// JSON
{
  "proxy": {
    "/auth": {
      "targets": ["http://auth1:5000", "http://auth2:5000"],
      "strategy": "ip-hash"
    }
  }
}

consistent-hash

Hashes a configurable hashKey (the client address, the URL path, or the value of any request header) and maps it to an upstream by rendezvous hashing. Identical to ip-hash in implementation, so it behaves the same when the pool changes: only the keys that were on a removed or ejected upstream move. The distinction is which value is hashed, and the default here is the same ip.

Use when: requests with the same key must meet the same upstream, and the key is not (only) the client address:

The hashKey field controls what is hashed:

hashKey value Hashes Example use case
ip (default) The address of the TCP peer that connected to Conduit (not X-Forwarded-For) Per-client affinity
url The request path, without the query string (/a?x=1 and /a?x=2 hash alike) Cache locality: the same page always hits the same backend
header:X-Name The value of header X-Name Per-tenant or per-user routing

Details that decide whether the result is what you expect:

proxy:
  /api:
    targets:
      ["http://shard-1:4000", "http://shard-2:4000", "http://shard-3:4000"]
    strategy: consistent-hash
    hashKey: "header:X-Tenant-ID"
// JSON
{
  "proxy": {
    "/api": {
      "targets": [
        "http://shard-1:4000",
        "http://shard-2:4000",
        "http://shard-3:4000"
      ],
      "strategy": "consistent-hash",
      "hashKey": "header:X-Tenant-ID"
    }
  }
}

Cache locality, and the real client address behind a proxy:

proxy:
  /static-pages:
    targets: ["http://render-1:4000", "http://render-2:4000"]
    strategy: consistent-hash
    hashKey: url
  /app:
    targets: ["http://app-1:4000", "http://app-2:4000"]
    strategy: consistent-hash
    hashKey: "header:X-Real-IP" # set by the proxy in front; clients must not reach Conduit directly

Same behaviour as ip-hash: removing an upstream moves only the keys that were on it.


random

Selects an upstream uniformly at random on each request using a fast thread-local RNG.

Use when: you want an even distribution without any coordination overhead — useful for very large pools where maintaining a round-robin counter per route is unnecessary. In practice, round-robin is usually preferred since it provides better uniformity over small sample sizes.

proxy:
  /api:
    targets: ["http://a:4000", "http://b:4000", "http://c:4000"]
    strategy: random

p2c (Power of Two Choices)

On each request, samples two upstreams at random and forwards to the one with the lower cost:

cost = EWMA latency × (requests in flight + 1) ÷ weight

The latency is the passive, time-decayed measurement over all traffic that GET /upstreams reports as ewma_latency_ms (an upstream with no measurement yet counts as 30 ms). The in-flight count is the one least-conn and healthCheck.maxConnectionsPerUpstream use, reported as active_connections. This is Tower’s PeakEwma load, which linkerd’s P2C balancer uses, divided by the weight. Ties are broken in favour of the first sample. Selection costs O(1) — no scan of the full pool.

Both factors matter. Latency alone would send every request to the faster upstream however busy it was; with the in-flight factor an upstream twice as fast settles at about twice the in-flight requests of the slower one, and a busy upstream hands requests back to its sibling.

Failures count as slow. A response of 500 or more, a connect failure and a timeout are charged to the estimate as at least one second, however fast the error came. Without that, an upstream that answers every request with an error right away would have the lowest latency in the pool and attract the traffic (the fast-failing-peer problem). One failure moves the traffic away from that upstream for a few seconds (the estimate decays with a 10 s time constant); one that keeps failing stays out. It shows in ewma_latency_ms of GET /upstreams.

Weights. The cost is divided by weight, so at equal latency a weight-3 upstream carries about three times the in-flight requests of a weight-1 upstream when the pool has two upstreams. With more, only two random samples are compared and the in-flight counts are small whole numbers, so the split is coarser: weights 3:1:1 with 32 concurrent clients measured 47/26/27 of the requests (60/20/20 would be proportional). Use least-conn, least-bandwidth or weighted-round-robin when proportional shares matter. Plain string targets have weight 1. An upstream with weight 0 loses every comparison. With nothing in flight the weight-3 upstream is simply the cheaper one every time, so serial requests all go to it; the in-flight shares become proportional once requests overlap.

With a single upstream in the pool, P2C falls back to round-robin.

Use when: the upstream pool is large (10+) and least-conn would scan the entire list on every request. Also useful as a drop-in replacement for least-conn when you want reduced coordination overhead.

proxy:
  /api:
    targets:
      - "http://a:4000"
      - "http://b:4000"
      - "http://c:4000"
      - "http://d:4000"
    strategy: p2c
// JSON
{
  "proxy": {
    "/api": {
      "targets": [
        "http://a:4000",
        "http://b:4000",
        "http://c:4000",
        "http://d:4000"
      ],
      "strategy": "p2c"
    }
  }
}

least-bandwidth

Routes each request to the upstream that is currently moving the least traffic. Of two upstreams sampled at random (all of them, when the pool has two), it picks the one with the lower cost:

cost = √((bytes per second + 1) × (requests in flight + 1)) ÷ weight

Use when: responses differ a lot in size, for example large downloads next to small API calls, so equal connection counts hide very unequal network load and the upstream’s network is the bottleneck. When the limit is CPU or memory, least-conn or p2c is the better signal.

Typical cases:

Not a good fit: very short, equal-sized requests (the rate is noise and the in-flight term does the work, so least-conn or p2c is simpler), and routes where the upstream’s limit is CPU, memory or a database, which bytes do not show.

Parameters. There are none of its own: strategy: least-bandwidth is the whole setting. The only input you control is each target’s weight (default 1, as { url, weight }). The 10-second time constant and the 250 ms refresh are fixed.

What it does in practice. In the load-balancing report that CI posts on pull requests (four local upstreams, upstream 0 taking 8 ms per request and the other three answering at once, one worker thread), round-robin gave each upstream 25 % of the requests while least-bandwidth gave the slow one 12 % and the others 29 % each. The report’s “even” scenario (four equal upstreams) shows the same strategy splitting 25 / 25 / 25 / 25, so it costs nothing when there is nothing to correct.

proxy:
  /files:
    targets:
      - { url: "http://store-1:4000", weight: 1 }
      - { url: "http://store-2:4000", weight: 2 }
    strategy: least-bandwidth

Sticky sessions

Keep a browser session on one upstream by looking at a cookie. There are two modes, chosen by whether you set sticky.secret:

  Without secret With secret (recommended)
Who sets the cookie Your application (a session id it already sets) Conduit, on every response
What the cookie holds whatever the application put there a signature that names the upstream that served the request
How routing uses it the value is a hash key: the same value always maps to the same upstream Conduit verifies the signature and sends the request straight to that upstream
Forged or invalid cookie still used as a key: a client can steer itself to the upstream a chosen value hashes to ignored: the request is balanced normally
strict has no effect true: answer 503 if the pinned upstream is down; false: move to another

All the options of sticky:

Option Type Default Meaning
cookie string required Cookie name to read (and, with secret, to set).
secret string none Key for signing and verifying. Use an environment variable ("$STICKY_SECRET").
strict boolean false With secret: refuse with 503 (reason sticky_upstream_unavailable) instead of relocating when the pinned upstream is unhealthy.
secure boolean Secure when the site has tls With secret: the Secure attribute of the cookie. true always (use it behind a load balancer that terminates TLS: Conduit then sees plain HTTP); false never.
maxAgeSecs integer ≥ 1 session cookie With secret: the Max-Age of the cookie.

Use when: the application keeps session state in the memory of one process (a shopping cart, a login held in the worker, an upload that must finish on the node that started it) and a shared session store is not an option. If you can add a shared store (Redis, a database), do so: sessions then survive an upstream restart and no stickiness is needed.

Before the first cookie. A request with no cookie is balanced by the route’s strategy as usual. In secret mode Conduit then sets the cookie on the response, and the following requests follow it. In the mode without secret Conduit sets nothing: the first request is balanced normally, and affinity starts only once your application has set the cookie and the client sends it back. While a cookie is present and honoured, it replaces the route’s strategy for that request.

Not with groups. A route that has groups ignores sticky: no cookie is set and none is honoured. conduit validate and the start-up log say so. strict without secret is ignored too, and is reported the same way.

It is affinity, not a guarantee. If the pinned upstream is unhealthy (or at its maxConnectionsPerUpstream) and strict is off, the session moves to another upstream and loses whatever state the first one held. Sticky routing cannot keep a session on an upstream that is down; it only prefers the same one while it is up.

proxy:
  /app:
    targets: ["http://a:4000", "http://b:4000"]
    strategy: consistent-hash
    sticky:
      cookie: session_id
// JSON
{
  "proxy": {
    "/app": {
      "targets": ["http://a:4000", "http://b:4000"],
      "strategy": "consistent-hash",
      "sticky": { "cookie": "session_id" }
    }
  }
}

Without a secret, your application must set the cookie (see “Before the first cookie” above); Conduit never sets it.

HMAC-signed sticky cookies

Without a secret, the cookie value is used as a raw consistent-hash key. An attacker can craft a cookie to force routing to any backend they choose.

Set sticky.secret to make Conduit sign cookies with HMAC-SHA256 and verify them on every request. Forged cookies silently fall back to normal load-balancing rather than pinning to an attacker-controlled backend.

proxy:
  /app:
    targets: ["http://a:4000", "http://b:4000"]
    strategy: consistent-hash
    sticky:
      cookie: srv_id       # Conduit sets this cookie on every response
      secret: "$STICKY_SECRET"  # HMAC key — use an env var, never hardcode
      strict: false        # true = 503 when pinned upstream is down
Option Behaviour
No secret Cookie value is the raw consistent-hash key (legacy, no forgery protection)
secret set Conduit signs the URL with HMAC-SHA256 and injects a Set-Cookie on every response
strict: false (default) If the pinned upstream is unhealthy, fall back to the next available backend
strict: true If the pinned upstream is unhealthy, return 503 Service Unavailable immediately

The injected cookie attributes are Path=/; HttpOnly; SameSite=Lax, plus Secure and Max-Age as configured, and SameSite as sameSite says:

How the pin is applied. With a secret set, the verified cookie names one exact upstream, and Conduit routes to that upstream directly — the configured strategy is not consulted at all while the pin can be honored. A pin is honored whenever its upstream is healthy and below maxConnectionsPerUpstream; otherwise Conduit falls back to the strategy and:

Without a secret, there is no pinned URL to honor — the cookie value is only a hash key, and routing goes through consistent-hash as usual.

Security note: store the HMAC secret in an environment variable (secret: "$STICKY_SECRET"). Rotate by changing the value and reloading; existing cookies will silently fall through to normal load-balancing for one request and then get a new signed cookie.


Upstream groups (two-level balancing)

Instead of one flat pool, a route can have several named groups of upstreams. Balancing then takes two steps: the outer strategy (groupStrategy) picks a group for the request, and the group’s own strategy picks an upstream inside it. Use it when the upstreams are not interchangeable and you want to say which ones a request may use, for example one pool per region, per customer tier, or per hardware generation.

Field Where Type Default Meaning
groups route array none The groups. Use it instead of targets (a route needs one of the two).
groups[].name group string required Name of the group; the outer strategy chooses among these names.
groups[].targets group array required The group’s upstreams, as on a flat route (URLs or { url, weight }).
groups[].strategy group strategy round-robin How an upstream is picked inside this group. Any of the strategies, each group can differ.
groupStrategy route strategy round-robin How a group is picked. See the table below for which values make sense.
hashKey route string ip What ip-hash / consistent-hash hash, for the outer pick and for a hash strategy inside a group (see consistent-hash).

Typical shapes:

Which outer strategy to use:

groupStrategy Result
round-robin, random The groups take turns / are chosen at random, regardless of how many upstreams each has.
ip-hash, consistent-hash A client (or key) keeps its group.
least-conn, p2c, least-bandwidth, least-response-time Not meaningful: see below.

The outer strategy chooses among the group names, and a name has no load of its own: nothing is in flight on it, no latency is measured for it and no bytes move through it. So round-robin, random, ip-hash and consistent-hash work as described, while least-conn, p2c, least-bandwidth and least-response-time cannot tell the groups apart by load (the first three choose at random, the last one in turn) and Conduit logs a warning for them. Put the load-aware strategy on each group’s own strategy instead, as below.

proxy:
  /api:
    groups:
      - name: us-east
        targets: ["http://us-east-1:4000", "http://us-east-2:4000"]
        strategy: least-conn
      - name: eu-west
        targets: ["http://eu-west-1:4000", "http://eu-west-2:4000"]
        strategy: least-conn
    groupStrategy: ip-hash # outer: same client IP always hits same region
// JSON
{
  "proxy": {
    "/api": {
      "groups": [
        {
          "name": "us-east",
          "targets": ["http://us-east-1:4000", "http://us-east-2:4000"],
          "strategy": "least-conn"
        },
        {
          "name": "eu-west",
          "targets": ["http://eu-west-1:4000", "http://eu-west-2:4000"],
          "strategy": "least-conn"
        }
      ],
      "groupStrategy": "ip-hash"
    }
  }
}

See examples/upstream-groups.yaml

What happens when a group fails

A group is a unit of affinity, not (yet) of failover. Measured with the real server (two groups of one upstream each, eu-west down, 40 requests from one client):

Setup Result
groupStrategy: round-robin Every second request goes to eu-west and fails (20 of 40).
groupStrategy: ip-hash A client that hashes to eu-west fails on every request (40 of 40); a client that hashes to us-east is never affected.
Route backup: set to a live upstream No difference: backup is not used on a route with groups.

Why: the outer pick chooses among group names and does not look at the health of their upstreams. Inside a group, unhealthy upstreams are skipped, but when none is healthy the group does not refuse: it hands the request to one of them anyway (so a group whose health checks are all failing still gets traffic). Nothing moves a failed group’s traffic to another group, so with a hash outer strategy the problem stays local to the clients of that group, and with a rotating one it hits a fixed share of everyone. Tracked in #643.

Also true of a route with groups today:

If you need regional failover today: keep the regions out of groups: use two routes or sites behind a DNS or external load balancer that health-checks the regions, or one flat pool with weighted-round-robin (a small weight for the far region): a flat pool skips its unhealthy upstreams, so a failed region’s share moves to the others.


Static Files

Simple directory

# YAML
static: ./dist
// JSON
{ "static": "./dist" }

Multiple directories

# YAML
static:
  - ./dist
  - ./public
// JSON
{ "static": ["./dist", "./public"] }

Path-mapped directories

# YAML
static:
  /: ./dist
  /docs: ./docs-dist
// JSON
{ "static": { "/": "./dist", "/docs": "./docs-dist" } }

Static options

# YAML
static: ./dist
staticOptions:
  index: [index.html] # default files for directory requests
  dotFiles: ignore # "ignore" | "allow" | "deny"
  preCompressed: true # serve .br / .gz if present
  etag: true # ETag / 304 Not Modified support
  lastModified: true # Last-Modified header
  maxAge: "1y" # Cache-Control max-age (humantime: "1d", "30m", "1y")
// JSON
{
  "static": "./dist",
  "staticOptions": {
    "index": ["index.html"],
    "dotFiles": "ignore",
    "preCompressed": true,
    "etag": true,
    "lastModified": true,
    "maxAge": "1y"
  }
}
Field Type Default Description
index string[] ["index.html"] Default files for directory requests
dotFiles string "ignore" "ignore", "allow", or "deny"
preCompressed bool false Serve pre-compressed .br / .gz files
etag bool true ETag + conditional GET support
lastModified bool true Last-Modified header
maxAge string — Cache-Control: max-age — humantime duration string

A symlink below a static root is never served, whether it points to a file or to a directory: the request is treated as if the file did not exist. Every component under the root is also opened relative to the directory above it without following links (openat with O_NOFOLLOW on Unix, NtCreateFile with FILE_OPEN_REPARSE_POINT on Windows, which covers directory junctions too), so a directory swapped for a symlink or junction between the check and the open is refused as well. On Windows, a file or directory that is a reparse point but not a link (a OneDrive placeholder, a deduplicated file) is opened normally after an identity check; that path is written from the API contract and has not been run against a real placeholder, so such a file may be refused rather than served: answered as not found when the second open lands on another file, and as a 500 when the second open itself fails (for example a reparse tag nothing handles). On any other platform the check runs before the open, so a symlink swapped in between the two could still be followed: keep the served tree writable by trusted accounts only.

The file is opened once, before the first response header is written, and its size, modification time, ETag and Last-Modified are read from that open handle, which the body is then streamed from. A file that disappears or turns into a link between the lookup and the open is answered as not found (the fallback runs) before anything is sent, never as a 200 cut off after its headers; so is a directory that took the file’s place on Unix (on Windows that case is reported by the system as access denied, a 403). A file the server cannot read is a 403, any other open failure a 500, both before the headers. A 304 or a HEAD request therefore also opens the file.

On Windows, NTFS keeps a second, 8.3 short name for each long name on a volume that creates them (the system volume by default), and resolves it to the same file: /HTPASS~1 would open .htpasswd without dotFiles ever seeing a dot. A name shaped like a generated short name (BASE~N or BASE~N.EXT, at most 8 characters before the last dot and 3 after, with a ~ and digits at the end of the base) is therefore answered as not found, in any path segment and as an index name. A real file named like that (report~1.pdf) is not served on Windows; a longer base or extension (report~1.html) is. A short name an administrator chose by hand (fsutil file setshortname) is not recognised: that needs the same rights as planting a link.

The access-log file (logging.file) gets the same protection for its last path component: a symlink planted at the log path is refused, and on Windows so is a junction or any other reparse point (a OneDrive placeholder, a deduplicated file), so keep the log on a plain folder there. The directories above it are not checked, so keep the log directory writable by trusted accounts only.

The root path itself is resolved normally: a symlinked root such as current -> releases/42 works, and switching that link takes effect on the next request. Whoever can replace the root path, or one of its parent directories, decides what is served, so keep those writable by the operator only.


Redirects

redirects is an array of redirect rules.

# YAML
redirects:
  - from: /old-path
    to: "https://example.com/new-path"
    status: 301

  - from: "/blog/(.+)" # regex capture group
    to: "https://blog.example.com/$1"
    status: 308
// JSON
{
  "redirects": [
    {
      "from": "/old-path",
      "to": "https://example.com/new-path",
      "status": 301
    },
    { "from": "/blog/(.+)", "to": "https://blog.example.com/$1", "status": 308 }
  ]
}
Field Type Default Description
from string — Path or regex pattern to match
to string — Destination URL (capture groups $1…$N are expanded)
status number 301 HTTP redirect status code

Fallback

Return a response when no route matches.

# YAML — SPA: serve index.html for all unmatched browser routes
fallback:
  file: ./dist/index.html
  status: 200
# YAML — content-type-aware fallback (Accept header negotiation)
fallback:
  byAccept:
    html:
      file: ./dist/index.html
      status: 200
    json:
      body: { "error": "Not Found", "status": 404 }
      status: 404
  status: 404
  body: "Not Found"
// JSON
{
  "fallback": {
    "file": "./dist/index.html",
    "status": 200
  }
}
// JSON
{
  "fallback": {
    "byAccept": {
      "html": { "file": "./dist/index.html", "status": 200 },
      "json": { "body": { "error": "Not Found", "status": 404 }, "status": 404 }
    },
    "status": 404,
    "body": "Not Found"
  }
}
Field Type Default Description
file path — File to serve
body any — Response body (string or JSON object)
status number 200 HTTP status code
headers object — Response headers to set
byAccept object — Content-type-aware rules keyed by Accept type (see key matching below)

byAccept keys are matched against the request’s Accept header (the header value is lowercased before matching; a configured key like xml is matched case-sensitively against it, so a literal-substring key should be written in lowercase), checked in the order they’re defined, first match wins:

Key Matches when Accept contains
html text/html
json application/json
text text/plain or text/
image image/
any other key the key itself, as a literal substring (e.g. xml matches application/xml)
* wildcard fallback, checked only after every other key has been tried

Health Checks

“Health check” means three different things in Conduit. Only the first two decide where a request goes:

  What it is Configured with Does the balancer use it?
Active probes Conduit sends a request to every upstream of a route on a timer and marks it healthy or unhealthy healthCheck on the route (below) Yes. Every strategy skips an unhealthy upstream
Passive ejection Conduit watches the real responses and ejects an upstream that returns too many 5xx outlierDetection Yes, the same way
Site health endpoint A URL Conduit itself serves (/__health__) so that something in front of it (a cloud load balancer, Kubernetes) can ask whether Conduit is alive healthCheck on the site (see below) No: it is for others to call

What the balancer does with the health state

An upstream that is unhealthy (a failed probe series or an ejection) is left out of the candidates of every pick: round-robin, least-conn, the hash strategies, sticky pins, the inside of an upstream group and the retry list all choose among the healthy ones only. When it recovers it is a candidate again; slowStartSecs can bring it back gradually (see Slow start for when it does not: the hash strategies and sticky pins send it its clients at once, and a route that fails open has no ramp). If every upstream of a route (or of a group) is unhealthy, all of them stay candidates and the strategy picks one as usual: it does not try them in turn, and a route with groups has no retry. So a wrongly failing probe cannot take a route down by itself, but nothing protects the requests then.

A passive ejection ends only through a real request: when it expires, one request is offered to the upstream as a probe (a success restores it, a failure ejects it again for twice as long, up to maxEjectionTimeSecs). If the strategy sends that request to another upstream, the offer lapses after 10 seconds and is repeated; measured with two upstreams, the upstream was back after about 10 seconds (before #650 it stayed out for good). Active probes do not lift a passive ejection.

Without active probes and without outlierDetection the balancer knows nothing: a dead upstream keeps receiving its share of the requests until you fix it. Both are off by default. Measured with the real server (two upstreams, round-robin, one of them stopped, 20 requests right after and 20 six seconds later):

Configuration Right after the stop Six seconds later
nothing configured 10 ok, 10 502 10 ok, 10 502: it never stops
healthCheck every 1 s, unhealthyThreshold: 2 10 ok, 10 502 20 ok
outlierDetection, consecutive5xx: 2, maxEjectionPercent: 50 18 ok, 2 502 20 ok

So there is always a window in which some requests still go to the dead upstream. For probes it is about (unhealthyThreshold − 1) to unhealthyThreshold times intervalSecs (it depends on where the failure falls between two probe ticks), plus the time the probes take. The measurement above used an upstream that refuses connections, which fails at once; one that hangs takes up to timeoutMs (default 5000, one deadline for the whole probe) before the probe counts as failed, so the window grows by that much per failed probe: lower it for upstreams that answer in a few milliseconds. Passive ejection closes it after consecutive5xx failed requests, as long as the ejection cap below allows another ejection, and it reacts only to real requests (an upstream that gets none is never examined). To lose fewer requests during that window add retry, which repeats a failed request on another upstream (on a flat route: a route with groups ignores it). A real deployment usually wants active probes (they find a dead upstream before a user does and also bring it back), plus outlierDetection for upstreams that answer probes but fail real requests.

maxEjectionPercent limits how many upstreams passive ejection may remove at once: that percentage (default 10%) of all the upstreams Conduit tracks, not only this route’s, rounded down but never below one. So one upstream can always be ejected however low the percentage is; with the default 10%, more than one needs at least 20 tracked upstreams. The cap is checked and applied without a lock, so when several upstreams reach the threshold at the same moment the limit can briefly be exceeded.

Also: least-response-time takes its latencies from the active probes, so it needs healthCheck or it behaves like round-robin; and a route with groups skips unhealthy upstreams only inside the chosen group, it does not move traffic to another group (see Upstream groups).

Active upstream probes

Probing is optional and off by default: nothing is sent to an upstream for health unless the route has a healthCheck. When it has, Conduit sends each of the route’s upstreams one HEAD request (a new TCP connection, Connection: close) to path every intervalSecs (default 10 seconds), one upstream after the other. A probe passes when the upstream answers with any HTTP status below 500 (waiting at most 5 seconds for each step: connect, send, answer); a refused or timed-out connection, a missing answer or a 5xx is a failure. So the service does not need a health endpoint: any path that answers (the default is /) is enough, a 404 counts as alive, and a service that cannot or must not be asked simply gets no healthCheck (and, if wanted, outlierDetection instead, which sends nothing and judges the real requests).

What can be set today: the path, the interval, and how many failures or passes change the state. What cannot: the probe timeout (fixed, #652), the method, what counts as a pass (the status below 500 rule is fixed), probing after a number of requests instead of after a time, or switching probes off for one upstream of a route. Two timings of the passive side are fixed as well: how long a probe offer to an ejected upstream waits for its answer (10 seconds) and the backoff after a failed offer (30 seconds, doubling up to 300). All of this is tracked in #653.

# YAML
proxy:
  /api:
    targets: ["http://a:4000", "http://b:4000"]
    healthCheck:
      path: /health
      intervalSecs: 10
      unhealthyThreshold: 3
      healthyThreshold: 1
      slowStartSecs: 30
      unhealthyStatus: [429, 500, 502, 503, 504] # real responses with these status codes count as failures
      unhealthyLatencyMs: 2000 # real responses slower than 2 s count as failures
// JSON
{
  "proxy": {
    "/api": {
      "targets": ["http://a:4000", "http://b:4000"],
      "healthCheck": {
        "path": "/health",
        "intervalSecs": 10,
        "unhealthyThreshold": 3,
        "healthyThreshold": 1,
        "slowStartSecs": 30,
        "unhealthyStatus": [429, 500, 502, 503, 504],
        "unhealthyLatencyMs": 2000
      }
    }
  }
}

Site health endpoint (for load balancer probes)

# YAML
healthCheck: true

healthCheck:
  path: /__health__
  includeUpstreams: true   # include per-upstream health in JSON response
// JSON
{ "healthCheck": { "includeUpstreams": true } }

Health check field reference

Field Type Default Description
path string / Path of the probe’s HEAD request (a path without a leading / gets one; an https:// or wss:// upstream is probed by opening a TCP connection only, because the probe is plaintext HTTP/1.1 and a TLS listener would not understand it, so path is not used for it). The default is /, not /__health__ (that is the path of Conduit’s own site health endpoint)
intervalSecs number 10 Seconds between probes of each upstream (minimum 1)
unhealthyThreshold number 3 Consecutive failed probes before the upstream is left out
healthyThreshold number 1 Consecutive passed probes before it is brought back
timeoutMs number 5000 Probe timeout in milliseconds (minimum 1): one deadline for the whole probe, connecting, sending the request and receiving the first line of the answer together. A probe that does not finish in time fails like one that is refused
unhealthyStatus number[] none Real responses, not probes (passive): a response from the upstream with one of these status codes counts as a failure of that upstream; enough of them in a row eject it when outlierDetection is configured. Example: [429, 500, 502, 503, 504]
unhealthyLatencyMs number — Real responses, not probes (passive): a response slower than this (ms) counts as a failure of that upstream, even if its status is 2xx; ejects it only with outlierDetection
slowStartSecs number 0 Traffic ramp-up period after recovery. Ignored for ipHash/consistentHash and sticky routes.
maxConnectionsPerUpstream number — Circuit breaker threshold
prewarmConnections number 0 Pre-establish N keepalive connections at startup (max 8). 🚫 Blocked — warms a throwaway client, not Conduit’s real upstream pool (Pingora 0.9 has no public API for it) — see note below.
includeUpstreams bool false Include upstream health in /__health__ response

Circuit Breaker

maxConnectionsPerUpstream enforces a per-upstream connection cap for every load-balance strategy, across all three config shapes (proxy: {} map, routes[] array, and groups):

Known limitations still open after the 2026-08-03 integrity audit — see the repo’s issue tracker for current status:

# YAML
proxy:
  /api:
    targets: ["http://a:4000", "http://b:4000", "http://c:4000"]
    healthCheck:
      maxConnectionsPerUpstream: 100
    backup: "http://replica:4000"
// JSON
{
  "proxy": {
    "/api": {
      "targets": ["http://a:4000", "http://b:4000", "http://c:4000"],
      "healthCheck": { "maxConnectionsPerUpstream": 100 },
      "backup": "http://replica:4000"
    }
  }
}

See examples/circuit-breaker.yaml


Slow start

healthCheck.slowStartSecs ramps traffic to an upstream that just recovered from an unhealthy state, instead of sending it 100% of its normal share immediately (the classic thundering-herd-into-a-just-recovered-backend scenario).

For the slowStartSecs seconds immediately after recovery, the upstream participates in each pick with a probability equal to how far through the ramp window it is (0% right after recovery, rising linearly to 100% once the window elapses). This applies to every load-balance strategy except ipHash/consistentHash and sticky sessions:

Recovery is recorded both when an active health-check probe flips an upstream back to healthy, and when a half-open outlier-detection probe succeeds — the latter is the only recovery signal available for upstreams configured on a route that has no healthCheck block (active probes run for the proxy: {} map, the routes[] array and groups; without a healthCheck there is no probe).

# YAML — pairs well with least-conn, since that's the strategy slow-start
# benefits the most
proxy:
  /api:
    targets: ["http://a:4000", "http://b:4000"]
    strategy: least-conn
    healthCheck:
      slowStartSecs: 30
// JSON
{
  "proxy": {
    "/api": {
      "targets": ["http://a:4000", "http://b:4000"],
      "strategy": "least-conn",
      "healthCheck": { "slowStartSecs": 30 }
    }
  }
}

Retry

# YAML
proxy:
  /api:
    targets: ["http://a:4000", "http://b:4000"]
    retry:
      attempts: 3
      conditions:
        - connection_error
        - "5xx"
        - timeout
      backoffMs: 100
      backoffJitter: true # add ±50% random spread to backoffMs
      budgetPercent: 20
    timeout:
      perTryMs: 2000
// JSON
{
  "proxy": {
    "/api": {
      "targets": ["http://a:4000", "http://b:4000"],
      "retry": {
        "attempts": 3,
        "conditions": ["connection_error", "5xx", "timeout"],
        "backoffMs": 100,
        "backoffJitter": true,
        "budgetPercent": 20
      },
      "timeout": { "perTryMs": 2000 }
    }
  }
}

Retry field reference

Field Type Default Description
attempts number 0 Number of retry attempts (0 = disabled)
conditions string[] — Triggers: "connection_error", "5xx", "timeout". Retries only happen when at least one matches.
backoffMs number 0 Fixed wait between attempts (ms). 0 = immediate retry.
backoffJitter bool false Apply ±50% random spread to backoffMs to avoid thundering herd. Effective delay: [ms/2, ms*3/2)
budgetPercent number — Soft cap: at most this fraction of in-flight requests may be retries. Prevents retry storms under mass failure.

Body buffering for retry — POST/PUT/PATCH requests are only retried when limits.maxBodyBufferBytes is set. Without it, request bodies are not buffered and connection_error retries on non-GET methods are skipped silently.

1xx interim responses

Some upstream backends (Spring Boot, CDNs, gRPC gateways) send one or more 1xx informational responses before the final response — for example 103 Early Hints for browser resource preloading, or 100 Continue after a Expect: 100-continue request header.

Conduit passes 1xx responses through to the client without running any middleware (retry logic, error masking, response transforms, etc.), then continues waiting for the real response. No configuration is required.

Exception: 101 Switching Protocols (WebSocket upgrade) is handled separately by the websocket: true route option — see the field reference table.


Outlier Detection

Passively eject upstreams that return too many 5xx responses from real traffic. Tracks and ejects for every load-balance strategy, not just LeastConn.

# YAML
outlierDetection:
  consecutive5xx: 5
  baseEjectionTimeSecs: 30
  maxEjectionTimeSecs: 300
  maxEjectionPercent: 33
// JSON
{
  "outlierDetection": {
    "consecutive5xx": 5,
    "baseEjectionTimeSecs": 30,
    "maxEjectionTimeSecs": 300,
    "maxEjectionPercent": 33
  }
}

Ejection uses exponential backoff: 30 s → 60 s → 120 s → … up to maxEjectionTimeSecs.

Half-open circuit breaker: when the ejection period expires, the first request is allowed through as a probe. If the probe succeeds (non-5xx), the upstream is fully restored and ejection_count is reset. If it fails, the upstream is re-ejected with the next backoff level. All other requests during the probe are blocked until the probe completes.

Field Type Default Description
consecutive5xx number 5 Consecutive errors before ejection
baseEjectionTimeSecs number 30 Initial ejection duration
maxEjectionTimeSecs number 300 Maximum ejection duration (cap on backoff)
maxEjectionPercent number 10 Max % of cluster that may be ejected at once

Limits

# YAML
limits:
  maxBodyBytes: 10485760 # reject request bodies over 10 MB (413)
  maxHeaderBytes: 65536 # reject headers over 64 KB
  timeoutSecs: 30 # global request timeout (seconds)
  maxInflightRequests: 1000 # return 503 when 1000 requests are in flight
  maxBodyBufferBytes: 1048576 # buffer up to 1 MB per request for retry replay
  maxConnectionsPerIp: 50 # max simultaneous connections from one IP (429)
  keepaliveRequestLimit: 1000 # recycle connections after this many requests
  priorityThreshold: 0.8 # shed low-priority routes above 80% concurrency
  minUploadRateBytesPerSec: 1024 # reject uploads slower than 1 KiB/s (408)
// JSON
{
  "limits": {
    "maxBodyBytes": 10485760,
    "maxHeaderBytes": 65536,
    "timeoutSecs": 30,
    "maxInflightRequests": 1000,
    "maxBodyBufferBytes": 1048576,
    "maxConnectionsPerIp": 50,
    "keepaliveRequestLimit": 1000,
    "priorityThreshold": 0.8,
    "minUploadRateBytesPerSec": 1024
  }
}
Field Type Default Description
maxBodyBytes number — Max request body size — returns 413 if exceeded (declared Content-Length, or the bytes actually received for a chunked body)
maxHeaderBytes number — Max request header size
timeoutSecs number — Global request timeout
maxInflightRequests number — Max concurrent requests — returns 503 if exceeded (must be ≥ 1)
maxBodyBufferBytes number — Max body buffered per request for retry replay
maxConnectionsPerIp number — Max simultaneous open connections from a single client IP — returns 429 if exceeded
maxRequestHeaders number — Max number of request headers — returns 431 Request Header Fields Too Large if exceeded
keepaliveRequestLimit number — Max requests per keepalive connection; closes and recycles after. Equivalent to nginx’s keepalive_requests.
priorityThreshold number 0.8 Fraction of maxInflightRequests at which low-priority routes are shed (0.0–1.0) — see Priority routing
minUploadRateBytesPerSec number — Minimum upload rate in bytes/s — closes slow uploads with 408 Request Timeout (slow-loris protection)

Priority Routing

Priority routing lets high-value routes continue to be served when the site is under load, while low-priority routes are shed with 503 Load Shedding.

How it works

  1. Set limits.maxInflightRequests to cap total concurrency.
  2. Set limits.priorityThreshold (default 0.8) — the fraction of the cap at which shedding begins.
  3. Mark routes with priority: 0–100 (50 = normal, omitted = normal).
  4. When inflight / maxInflightRequests ≥ priorityThreshold, any request whose effective priority is below 50 receives 503 Load Shedding.

Requests with priority ≥ 50 (normal or high) are never shed by this mechanism. The X-Priority: <0–100> request header can raise the effective priority above the configured route value (useful for trusted internal callers).

# YAML
limits:
  maxInflightRequests: 2000
  priorityThreshold: 0.8 # shed low-priority at 1600+ concurrent

routes:
  - match:
      path: /api/critical/**
    proxy:
      targets: [http://api:4000]
      priority: 90 # always served

  - match:
      path: /api/batch/**
    proxy:
      targets: [http://api:4000]
      priority: 10 # shed first when overloaded

  - match:
      path: /api/**
    proxy:
      targets: [http://api:4000]
      # no priority → defaults to 50 (normal, not shed)
{
  "limits": {
    "maxInflightRequests": 2000,
    "priorityThreshold": 0.8
  },
  "routes": [
    {
      "match": { "path": "/api/critical/**" },
      "proxy": { "targets": ["http://api:4000"], "priority": 90 }
    },
    {
      "match": { "path": "/api/batch/**" },
      "proxy": { "targets": ["http://api:4000"], "priority": 10 }
    }
  ]
}
Field Type Default Description
limits.priorityThreshold number 0.8 Load fraction at which shedding begins (0.0–1.0)
proxy.*.priority number (0–100) 50 Route priority; below 50 = sheddable

Note: Priority routing only applies when both maxInflightRequests and priorityThreshold are configured on the site.


Fault Injection

Requires cargo build --features fault-injection

For testing only — do not use in production.

# YAML
faultInjection:
  abort:
    percent: 5
    status: 503
    body: "Injected fault"
  delay:
    percent: 10
    ms: 500
// JSON
{
  "faultInjection": {
    "abort": { "percent": 5, "status": 503, "body": "Injected fault" },
    "delay": { "percent": 10, "ms": 500 }
  }
}

Proxy Cache

Requires cargo build --features cache For Redis-backed cache also add --features redis; for disk cache add --features disk-cache.

Size limit: cache.maxSizeMb bounds the store with an LRU eviction manager (least-recently-used entries are purged once the total exceeds the budget). There is no per-body cap: a single response larger than the budget is written and then evicted again, because capping bodies without a Content-Length would abort the client mid-transfer. Limits of the current implementation: the budget of a store is fixed by the first route that uses it (changing maxSizeMb needs a restart, not a reload), routes sharing a store share its budget, and for disk:/redis:// stores only entries admitted since the process started are counted, so entries left over from a previous run are not included until they are rewritten.

# YAML
proxy:
  /api:
    targets: ["http://backend:4000"]
    cache:
      store: memory
      ttlSecs: 60
      maxSizeMb: 256 # store budget (MiB), LRU eviction
      staleWhileRevalidateSecs: 300 # serve stale up to 5 min while refreshing
      staleIfErrorSecs: 600 # serve stale up to 10 min if upstream fails
      varyHeaders: [Accept-Language, Accept-Encoding]
      skipPaths: [/api/me, /api/cart] # never cache these paths
      skipIfCookie: true
      methods: [GET, HEAD]
// JSON
{
  "proxy": {
    "/api": {
      "targets": ["http://backend:4000"],
      "cache": {
        "store": "memory",
        "ttlSecs": 60,
        "maxSizeMb": 256,
        "staleWhileRevalidateSecs": 300,
        "staleIfErrorSecs": 600,
        "varyHeaders": ["Accept-Language", "Accept-Encoding"],
        "skipPaths": ["/api/me", "/api/cart"],
        "skipIfCookie": true,
        "methods": ["GET", "HEAD"]
      }
    }
  }
}

Cache field reference

Field Type Default Description
store string — "memory", "redis" (the address of global.redis.url, --features redis), "disk:/path" (--features disk-cache); a "redis://..." address here still works but is deprecated
ttlSecs number — Fresh cache TTL (seconds)
maxSizeMb number — Size budget of the store in MiB (LRU eviction) (≥ 1; unset = unlimited)
staleWhileRevalidateSecs number 0 Serve stale while refreshing in background (RFC 5861)
staleIfErrorSecs number 0 Serve stale when upstream returns 5xx, including after retries are exhausted (RFC 5861)
earlyRefreshSecs number 0 Refresh cache in the background when remaining TTL < this value (see below)
varyHeaders string[] — Vary cache key by these request headers
skipPaths string[] — Paths to never cache
skipIfCookie bool false Skip caching when request has a cookie
methods string[] [GET, HEAD] Cacheable HTTP methods

Cache key — scheme + host + path + query string. Request body is never part of the key, so POST responses are not cached by default (add "POST" to methods only for idempotent endpoints). Use varyHeaders to differentiate responses by Accept-Language or Accept-Encoding.

Upgrading from a Pingora 0.8 based release: the key is now built with an explicit boundary between the host and the rest, so every key hashes differently. A persistent store (disk: or redis://) starts cold once; Redis entries expire on their own TTL, but the old disk: files are never read again and are not removed automatically — delete the cache directory to reclaim the space.

Age header (RFC 7234 §5.1): Conduit automatically injects an `Age:

` header on every cache hit, computed as `now − Date` from the stored response. Any `Age` header carried by the cached response is replaced to prevent double-counting across proxy hops. No configuration is required. **Stale-while-revalidate** (RFC 5861): the first request after TTL expiry returns the stale response immediately while a background request refreshes the cache. Zero latency penalty for users. A built-in cache lock prevents thundering herd — only one background fetch goes to the upstream at a time. **Stale-if-error** (RFC 5861): when the upstream returns a 5xx error, Conduit serves the last known good cached response instead of forwarding the error to the client. This works in all three scenarios: 1. **No retry configured** — upstream 5xx immediately falls back to stale cache. 2. **Retry configured, budget exhausted** — after all retry attempts fail, stale cache is served instead of the final 5xx error. 3. **Retry + stale together** — Conduit retries the configured number of times; if all retries fail and stale cache is available, it serves stale. Set `staleIfErrorSecs` to the maximum age (in seconds) of a stale response you are willing to serve. When no stale entry exists or the stale entry is older than `staleIfErrorSecs`, the upstream error is forwarded to the client. **Early refresh** (`earlyRefreshSecs`): when the remaining TTL of a cached entry drops below `earlyRefreshSecs`, Conduit fires a background GET request directly to the upstream while the **current** client request is still served the (still-valid) cached response with zero latency. The cache is updated before it ever expires, so clients never see stale content as long as the upstream is reachable. Comparison with `staleWhileRevalidateSecs`: | Feature | Activates | Clients see stale? | | --------------------------- | ---------------- | ------------------ | | `staleWhileRevalidateSecs` | After TTL expires | Yes, until refresh | | `earlyRefreshSecs` | Before TTL expires | No | Use `earlyRefreshSecs` when zero-stale is important (news feeds, pricing data, session-sensitive API). Use `staleWhileRevalidateSecs` when occasional stale is acceptable and you want a simpler setup. ```yaml # Never-stale cache: refresh 10 s before the 60-second TTL expires. cache: store: memory ttlSecs: 60 earlyRefreshSecs: 10 ``` Source: h2o `lib/common/cache.c` — `H2O_CACHE_FLAG_EARLY_UPDATE`. **`s-maxage` handling**: Conduit respects the upstream `Cache-Control: s-maxage=N` directive as the effective TTL when the upstream returns it. `s-maxage=0` explicitly prevents caching regardless of `ttlSecs`. When the upstream returns no `Cache-Control` directive, `ttlSecs` from the route config is used. `ttlSecs` in the config always caps the maximum TTL — upstream headers cannot extend it beyond the configured limit. | Upstream `Cache-Control` | Effect | | ------------------------ | -------------------------- | | not present | Use `ttlSecs` from config | | `s-maxage=N` | Use `min(N, ttlSecs)` | | `s-maxage=0` | Do not cache this response | | `no-store` or `private` | Do not cache this response | ### Cache store options **`"memory"`** — in-process cache, lost on restart. Best for single-instance deployments with small response bodies. **`"redis"`** — shared Redis cache, on the one Redis address of the process ([`global.redis.url`](#global-redis)). (`--features redis` required) All Conduit instances share the same cache — consistent hit rate under horizontal scaling. A `rediss://` address enables TLS (AWS ElastiCache, Azure Cache). ```yaml # conduit.yaml — Redis cache shared across multiple instances global: redis: url: "redis://redis:6379" sites: - port: 8080 proxy: /api: targets: ["http://api1:4000", "http://api2:4000"] cache: store: redis ttlSecs: 300 staleWhileRevalidateSecs: 60 varyHeaders: [Accept-Language] ``` ```json // conduit.json { "global": { "redis": { "url": "redis://redis:6379" } }, "sites": [{ "port": 8080, "proxy": { "/api": { "targets": ["http://api1:4000", "http://api2:4000"], "cache": { "store": "redis", "ttlSecs": 300, "staleWhileRevalidateSecs": 60 } } } }] } ``` A `store: "redis://host:port"` written on the route still works (the address is then that of the route), but it is deprecated: it is a warning at start, and an error when it differs from `global.redis.url`. If Redis is unreachable at startup or during a request, caching is silently disabled for that request — the proxy continues to work normally (fail-open). **`"disk:/path/to/dir"`** — filesystem cache, survives restarts. (`--features disk-cache` required) Useful for large response bodies or when Redis is not available. ```yaml proxy: /assets: targets: ["http://assets:4000"] cache: store: "disk:/var/cache/conduit" ttlSecs: 86400 # 1 day ``` ```json { "proxy": { "/assets": { "targets": ["http://assets:4000"], "cache": { "store": "disk:/var/cache/conduit", "ttlSecs": 86400 } } } } ``` See [`examples/stale-while-revalidate.yaml`](/conduit/examples/stale-while-revalidate.yaml) --- ## Basic Auth ```yaml # YAML basicAuth: users: alice: "$ALICE_PASSWORD" bob: "$BOB_PASSWORD" realm: "My App" challenge: true # send WWW-Authenticate header (default: true) skipPaths: [/__health__] ``` ```json // JSON { "basicAuth": { "users": { "alice": "$ALICE_PASSWORD", "bob": "$BOB_PASSWORD" }, "realm": "My App", "challenge": true, "skipPaths": ["/__health__"] } } ``` | Field | Type | Default | Description | | ----------- | -------- | ----------- | ------------------------------------------------------------------------ | | `users` | object | — | `{ username: password }` map | | `realm` | string | `"Conduit"` | Shown in browser login dialog | | `challenge` | bool | `true` | Whether to send `WWW-Authenticate` header | | `skipPaths` | string[] | — | Paths that bypass Basic Auth — see [glob syntax](#skippaths-glob-syntax) | --- ## API Key ```yaml # YAML apiKey: keys: - "$PRIMARY_API_KEY" - "$SECONDARY_API_KEY" header: X-API-Key skipPaths: [/__health__, /public/**] ``` ```json // JSON { "apiKey": { "keys": ["$PRIMARY_API_KEY", "$SECONDARY_API_KEY"], "header": "X-API-Key", "skipPaths": ["/__health__", "/public/**"] } } ``` The key may be sent in the configured `header` or as a `?api_key=` query parameter. --- ## JWT Auth > **Requires** `cargo build --features jwt` Validates `Authorization: Bearer ` on every request. ### JWKS endpoint (recommended for production) ```yaml # YAML jwtAuth: jwksUrl: "https://YOUR_DOMAIN.auth0.com/.well-known/jwks.json" audience: ["https://api.example.com"] issuer: "https://YOUR_DOMAIN.auth0.com" jwksRefreshSecs: 3600 skipPaths: [/__health__, /public/**] ``` ```json // JSON { "jwtAuth": { "jwksUrl": "https://YOUR_DOMAIN.auth0.com/.well-known/jwks.json", "audience": ["https://api.example.com"], "issuer": "https://YOUR_DOMAIN.auth0.com", "jwksRefreshSecs": 3600, "skipPaths": ["/__health__", "/public/**"] } } ``` JWKS keys are fetched on the first request that needs them (that request waits for the fetch; concurrent first requests share one fetch) and refreshed once they are `jwksRefreshSecs` old (minimum 60s, enforced). The refresh runs in the background: requests keep verifying against the last good keys and never wait for the network. If the JWKS endpoint is unreachable, the last good keys keep verifying tokens for up to 24 hours past the refresh interval, and a failed fetch is not retried for 30 seconds. Beyond that window the keys are no longer trusted (a key the issuer has rotated out or revoked must not verify forever) and JWT requests return 401 until a fetch succeeds. If the very first fetch fails there are no keys to fall back on, so requests return 401 until the endpoint is reachable. ### Shared secret (HS256) ```yaml jwtAuth: secret: "$JWT_SECRET" skipPaths: [/__health__] ``` ```json // JSON { "jwtAuth": { "secret": "$JWT_SECRET", "skipPaths": ["/__health__"] } } ``` ### JWT field reference | Field | Type | Default | Description | | ----------------- | -------- | ------- | ------------------------------------------------------- | | `secret` | string | — | HS256 shared secret (mutually exclusive with `jwksUrl`) | | `jwksUrl` | string | — | JWKS endpoint URL (RS256 / ES256) | | `jwksRefreshSecs` | number | `3600` | JWKS key refresh interval (minimum `60`) | | `audience` | string[] | — | Required `aud` claims | | `issuer` | string | — | Required `iss` claim | | `skipPaths` | string[] | — | Paths that bypass JWT validation | ### Injecting JWT claims as upstream headers ```yaml requestTransform: setHeaders: X-User-ID: "" X-User-Email: "" X-Tenant: "" removeHeaders: - Authorization ``` ```json // JSON { "requestTransform": { "setHeaders": { "X-User-ID": "", "X-User-Email": "" }, "removeHeaders": ["Authorization"] } } ``` Unknown claims expand to empty string. Non-string claims (numbers, booleans, arrays, objects) expand to their JSON text representation — e.g. a `roles` claim holding `["admin", "editor"]` expands `` to the literal text `["admin","editor"]`, brackets and quotes included. See [Request / Response Transform](#request--response-transform). See [`examples/jwt-auth.yaml`](/conduit/examples/jwt-auth.yaml) --- ## Forward Auth > **Requires** `cargo build --features forward-auth` Delegate authentication to an external HTTP service. ```txt Client -> Conduit -> Auth service 2xx -> copy responseHeaders, forward to upstream 4xx -> return to client, stop fail -> 401 (fail closed) ``` ```yaml # YAML forwardAuth: url: "http://auth-service:9000/verify" requestHeaders: [Authorization, Cookie] responseHeaders: [X-User-ID, X-Role] timeoutMs: 3000 skipPaths: [/__health__, /public/**] ``` ```json // JSON { "forwardAuth": { "url": "http://auth-service:9000/verify", "requestHeaders": ["Authorization", "Cookie"], "responseHeaders": ["X-User-ID", "X-Role"], "timeoutMs": 3000, "skipPaths": ["/__health__", "/public/**"] } } ``` | Field | Type | Default | Description | | ----------------- | -------- | ------- | ----------------------------------------------------- | | `url` | string | — | Auth service URL (required) | | `requestHeaders` | string[] | — | Client headers to forward to auth service | | `responseHeaders` | string[] | — | Auth response headers to inject into upstream request | | `timeoutMs` | number | `5000` | Auth service timeout | | `skipPaths` | string[] | — | Paths that bypass forward auth | The auth service receives `X-Forwarded-Method`, `X-Forwarded-Uri`, `X-Forwarded-For`, plus any `requestHeaders`. See [`examples/forward-auth.yaml`](/conduit/examples/forward-auth.yaml) --- ## Consumers > **Requires** `cargo build --features consumers` > JWT consumers (V2 / V3) additionally require `--features jwt`. Named API clients with per-consumer credentials, rate limits, and headers. After identification, the consumer's username is injected as `X-Consumer-ID`. Unidentified requests receive `401`. ```yaml # YAML — V1 (API key / Basic Auth) + V2 (per-consumer JWT) consumers: idHeader: "X-Consumer-ID" apiKeyHeader: "X-API-Key" skipPaths: [/__health__] consumers: # V1: API key - username: alice apiKey: "$ALICE_KEY" rateLimit: { windowSecs: 60, limit: 100 } headers: { X-Tier: free } # V1: Basic Auth (username from consumer.username, password from basicAuth.password) - username: billing-service basicAuth: { password: "$BILLING_PASSWORD" } headers: { X-Internal: "true" } # V2: JWT with HS256 secret — token must be signed with this secret - username: mobile-app jwt: secret: "$MOBILE_JWT_SECRET" issuer: "https://auth.internal" rateLimit: { windowSecs: 60, limit: 500 } # V2: JWT with JWKS — token validated against public keys from this endpoint - username: partner-app jwt: jwksUrl: "https://partner.example.com/.well-known/jwks.json" audience: ["my-api"] ``` ```json // JSON { "consumers": { "idHeader": "X-Consumer-ID", "skipPaths": ["/__health__"], "consumers": [ { "username": "alice", "apiKey": "$ALICE_KEY", "rateLimit": { "windowSecs": 60, "limit": 100 }, "headers": { "X-Tier": "free" } }, { "username": "billing-service", "basicAuth": { "password": "$BILLING_PASSWORD" }, "headers": { "X-Internal": "true" } }, { "username": "mobile-app", "jwt": { "secret": "$MOBILE_JWT_SECRET" }, "rateLimit": { "windowSecs": 60, "limit": 500 } }, { "username": "partner-app", "jwt": { "jwksUrl": "https://partner.example.com/.well-known/jwks.json", "audience": ["my-api"] } } ] } } ``` ### V3: Shared JWT (Auth0 / Cognito / Keycloak pattern) One JWKS endpoint for all consumers; consumers are identified by `sub` claim. ```yaml # YAML consumers: sharedJwt: jwksUrl: "https://YOUR_DOMAIN.auth0.com/.well-known/jwks.json" audience: ["https://api.example.com"] issuer: "https://YOUR_DOMAIN.auth0.com" usernameClaim: "sub" # default consumers: - username: "auth0|alice123" rateLimit: { windowSecs: 60, limit: 100 } headers: { X-Tier: free } - username: "auth0|bob456" rateLimit: { windowSecs: 60, limit: 10000 } headers: { X-Tier: premium } ``` ```json // JSON { "consumers": { "sharedJwt": { "jwksUrl": "https://YOUR_DOMAIN.auth0.com/.well-known/jwks.json", "audience": ["https://api.example.com"], "issuer": "https://YOUR_DOMAIN.auth0.com", "usernameClaim": "sub" }, "consumers": [ { "username": "auth0|alice123", "rateLimit": { "windowSecs": 60, "limit": 100 } }, { "username": "auth0|bob456", "rateLimit": { "windowSecs": 60, "limit": 10000 } } ] } } ``` ### `ConsumersConfig` field reference | Field | Type | Default | Description | | -------------- | -------- | --------------- | ---------------------------------------------------- | | `consumers` | object[] | — | List of named consumers | | `idHeader` | string | `x-consumer-id` | Header injected into upstream with consumer username | | `apiKeyHeader` | string | `x-api-key` | Header to read API keys from | | `skipPaths` | string[] | — | Paths that bypass consumer auth | | `sharedJwt` | object | — | Single JWKS for all consumers, identified by `sub` claim — Auth0/Cognito/Keycloak pattern (`--features jwt` required) | ### Per-consumer fields | Field | Type | Description | | ----------- | ------ | ----------------------------------------------------------- | | `username` | string | Required — unique name, injected as `X-Consumer-ID` | | `apiKey` | string | API key credential | | `basicAuth` | object | `{ password }` — username is taken from `consumer.username` | | `jwt` | object | `{ secret? jwksUrl? audience? issuer? }` — per-consumer JWT identification (`--features jwt` required) | | `rateLimit` | object | Per-consumer rate limit (global, not per-IP) | | `headers` | object | Additional headers to inject into upstream request | See [`examples/consumers.yaml`](/conduit/examples/consumers.yaml) --- ## Rate Limiting In-memory rate limiting requires no feature flag — available in every build, including the minimal `default = ["proxy", "compression", "static", "hotreload", "mimalloc"]`. `store: "redis://..."` requires `--features redis`. ### Site-level Applied to all requests before authentication. ```yaml # YAML rateLimit: windowSecs: 60 limit: 1000 keyBy: ip store: memory # or "redis://host:port" for multi-instance skipPaths: [/__health__] ``` ```json // JSON { "rateLimit": { "windowSecs": 60, "limit": 1000, "keyBy": "ip", "store": "memory", "skipPaths": ["/__health__"] } } ``` ### Per-route Applied after routing, independently of the site-level limit. ```yaml proxy: /api/payments: targets: ["http://payments:4000"] rateLimit: windowSecs: 60 limit: 10 keyBy: "header:X-User-ID" ``` ```json // JSON { "proxy": { "/api/payments": { "targets": ["http://payments:4000"], "rateLimit": { "windowSecs": 60, "limit": 10, "keyBy": "header:X-User-ID" } } } } ``` Per-route rate limiting also applies to routes matched via the advanced `routes[]` mechanism (`site.routes[*].proxy.rateLimit`), not just the `proxy` map shown above — each `routes[]` entry gets its own bucket, keyed by its position (`routes[0]`, `routes[1]`, ...). One consequence of the positional key: reordering `site.routes[]` entries across a hot reload can hand a route a bucket previously used by whatever entry occupied that position before — the same accepted trade-off as this codebase's existing "buckets aren't preserved across a config reload" behavior elsewhere. If this matters for a specific deployment, avoid reordering `routes[]` entries in a live config (appending/removing at the end is unaffected). ### Rate limit field reference | Field | Type | Default | Description | | ------------ | -------- | ---------- | ----------------------------------------------------------------------------------------------------------- | | `windowSecs` | number | — | Sliding window duration (seconds) — **required** | | `limit` | number | — | Max requests per key per window — **required** | | `burst` | number | `0` | Extra burst capacity above `limit` (see below) | | `algorithm` | string | — | Optional; only `"token-bucket"` is supported — a typo fails validation | | `keyBy` | string | `"ip"` | `"ip"` or `"header:"` | | `store` | string | `"memory"` | `"memory"` or `"redis"` (the address of [`global.redis.url`](#global-redis); `--features redis` required) | | `skipPaths` | string[] | — | Paths that bypass rate limiting — see [skipPaths glob syntax](#skippaths-glob-syntax) | | `dryRun` | bool | `false` | Log rate-limit violations without actually rejecting requests — useful for tuning limits before enforcement | The rate limiter uses a **token-bucket** algorithm. Tokens refill at `limit / windowSecs` per second. Without `burst`, the bucket holds `limit` tokens. **Burst capacity** (`burst: N`): the bucket starts with `limit + N` tokens, allowing short spikes above the sustained rate. The refill rate stays at `limit / windowSecs` — burst is absorbed and not refilled. ```yaml # Allow up to 80 requests in a burst, sustained at 1 req/s rateLimit: windowSecs: 60 limit: 60 burst: 20 ``` **Validation applies at every level.** `windowSecs`/`limit`/`algorithm`/`keyBy`/`store` are checked at config-load and reload time for site-level, per-route, and per-consumer `rateLimit` blocks alike — a malformed value (e.g. `keyBy: "header:bad name"`, which contains a space and isn't a valid HTTP header name) fails validation instead of silently collapsing every client into one shared bucket at runtime. **`store` (Redis) works at every level** — site, per-route, and per-consumer (issue #322). Each level uses its own Redis key scope so buckets never collide: site-level uses the site label, per-route uses `"route\0{site}\0{route}"`, and per-consumer uses the fixed scope `"consumer"` with the consumer's username as the client key (mirroring the in-memory limiter's own `\0`-separated key namespaces — see #303/#304). `keyBy` is inert at the consumer level specifically, regardless of backend (the bucket key is always the username, not derived from the request). `burst`, `skipPaths`, and `dryRun` all work at every level that accepts them — `dryRun` isn't accepted at the route level at all (the schema rejects it there; it's a site/consumer-only field). `burst` also works under a Redis `store`, not just in-memory — implemented as the fixed-window counter's admission ceiling rising from `limit` to `limit + burst` within the current window, rather than a continuously-refilling allowance like the in-memory token bucket's burst. **There is one Redis per process, and the operator names it once** (issue #760). Write `store: redis` at whatever level needs Redis (site, route, consumer, and `cache.store`), and set the address in [`global.redis.url`](#global-redis), or in the `CONDUIT_REDIS_URL` environment variable (a pod that reads `ConduitSite` objects cannot set `global`). Every level shares the one connection, so a limit is shared by all replicas. The address is read at startup only: a change takes a restart, and a reload that changes it is refused (cold field). With `--features redis` the connection is made at start whenever an address is set, even if no site uses `store: redis` yet, so a `ConduitSite` added later shares the limit without a restart. A `store: "redis://host:port"` written on a site or route still works, as before, but is **deprecated**: it is a warning when the config is loaded. When `global.redis.url` is set it must be that same address; another address is a validation error. Without `global.redis.url`, the first legacy URL found (site, then route, then consumer) is the process's address, and more than one distinct URL is an advisory warning naming the one used (issue #357). --- ## Request / Response Transform ### Static header transforms ```yaml # YAML requestTransform: setHeaders: X-User-ID: "" X-Gateway: conduit removeHeaders: - Authorization responseTransform: setHeaders: X-Served-By: conduit removeHeaders: - Server - X-Powered-By - X-AspNet-Version ``` ```json // JSON { "requestTransform": { "setHeaders": { "X-User-ID": "", "X-Gateway": "conduit" }, "removeHeaders": ["Authorization"] }, "responseTransform": { "setHeaders": { "X-Served-By": "conduit" }, "removeHeaders": ["Server", "X-Powered-By", "X-AspNet-Version"] } } ``` ### JWT claim templates > **Requires** `cargo build --features jwt` — templates expand to `""` when JWT auth is not active. Available in `requestTransform.setHeaders` after JWT validation: | Template | Claim | Notes | | ----------------- | ------- | --------------------------------------------------- | | `` | `sub` | User identifier — always present | | `` | `email` | Email claim (if IdP includes it) | | `` | `iss` | Token issuer | | any claim | any | `` — unknown claims expand to `""` | Non-string claims (numbers, booleans, arrays, objects) expand to their JSON text representation — e.g. `` for `roles: ["admin", "editor"]` expands to the literal text `["admin","editor"]`. --- ## Traffic Mirroring Send a copy of requests to a shadow backend. The shadow response is discarded — clients only see the primary response. ```yaml proxy: /api: targets: ["http://api-v1:4000"] mirror: "http://api-v2:4000" ``` ```json // JSON { "proxy": { "/api": { "targets": ["http://api-v1:4000"], "mirror": "http://api-v2:4000" } } } ``` The mirrored request includes all original headers plus `X-Mirrored-From: `. Mirror failures do not affect clients. > **Note:** request body is not mirrored — only headers are forwarded to the shadow > backend. This is sufficient for observability and shadow testing of read workloads. --- ## Custom Response Headers Inject headers into every response site-wide. These are in addition to any headers set by `responseTransform`. ```yaml # YAML headers: X-Environment: production X-API-Version: "3" ``` ```json // JSON { "headers": { "X-Environment": "production", "X-API-Version": "3" } } ``` --- ## Logging ```yaml # YAML — shorthand logging: dev # colorized, short — for development logging: json # structured JSON — for production logging: combined # Apache Combined Log Format ``` ```json // JSON { "logging": "json" } ``` Full config: ```yaml logging: format: json file: ./logs/access.log stripQuery: true # omit query string from logged path (e.g. /search?q=... → /search) skipPaths: - /__health__ - /__metrics__ - /favicon.ico ``` ```json // JSON { "logging": { "format": "json", "file": "./logs/access.log", "stripQuery": true, "skipPaths": ["/__health__", "/__metrics__", "/favicon.ico"] } } ``` | Field | Type | Default | Description | | ------------ | -------- | ------- | ----------------------------------------------------------------------------------- | | `format` | string | `dev` | Log format — see table below | | `file` | string | — | Append access logs to this file path (in addition to stdout) | | `stripQuery` | bool | `false` | Remove query string from the logged path. Useful when queries contain PII or tokens | | `skipPaths` | string[] | — | Glob patterns — requests matching these paths are not logged | | Format | Description | | ---------- | -------------------------------------------- | | `dev` | Colorized, short — development | | `combined` | Apache Combined Log Format | | `common` | Apache Common Log Format | | `short` | Short, no timestamps | | `json` | Structured JSON — Loki, Datadog, Splunk, ELK | ### JSON log fields ```json // JSON { "time": "2026-01-15T14:23:01Z", "method": "GET", "path": "/api/users", "status": 200, "bytes": 1234, "duration_ms": 42, "upstream_ms": 38, "ip": "10.0.0.1", "request_id": "a1b2c3d4-e5f6-...", "upstream": "http://api-1:4000" } ``` | Field | Description | | ------------- | --------------------------------------------------------------------------------------------- | | `duration_ms` | Total request time from accept to response sent (ms) | | `upstream_ms` | Time spent waiting for the upstream response (ms). Absent for local handlers (health, static) | | `request_id` | Value of `X-Request-ID` — auto-generated UUID v4 if absent | | `upstream` | Selected upstream URL | --- ## Metrics ```yaml # YAML metrics: path: /__metrics__ token: "$METRICS_TOKEN" ``` ```json // JSON { "metrics": { "path": "/__metrics__", "token": "$METRICS_TOKEN" } } ``` Prometheus scrape config: ```yaml scrape_configs: - job_name: conduit static_configs: [{ targets: ["conduit-host:8080"] }] metrics_path: /__metrics__ bearer_token: "my-token" ``` ### Per-upstream metrics In addition to the site-level metrics, Conduit exposes per-upstream URL metrics: | Metric | Type | Labels | Description | | ------------------------------------- | --------- | -------------------- | ------------------------------------------------------------- | | `conduit_upstream_requests_total` | counter | `upstream`, `status` | Requests forwarded to each upstream (including retries) | | `conduit_upstream_latency_seconds` | histogram | `upstream` | Upstream response latency (request sent → response received) | | `conduit_upstream_active_connections` | gauge | `upstream` | In-flight requests currently being processed by each upstream | These complement `conduit_upstream_errors_total{route}` for diagnosing which specific backend is slow or returning errors. --- ## OpenTelemetry Tracing > **Requires** `cargo build --features otlp` ```yaml # YAML global: otlp: endpoint: "http://tempo:4317" serviceName: "my-api" sampleRate: 0.1 timeoutMs: 5000 sites: - port: 8080 proxy: http://127.0.0.1:4000 ``` ```json // JSON { "global": { "otlp": { "endpoint": "http://tempo:4317", "serviceName": "my-api", "sampleRate": 0.1, "timeoutMs": 5000 } }, "sites": [ { "port": 8080, "proxy": "http://127.0.0.1:4000" } ] } ``` Each span: `method`, `path`, `status`, `duration_ms`, `upstream_url`, `request_id`. 5xx responses set span status to `ERROR`. | Field | Type | Default | Description | | ------------- | ------ | ------- | --------------------------------------- | | `endpoint` | string | — | gRPC OTLP endpoint URL | | `serviceName` | string | — | `service.name` in all spans | | `sampleRate` | number | `1.0` | Fraction of requests to trace (0.0–1.0) | | `timeoutMs` | number | `5000` | Export timeout | See [`examples/observability.yaml`](/conduit/examples/observability.yaml) --- ## Hot Reload Live reload for development: when a file in a served `static` directory changes, connected browsers are told to reload. `hotReload` watches the `static` directories (limited to `extensions` if you set them); it does **not** watch the config file. To apply a config change without a restart, run `conduit reload` (or `POST /reload`, see [admin.md](/conduit/docs/admin/)). ```yaml # YAML hotReload: true hotReload: extensions: [html, css, js, ts, jsx, tsx] # file types that trigger browser reload ``` ```json // JSON { "hotReload": true } ``` ```json // JSON { "hotReload": { "extensions": ["html", "css", "js"] } } ``` **Config fields applied by `conduit reload`** (no restart): `proxy`, `static`, `routes`, `rateLimit`, `basicAuth`, `apiKey`, `jwtAuth`, `forwardAuth`, `consumers`, `middleware`, `logging`, `cors`, `securityHeaders`, `cache`, `outlierDetection`, `limits`, `requestTransform`, `responseTransform`, `maskErrors`. **Requires cold restart:** `port`, `tls.cert/key`, every field of `tls.acme` (and adding or removing it on a site), `workers`, `global.shutdownTimeoutSecs`, `global.admin.bind`, `global.redis.url` (the one Redis connection is made at start-up; a reload that changes it is refused), and adding, removing or changing a `tcp` site (the TCP services are started once). (`tls.versions`/`tls.ciphers` are not listed here because they're rejected at validate-time — see [TLS field reference] (#tls-field-reference) — not merely cold-restart-only.) --- ## Security Headers ### `securityHeaders: true` — safe defaults ```yaml securityHeaders: true ``` Sets these four headers on every response: | HTTP header | Value | | ------------------------ | --------------------------------- | | `X-Content-Type-Options` | `nosniff` | | `X-Frame-Options` | `SAMEORIGIN` | | `Referrer-Policy` | `strict-origin-when-cross-origin` | | `X-XSS-Protection` | `1; mode=block` | ### Custom security headers ```yaml securityHeaders: hstsMaxAgeSecs: 63072000 # → Strict-Transport-Security: max-age=63072000; includeSubDomains csp: "default-src 'self'; script-src 'self'" xFrameOptions: DENY referrerPolicy: "strict-origin-when-cross-origin" ``` ```json // JSON { "securityHeaders": { "hstsMaxAgeSecs": 63072000, "csp": "default-src 'self'", "xFrameOptions": "DENY", "referrerPolicy": "strict-origin-when-cross-origin" } } ``` Full example with all fields: ```yaml securityHeaders: hstsMaxAgeSecs: 63072000 hstsIncludeSubDomains: true # add includeSubDomains to HSTS header hstsPreload: true # add preload to HSTS (see hstspreload.org) csp: "default-src 'self'" xFrameOptions: DENY referrerPolicy: "no-referrer" permissionsPolicy: "geolocation=(), microphone=()" allowedHosts: # reject Host headers not in this list (→ 400) - "example.com" - "www.example.com" ``` | Field | Type | Default (object form) | Sets HTTP header / action | | ----------------------- | -------- | --------------------------------- | ------------------------------------------------------------------------------------ | | `hstsMaxAgeSecs` | number | — (not set) | `Strict-Transport-Security: max-age=` | | `hstsIncludeSubDomains` | bool | `true` when hstsMaxAgeSecs is set | Append `; includeSubDomains` to HSTS header | | `hstsPreload` | bool | `false` | Append `; preload` to HSTS header (see [hstspreload.org](https://hstspreload.org)) | | `hstsOverHttp` | bool | `false` | Also send HSTS on plain-HTTP responses (see the note below) | | `csp` | string | — (not set) | `Content-Security-Policy` | | `xFrameOptions` | string | `SAMEORIGIN` | `X-Frame-Options` | | `referrerPolicy` | string | `strict-origin-when-cross-origin` | `Referrer-Policy` | | `permissionsPolicy` | string | — (not set) | `Permissions-Policy` — restrict browser feature access | | `allowedHosts` | string[] | falls back to the site's `host:` | Reject requests with a `Host` header not in this list with `400 Bad Request` | > **Always set:** `X-Content-Type-Options: nosniff` and `X-XSS-Protection: 1; mode=block` > are added in both `true` and object forms — they cannot be disabled. > > **HSTS and CSP** are only set when explicitly configured. > HSTS should only be used on HTTPS sites — omit it for HTTP-only configs. > RFC 6797 section 7.2 forbids sending it over plain HTTP, so Conduit sends it only when the client > connection is TLS or the request carries `X-Forwarded-Proto: https` (a TLS-terminating load balancer). > If such a balancer does not set that header, set `hstsOverHttp: true`. > > **Permissions-Policy** restricts access to browser APIs (geolocation, camera, microphone, etc.). > See the [Permissions Policy spec](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy). > > **`allowedHosts`** prevents host-header injection attacks where an attacker sends a request with > a forged `Host` header to bypass routing or cache-keying logic — the classic exploit is a > poisoned password-reset link: an app that builds absolute URLs from `Host`/`X-Forwarded-Host` > will happily email a reset link pointing at an attacker-controlled domain. > > **Secure by default even without this option:** when `allowedHosts` is not set, Conduit falls > back to validating the incoming `Host` against the site's own `host:` value (when one is > configured) and rejects anything else. Set `allowedHosts` explicitly when a site must accept > more than one hostname (e.g. `example.com` and `www.example.com`), or leave a site's `host:` > unset/`"*"` for an intentional catch-all that accepts any Host. --- ## CORS ```yaml # YAML — open CORS (development only) cors: true # Locked to specific origins (production) cors: origins: ["https://app.example.com", "https://admin.example.com"] credentials: true methods: [GET, POST, PUT, DELETE, OPTIONS] allowedHeaders: [Authorization, Content-Type, X-Request-ID] maxAgeSecs: 86400 ``` ```json // JSON { "cors": { "origins": ["https://app.example.com"], "credentials": true, "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"], "allowedHeaders": ["Authorization", "Content-Type"], "maxAgeSecs": 86400 } } ``` | Field | Type | Default | Description | | ---------------- | -------- | ------- | -------------------------------------------- | | `origins` | string[] | `["*"]` | Allowed origins | | `methods` | string[] | all | Allowed methods | | `allowedHeaders` | string[] | all | Allowed request headers | | `credentials` | bool | `false` | Allow `Authorization` / cookies cross-origin | | `maxAgeSecs` | number | — | `Access-Control-Max-Age` (preflight cache) | `cors: true` allows any origin (`*`). Always use the object form in production. `credentials: true` requires an explicit, non-wildcard `origins` list — config validation rejects `credentials: true` with `origins` unset or containing `"*"` at startup/reload. Without this, every origin's credentialed (cookie-bearing) cross-origin requests would be allowed, which defeats the purpose of the credentials gate. --- ## IP Filter Allow or deny requests by client IP or CIDR range. Evaluated **before** authentication — blocked IPs get `403` immediately. ```yaml # YAML — allowlist (deny all others) ipFilter: allow: - "10.0.0.0/8" - "172.16.0.0/12" - "203.0.113.0/24" trustProxy: true # trust X-Forwarded-For for client IP detection # Denylist ipFilter: deny: - "192.0.2.0/24" # Dry-run mode — log violations without blocking ipFilter: deny: - "192.0.2.0/24" dryRun: true # IPv6 CIDR ranges are supported alongside IPv4 ipFilter: allow: - "2001:db8::/32" - "::1" # exact match, not just CIDR - "10.0.0.0/8" # IPv4 and IPv6 rules can be mixed freely ``` ```json // JSON { "ipFilter": { "allow": ["10.0.0.0/8", "172.16.0.0/12"], "trustProxy": true } } ``` | Field | Type | Default | Description | | ------------ | -------- | ------- | ----------------------------------------------------------------------------------------- | | `allow` | string[] | — | Allowed CIDRs — deny all others | | `deny` | string[] | — | Denied CIDRs — allow all others | | `trustProxy` | bool | `false` | Trust `X-Forwarded-For` for client IP | | `dryRun` | bool | `false` | Log blocks without enforcing them — useful for auditing a new deny list before going live | When both `allow` and `deny` are set, `allow` takes precedence. > **Dynamic CIDR management:** use the Admin API to add or remove deny entries at runtime > without a configuration reload — see [Admin API — IP deny list](#admin-api). --- ## Error Masking Replace upstream `5xx` bodies with a generic JSON error. ```yaml maskErrors: true ``` ```json // JSON { "maskErrors": true } ``` Clients receive: `{ "error": "Internal Server Error", "status": 500 }` --- ## Upstream Protocol Compatibility ### allowDuplicateChunked By default, Conduit deduplicates `Transfer-Encoding: chunked` headers from upstream responses. Some misconfigured origins emit `Transfer-Encoding: chunked, chunked` or two separate `Transfer-Encoding: chunked` headers, which confuses strict HTTP clients. ```yaml allowDuplicateChunked: true # pass duplicate chunked headers through unmodified ``` Only enable this for upstreams that deliberately rely on duplicate chunked headers. --- ## Upstream TLS Verification ```yaml proxy: /api: targets: ["https://api-internal.svc.cluster.local:8443"] upstreamTls: verify: true ``` ```json // JSON { "proxy": { "/api": { "targets": ["https://api-internal.svc.cluster.local:8443"], "upstreamTls": { "verify": true } } } } ``` | Field | Type | Default | Description | | ------------ | ------ | -------- | -------------------------------------------- | | `verify` | bool | `true` | Verify the upstream certificate against the system CA store, using the host in the target URL; `false` turns the check off | | `serverName` | string | none | The name sent as SNI and used to verify the upstream certificate, instead of the host in the target URL (like nginx `proxy_ssl_name`). Use it when the upstream is reached by an address or alias that its certificate does not name | Do not set `verify: false` to work around a name mismatch: it also turns off the check that the certificate was issued by a trusted authority. Use the name from the certificate in the target URL, or set `serverName` to it. **The host needs a CA bundle even with `verify: false`.** Conduit loads the system CA store (or the file named by the `SSL_CERT_FILE` environment variable, or the directory in `SSL_CERT_DIR`) and the TLS library builds its verifier from it before the setting is applied. On a host or container image without any CA certificates, such as a minimal base image, every HTTPS upstream fails with `no root trust anchors were provided` (HTTP 502), whatever `verify` says. Install the `ca-certificates` package, or point `SSL_CERT_FILE` at a bundle that holds at least one certificate (checked with a TLS gRPC upstream in `scripts/e2e/grpc.sh`: `verify: false` with an empty root store gives 502, with a one-certificate `SSL_CERT_FILE` it works). --- ## mTLS — Client Certificate Authentication Require clients to present a TLS certificate signed by a trusted CA. ```yaml tls: cert: /etc/tls/server.crt key: /etc/tls/server.key clientAuth: ca: /etc/tls/client-ca.crt optional: false # true = allow connections without cert ``` ```json // JSON { "tls": { "cert": "/etc/tls/server.crt", "key": "/etc/tls/server.key", "clientAuth": { "ca": "/etc/tls/client-ca.crt", "optional": false } } } ``` | Field | Type | Default | Description | | ---------- | ---- | ------- | ------------------------------------------------------------- | | `ca` | path | — | CA PEM file that signs authorized client certs — **required** | | `optional` | bool | `false` | `false` = reject without cert; `true` = allow without cert | See [`examples/mtls.yaml`](/conduit/examples/mtls.yaml) --- ## Rhai Script Middleware > **Requires** `cargo build --features rhai` Execute custom Rhai scripts per request. Scripts run in order; any script can reject the request or read headers to make decisions. **→ Full guide with examples: [rhai.md](/conduit/docs/rhai/)** ```yaml # YAML middleware: - type: script path: ./scripts/auth-check.rhai - type: script path: ./scripts/add-headers.rhai config: tier: premium ``` ```json // JSON { "middleware": [ { "type": "script", "path": "./scripts/auth-check.rhai" }, { "type": "script", "path": "./scripts/add-headers.rhai", "config": { "tier": "premium" } } ] } ``` > **Note:** inline scripts are not supported — use `path` to a `.rhai` file. > Optional `config` is passed to the script as a JSON value. **Available Rhai functions** (request phase — `request` is **read-only**; mutating a live request isn't supported here. A response *can* be rewritten on the way out, either via a `phase: "response"` Rhai script — see the "Rhai `on_response`" backlog entry in `CLAUDE.md` for its separate `response`/`upstream` API — or via WASM's response phase, see [WASM Middleware](#wasm-middleware) below): | Function | Description | | ----------------------------- | ---------------------------------------------------------- | | `request.header(name)` | Read a request header | | `request.path` | Get the request path | | `request.method` | Get the HTTP method | | `request.query` | Get the raw query string | | `response.status` | Get/set the short-circuit response status (default `200`) | | `response.body` | Get/set the short-circuit response body | | `response.header(name, value)` | Append a header to the short-circuit response | Return `false` from the script to abort the request with whatever `response.status`/`response.body` were set (defaults to `200`/empty if untouched); return `true` (or nothing) to continue the pipeline. --- ## WASM Middleware > **Requires** the `wasm` feature, part of `full` (the plain-named downloads, `:latest` and the npm package). > A plugin that fails lets the request through; `conduit validate` reports a plugin file that cannot run. **→ Full guide with ABI reference, Rust examples, and build instructions: [wasm.md](/conduit/docs/wasm/)** ```yaml # YAML middleware: - type: wasm path: ./plugins/my-plugin.wasm ``` ```json // JSON { "middleware": [{ "type": "wasm", "path": "./plugins/my-plugin.wasm" }] } ``` Plugins export `on_request() -> i32` and a `memory` export. Return `0` to continue, non-zero to reject. Conduit **fails open** on errors. **Host functions (request phase, `on_request`):** | Function | Description | | --------------------------------- | -------------------------- | | `conduit_get_header` | Read a request header | | `conduit_set_request_header` | Set a request header | | `conduit_remove_request_header` | Remove a request header | | `conduit_get_uri` | Get request URI | | `conduit_get_method` | Get HTTP method | | `conduit_get_header_names` | List all header names | | `conduit_abort_with_redirect` | Redirect the client | | `conduit_get_request_id` | Get X-Request-ID | | `conduit_log` | Write to Conduit log | An optional `on_response(status: i32) -> i32` export gets its own set of host functions (read/set/remove response headers and status, replace the response body, read plugin config). See [wasm.md](/conduit/docs/wasm/) for the complete, authoritative ABI reference (request- and response-phase) — this table only covers the request phase and isn't meant to be exhaustive. --- ## External processing (ext_proc) > **Requires** the `ext-proc` feature, part of `full`. A build without it **refuses to start** with a fail-closed > entry (the default); a `failOpen: true` entry is ignored with a warning. An `ext_proc` entry sends a request to an **external processor**, a gRPC service that speaks the `envoy.service.ext_proc.v3.ExternalProcessor/Process` protocol of Envoy, and applies the answer: set or remove request headers, rewrite the request body, change the response headers, replace the response, or answer the request itself. What is sent is chosen per entry: the request headers (default), the request body, the response headers, a copy of the response body. ```yaml # YAML middleware: - type: ext_proc config: grpc: "grpc://127.0.0.1:50051" # or grpcs://host:port (TLS) timeoutMs: 200 failOpen: false ``` ```json // JSON { "middleware": [{ "type": "ext_proc", "config": { "grpc": "grpc://127.0.0.1:50051", "timeoutMs": 200, "failOpen": false } }] } ``` | `config` key | Default | Meaning | | --- | --- | --- | | `grpc` | required | The processor: `grpc://host:port` (plain text) or `grpcs://host:port` (TLS). The port is mandatory (gRPC has no default one). `grpc://` is plain text: keep it on loopback or a private network. | | `timeoutMs` | `200` | How long one exchange may take, 1 to 60000. A processor that is late counts as failed. | | `failOpen` | `false` | `true`: when the processor fails the request continues unchanged. `false`: it is refused with `statusOnError`. | | `statusOnError` | `503` | The status of that refusal, 400 to 599. | | `caFile` | bundled public roots | PEM file with the certificate authority that signed the processor's certificate (`grpcs://` only). Read when the first request connects, and again after a reload. | | `maxHeaderMutations` | `64` | The most header sets plus removals in one answer, up to 1024. | | `maxHeaderValueBytes` | `8192` | The longest header value the processor may set, up to 65536. | | `requestPhase` | `true` | `false`: the request headers are not sent (a processor that wants only bodies, or only the response). | | `requestBody` | `none` | `buffered`: the whole request body is held, sent as one message and replaced by the answer. `streamed`: every chunk is sent as it arrives and replaced by the answer to it. `none`: the body is not sent. | | `maxBodyBytes` | `1048576` | `buffered` only: the largest body that is held (1 to 16777216). A larger body is refused with **413** and never sent to the processor. An answer from the processor may be about this size (plus 64 KiB), never less than 4 MiB; a bigger one is a failure and follows `failOpen`. | | `responsePhase` | `false` | `true`: the response headers (`:status` and the upstream's headers) are sent; the processor may change them or replace the response. | | `responseBody` | `none` | `observe`: every chunk of the response body is copied to the processor without waiting for it. | Unknown keys are an error: options that this version does not implement are not accepted and then ignored. **→ Full guide: what is sent in each phase, what a processor may change, failures, limits, a first processor, recipes and a comparison with Rhai and WASM: [ext-proc.md](/conduit/docs/ext-proc/)** --- ## Connection Pool Configure the upstream HTTP connection pool per route. ```yaml proxy: /api: targets: ["http://backend:4000"] pool: maxIdle: 100 # max idle connections to keep open idleTimeoutSecs: 90 # close idle connections after 90 s ``` ```json // JSON { "proxy": { "/api": { "targets": ["http://backend:4000"], "pool": { "maxIdle": 100, "idleTimeoutSecs": 90 } } } } ``` | Field | Type | Default | Description | | ----------------- | ------ | ------- | ---------------------------------------------- | | `maxIdle` | number | — | Max idle connections kept alive | | `idleTimeoutSecs` | number | — | Close idle connections after this many seconds | --- ## Multi-Site Run multiple virtual hosts from one process. ```yaml # YAML global: workers: 4 shutdownTimeoutSecs: 30 admin: bind: "127.0.0.1:2019" token: "$ADMIN_TOKEN" sites: - port: 443 host: app.example.com tls: { cert: ./certs/app.crt, key: ./certs/app.key } jwtAuth: { jwksUrl: "https://auth.example.com/.well-known/jwks.json" } proxy: /api: "http://app-backend:4000" - port: 443 host: admin.example.com tls: { cert: ./certs/admin.crt, key: ./certs/admin.key } basicAuth: { users: { admin: "$ADMIN_PASS" } } proxy: /: "http://admin-ui:3000" - port: 8080 static: ./public fallback: { file: ./public/404.html, status: 404 } ``` ```json // JSON { "global": { "workers": 4, "shutdownTimeoutSecs": 30, "admin": { "bind": "127.0.0.1:2019", "token": "$ADMIN_TOKEN" } }, "sites": [ { "port": 443, "host": "app.example.com", "tls": { "cert": "./certs/app.crt", "key": "./certs/app.key" }, "proxy": { "/api": "http://app-backend:4000" } } ] } ``` ### Global field reference | Field | Type | Default | Description | | --------------------- | ------ | --------------- | ------------------------------------------------------------------------------------ | | `workers` | number | `1` | Worker threads per service. Pingora's default is one thread, **not** one per CPU core; raise it to use more cores. Cold restart to change | | `backlog` | number | — | **Ignored.** Pingora fixes the listen backlog at 65535; validation warns | | `shutdownTimeoutSecs` | number | `30` | Shutdown grace period; SIGTERM waits all of it. Cold restart to change | | `admin.bind` | string | — (not started) | Admin API address. **Required to enable the Admin API.** Omit to disable it entirely | | `admin.token` | string | — | Bearer token required for every Admin API request (strongly recommended) | | `otlp` | object | — | OpenTelemetry tracing config (`--features otlp` required — see [OpenTelemetry Tracing](#opentelemetry-tracing)) | | `redis.url` | string | — | The one Redis of the process, for `store: redis` (see [below](#global-redis)). Read at startup | **`global.redis.url`** is the address of the Redis that shared rate limits (`rateLimit.store: redis`) and caches (`cache.store: redis`) use. The operator sets it once; sites, routes and consumers only write `store: redis`, with no address. It is a `redis://` (plaintext) or `rediss://` (TLS) URL and may carry a password, which is not logged. A pod that reads its sites from `ConduitSite` objects cannot set `global` and takes the address from the `CONDUIT_REDIS_URL` environment variable instead (from a `Secret`; surrounding whitespace is trimmed). When both are set, `global.redis.url` is used. `store: redis` with no address anywhere is a validation error, not a silent in-memory fallback. See [Rate limiting](#rate-limiting) and [Cache store options](#cache-store-options). ### What happens on SIGTERM 1. Conduit stops accepting new connections. 2. **Grace period** (`shutdownTimeoutSecs`, default 30 s): Pingora waits the whole period, whether or not the connections have drained. Requests already in flight finish during it, and a request that is still open when it ends is **cut**: with a 12-second request open at SIGTERM and a 1-second grace period the client lost the connection one second after the signal, over HTTP/1.1 and over HTTP/2 (TLS) (`scripts/repro-shutdown-and-reload.sh` runs it). So set it longer than your slowest request. (`POST /shutdown` and `conduit shutdown` do not wait the period out, and they do not stop accepting connections either: they poll the number of in-flight requests and exit as soon as it is zero, or when the period expires; see [Admin API](/conduit/docs/admin/).) 3. The process exits at the end of the period. Pingora also allows the runtimes a second timeout after it (`graceful_shutdown_timeout_seconds`, 5 s by default), which it applies to the runtimes' own blocking work (it made no difference to the cut request in the run above, so Conduit does not expose it: issue #36). The drain ceiling for requests is `shutdownTimeoutSecs` itself. Exiting as soon as the in-flight requests are done, instead of sleeping the whole period, is #655. A supervisor that kills the process after its own deadline (Kubernetes `terminationGracePeriodSeconds`, systemd `TimeoutStopSec`) should allow a margin of a few seconds over `shutdownTimeoutSecs` for that second timeout and for scheduling. A hot reload is not a shutdown: it swaps the configuration without closing a connection, so there is nothing to drain. A request that is already in flight keeps the upstream it was given (a 4-second request open while the upstream was changed and the configuration reloaded completed normally, same script), unless a retry moves it to another of the upstreams it was given as candidates. A setting that is read again while a request goes on may apply to a request that is already in progress (the upload-rate limit `limits.minUploadRateBytesPerSec` is checked as the body arrives, so a reload that raises it can end a slow upload that was fine before; this part comes from reading the code, not from a run). --- ## TCP Proxy > **Requires** `cargo build --features tcp` Forward raw TCP connections without HTTP parsing. Useful for MySQL, PostgreSQL, Redis, SMTP, and any other non-HTTP protocol. What a TCP site does and does not do, and a working config for RTMP, MQTT, PostgreSQL, Redis, SMTP, FTP (passive ports) and SSH, are in the [protocol guide](/conduit/docs/protocols/#what-a-tcp-site-does-and-does-not-do). HTTP-based protocols (SSE, WebSocket, gRPC, GraphQL, HLS) are best served by ordinary routes, also in that guide: only a route can apply access control, rate limits, routing by host or path, and the HTTP-aware handling those protocols need. A TCP site can still relay their bytes untouched (for example TLS that the upstream terminates itself), with none of that. ```yaml # conduit.yaml sites: - port: 3306 tcp: targets: - "mysql-primary:3306" - "mysql-replica:3306" strategy: round-robin # or "random" (default: round-robin) connectTimeoutMs: 5000 # upstream connect timeout (default: 5000) maxConnections: 1000 # connections open on this site at once (default: no limit) maxConnectionsPerIp: 20 # connections open from one client at once (default: no limit) idleTimeoutSecs: 3600 # close a connection quiet in both directions (default: 3600; 0 = never) sendProxyProtocol: v2 # tell the upstream who the client is (default: none), see PROXY protocol below ``` ```json // conduit.json { "sites": [ { "port": 3306, "tcp": { "targets": ["mysql-primary:3306", "mysql-replica:3306"], "strategy": "round-robin", "connectTimeoutMs": 5000, "maxConnections": 1000, "maxConnectionsPerIp": 20, "idleTimeoutSecs": 3600, "sendProxyProtocol": "v2" } } ] } ``` | Field | Type | Default | Description | | --------------------- | -------- | ------------- | -------------------------------------------------------------------------------------------------------------------------- | | `targets` | string[] | — | Upstream `host:port` addresses — **required** | | `strategy` | string | `round-robin` | `"round-robin"` or `"random"` | | `connectTimeoutMs` | number | `5000` | Upstream connect timeout (ms) | | `maxConnections` | number | no limit | Most connections open on the site at once, at least 1. A connection over it is closed at accept, before any upstream is tried | | `maxConnectionsPerIp` | number | no limit | Most connections open at once from one client address, at least 1. IPv6 clients are counted per /64, IPv4-mapped as IPv4 | | `idleTimeoutSecs` | number | `3600` | Seconds a connection may be quiet, in both directions, before it is closed. `0` = never | | `sendProxyProtocol` | string | none | `"v1"` (text) or `"v2"` (binary): write a [PROXY protocol](#proxy-protocol) header naming the client to the upstream first | > **Limits and idle time:** the caps are checked when a connection is accepted and a refused one is closed at once (nothing > is queued); the refusals are logged as one `warn` line per site every 10 seconds with their count. A connection that is > already relayed is never cut because a cap was lowered (the TCP services start with the process: a reload that adds, > removes or changes a `tcp` site is refused, restart instead). The idle time counts bytes moving either way, so a stream that sends nothing but receives something stays open; a > client that stops reading while the upstream keeps sending is cut once nothing can be written. The default of one hour is > new: before it a connection lived until a side closed it, so a session that must stay silent for longer needs `0` or a larger value. > **Failover:** a connect error or timeout is not the end of the connection: the other targets are tried once > each, starting from the one picked, and a target that just failed is passed over for 5 seconds while another > one is available, so a dead target does not cost a connect timeout per connection. Worst case, when every > target is down, a client waits `connectTimeoutMs` for each of them before it is dropped. Once a connection > is relayed it is not moved to another target. > **Note:** `tcp` cannot be combined with `proxy`, `static`, or other HTTP > features on the same site. Use a separate port/site for HTTP traffic. > **TLS on a TCP site:** without a `tls` block, TLS passes through untouched and the client verifies the upstream's > certificate. With `tls: { cert, key }` on the site Conduit terminates TLS and relays the decrypted bytes; `tls.clientAuth` > requires a client certificate, and `proxyProtocol` is then read before the handshake. `tls.acme`, `tls.httpRedirectPort`, > `tls.versions` and `tls.ciphers` are refused on such a site, it needs an explicit `port`, and a changed `tls` block needs a > restart. See [TLS on a TCP site](/conduit/docs/protocols/#tls-on-a-tcp-site). > > ```yaml > sites: > - port: 993 > tls: { cert: ./mail.crt, key: ./mail.key } > tcp: { targets: ["dovecot.internal:143"] } > ``` > **Not supported on a TCP site:** UDP, port ranges, TLS **to** the upstream, and one certificate per SNI name. The upstream sees Conduit's address unless `sendProxyProtocol` is set. `ipFilter`, `rateLimit`, `basicAuth`, `apiKey`, `consumers`, `limits` and > `middleware` next to `tcp` are refused at validation (they would be ignored). See the [guide](/conduit/docs/protocols/#what-a-tcp-site-does-and-does-not-do). --- ## PROXY protocol A load balancer in front of Conduit (HAProxy, an AWS Network Load Balancer, nginx with `proxy_protocol on`) hides the client behind its own address. The [PROXY protocol](https://www.haproxy.org/download/2.8/doc/proxy-protocol.txt) (versions 1 and 2) is how it passes the client on: a header at the start of each connection. Conduit reads it on plain HTTP and TLS ports, and on `tcp` sites (`proxyProtocol`), and writes one to the upstream of a `tcp` site (`tcp.sendProxyProtocol`). ```yaml sites: # HTTPS behind a load balancer: the header comes before the TLS handshake - port: 443 host: app.example.com tls: { cert: ./cert.pem, key: ./key.pem } proxyProtocol: trustedSources: ["10.0.0.0/8"] # the load balancers ipFilter: allow: ["203.0.113.0/24"] # judged on the client of the header proxy: "http://app.internal:8080" # a database port behind the same load balancer, and the real client passed on to the database - port: 5432 proxyProtocol: trustedSources: ["10.0.0.0/8"] tcp: targets: ["db.internal:5432"] sendProxyProtocol: v2 maxConnectionsPerIp: 20 # counted per client, not per load balancer ``` | `proxyProtocol` field | Type | Default | Description | | --------------------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `trustedSources` | string[] | — | Addresses or CIDR blocks of the load balancers whose header is believed — **required**, at least one | | `timeoutMs` | number | `5000` | Milliseconds a trusted peer has to send the whole header (one deadline, a byte at a time does not extend it) | | `maxHeaderBytes` | number | `4096` | Longest header accepted, from 107 (the longest v1 header) to 65551. A v2 header may carry TLVs, which are checked and then ignored | What it does: - **The header is required and is believed only from `trustedSources`.** A connection from any other address, or from a trusted one that does not open with a valid header (or does not finish it within `timeoutMs`), is closed before a byte of it is read as TLS, parsed as HTTP, or relayed. There is no "optional" mode: a port that takes both direct clients and a load balancer cannot tell a spoofed header from a real one. This also means that **the load balancer's own health checks must send the header** (HAProxy: `check-send-proxy`) or be answered on another port. - **The client of the header is the client everywhere after it**: `ipFilter`, rate limits, `tcp.maxConnectionsPerIp`, the access log, `X-Forwarded-For` and the address `sendProxyProtocol` passes on. `trustProxy` is a different thing (it trusts an `X-Forwarded-For` header inside HTTP) and is not needed for this. - Both versions are accepted. A v2 `LOCAL` header and a v1 `UNKNOWN` line (a load balancer's own probe) keep the address of the socket. An IPv4-mapped IPv6 address (`::ffff:a.b.c.d`) is the IPv4 address it carries, so an `ipFilter` with IPv4 CIDRs matches it. A header that breaks the specification (a wrong length, a TLV that overruns, a datagram transport) is refused, never guessed at. - `sendProxyProtocol` writes `v1` or `v2` to the upstream before any client byte. The client is the one of the incoming header when there is one, otherwise the socket peer. The upstream must be set up to expect it (`listen ... proxy_protocol` in nginx, `bind ... accept-proxy` in HAProxy): one that is not reads it as garbage and drops the connection. - Sites that share an HTTPS or plain HTTP port must have the same `proxyProtocol` (the header is read before the TLS handshake or HTTP parsing identifies a host); a difference is a validation error. Limits of this version: - A site with `proxyProtocol` that has a `tls` block must have a live TLS listener. If it ends up on a plain listener at start (its certificate is missing or its ACME order failed), Conduit does not start. - A connection refused on an HTTPS port is logged by the server as `Downstream handshake error from
: ProxyProtocol context: `, one line per connection at `error` level. Plain HTTP refusals are logged at `debug`, one line per connection, so they are not visible at the default level. On a plaintext `tcp` site (no `tls`) refusals are logged as one `warn` line per port every 10 seconds, with their count. The HTTPS lines are not rate-limited, and a `tcp` site with `tls` reads the header the same way as an HTTPS port (before the handshake), so its refusals are not rate-limited either: let only the load balancer reach such a port (a firewall or security group): a scanner that can reach it fills the log. - The separate `tls.httpRedirectPort` listener is plain HTTP and does not read the header: a load balancer that sends the header to every port needs that port left out, or its redirect done by the load balancer. - Writing a header to an HTTP upstream is not supported (only `tcp.sendProxyProtocol`). - `proxyProtocol` is read at start: a reload that adds, removes or changes one is refused as a cold change (restart to apply). - Write an IPv4 load balancer as a plain IPv4 address or network (`10.0.0.0/8`). An IPv4-mapped IPv6 network such as `::ffff:10.0.0.0/104` also matches the IPv4 addresses it names; its prefix counts bits of the 128-bit address, so it is 96 plus the IPv4 prefix. A mapped network shorter than `/96` (`::ffff:10.0.0.0/8`) is refused, because as an IPv6 network it would name every IPv4 address. - An HTTPS site with `proxyProtocol` needs a fixed `port`: `port: 0` (an OS-assigned port) is refused, because the policy is found by the port a connection arrives on. - `0.0.0.0/0` (or `::/0`) in `trustedSources` is a warning: it trusts every client, and any of them can name any address as its own and walk past `ipFilter` and the rate limits. --- ## Upload > **Requires** `cargo build --features upload` Enable multipart file upload. The upload handler is only started when this section is present in the config. ```yaml # YAML upload: path: /upload # URL path for the upload endpoint (required) dir: ./uploads # directory where files are saved (required) maxFileSizeBytes: 52428800 # 50 MB per file maxTotalSizeBytes: 209715200 # 200 MB total per request maxFiles: 10 allowedMimeTypes: ["image/jpeg", "image/png", "application/pdf"] fieldName: file # multipart field name (default: "file") ``` ```json // JSON { "upload": { "path": "/upload", "dir": "./uploads", "maxFileSizeBytes": 52428800, "maxTotalSizeBytes": 209715200, "maxFiles": 10, "allowedMimeTypes": ["image/jpeg", "image/png", "application/pdf"], "fieldName": "file" } } ``` | Field | Type | Default | Description | | ------------------- | -------- | -------- | ----------------------------------------------- | | `path` | string | — | URL path for upload endpoint — **required** | | `dir` | string | — | Directory to save uploaded files — **required** | | `maxFileSizeBytes` | number | — | Max size per individual file | | `maxTotalSizeBytes` | number | 5 GiB (see below) | Max total size of all files in one request | | `maxFiles` | number | — | Max number of files per request | | `allowedMimeTypes` | string[] | all | Allowed MIME types (e.g. `"image/jpeg"`) | | `fieldName` | string | `"file"` | Multipart field name to read | **How large one request may be.** Both size limits are enforced while the body streams to disk, and a file that goes over its limit is removed again, and so are the files an earlier part of a refused request had already saved. A site that sets no `maxTotalSizeBytes` is still bounded per request: one request may carry up to the larger of **5 GiB** and `maxFileSizeBytes`. That bound is for one request, not a storage quota: many successful uploads can still fill the disk, so put the upload directory on a volume with its own limit or quota. To accept bigger uploads (AI model files are tens of gigabytes), set the limit you want: `maxFileSizeBytes: 53687091200` accepts one 50 GiB file, and `maxTotalSizeBytes` sets the bound for the whole request. A request whose `Content-Length` is already more than 1 MiB plus 0.1% above that bound is refused with `413` before its body is read (that margin is the room for the multipart framing). The whole body is counted as it arrives, whatever the field names are and whether or not there is a `Content-Length` (a chunked body has none), and a body that passes the bound plus that margin is cut off with `413`. The limits are 64-bit numbers on every platform. A saved file is named by a random UUID. It keeps the extension of the uploaded name only when that is ASCII letters and digits (16 at most); any other extension is dropped, so a client cannot put a `:` (an NTFS alternate data stream on Windows), a space or a control character into a file name on the server. A request that is refused, or that is cancelled because the client went away, keeps none of the files it had saved. (The removal of a cancelled request is handed to a background thread; if the server itself is shutting down at that moment it may not run, as when the process is killed in the middle of a write.) --- ## Admin API Configure with [`global.admin`](#multi-site): ```yaml global: admin: bind: "127.0.0.1:2019" # loopback only token: "$ADMIN_TOKEN" # optional Bearer token sites: - port: 8080 proxy: http://127.0.0.1:4000 ``` The Admin API covers hot reload, status, upstream management, cache purge, certificate reload, rate-limit stats and the runtime IP deny list. **→ Full reference with request/response examples: [docs/admin.md](/conduit/docs/admin/)** --- ## Prometheus Metrics Reference All metrics are at the [`metrics.path`](#metrics) endpoint. | Metric | Type | Labels | Description | | ------------------------------------- | --------- | -------------------- | ---------------------------------------------------------------- | | `conduit_requests_total` | counter | `method`, `status` | Total HTTP requests handled | | `conduit_request_duration_seconds` | histogram | `method`, `status` | Full request latency (accept → response sent) | | `conduit_active_connections` | gauge | — | Requests currently in-flight (site-wide) | | `conduit_upstream_errors_total` | counter | `route`, `status` | Upstream 5xx responses per route | | `conduit_upstream_requests_total` | counter | `upstream`, `status` | Requests forwarded to each upstream URL | | `conduit_upstream_latency_seconds` | histogram | `upstream` | Upstream response latency per URL | | `conduit_upstream_active_connections` | gauge | `upstream` | In-flight requests per upstream URL | | `conduit_retry_attempts_total` | counter | `route`, `condition` | Retry attempts by trigger (`5xx`, `connection_error`, `timeout`) | | `conduit_rate_limit_rejected_total` | counter | `site` | Rate-limited (429) requests per site | | `conduit_cache_hits_total` | counter | `route` | Proxy cache hits | | `conduit_cache_misses_total` | counter | `route` | Proxy cache misses | | `conduit_eventloop_lag_ms` | gauge | — | Mean scheduling delay (ms) of the admin runtime (**`--features tokio-metrics`**) | **Example Grafana queries:** ```promql # Request rate rate(conduit_requests_total[5m]) # p99 latency histogram_quantile(0.99, rate(conduit_request_duration_seconds_bucket[5m])) # Error rate rate(conduit_upstream_errors_total[5m]) # Cache hit ratio rate(conduit_cache_hits_total[5m]) / (rate(conduit_cache_hits_total[5m]) + rate(conduit_cache_misses_total[5m])) ```