Repository navigation
Description
Epic: Namespace-Based Token Usage Quotas for AI Agents
Summary
Implement namespace-level token usage quotas to enable multi-tenant cost control and resource governance for AI agent workloads. This feature allows platform administrators to set daily, weekly, and monthly token limits per namespace (team), with optional user-level and agent-level quotas.
Motivation
As AI agent deployments scale in production environments, organizations face critical challenges:
- Cost Control: LLM API costs can escalate rapidly without usage limits
- Fair Resource Distribution: Multiple teams sharing infrastructure need usage boundaries
- Compliance & Budgeting: Enterprise environments require predictable spending aligned with FinOps practices
- Preventing Runaway Agents: Agentic AI systems with tool-calling can generate unbounded token consumption
Industry Context
According to recent FinOps for AI research, organizations using GenAI services face consumption-based pricing where costs scale with tokens, API calls, and processing time. Multi-tenant environments need chargeback/showback mechanisms to attribute AI costs to specific teams or projects.
Production deployments handling 5-10 million tokens monthly typically incur $1,000-$5,000 in operational costs, making quota enforcement essential for budget management.
Design Priorities
When evaluating architecture options, we prioritize:
| Priority | Requirement | Rationale |
|---|---|---|
| P0 | Hard enforcement | Quotas must be enforced, not advisory |
| P0 | Minimal agent changes | Agent developers shouldn't need to implement quota logic |
| P1 | Pre-request blocking | Reject requests BEFORE tokens are consumed |
| P1 | Namespace-level quotas | Teams need independent budgets |
| P2 | User/agent-level quotas | Finer-grained control within namespaces |
| P2 | Cost attribution | FinOps chargeback/showback support |
Architecture Options
We propose three implementation approaches. Each is evaluated against our design priorities.
Option A: Metrics-Based Approach
This approach uses OpenTelemetry Metrics SDK for 100% accurate token counting, separate from sampled traces. Agents emit metrics after each LLM call, which flow to Prometheus for aggregation and Redis for real-time enforcement.
flowchart TB
subgraph AgentPod["Agent Pod"]
Agent[Agent Application]
LLM[LLM Call]
Extract[Extract Token Counts]
Record[record_tokens]
LLM --> Extract --> Record
end
subgraph Telemetry["Telemetry Pipeline"]
OTELMetrics[OTEL Metrics<br/>100% capture]
OTELTraces[OTEL Traces<br/>10% sampled]
end
subgraph Storage["Storage Layer"]
Prometheus[(Prometheus<br/>Recording Rules)]
Phoenix[(Phoenix<br/>Trace Analysis)]
Redis[(Redis<br/>Real-time Counters)]
end
subgraph Enforcement["Enforcement Layer"]
OPA[OPA ext_authz<br/>Quota Check]
Istio[Istio Waypoint]
end
Record --> OTELMetrics
Record --> Redis
Agent --> OTELTraces
OTELMetrics --> Prometheus
OTELTraces --> Phoenix
Prometheus -->|Sync 30s| Redis
Redis --> OPA
OPA --> Istio
style OTELMetrics fill:#4CAF50
style Redis fill:#F44336
style OPA fill:#2196F3
Advantages
| Advantage | Description |
|---|---|
| 100% Accurate Counting | Metrics are never sampled, unlike traces |
| Leverages Existing Infrastructure | Uses Prometheus already deployed for Istio |
| Flexible Aggregation | Recording rules support any time window |
| OTel Standard | Follows GenAI semantic conventions |
Disadvantages
| Disadvantage | Impact | Severity |
|---|---|---|
| Requires Agent Code Changes | Every agent must implement OTEL metrics SDK and record_tokens() function |
HIGH |
| Post-Request Counting | Tokens already consumed before quota can reject; enforcement is reactive | HIGH |
| Inconsistent Implementation Risk | Each agent team must implement correctly; bugs lead to inaccurate counts | MEDIUM |
| Near Real-Time Only | 30s sync delay between Prometheus and Redis means enforcement lag | MEDIUM |
| Two Systems to Maintain | Separate metrics and traces pipelines add operational complexity | LOW |
Priority Assessment
| Priority | Requirement | Met? | Notes |
|---|---|---|---|
| P0 | Hard enforcement | Partial | Enforcement exists but is reactive (post-token-consumption) |
| P0 | Minimal agent changes | NO | Requires SDK integration in every agent |
| P1 | Pre-request blocking | NO | Counts happen after LLM call completes |
| P1 | Namespace-level quotas | Yes | Via Prometheus recording rules |
Option B: LLM Gateway Pattern (Recommended)
Route all LLM calls through a centralized gateway that handles token counting, quota enforcement, and routing. This is the recommended approach because it requires zero agent code changes and provides true pre-request enforcement.
flowchart TB
subgraph Agents["Agent Workloads"]
A1[Agent<br/>team1]
A2[Agent<br/>team2]
A3[Agent<br/>team3]
end
subgraph Gateway["LLM Gateway - LiteLLM Proxy"]
direction TB
PreCheck["Pre-Request Check<br/>1. Parse user/ns headers<br/>2. Query Redis quota<br/>3. REJECT if over limit"]
Route[Model Router]
PostCount["Post-Response<br/>1. Count tokens<br/>2. Update Redis<br/>3. Emit metrics"]
PreCheck --> Route --> PostCount
end
subgraph LLMs["LLM Providers"]
OpenAI[OpenAI API]
Ollama[Ollama Local]
Azure[Azure OpenAI]
end
subgraph State["State Store"]
Redis[(Redis<br/>Quotas & Counters)]
Postgres[(PostgreSQL<br/>Audit Log)]
end
A1 & A2 & A3 --> Gateway
Route --> OpenAI & Ollama & Azure
PreCheck <--> Redis
PostCount --> Redis
PostCount --> Postgres
style Gateway fill:#FF9800
style Redis fill:#F44336
Why LLM Gateway is Recommended
The gateway pattern addresses our core priorities:
- Zero Agent Code Changes: Agents only need to change
LLM_BASE_URLenvironment variable - True Pre-Request Enforcement: Quota check happens BEFORE tokens are consumed
- Hard Enforcement by Default: Requests are rejected at the gateway, not logged after the fact
- Centralized Policy Management: One place to update quotas, not N agents
Advantages
| Advantage | Description |
|---|---|
| Zero Agent Changes | Only requires changing LLM_BASE_URL env var to point at gateway |
| Pre-Request Blocking | Quota exceeded? Request rejected BEFORE any tokens consumed |
| Hard Enforcement | Gateway rejects requests; agents cannot bypass |
| Centralized Management | Single configuration for all quota policies |
| Built-in Features | Caching (reduce token usage), model routing, fallbacks, retries |
| Multi-Provider Support | OpenAI, Azure, Anthropic, Ollama, 100+ providers via single API |
| Audit Trail | All LLM calls logged centrally for compliance |
Disadvantages
| Disadvantage | Impact | Mitigation |
|---|---|---|
| Additional Infrastructure | New component (LiteLLM Proxy) to deploy and operate | Helm chart available; straightforward K8s deployment |
| Single Point of Failure | Gateway down = no LLM calls | Deploy with replicas + Redis for HA |
| Added Latency | Extra network hop (~10-50ms) | Minimal vs LLM response time (seconds) |
| Dependency on LiteLLM | Tied to open-source project | MIT licensed, active community |
Priority Assessment
| Priority | Requirement | Met? | Notes |
|---|---|---|---|
| P0 | Hard enforcement | YES | Gateway rejects over-quota requests |
| P0 | Minimal agent changes | YES | Only env var change needed |
| P1 | Pre-request blocking | YES | Check happens before LLM call |
| P1 | Namespace-level quotas | YES | Via team/key configuration |
LiteLLM Gateway Features
- Budget/Rate Limit Tiers with per-team/user limits
- Priority-Based Rate Limiting for critical workloads
- Redis-backed multi-instance coordination for horizontal scaling
- Native Kubernetes deployment with ConfigMaps
- Model routing, fallbacks, and caching
Option C: Hybrid Tracing with Selective Sampling
Configure OpenTelemetry to always sample LLM-related spans while applying normal sampling to other traces. This extracts token counts from trace spans for quota tracking.
flowchart TB
subgraph Sampler["TokenAwareSampler Logic"]
direction TB
Check{Span has<br/>gen_ai.* or<br/>llm.* attrs?}
Sample100[ALWAYS SAMPLE<br/>100%]
Sample10[PROBABILISTIC<br/>10% rate]
Check -->|Yes| Sample100
Check -->|No| Sample10
end
subgraph Pipeline["OTEL Pipeline"]
Collector[OTEL Collector]
SpanMetrics[SpanMetricsProcessor<br/>Extract token counts]
end
subgraph Backends["Backends"]
Phoenix[(Phoenix<br/>Full LLM Traces)]
Prometheus[(Prometheus<br/>Token Metrics)]
end
Sample100 & Sample10 --> Collector
Collector --> Phoenix
Collector --> SpanMetrics --> Prometheus
style Sample100 fill:#4CAF50
style Sample10 fill:#FFC107
Advantages
| Advantage | Description |
|---|---|
| Uses Existing Infrastructure | Leverages OTEL Collector and Phoenix already deployed |
| Full Trace Context | LLM debugging benefits from complete request traces |
| OTel Standard Compliant | Follows GenAI semantic conventions |
| No New Components | Just configuration changes to existing OTEL setup |
Disadvantages
| Disadvantage | Impact | Severity |
|---|---|---|
| Requires Agent Code Changes | Must implement custom sampler in each agent | HIGH |
| Complex Sampler Logic | TokenAwareSampler must be correctly implemented and tested | HIGH |
| Async Trace Processing | Traces processed asynchronously; not suitable for real-time enforcement | HIGH |
| Phoenix Not Optimized for Quotas | Phoenix is for debugging, not aggregation; need SpanMetricsProcessor | MEDIUM |
| Storage Overhead | 100% LLM span sampling increases trace storage costs | MEDIUM |
Priority Assessment
| Priority | Requirement | Met? | Notes |
|---|---|---|---|
| P0 | Hard enforcement | NO | Traces are async; cannot block requests |
| P0 | Minimal agent changes | NO | Custom sampler required in each agent |
| P1 | Pre-request blocking | NO | Traces captured after request completes |
| P1 | Namespace-level quotas | Partial | Requires SpanMetricsProcessor + Prometheus |
Comparison Summary
| Criteria | Option A (Metrics) | Option B (Gateway) | Option C (Tracing) |
|---|---|---|---|
| Agent Code Changes | Required (SDK) | None (env var only) | Required (sampler) |
| Pre-Request Blocking | No | Yes | No |
| Hard Enforcement | Partial | Yes | No |
| Infrastructure | Prometheus + Redis + OPA | LiteLLM + Redis | OTEL + Prometheus |
| Latency Impact | None | ~10-50ms | None |
| Implementation Complexity | Medium | Low | High |
Recommended Architecture: LLM Gateway
Based on our design priorities (minimal agent changes + hard enforcement), Option B (LLM Gateway) is the recommended approach.
flowchart TB
subgraph Cluster["Kagenti Cluster"]
subgraph Namespaces["Agent Namespaces"]
T1[team1 agents]
T2[team2 agents]
T3[team3 agents]
end
subgraph Platform["kagenti-system"]
Gateway["LiteLLM Gateway<br/>─────────────────<br/>• Pre-request quota check<br/>• Token counting<br/>• Model routing"]
Redis[(Redis<br/>Quota State)]
Config[ConfigMap<br/>Quota Policies]
end
end
subgraph External["External LLM Providers"]
Ollama[Ollama<br/>Local]
OpenAI[OpenAI<br/>API]
Azure[Azure<br/>OpenAI]
end
T1 & T2 & T3 -->|LLM_BASE_URL| Gateway
Gateway <--> Redis
Config --> Gateway
Gateway --> Ollama & OpenAI & Azure
style Gateway fill:#FF9800
style Redis fill:#F44336
Implementation Phases
flowchart LR
subgraph Phase1["Phase 1: Core Quotas"]
P1A[Deploy LiteLLM Gateway]
P1B[Redis for state]
P1C[Namespace quotas]
P1D[Update agent env vars]
end
subgraph Phase2["Phase 2: Observability"]
P2A[Grafana dashboards]
P2B[AlertManager integration]
P2C[Usage reports]
end
subgraph Phase3["Phase 3: Advanced"]
P3A[User-level quotas]
P3B[Cost attribution]
P3C[Model fallbacks]
P3D[Response caching]
end
Phase1 --> Phase2 --> Phase3
style Phase1 fill:#4CAF50
style Phase2 fill:#2196F3
style Phase3 fill:#9C27B0
Quota Configuration in LiteLLM
Quotas are configured natively in LiteLLM using its team and user management system. This provides immediate enforcement without custom components.
Team Quotas (Namespace-Level)
Each Kubernetes namespace maps to a LiteLLM team. Teams can be configured via:
- LiteLLM config.yaml (static, GitOps-friendly)
- LiteLLM Admin API (dynamic, runtime updates)
- Database seeding (init container or Job)
# LiteLLM team configuration via API or database
# POST /team/new or seed via ConfigMap
teams:
- team_id: "team1"
team_alias: "Team 1 - Production"
max_budget: 50.0 # $50 monthly budget
budget_duration: "monthly" # daily | weekly | monthly
tpm_limit: 1000000 # 1M tokens per minute
rpm_limit: 1000 # 1000 requests per minute
models: # Allowed models
- "gpt-4"
- "gpt-3.5-turbo"
- "llama3.2"
metadata:
namespace: "team1"
cost_center: "engineering"
- team_id: "team2"
team_alias: "Team 2 - Analytics"
max_budget: 25.0
budget_duration: "monthly"
tpm_limit: 500000
rpm_limit: 500
models:
- "gpt-3.5-turbo"
- "llama3.2"
- team_id: "dev"
team_alias: "Development"
max_budget: 10.0
budget_duration: "monthly"
tpm_limit: 100000
rpm_limit: 100
models:
- "llama3.2" # Dev only gets local modelsUser Quotas (Within Teams)
Individual users can have quotas within their team's budget:
# POST /user/new
users:
- user_id: "[email protected]"
teams: ["team1"]
max_budget: 10.0 # $10 of team1's $50 budget
budget_duration: "monthly"
tpm_limit: 100000 # Lower than team limit
rpm_limit: 100
- user_id: "[email protected]"
teams: ["team1"]
max_budget: 5.0
budget_duration: "daily" # Daily reset for this user
- user_id: "[email protected]"
teams: ["team1", "team2", "dev"]
max_budget: null # Unlimited (admin)Authentication Options
LiteLLM supports multiple authentication methods. For Kagenti, we recommend Keycloak JWT authentication since Keycloak is already deployed.
Option 1: Keycloak JWT Authentication (Recommended)
Since Kagenti already uses Keycloak, agents can authenticate to the LLM Gateway using JWT tokens from Keycloak. This eliminates the need for separate API keys.
# litellm-config.yaml - Keycloak JWT integration
general_settings:
master_key: "os.environ/LITELLM_MASTER_KEY"
enable_jwt_auth: true
litellm_settings:
jwt_public_key_url: "http://keycloak.keycloak.svc.cluster.local:8080/realms/master/protocol/openid-connect/certs"
# Map Keycloak JWT fields to LiteLLM
user_id_jwt_field: "sub" # Keycloak user ID
user_email_jwt_field: "email" # User email
team_id_jwt_field: "namespace" # Custom claim for K8s namespace
# Auto-create users from JWT (no pre-registration needed)
user_id_upsert: true
# Map Keycloak roles to LiteLLM roles
roles_jwt_field: "realm_access.roles"
role_mappings:
- jwt_role: "kagenti-admin"
litellm_role: "proxy_admin"
- jwt_role: "kagenti-user"
litellm_role: "internal_user"
# OIDC UserInfo for additional claims (optional)
oidc_userinfo_enabled: true
oidc_userinfo_endpoint: "http://keycloak.keycloak.svc.cluster.local:8080/realms/master/protocol/openid-connect/userinfo"Agent configuration with Keycloak JWT:
# Agent deployment - uses Keycloak token
env:
- name: LLM_BASE_URL
value: "http://llm-gateway.kagenti-system.svc.cluster.local:4000"
- name: LLM_API_KEY
valueFrom:
secretKeyRef:
name: agent-keycloak-token
key: access_token # JWT from KeycloakHow it works:
sequenceDiagram
participant Agent
participant Keycloak
participant LLMGateway as LLM Gateway
participant LLM as Ollama/OpenAI
Agent->>Keycloak: Authenticate (client credentials)
Keycloak-->>Agent: JWT access token
Agent->>LLMGateway: POST /chat/completions<br/>Authorization: Bearer {JWT}
LLMGateway->>Keycloak: Validate JWT (via JWKS)
Keycloak-->>LLMGateway: JWT valid, claims
LLMGateway->>LLMGateway: Extract team from JWT<br/>Check quota
alt Quota OK
LLMGateway->>LLM: Forward request
LLM-->>LLMGateway: Response
LLMGateway->>LLMGateway: Count tokens, update quota
LLMGateway-->>Agent: Response
else Quota Exceeded
LLMGateway-->>Agent: 400 Budget exceeded
end
Keycloak client configuration:
{
"clientId": "llm-gateway",
"enabled": true,
"protocol": "openid-connect",
"publicClient": false,
"serviceAccountsEnabled": true,
"authorizationServicesEnabled": false,
"standardFlowEnabled": false,
"directAccessGrantsEnabled": true,
"attributes": {
"namespace": "${user.attributes.namespace}"
},
"protocolMappers": [
{
"name": "namespace-mapper",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-attribute-mapper",
"config": {
"claim.name": "namespace",
"user.attribute": "namespace",
"id.token.claim": "true",
"access.token.claim": "true"
}
}
]
}Option 2: Static API Keys (Simple)
For simpler deployments or service accounts, use static API keys:
# POST /key/generate
keys:
- key_alias: "team1-agents"
team_id: "team1"
# Key inherits team's budget/limits
# Returns: sk-team1-xxxxxxxxxxxx
- key_alias: "alice-personal"
user_id: "[email protected]"
# Key inherits user's budget/limits
# Returns: sk-alice-xxxxxxxxxxxxKubernetes Secret for Team Keys
apiVersion: v1
kind: Secret
metadata:
name: llm-gateway-keys
namespace: team1
type: Opaque
stringData:
api-key: "sk-team1-xxxxxxxxxxxx" # Generated by LiteLLMMapping Namespaces to Teams via Keycloak
With Keycloak JWT auth, the namespace→team mapping happens automatically:
- User signs into Keycloak with their team/namespace as a user attribute
- JWT contains
namespaceclaim (via protocol mapper) - LiteLLM extracts team from JWT using
team_id_jwt_field: "namespace" - Quota is enforced per team based on the JWT claim
This means:
- No manual team/key management in LiteLLM
- Users automatically get their namespace's quota
- Central identity management in Keycloak
Model-Level Cost Configuration
LiteLLM tracks costs per model automatically, but custom costs can be set:
# In litellm config.yaml
model_list:
- model_name: "gpt-4"
litellm_params:
model: "gpt-4"
model_info:
input_cost_per_token: 0.00003 # $30/1M tokens
output_cost_per_token: 0.00006 # $60/1M tokens
- model_name: "llama3.2"
litellm_params:
model: "ollama/llama3.2"
api_base: "http://ollama:11434"
model_info:
input_cost_per_token: 0.0 # Free (local)
output_cost_per_token: 0.0Future: Kagenti CRD for Quota Sync
For GitOps workflows, a future Kagenti controller could sync CRDs to LiteLLM:
apiVersion: kagenti.io/v1alpha1
kind: TeamQuota
metadata:
name: team1-quota
namespace: kagenti-system
spec:
teamId: "team1"
namespace: "team1" # K8s namespace to map
budget:
amount: 50.0
duration: monthly
limits:
tpm: 1000000
rpm: 1000
allowedModels:
- "gpt-4"
- "llama3.2"
status:
synced: true
lastSyncTime: "2025-12-04T10:30:00Z"
currentSpend: 23.45
budgetRemaining: 26.55The controller would watch TeamQuota resources and call LiteLLM's /team/update API.
Implementation Details
Redis Key Structure
Using sliding window rate limiting pattern:
# Namespace quotas
tokens:ns:{namespace}:daily:{YYYY-MM-DD} → counter with 2-day TTL
tokens:ns:{namespace}:weekly:{YYYY-Www} → counter with 14-day TTL
tokens:ns:{namespace}:monthly:{YYYY-MM} → counter with 60-day TTL
# User quotas (optional)
tokens:user:{user_id}:daily:{YYYY-MM-DD} → counter with 2-day TTL
# Agent quotas (optional)
tokens:agent:{agent_name}:ns:{ns}:daily:{YYYY-MM-DD} → counter
# Examples:
tokens:ns:team1:daily:2025-12-04 → 847293
tokens:ns:team1:weekly:2025-W49 → 3421847
tokens:ns:team1:monthly:2025-12 → 12847293
tokens:user:john.doe:daily:2025-12-04 → 52847
Prometheus Recording Rules
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: kagenti-quota-rules
namespace: istio-system
spec:
groups:
- name: kagenti.token.quotas
interval: 30s
rules:
# Namespace daily token usage
- record: kagenti:namespace_tokens:daily
expr: |
sum by (namespace) (
increase(gen_ai_client_token_usage_total[24h])
)
# Namespace weekly token usage
- record: kagenti:namespace_tokens:weekly
expr: |
sum by (namespace) (
increase(gen_ai_client_token_usage_total[7d])
)
# Namespace monthly token usage
- record: kagenti:namespace_tokens:monthly
expr: |
sum by (namespace) (
increase(gen_ai_client_token_usage_total[30d])
)
# Usage ratio for alerting
- record: kagenti:namespace_quota_usage_ratio:daily
expr: |
kagenti:namespace_tokens:daily
/ on(namespace) group_left
kagenti:namespace_quota_limit:dailyLiteLLM Gateway Configuration
# kagenti/installer/app/resources/litellm-config.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: litellm-config
namespace: kagenti-system
data:
config.yaml: |
model_list:
# Ollama local models
- model_name: "llama3.2"
litellm_params:
model: "ollama/llama3.2"
api_base: "http://ollama.kagenti-system:11434"
- model_name: "qwen2.5:0.5b"
litellm_params:
model: "ollama/qwen2.5:0.5b"
api_base: "http://ollama.kagenti-system:11434"
# OpenAI (if configured)
- model_name: "gpt-4"
litellm_params:
model: "gpt-4"
api_key: "os.environ/OPENAI_API_KEY"
general_settings:
master_key: "os.environ/LITELLM_MASTER_KEY"
database_url: "os.environ/DATABASE_URL" # PostgreSQL for persistent state
router_settings:
redis_host: "redis.kagenti-system"
redis_port: 6379
# Enable multi-instance rate limiting
enable_pre_call_check: true
litellm_settings:
# Emit Prometheus metrics
success_callback: ["prometheus"]
failure_callback: ["prometheus"]
# Default rate limits (can be overridden per team)
max_budget: 100 # $100 default monthly budget
budget_duration: "monthly"LiteLLM Team/Namespace Quota Configuration
Teams (namespaces) are configured via LiteLLM's /team/new API or ConfigMap:
# kagenti/installer/app/resources/litellm-teams.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: litellm-teams
namespace: kagenti-system
data:
teams.json: |
[
{
"team_id": "team1",
"team_alias": "team1",
"max_budget": 50.0,
"budget_duration": "monthly",
"tpm_limit": 1000000,
"rpm_limit": 1000,
"models": ["llama3.2", "qwen2.5:0.5b", "gpt-4"]
},
{
"team_id": "team2",
"team_alias": "team2",
"max_budget": 25.0,
"budget_duration": "monthly",
"tpm_limit": 500000,
"rpm_limit": 500,
"models": ["llama3.2", "qwen2.5:0.5b"]
},
{
"team_id": "dev",
"team_alias": "dev",
"max_budget": 10.0,
"budget_duration": "monthly",
"tpm_limit": 100000,
"rpm_limit": 100,
"models": ["qwen2.5:0.5b"]
}
]LiteLLM Gateway Deployment
# kagenti/installer/app/resources/litellm-gateway.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: llm-gateway
namespace: kagenti-system
spec:
replicas: 2 # HA setup
selector:
matchLabels:
app: llm-gateway
template:
metadata:
labels:
app: llm-gateway
spec:
containers:
- name: litellm
image: ghcr.io/berriai/litellm:main-latest
ports:
- containerPort: 4000
env:
- name: LITELLM_MASTER_KEY
valueFrom:
secretKeyRef:
name: litellm-secrets
key: master-key
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: litellm-secrets
key: database-url
- name: REDIS_HOST
value: "redis.kagenti-system"
volumeMounts:
- name: config
mountPath: /app/config.yaml
subPath: config.yaml
volumes:
- name: config
configMap:
name: litellm-config
---
apiVersion: v1
kind: Service
metadata:
name: llm-gateway
namespace: kagenti-system
spec:
selector:
app: llm-gateway
ports:
- port: 4000
targetPort: 4000
type: ClusterIPComparison with Industry Solutions
| Feature | Kagenti + LiteLLM | Azure API Mgmt | Portkey | Helicone |
|---|---|---|---|---|
| Namespace/Team quotas | Yes (LiteLLM teams) | Via subscription | Via org | Via API key |
| User quotas | Yes (LiteLLM users) | Yes | Yes | Yes |
| Per-request limits | Yes (tpm_limit, rpm_limit) | Yes | Yes | Yes |
| Time windows | Monthly (extensible) | Per-minute/Period | Monthly | Monthly |
| Enforcement | Pre-request (gateway) | Pre-request | Pre-request | Pre-request |
| Open Source | Yes (MIT) | No | No | Yes |
| K8s Native | Yes (Helm/YAML) | No | No | Partial |
| Cost tracking | Built-in | Built-in | Built-in | Built-in |
| Model routing | Yes | No | Yes | No |
| Caching | Yes | No | Yes | Yes |
| Multi-provider | 100+ providers | Azure only | 250+ | Many |
Open Questions
Q1: Calendar vs Rolling Windows?
Calendar Windows (midnight reset):
- Pros: Clear reset time, easier to explain to users
- Cons: Can spike at period boundaries
Rolling Windows (last 24h):
- Pros: Smoother rate limiting
- Cons: Users don't know when quota resets
Recommendation: LiteLLM uses calendar-based budget_duration (daily/weekly/monthly) by default, which aligns with FinOps billing cycles.
Q2: What HTTP status for quota exceeded?
LiteLLM follows Azure's pattern:
429 Too Many Requests- Rate limit (RPM/TPM) exceeded400 Bad Requestwith{"error": "Budget exceeded"}- Budget quota exceeded
Q3: How to map Kubernetes namespaces to LiteLLM teams?
Options:
- Manual mapping: Admin creates LiteLLM team per namespace
- Automatic sync: Controller watches namespaces, creates teams
- Convention-based: Team ID = namespace name
Recommendation: Start with convention-based (team_id = namespace), add controller later for dynamic namespaces.
Q4: How do agents authenticate to the gateway?
Options:
- Team API keys: Each namespace gets a team-specific key via Secret
- Service account tokens: Use K8s OIDC tokens for auth
- mTLS via Istio: Gateway trusts mesh identity
Recommendation: Team API keys for MVP (simple), consider mTLS for production.
Q5: What about Ollama (free) vs paid APIs?
Token costs vary dramatically:
- Ollama local: $0/token
- GPT-4: ~$30/1M tokens
- GPT-3.5: ~$0.50/1M tokens
Recommendation: Track token counts for all models. Apply cost multipliers for budgeting. LiteLLM supports this via model_info.input_cost_per_token.
Acceptance Criteria
- LLM Gateway (LiteLLM Proxy) deployed in
kagenti-system - Redis deployed for quota state persistence
- Team quotas configurable via ConfigMap (MVP)
- Agents use gateway via
LLM_BASE_URLenvironment variable - Pre-request quota check rejects over-limit requests
- Rejected requests return clear error message with quota info
- Prometheus metrics exported for usage dashboards
- Grafana dashboard shows team usage vs quotas
- AlertManager fires at 80% and 100% thresholds
- New
llm_gatewaycomponent in Kagenti installer - E2E test validates quota enforcement
- Documentation for quota configuration
References
LiteLLM Documentation
- LiteLLM Budget/Rate Limits - Team and user quota configuration
- LiteLLM Rate Limit Tiers - Priority-based rate limiting
- LiteLLM JWT/OIDC Auth - Keycloak JWT authentication
- LiteLLM JWT Auth Architecture - Role mapping and team extraction
- LiteLLM Proxy Configuration - Complete config reference
- LiteLLM Kubernetes Deployment - Production deployment guide
Industry Standards & Comparisons
- OpenTelemetry GenAI Metrics Spec - Token counting standards
- Azure API Management llm-token-limit - Enterprise pattern
- Helicone LLM Gateway Comparison 2025 - Gateway comparison
- LLMs in Production 2025 Report - Industry benchmarks
FinOps & Cost Management
- FinOps for AI Overview - AI cost management practices
- Kubernetes Resource Quotas - K8s native quotas
Technical References
- Redis Rate Limiting Patterns - Sliding window algorithms
Demo Steps
TBD: showing the quotas in action with agents
Stories
- TBD: showing the quotas in action with agents
Metadata
Metadata
Assignees
Type
Projects
- StatusShow more project fieldsDone
Activity
pdettori commentedon Dec 4, 2025
@Ladas this looks great, I can definitely see the need for tokens quota in organization as they start deploying agents in shared clusters.
On
Integration with Kagenti Installer- this section relies on the legacy python installer which we will be deprecating soon - I think we should target helm charts + the new ansible-based installer - we could add a new helm chart to deploy what is needed for the LiteLLM deployment and configurationLadas commentedon Dec 5, 2025
ok, removed the installer section for now (will add the ansible-installer part if we'll decide to do this short-term)
mrsabath commentedon Feb 16, 2026
@Ladas should we consider this proposal?
Ladas commentedon Feb 16, 2026
@mrsabath I think there are more ideas flowing around, but if we'll want to deploy agents to do something, we need to have some kind of llm proxy that can control token budget. (otherwise some agents could be consuming a lot of tokens by accident)
So I would still keep this, until we have replacement? (and we could try quick LiteLLM deployment when we need it?)
github-actions commentedon Apr 25, 2026
This issue has been automatically marked as stale because it has not had recent activity. It will be closed in 14 days if no further activity occurs. If this issue is still relevant, please comment or remove the stale label.
kinthaiofficial commentedon Apr 28, 2026
This epic addresses the right problem. Namespace-level quotas are essential for multi-tenant agent deployments. From implementing similar cost governance:
Three-level quota hierarchy is necessary: namespace → user → agent. Namespace-level alone is insufficient because one user's runaway agent can consume the entire namespace quota, blocking other users. And user-level alone misses the case where a user has 10 agents, one of which consumes 90% of the budget. We enforce all three levels simultaneously, with the most restrictive applying at each operation.
Per-hour caps matter more than daily/weekly/monthly. A monthly quota of 10M tokens does not prevent a cost spike. An agent can consume the entire monthly quota in 2 hours if it hits a retry loop or generates verbose outputs. We enforce:
The per-hour ceiling is the most operationally important because it catches problems before they become expensive.
Quota enforcement must happen before the LLM call, not after. If the quota check happens after the response is received, the tokens are already consumed and billed. We estimate cost before each call using a simple
estimated_tokens = input_token_count + expected_output_tokens(where expected_output is based on the model's average output length for similar prompts). If the estimate would exceed the remaining budget, the call is blocked before it reaches the LLM.On the runaway agent problem: the most dangerous pattern is an agent that retries failed calls in a loop. Each retry consumes tokens, and the failures often repeat, creating unbounded token drain. We enforce a "retry budget" per task: maximum 3 retries, after which the agent must escalate to a human rather than keep trying.
We documented the per-agent cost enforcement and multi-agent budget governance at https://blog.kinthai.ai/221-agents-multi-agent-coordination-lessons
desiorac commentedon Apr 30, 2026
The LiteLLM gateway approach covers the P0 requirements well. Worth adding to open questions: does this epic need audit-grade billing records, or just showback dashboards?
PostgreSQL stores consumption but is mutable - any DBA can backfill rows. For enterprise chargeback where teams dispute bills, the gateway should emit per-request receipts that are tamper-evident: namespace + token count + model + timestamp, chained so retroactive edits are detectable.
If chargeback is in scope, the acceptance criteria should distinguish "audit log" (mutable, debugging) from "billing record" (append-only, cryptographically chained). Cloud provider billing works this way already.
desiorac commentedon Apr 30, 2026
The pre-commitment model addresses the mutable-record problem cleanly. The locked commitment predates the work, so the audit record is independent of whatever the gateway logs later.
Two questions on the mechanics: (1) What happens when the agent needs to extend the ceiling mid-task? LLM output variance can be 10x the input estimate, so blocking at a declared ceiling will generate false positives on any task with variable-length generation. (2) Is the commitment scoped to a single task, or does it aggregate across concurrent runs from the same agent?
The separation of enforcement from audit is the right framing. Whether enforcement lives at the gateway or agent level depends on which party you are willing to trust at execution time.
github-actions commentedon Jul 22, 2026
This issue has been automatically marked as stale because it has not had recent activity. It will be closed in 14 days if no further activity occurs. If this issue is still relevant, please comment or remove the stale label.
github-actions commentedon Aug 5, 2026
This issue was closed because it has been stale for 14 days with no activity. Feel free to reopen if this is still relevant.