Tollgate sits between your agents, such as Claude Code and Codex CLI, and the Anthropic and OpenAI APIs.
It refuses requests that would go over a budget, stops agents that repeat a failed tool use,
fails over when a provider goes down, and puts a price on every request. One static Go binary, no database.
Quick start · Production config · How it works · Deployment · Security · Documentation
Coding agents do not spend money like chat apps. One task can send hundreds of large requests and run for an hour while nobody watches the meter. One bad minute at the provider can stop the task.
- Hard budgets. Each tenant gets a month budget and a budget for each agent session. Tollgate reserves the estimated cost before it sends a request, and refuses with HTTP 402 when the money is gone. Spend alerts at 50%, 80% or any other part of a budget go to the log, to Prometheus, and to a signed webhook.
- Runaway agents stopped. If an agent repeats the same failed tool use, with the same input and the same result, in 5 of its last 10 tool turns, Tollgate refuses the request with HTTP 422 before it costs money. This is on by default. Set
runaway.mode: offto turn it off. - Failover before the first byte. When a provider returns
529 Overloadedor times out, Tollgate tries the next target, such as a second account or Claude on Vertex AI. The agent gets a normal response. - A price on every request. Each request is priced and tagged with its tenant, key, and session. The dashboard and
tollgate reportshow where the money went. - One key for each person or agent. Each Tollgate key can have its own month and session budgets, inside the models, rate limits, and budgets of its tenant. The provider keys stay on the gateway.
Clients keep their native API. They change only the base URL and the key.
When Tollgate is not a good fit: if you need dozens of providers, translation between API formats, or a hosted service, use a general-purpose gateway. Tollgate does less, on purpose.
Note
Tollgate is pre-1.0 software. The configuration format can change between minor versions. Read the CHANGELOG before you upgrade, and the budget tolerances before you depend on a budget.
The other gateways do more: many more providers, hosted plans, and more enterprise controls. Tollgate does the few things that a team of coding agents needs, in one binary. The comparison has the source of each cell and the commands to measure the other gateways.
| Tollgate | LiteLLM proxy | Portkey gateway | Bifrost | Kong AI Gateway | |
|---|---|---|---|---|---|
| Runtime | One Go binary | Python | Node.js | Go | Kong Gateway and plugins |
| Providers | 4 kinds | 100+ | 45+ | 23+ | 17 |
| Hosted option | No | Yes | Yes | ? | Yes |
| Session budget | Refused before the spend (402) | Refused after the spend (429) | Not in docs | Not in docs | Not in docs |
| Failover before the first byte | Yes | Yes | Yes | Yes | Enterprise |
| Sticky routing for the prompt cache | Yes | Yes | Sticky hashing | Not in docs | Enterprise |
| Streams passed byte for byte | Yes | ? | ? | No | ? |
| Anthropic, OpenAI and Responses APIs | Yes | Yes | Yes | Yes | Yes |
| PII redaction | Built in | Presidio service | Enterprise | Enterprise | Enterprise |
| Dashboard, Prometheus, OpenTelemetry | All three | All three | Console only | All three | Konnect, OTel |
| License | Apache-2.0 | MIT and enterprise | MIT | Apache-2.0 and enterprise | Apache-2.0 and enterprise |
| Added TTFT, p50 / p99 | +0.5–0.7 ms / up to +3.3 ms | Not measured yet | Not measured yet | Not measured yet | Not measured yet |
| CPU and memory at 1,000 req/s | 1.3 cores, 166 MiB | Not measured yet | Not measured yet | Not measured yet | Not measured yet |
| Added latency p50, no-delay upstream | 0.18 ms | 5.83 ms | Not measured yet | Not measured yet | Not measured yet |
The speed rows come from the gateway overhead benchmark and the proxy benchmark, on one machine over loopback, with a fake provider. The TTFT rows use a fake provider that sends the first token after 300 ms. The reports link to the archived benchmark harness. Each response also has an x-tollgate-overhead-ms header, so you can measure the overhead on your own traffic.
Prerequisites: Go 1.27 or later. No API key, Node.js, or Docker. From v0.2.0, you can use a release binary or Homebrew instead of Go.
go install github.com/ykakade/tollgate/cmd/tollgate@latest
tollgate demoOpen the dashboard at http://127.0.0.1:9090. The demo runs fake providers in the same process, with 7 days of synthetic history and live agent-like sessions. The first target of the claude-haiku-5-5 route always returns 529, so you can see failover and circuit breakers at work. Stop the demo with Ctrl-C.
The demo prints a curl command with a demo key. Send it with "model":"claude-haiku-5-5" to see a failover in the response headers:
HTTP/1.1 200 OK
X-Tollgate-Attempts: 2
X-Tollgate-Model: claude-haiku-5-5
X-Tollgate-Provider: fake-backup
X-Tollgate-Session-Remaining-Usd: 1.999965If tollgate is not found, add $(go env GOPATH)/bin to your PATH. If port 8080 or 9090 is in use, run tollgate demo -listen 127.0.0.1:18080 -admin-listen 127.0.0.1:19090.
Prerequisites: Tollgate from the step above, Claude Code, and an Anthropic API key.
-
Download the Claude Code example configuration, and make a key:
curl -fsSLO https://raw.githubusercontent.com/ykakade/tollgate/main/examples/claude-code/tollgate.yaml tollgate keys create -id laptop
In
tollgate.yaml, remove[]afterkeys:and add the two lines that the command shows. Keep the key that starts withtg_. Tollgate shows it one time only. -
Start the gateway with your Anthropic API key:
export ANTHROPIC_API_KEY='YOUR_ANTHROPIC_API_KEY' tollgate serve -config tollgate.yaml
-
In a second terminal, start Claude Code through Tollgate with the Tollgate key and a session name:
export TOLLGATE_KEY='YOUR_TOLLGATE_KEY' tollgate claude -session my-task
tollgate claudesets the Tollgate address, the key, and thex-tollgate-sessionheader for Claude Code only, and removes the variables that send requests around Tollgate. To startclaudeyourself, see the Claude Code example.
Result: Claude Code works as usual, and its status line shows the money left in the session and month budgets. The task my-task has a $5 session budget, the month has a $50 budget, and each request writes its cost to data/usage.jsonl. Open http://127.0.0.1:9090 to see the spend, or run tollgate report -file data/usage.jsonl.
See the quick start guide for a first request with curl, the Claude Code example for fallbacks and the status line, and the Codex CLI example for Codex CLI.
| Method | Command or link | Notes |
|---|---|---|
| Release binary | Releases page | Linux on amd64 and arm64. macOS and Windows on amd64 and arm64 from v0.2.0. Each release has checksums, a keyless cosign signature, and GitHub build provenance. See verify a release and install on Windows. |
| Homebrew | brew install ykakade/tap/tollgate |
macOS. The release workflow publishes the cask to the tap ykakade/homebrew-tap after the maintainer sets up the tap. The tap does not exist yet, so use a release archive or Go until then. Homebrew checks the SHA-256 of the archive. See install with Homebrew to verify its provenance. |
| Docker | docker run ghcr.io/ykakade/tollgate:latest |
Linux on amd64 and arm64. The release workflow publishes the image from v0.2.0, with a cosign signature, an SBOM, and build provenance. v0.1.1 has no image. See run with Docker. |
| Go | go install github.com/ykakade/tollgate/cmd/tollgate@latest |
Use this on a system that has no release binary. Needs Go 1.27 or later. |
| From source | git clone https://github.com/ykakade/tollgate.git && cd tollgate && make build |
The binaries are in bin/. The dashboard assets are committed, so the build needs no Node.js. make image builds the Docker image. |
Run tollgate version to show the version, the commit, and the Go version of the binary.
This configuration runs several Tollgate copies that share their limits through Redis, fails over to a second Anthropic account, protects the admin port with a token, and sends traces to an OpenTelemetry Collector.
version: 1
server:
listen: ":8080"
admin_listen: "0.0.0.0:9090" # dashboard, admin API, /metrics
admin_token: env:TOLLGATE_ADMIN_TOKEN # required when the admin port is not on loopback
drain_timeout: 10m
store:
kind: redis # all copies share rate limits and budgets
redis_url: env:REDIS_URL
usage:
path: /var/lib/tollgate/usage.jsonl
telemetry:
otlp_endpoint: http://otel-collector:4318
providers:
anthropic:
kind: anthropic
api_key: env:ANTHROPIC_API_KEY
anthropic-backup: # a second account for failover
kind: anthropic
api_key: file:/run/secrets/anthropic-backup-key
routes:
- model: claude-sonnet-5-5
api: anthropic
targets: # tried in order, before the first byte
- provider: anthropic
- provider: anthropic-backup
tenants:
- id: platform-team
keys: # from "tollgate keys create -id ci-agent"
- id: ci-agent
hash: sha256:2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae
models: [claude-sonnet-5-5]
limits:
requests_per_minute: 600
tokens_per_minute: 4000000
budgets:
- window: month
limit_usd: 500
- window: session
limit_usd: 10Check the file, then start the gateway:
tollgate config validate -config tollgate.yaml
tollgate serve -config tollgate.yamlconfig validate shows all errors at once, each with its line number. Unknown fields are errors, and secrets in plain text are refused. Run tollgate init for a commented starter file, and see configuration for every field.
| Capability | What you get |
|---|---|
| Budgets | Month and session budgets for each tenant, and optional budgets for each key inside them. A hard budget reserves the estimated cost first, refuses with HTTP 402, and stops a stream near the limit. A soft budget only warns. See key budgets. |
| Spend alerts | For each tenant or key, alerts at the parts of a budget that you choose. Each alert fires one time in each window, also with more than one copy on Redis, and goes to the log, a Prometheus counter, and an optional webhook with an HMAC-SHA256 signature. Gauges show the spend and the limit of each month budget. See spend alerts. |
| Model downgrade | Opt-in for each tenant. Near a budget limit, Tollgate sends a request to a cheaper route model instead of HTTP 402, and sets x-tollgate-downgraded-to. See model downgrade. |
| Runaway agents | On by default. Tollgate reads the tool turns of the conversation in the request, and refuses an agent that repeats the same failed tool use with HTTP 422 and runaway_detected. The soft mode only warns. See runaway agent detection. |
| Failover | Up to 10 ordered targets for each route, bounded retries, a retry budget, circuit breakers, and separate connect, first-token, idle, and total timeouts. |
| Agent sessions | Session IDs from the x-tollgate-session header, or from a hash of the prompt prefix. Sticky routing keeps a session on the target with the warm prompt cache. |
| Rate limits | Requests and tokens per minute for each tenant, with ratelimit-* and retry-after headers. |
| Redaction | Opt-in masking of emails, card numbers, IPv4 addresses, US SSNs, and your own patterns, with placeholders restored in the response. |
| Response cache | Opt-in exact cache for each route, scoped by tenant. A hit costs no provider tokens. |
| Visibility | An embedded dashboard, a JSONL usage file, tollgate report, Prometheus metrics, and OpenTelemetry traces. |
| Claude Code wrapper | tollgate claude starts Claude Code through Tollgate with one session ID, and tollgate statusline shows the money left in the Claude Code status line. See the Claude Code example. |
The agent features and reliability guides give the exact behavior.
flowchart LR
clients["Claude Code, Codex CLI,<br/>Anthropic and OpenAI SDKs"]
subgraph gateway["tollgate serve"]
direction LR
auth["Authenticate<br/>tg_ key"] --> pre["Preflight<br/>estimate, redact,<br/>runaway check"]
pre --> limits["Reserve<br/>limits and budgets"]
limits --> cache["Response cache<br/>(opt-in)"]
cache --> router["Route<br/>retries, breakers"]
router --> settle["Settle<br/>real cost"]
end
clients -- "data port :8080" --> auth
limits <--> store[("Memory or Redis")]
router --> providers["Anthropic, Vertex AI,<br/>OpenAI, Ollama"]
settle --> sinks["usage.jsonl,<br/>metrics, traces"]
admin["Admin port :9090<br/>dashboard, admin API, /metrics"] -.-> gateway
For each request, Tollgate:
- Authenticates the Tollgate key and finds its tenant, models, and limits.
- Estimates the input tokens and reads the output token limit. With redaction on, it masks personal data in the body.
- Checks the tool turns of the conversation for a runaway agent. A refused request gets 422, reserves no money, and the provider never sees it.
- Reserves the rate limit and the estimated cost. A tenant over a limit gets 429 or 402, and the provider never sees the request. With a model downgrade, a request near the budget limit goes to the cheaper model instead.
- Checks the opt-in response cache.
- Forwards the request to the first healthy target. If that target fails before the first response byte, Tollgate tries the next one.
- Settles the real cost from the reported usage, and writes one usage event.
Streams pass through byte for byte, unless redaction or a budget cutoff changes them. After the first byte, Tollgate never retries. The architecture decision records explain each design choice and the alternatives that were rejected.
Clients send their native format. Tollgate does not translate between the Anthropic and OpenAI formats.
| Client API | Endpoints | Provider kinds |
|---|---|---|
| Anthropic Messages | POST /v1/messages (streaming and not streaming), POST /v1/messages/count_tokens |
anthropic, vertex (Claude on Vertex AI) |
| OpenAI Chat Completions | POST /v1/chat/completions (streaming and not streaming) |
openai, ollama |
| OpenAI Responses | POST /v1/responses (streaming and not streaming). Codex CLI uses this API. |
openai |
| Provider kind | Authentication | Notes |
|---|---|---|
anthropic |
api_key from env: or file: |
The default price table has the Claude models of tollgate init. |
vertex |
Google Application Default Credentials | Needs project and region. Add your own price entries for budgets. |
openai |
api_key from env: or file: |
The default price table has gpt-5.5, gpt-5.4, gpt-5.4-mini, and gpt-5.3-codex. Add your own price entries for other models. |
ollama |
None | Defaults to http://localhost:11434. Costs 0 without a price entry. |
Clients send the Tollgate key in x-api-key or as a bearer token. The test suite runs the official Anthropic and OpenAI Go SDKs against the gateway, and Claude Code passed the M1 validation. An openai route serves both OpenAI endpoints, and runaway agent detection checks both, also for Codex CLI. See pricing and cloud and local targets.
| Signal | Where | Guide |
|---|---|---|
| Access logs | One JSON line on standard error for each request, with tokens, cost, timings, and the target. No prompt text. | Logs |
| Usage events | One JSON line for each request in usage.path. tollgate report groups them by tenant, key, session, route, provider, hour, or day. |
Usage file |
| Metrics | GET /metrics on the admin port, with the prefix tollgate_. A Grafana dashboard is in deploy/grafana. |
Metrics |
| Traces | OTLP/HTTP to telemetry.otlp_endpoint, with GenAI attributes and one span for each upstream attempt. |
Traces |
| Response headers | x-request-id, x-tollgate-provider, x-tollgate-attempts, x-tollgate-overhead-ms, the remaining session budget, and x-tollgate-downgraded-to for a downgraded request. |
Response header |
| Dashboard | Built into the binary at / on the admin port: spend, sessions, provider health, and keys. |
Admin API |
One request ID ties together the log line, the trace, and the usage event of a request. To see Tollgate with Prometheus, Grafana, and Jaeger, run make demo with Docker Compose (demo stack).
The dashboard with synthetic data from tollgate demo. Watch the 81-second feature tour.
- Client keys. A Tollgate key is
tg_and 32 random bytes. The configuration file holds only its SHA-256 hash, andtollgate keys createshows the key one time only. Tollgate removes the client key from the request before it calls the provider. - Provider keys. Provider keys, the admin token, and the Redis URL come only from
env:NAMEorfile:/pathreferences. Tollgate refuses a secret in plain text in the configuration file. - Admin port. The dashboard, admin API, metrics, and profiles are on a separate listener (
server.admin_listen, default127.0.0.1:9090). Clients with a Tollgate key cannot reach it from the data port. Off loopback, Tollgate does not start withoutserver.admin_token. The admin port does not terminate TLS, so put it behind a trusted reverse proxy or keep it on a private network. The Go profiles are off unless you setserver.pprof: true. - No TLS on the data port. Terminate TLS at a load balancer or a reverse proxy in front of Tollgate.
- Prompts. Logs, usage events, and spans hold IDs, token counts, timings, and costs, never prompt or response text. A derived session ID is a SHA-256 hash. The opt-in response cache keeps responses in process memory only.
- Redaction is pattern-based. It does not find all personal data. Read its limits before you depend on it.
To report a vulnerability, use private vulnerability reporting. See SECURITY.md.
| Topic | What to do |
|---|---|
| One copy | Use store.kind: memory. At start, Tollgate reads the usage file to rebuild the spend of the month and of recent sessions. |
| Several copies | Use store.kind: redis and the same configuration file on each copy. One Lua script checks and reserves all limits of a request in one Redis round trip. Keep the clocks in sync with NTP. |
| Redis outage | Tenants with a hard budget get 503 with retry-after: 5. Other tenants continue on local rate limits. See when the limit store fails. |
| Health checks | GET /healthz for liveness. tollgate healthcheck checks it from images that have no shell or curl, and the Docker image uses it in its HEALTHCHECK. GET /readyz for readiness: it returns 503 during a drain. Its body has "store":"ok" or "store":"unavailable", and it stays 200 when Redis is down, so alert on that field. |
| Shutdown | On SIGTERM, /readyz returns 503 and open streams continue for up to server.drain_timeout. Give the orchestrator a termination grace period that is longer than drain_timeout. |
| State in each process | Circuit breakers, 429 cooldowns, the retry budget, the response cache, the runaway refusal records, the alert webhook queue, and the dashboard history are local to each copy. Redis shares only limits, spend, and the spend alert claims. |
Known limits of this version:
- Redis must be one server. Redis Cluster and Sentinel are not supported.
- Tollgate does not rotate the usage file, and it reads the full file at each start. Do not remove the events of the current month while you use the memory store.
- Configuration changes and new keys need a restart. The admin API is read-only.
- A hard budget can go over its limit by a bounded amount. To make the bound smaller, set
reservation.output_tokensto themax_tokensof your clients. See worst-case overspend.
See operations for the full procedures.
- Tollgate follows Semantic Versioning. Before v1.0, a minor version can change the configuration format and other behavior. The CHANGELOG lists the changes of each release.
- The configuration file has a format version (
version: 1). Tollgate refuses unknown fields, so a field that changes name fails at start, not silently. - Only the latest minor version gets security fixes. See SECURITY.md.
- Releases are built only in CI with GoReleaser. The checksum file has a keyless cosign signature, and each archive has a GitHub build provenance attestation. The release workflow builds the Docker image, with a keyless cosign signature, an SBOM, and a build provenance attestation.
How the project is tested:
- Byte-exact streams. Golden tests compare recorded provider streams byte for byte.
- Real clients. Integration tests run the official Anthropic and OpenAI Go SDKs against the gateway.
- Shared state. Cluster tests run three gateway copies on one real Redis, and check the rate limit tolerance and the worst-case budget overspend.
- CI. The race detector, 8 fuzz targets, golangci-lint,
govulncheck, a link check, a check of the Docker Compose demo stack, and a build and health check of the Docker image.
The documentation site has search and dark mode. The same guides are in docs/.
| Guide | Covers |
|---|---|
| Quick start | Installation with release archives, Homebrew, Docker, or Go, release verification, a first request, Claude Code, and Codex CLI |
| Configuration | Providers, routes, tenants, keys, pricing, and every YAML field |
| Limits and budgets | Rate limits, reservations, key budgets, spend alerts, model downgrade, Redis behavior, and overspend bounds |
| Reliability | Retry rules, retry budget, circuit breakers, timeouts, Vertex AI, and Ollama |
| Agent features | Sessions, runaway agent detection, sticky routing, reports, response cache, and redaction |
| Admin API | The dashboard, endpoints, authentication, and data limits |
| Observability | Metrics, traces, the admin port, and the demo stack |
| Operations | Start, health checks, more than one copy, shutdown, and logs |
| Decision records | 36 architecture decisions and their alternatives |
Bug reports, feature requests, and pull requests are welcome.
- Found a bug, or want a feature? Open an issue.
- Want to send a change? Read CONTRIBUTING.md.
make checkruns the same checks as CI. - Please follow the code of conduct.
Tollgate is licensed under the Apache License 2.0.