Docs/Budget Ai/Self Hosting And Configuration

Self-Hosting & Configuration

On ANTS Cloud the gateway is operated for you. This page is for self-hosted deployments, where the gateway runs as its own service next to web and worker. It is a separate, internet-facing service and is off by default.

Requirements

  • An Enterprise self-hosted license, which provides the llm-gateway entitlement.
  • The gatewayAi feature flag enabled for the users who manage Budget AI, or LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES=true. See What you need to turn it on.
  • The same Postgres and Redis as the rest of the platform, the same event storage bucket that ingestion uses, and a running worker. The worker processes gateway traces and runs the budget and key maintenance jobs.
  • The gateway must share SALT and ENCRYPTION_KEY with web. SALT hashes keys; changing it invalidates every issued key. ENCRYPTION_KEY (64 hex characters) opens provider secrets stored in the database.
  • Behind a proxy that inspects TLS, add your corporate root certificate with the Helm value global.extraCaCerts, so the gateway and the detection services can reach LLM providers. See Corporate Root Certificates.

Enable with Helm

The gateway ships as the gateway subchart of helm/ants-platform.

Turn on the service and set its public address

yaml
gateway: enabled: true global: gateway: publicBaseUrl: "https://<your-gateway-host>/v1"

global.gateway.publicBaseUrl is the externally reachable address callers point their SDKs at, ending in /v1. It is rendered into web as GATEWAY_PUBLIC_BASE_URL and shown in Project Settings → Budget AI and in key snippets. When it is empty, the settings tab reports that the gateway address is not configured and hides the snippets.

Publish it through the ingress

yaml
global: ingress: gateway: enabled: true host: "<your-gateway-host>" tls: enabled: true secretName: "<your-gateway-tls-secret>"

The gateway ingress routes /v1 only, to the gateway service. Its host must match global.gateway.publicBaseUrl. Enabling the ingress without gateway.enabled: true fails the render.

Set the proxy hop count

Set gateway.config.trustedProxyHops to the number of proxies in front of the gateway. See Client addresses behind proxies.

Deploy and turn on serving per project

After the rollout, an administrator turns on Serve gateway traffic for this project in Project Settings → Budget AI for each project that should use it.

Helm values

ValueDefaultPurpose
gateway.enabledfalseDeploy the gateway
gateway.replicaCount2Replicas when autoscaling is off
gateway.image.repository / tagants-gatewayGateway image
gateway.service.port3040API port, published by the Service
gateway.service.adminPort9091Admin port for health and metrics; a container port only, never on the Service
gateway.config.providerTimeoutMs60000Provider connect, headers and body timeout
gateway.config.providerStreamUsage"true"Ask OpenAI-compatible and Azure OpenAI providers for a usage chunk on streams
gateway.config.maxBodyBytes4718592Request body limit
gateway.config.configPollMs1000Configuration version poll interval
gateway.config.configStaleMs5000Fail-closed bound; must exceed configPollMs
gateway.config.configFullReloadMs60000Full configuration reload interval
gateway.config.probeIntervalMs60000Health check tick and default interval
gateway.config.probeTimeoutMs10000Timeout per health check
gateway.config.telemetryConcurrency16Concurrent trace recordings per replica
gateway.config.anthropicPromptCachingfalsePass cache_control markers in requests through to Anthropic. More than 4 markers is refused with a 400. Cache writes are priced whatever this is set to.
gateway.config.cooldownRateModefalseLets model groups bench a model by failure rate
gateway.config.ingestion.writeOncefalseWrite-once recording
gateway.config.ingestion.batchedfalseBatched recording
gateway.config.ingestion.batchMaxRecords500A batch is written when it holds this many records
gateway.config.ingestion.batchMaxAgeMs1000A batch is written when its oldest record has waited this long
gateway.config.ingestion.batchMaxBytes4194304A batch is written before it would exceed this size (4 MiB)
gateway.config.ingestion.flushConcurrency4Batch uploads in flight per replica
gateway.config.ingestion.memoryMaxBytes67108864Written batches waiting to upload that may be held in memory (64 MiB); beyond this they go to the spill
gateway.config.ingestion.spill.maxBytes1073741824Spill size cap (1 GiB). Also sizes the spill volume.
gateway.config.trustedProxyHops1Proxies in front of the gateway
gateway.config.trustedProxyCidrsemptyExact proxy addresses or CIDRs to trust instead of a hop count
gateway.config.secretsTtlMs300000How long a secret read from AWS Secrets Manager is cached
gateway.config.database.host / redis.hostemptyHosts the init containers wait for
gateway.resources200m / 256Mi requests, 1 CPU / 1Gi limitsContainer resources
gateway.autoscaling.enabledfalseHorizontal Pod Autoscaler, 2 to 6 replicas at 70 % CPU by default
gateway.podDisruptionBudget.enabledtrueKeeps at least one replica during voluntary disruptions
gateway.terminationGracePeriodSeconds120Lets streamed completions finish during a rollout
gateway.serviceAccount.annotationsemptyFor example an IAM role annotation when secrets are in AWS Secrets Manager
gateway.networkPolicy.enabledfalseEgress policy, see Network policy
gateway.guardrailScanning.enabledfalseLets the gateway reach the guardrail ML service for AI Guardrails scanning
gateway.guardrailScanning.mlService.urlemptyOverrides the in-cluster address of the guardrail ML service
gateway.guardrailScanning.mlService.port / podLabels8100 / app.kubernetes.io/name: guardrail-ml-serviceML service port and pod labels, used for the address and the network policy
gateway.guardrailScanning.rabbitmq.port / podLabels5672 / app: rabbitmqIn-cluster RabbitMQ, for the network policy
gateway.guardrailScanning.rabbitmq.external.cidrs / portempty / 5671An external RabbitMQ broker's subnets and port, for the network policy
global.gateway.publicBaseUrlemptyPublic address, see above
global.gateway.secrets.store / region / prefixdb / empty / ants/gatewayProvider secret storage, read by both web and the gateway
global.ingress.gateway.*disabledGateway ingress host, TLS and annotations

The gateway image is built from gateway/Dockerfile. A deployment that leaves gateway.enabled: false does not need it.

Environment variables

The gateway validates its configuration at start-up and refuses to start when it is incomplete.

VariableDefaultPurpose
PORT / HOSTNAME3040 / 0.0.0.0API listener
GATEWAY_ADMIN_PORT9091Admin listener for /health, /ready and /metrics
SALTrequiredKey hashing; must match web
ENCRYPTION_KEYrequired, 64 hex charactersOpens database-stored provider secrets; must match web
DATABASE_URL, Redis and event storage settingsas for workerConfiguration loading, admission and trace recording
NEXT_PUBLIC_LANGFUSE_CLOUD_REGION, LANGFUSE_EE_LICENSE_KEYunsetPlan resolution for the llm-gateway entitlement
GATEWAY_PROVIDER_TIMEOUT_MS60000Provider timeout
GATEWAY_PROVIDER_STREAM_USAGEtrueRequest usage chunks on OpenAI-compatible and Azure OpenAI streams
GATEWAY_MAX_BODY_BYTES4718592Request body limit
GATEWAY_TRUSTED_PROXY_HOPS1Proxies in front of the gateway
GATEWAY_TRUSTED_PROXY_CIDRSunsetProxy addresses or CIDRs to trust; takes precedence over the hop count
GATEWAY_CONFIG_POLL_MS1000Version poll interval
GATEWAY_CONFIG_STALE_MS5000Fail-closed bound; must be longer than the poll interval
GATEWAY_CONFIG_FULL_RELOAD_MS60000Full reload interval
GATEWAY_SECRETS_STOREdbdb or aws; must match web
GATEWAY_SECRETS_REGIONunsetAWS region for Secrets Manager
GATEWAY_SECRETS_PREFIXants/gatewaySecret path prefix; must match web
GATEWAY_SECRETS_TTL_MS300000Cache lifetime for managed secrets
GATEWAY_PROBE_INTERVAL_MS60000Health check tick and default interval
GATEWAY_PROBE_TIMEOUT_MS10000Timeout per health check
GATEWAY_PROBE_CONCURRENCY8Health checks in flight per replica, up to 64
GATEWAY_TELEMETRY_CONCURRENCY16Concurrent trace recordings
GATEWAY_TELEMETRY_MAX_QUEUE10000Trace recordings that may wait
GATEWAY_INGESTION_WRITE_ONCEfalseWrite-once recording
GATEWAY_INGESTION_BATCHEDfalseBatched recording
GATEWAY_INGESTION_BATCH_MAX_RECORDS500Records per batch
GATEWAY_INGESTION_BATCH_MAX_AGE_MS1000Longest wait of a record before its batch is written
GATEWAY_INGESTION_BATCH_MAX_BYTES4194304Largest batch size
GATEWAY_INGESTION_FLUSH_CONCURRENCY4Batch uploads in flight, up to 64
GATEWAY_INGESTION_MEMORY_MAX_BYTES67108864Batches waiting to upload held in memory
GATEWAY_TELEMETRY_SPILL_DIRants-gateway-spill in the system temporary directory; /var/lib/gateway/spill with HelmSpill directory
GATEWAY_TELEMETRY_SPILL_MAX_BYTES1073741824Spill size cap
GATEWAY_TELEMETRY_SPILL_SHIP_INTERVAL_MS5000How often spilled batches are retried
GUARDRAIL_ML_SERVICE_URLset by the chartGuardrail ML service address. Empty when gateway.guardrailScanning.enabled is false, so inspection reports the service as not deployed at once.
GATEWAY_GUARDRAIL_STREAM_MAX_BACKLOG_CHARS32768Most streamed text that may be sent ahead of inspection in Scan while streaming
GATEWAY_GUARDRAIL_BUFFER_MAX_CHARS1000000Largest response held in Hold until scanned
GATEWAY_GUARDRAIL_KEEPALIVE_MS10000Interval of : keepalive comments while a stream waits for inspection
GUARDRAIL_ML_TIMEOUT_MS10000Timeout of a single call to the guardrail ML service
GUARDRAIL_ML_BREAKER_THRESHOLD5Failures in a row that switch off calls to one detector, see Detector circuit breakers
GUARDRAIL_ML_BREAKER_RESET_MS60000How long a detector stays switched off before one trial call
GUARDRAIL_ML_BREAKER_HANG_MS1000How long a detector must have been waiting, when a project's time limit cuts it off, for that to count as a failure
BUILD_IDunsetReported on traces as gateway.version
OTEL_EXPORTER_OTLP_ENDPOINT / OTEL_SERVICE_NAMEhttp://localhost:4318 / gatewayOperational tracing of the gateway itself

On web, set GATEWAY_PUBLIC_BASE_URL (through global.gateway.publicBaseUrl) and the same GATEWAY_SECRETS_* values.

Also on web, set GATEWAY_DASHBOARD_WIDGETS_ENABLED=true (the web chart's config.features.gatewayDashboardWidgets) on deployments that run the gateway. It defaults to false, and while it is off, dashboard widgets that break down or filter by Source, Gateway key or Gateway model group are hidden and return no data.

⚠

The gateway accepts only ANTS-issued keys and provider credentials registered in a project. It refuses to start while any of GATEWAY_DEV_KEY, GATEWAY_DEV_PROJECT_ID, GATEWAY_PROVIDER_BASE_URL or GATEWAY_PROVIDER_API_KEY is set.

Provider secret storage

By default, provider secrets are encrypted into the platform database. To store new credentials in AWS Secrets Manager instead:

yaml
global: gateway: secrets: store: "aws" region: "<aws-region>" prefix: "ants/gateway" gateway: serviceAccount: annotations: eks.amazonaws.com/role-arn: "<role-arn-scoped-to-the-prefix>"

Both web (which writes secrets) and the gateway (which reads them) must see the same store, region and prefix. Scope the IAM policy to the prefix and grant GetSecretValue, PutSecretValue, CreateSecret, DeleteSecret and RestoreSecret; without the last two, deleting a credential or moving it back out of the managed store leaves the secret behind. Existing database credentials are moved one at a time with Move in Models & Routing. See Where provider secrets are stored.

AI Guardrails scanning

Inline AI Guardrails inspection needs the gateway to reach the guardrail ML service, the same service that runs AI Guardrails for the SDK. Both are off by default. While gateway scanning is off, projects that turn inspection on get the result "not deployed" at once: requests are forwarded uninspected and recorded as fail_open:not_deployed, or refused with 503 guardrail_unavailable when the project refuses what it cannot inspect.

Turn on the ML service and gateway scanning together

yaml
guardrailMlService: enabled: true gateway: guardrailScanning: enabled: true

The chart then gives the gateway the in-cluster address of the ML service. Set gateway.guardrailScanning.mlService.url only if the service runs elsewhere.

Allow the traffic in the network policy

With gateway.networkPolicy.enabled: true, turning on scanning also allows egress to the ML service pods (port 8100) and to RabbitMQ, through which the gateway publishes violations. By default that is the in-cluster app: rabbitmq pods on port 5672.

An external broker, such as a managed RabbitMQ service, has a DNS name a NetworkPolicy cannot follow. List its subnets instead:

yaml
gateway: guardrailScanning: enabled: true rabbitmq: external: cidrs: - "<broker-subnet-cidr>" port: 5671

Set these before turning on both the network policy and scanning, or violations cannot be published.

Turn on AI Guardrails for the organization and project

See Turn on inspection.

Detector circuit breakers

Each process that calls the ML service (web, worker and the gateway) keeps a circuit breaker per detector: PII, PCI and PHI entities, Ethics & Bias, and the safety detector. After GUARDRAIL_ML_BREAKER_THRESHOLD failures of one detector in a row (5 by default), calls to that detector stop for GUARDRAIL_ML_BREAKER_RESET_MS (60 seconds by default). Then a single trial call is let through: an answer closes the breaker, a failure opens it again.

  • Network errors, the ML client's own timeout, 5xx, 408 and 429 responses and invalid responses count as failures. Other 4xx responses, such as 422 for text the service will not take, never count.
  • A detector still waiting when a project's time limit cuts the inspection off counts as one failure, but only if it had been waiting at least GUARDRAIL_ML_BREAKER_HANG_MS, so a project with a very short time limit cannot switch detectors off for everyone else.
  • An open breaker affects only its own detector; the policy's other detectors run normally. In Budget AI an inspection that needed that detector did not finish, and follows the project's failure setting.

The chart has no dedicated values for these settings. Set them in the environment of each service that should use them.

Client addresses behind proxies

Per-key allowed source networks are checked against the caller's address, which the gateway reads from X-Forwarded-For counting proxies from the right. Set trustedProxyHops to exactly the number of proxies in your path: for example 1 for a load balancer straight to the service, 2 for a load balancer then an ingress controller, 0 when connections reach the pod directly.

  • Too high, and a caller can forge its own address and bypass network allow-lists.
  • Too low, and the gateway sees a proxy's address, so every network-confined key is refused.

trustedProxyCidrs lists the proxies exactly instead and takes precedence when set.

Trace recording

By default the gateway records each request on its own: it writes the trace and generation events to event storage and queues them, and the worker processes them after a delay of up to 5 seconds, as for SDK traffic. Two switches change how gateway records reach Tracing. Both are off by default and change only how records are stored, not what is recorded. SDK and OpenTelemetry traffic is never affected.

SwitchHelm valueWhat it doesEffect
Write-oncegateway.config.ingestion.writeOnceGateway events are queued with no delay, and the worker reads only the event named in the job and skips the read of the existing record. The gateway writes each of its records once and complete, so neither step is needed.Gateway traces appear in Tracing as soon as the worker processes them, without the wait. Fewer storage and database operations per request.
Batchedgateway.config.ingestion.batchedThe gateway collects finished requests per project and writes one file and one job per batch: when the batch holds 500 records, when its oldest record has waited 1 second, or before it would exceed 4 MiB. A batch never mixes projects. The worker stores every trace and generation in the batch with the same fields, cost, guardrail scans, sessions and agents as the per-request path. Includes write-once handling.Far fewer event storage writes and queue jobs for busy gateways. A trace can wait up to the batch age (1 second by default) before its batch is written.

Upgrade the worker first

An older worker does not process batches and ignores the write-once marking. Deploy the platform release to worker before you change the gateway settings.

Turn on write-once

yaml
gateway: config: ingestion: writeOnce: true

Turn on batched recording

yaml
gateway: config: ingestion: batched: true

Turning either switch off is safe at any time; batches already queued are still processed.

Batched recording details

  • Raw copies. On the batched path a batch file stays in event storage only until its batch is stored, usually seconds, and is then deleted. There is no longer-lived raw copy of gateway events on this path.
  • Retries and spill. Writing a batch and queueing its job are each retried three times. A batch that still fails goes to a local spill directory and is retried every 5 seconds (GATEWAY_TELEMETRY_SPILL_SHIP_INTERVAL_MS) until it is shipped, then deleted. Requests keep being served meanwhile.
  • Spill storage. With batched: true, the chart mounts a size-limited emptyDir volume at /var/lib/gateway/spill and adds a matching ephemeral-storage request, unless you set one. The volume is spill.maxBytes plus 10 %, and at least 64 MiB more. The spill holds the same prompts and responses that are recorded for the requests (none for usage-only keys). An emptyDir survives a container restart but is deleted with the pod; mount persistent storage at the spill directory if records must survive a pod deletion during an outage.
  • When the spill is full. The batch being closed is dropped and its records are counted as dropped. Records accepted earlier are never discarded to make room.
  • Recovery. The worker looks for batches that were written but never queued, every 5 minutes over the last 30 minutes, and queues them.
  • Shutdown. On SIGTERM the gateway writes every open batch, waits for the uploads and makes one last attempt to ship the spill. Records still in the spill are logged as a warning.

Worker settings for batches:

VariableDefaultPurpose
QUEUE_CONSUMER_GATEWAY_INGESTION_QUEUE_IS_ENABLEDtrueProcess gateway batches and run the recovery check
LANGFUSE_GATEWAY_INGESTION_QUEUE_CONCURRENCY4Batches processed at once per worker
GATEWAY_INGESTION_SWEEP_INTERVAL_MS300000How often the recovery check runs
GATEWAY_INGESTION_SWEEP_WINDOW_MINUTES30How far back the recovery check looks, 3 to 120 minutes. Batches younger than 2 minutes are left to the gateway.

Watch these metrics on the batched path. Alert on any dropped record, on a spill above half its cap, and on a 95th percentile batch lag above 30 seconds.

MetricWhereMeaning
gateway.ingestion.batchGatewayBatches written, by trigger: count, age, bytes or drain
gateway.ingestion.batch_records, gateway.ingestion.batch_bytesGatewayRecords and bytes per batch
gateway.ingestion.write_errorGatewayFailed batch writes (s3) or job adds (queue) after retries
gateway.ingestion.spilled, gateway.ingestion.spill_bytesGatewayRecords written to the spill, and its size
gateway.telemetry.droppedGatewayRecords lost, by reason: spill_full, spill_error or spill_corrupt
gateway.ingestion.orphanedGatewayRecords whose batch was written but left for the worker to queue
gateway.ingestion.spill_pending_recordsGatewayRecords still in the spill after shutdown
gateway.ingestion.batch_lag_msWorkerTime from the oldest record in a batch to its processing
gateway.ingestion.invalid_lineWorkerRecords in a batch that failed validation and were skipped
gateway.ingestion.orphan_requeuedWorkerBatches the recovery check queued
gateway.ingestion.batch_delete_failedWorkerBatch files that could not be deleted after processing; the recovery check retries

Ports, health and metrics

The gateway listens twice:

PortServesExposure
API (3040)/v1/*, /health, /readyPublished by the Service and the gateway ingress (/v1 only)
Admin (9091)/health, /ready, /metricsContainer port only. Do not publish it.

/metrics reports per-project and per-key counts, so it is kept off the public port. It returns JSON with request counts by status, refusal and error counters by code, in-flight requests, gateway latency before the provider call (percentiles), attempt, retry, fallback and benching counts, budget exhaustion counts, health check results, telemetry recorded and failed counts, batched recording figures under ingestion, configuration statistics (projects, keys, last successful version read, pending projects), AI Guardrails inspection outcomes by direction, and process memory and event loop delay.

The chart's liveness probe uses /health and the readiness probe uses /ready, both on the admin port. /health does not use Redis, so a Redis outage does not restart the pods. /ready checks Redis (2 second timeout) and fails while the replica is draining or its configuration is stale, so the load balancer stops sending it traffic. A replica that cannot load its first configuration within GATEWAY_STARTUP_TIMEOUT_MS (120 seconds by default) exits so it is restarted.

On SIGTERM the gateway marks itself not ready, lets in-flight requests and streams finish, and waits for pending trace recordings (with batched recording, open batches and the spill) before exiting, within a shutdown deadline.

Configuration propagation and fail-closed behaviour

The request path never reads Postgres. Each replica holds an in-memory snapshot of every served project's keys, model groups, deployments, credentials and budgets.

  • Every change in the product writes Postgres and its audit log entry in one transaction, then bumps the project's configuration version in Redis.
  • Each replica polls the versions every second (GATEWAY_CONFIG_POLL_MS) and reloads changed projects. A blocked key, a removed grant or a disabled project stops working on every replica within about a second.
  • Every 60 seconds (GATEWAY_CONFIG_FULL_RELOAD_MS) each replica reloads every enabled project. This picks up entitlement changes and any version bump that failed; the product says "Saved, but not yet in force" in that case.
  • Fail closed: if no version read has succeeded within 5 seconds (GATEWAY_CONFIG_STALE_MS), or a project's pending change has not loaded within that time, requests for that project get 503 gateway_config_stale. When the version read itself is failing, every request is refused and /ready fails.

Dependencies

DependencyUsed forIf it is unavailable
RedisConfiguration versions, rate limit and budget counters, reservations, benching, deployment status, response cache, health check schedulingRequests are refused with 503 gateway_config_stale; nothing reaches a provider
PostgresLoading project snapshots, recording threshold crossings and health check resultsReplicas keep serving from their last snapshot until it is older than the stale bound for a changed project
Event storage and workerTurning gateway records into traces, and the budget flush and key maintenance jobsRequests are still served; traces and durable spend catch up when they recover. With batched recording, batches that cannot be written wait in the spill.
AWS Secrets Manager (optional)Provider secrets in the managed storeReplicas keep the secrets they already hold
Guardrail ML service (optional)AI Guardrails inspectionInspection does not finish and follows each project's failure setting
RabbitMQ (with AI Guardrails scanning)Publishing AI Guardrails violationsRequests are served; violations may not be recorded

The gateway does not connect to ClickHouse.

The worker runs two Budget AI jobs: one every 10 seconds writes budget and org unit spend from Redis to Postgres, and one every minute blocks keys whose rotation grace window has ended.

Network policy

With gateway.networkPolicy.enabled: true, the gateway's egress is limited to DNS, the platform data namespace (Postgres and Redis ports), the guardrail ML service and RabbitMQ when AI Guardrails scanning is on, and the CIDRs in gateway.networkPolicy.allowedEgressCidrs on the ports in allowedEgressPorts (default 443). A compromised gateway holds provider secrets in memory, so this limits what it can reach. Before enabling it, list every provider endpoint, and when secrets are in AWS Secrets Manager the Secrets Manager and STS endpoints. A Postgres or Redis hosted outside the cluster must also be listed, with its port.

Scaling

Replicas are stateless; all shared state is in Redis. Scale with replicaCount or the autoscaler. Rate limits, budgets, reservations and benching are shared across replicas. The Lowest latency and Least busy strategies use measurements taken on each replica. Keep terminationGracePeriodSeconds long enough for your longest streamed completions.

© 2026 ANTS Platform, Inc.Docs v1.0 · Last updated June 2026