# dhananjaylab/llm-gateway architecture

> Architecture diagram of the GitHub repository dhananjaylab/llm-gateway, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-08-21). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/dhananjaylab/llm-gateway
- Repository: https://github.com/dhananjaylab/llm-gateway

## Overview

#### Purpose and Entry Points
This is a FastAPI LLM gateway that exposes one OpenAI-style chat API over OpenAI, Anthropic, Ollama, and Gemini. It applies team policy, quotas, budget enforcement, provider routing/fallback, and observability before returning normalized or streamed responses.

Primary runtime entry point: `app/main.py`. Public and administrative surfaces are in `app/api/v1_chat.py` and `app/api/admin.py`.

#### Application Composition and Startup
`app/main.py` builds the FastAPI app, initializes Redis-backed state, provider registry, metrics/tracing, and lifespan bootstrapping for team configuration. It serves health/readiness and Prometheus metrics alongside API routes.

Settings and bootstrap configuration are centralized in `app/core/config.py`; static policy inputs come from `config/teams.yaml`, `config/tiers.yaml`, and `config/pricing.yaml`. Runtime mutations are persisted through the Redis-backed team store in `app/core/team_store.py`.

#### Request Admission and Policy Boundary
Chat requests enter `app/api/v1_chat.py`, where the gateway authenticates `X-Gateway-API-Key`, resolves a team, normalizes the request schema, and applies policy before provider execution.

Core controls include API-key authentication (`app/core/auth.py`), system-prompt/PII policy (`app/core/policy.py`), and audit logging for administrative changes (`app/core/audit.py`). The boundary is deliberate: clients see a unified schema (`app/core/schema.py`), while provider-specific requests remain internal.

#### Quotas, Cost, and Redis Atomicity
Rate and token limits, request priority, and dollar budgets are Redis-backed and use Lua scripts for atomic checks/updates. This prevents concurrency races across gateway instances.

Key stages: combined quota checking in `app/ratelimit/combined.py`, token/RPM/TPM controls in `app/ratelimit/limiter.py`, and budget reservation/reconciliation in `app/ratelimit/budget.py`. Atomic operations are implemented in scripts such as `app/ratelimit/combined_check.lua` and `app/ratelimit/budget_increment.lua`. Pricing calculation uses `app/core/pricing.py` with `config/pricing.yaml`.

#### Provider Abstraction and Routing
Provider adapters implement distinct upstream wire protocols behind a common interface. `app/providers/registry.py` resolves literal `provider:model` targets or tier chains; adapters in `app/providers/openai_adapter.py`, `app/providers/anthropic_adapter.py`, and `app/providers/gemini_adapter.py` translate request, response, error, and streaming formats.

Tier definitions in `config/tiers.yaml` permit policy-controlled model selection and fallback without exposing vendor protocol differences to callers.

#### Resilience Execution Path
The fallback router executes a resolved provider chain, classifies retryable provider failures, retries with backoff, and records circuit state. It supports both standard completion and streaming paths, including fallback before streaming output is committed.

Core implementation: `app/resilience/fallback.py`, `app/resilience/retry.py`, and Redis/Lua-backed circuit logic in `app/resilience/circuit_breaker.py`. Active/passive provider health assessment is in `app/resilience/health.py`.

#### Observability and Operating Stack
Each request and provider attempt is instrumented with OpenTelemetry spans and Prometheus metrics. Per-app instrumentation avoids process-global state, supporting repeated app construction in tests and embedded usage.

Metrics/tracing implementations are `app/observability/metrics.py` and `app/observability/tracing.py`. The containerized operating stack in `docker-compose.yml` includes Redis, Prometheus, Grafana, Alertmanager, and Jaeger; Jaeger v2 receives OTLP via `deploy/jaeger/config.yaml`.

#### Deterministic Demo, Integration, and Load Boundary
The default deployment routes adapters to a wire-compatible mock-provider service rather than vendor APIs. `deploy/mock-providers/main.py` implements provider-shaped endpoints, while `deploy/mock-providers/chaos.py` exposes live outage/latency injection used to exercise retries, fallback, and circuit behavior.

The gateway image is defined in `Dockerfile`; stack orchestration is `docker-compose.yml`. `loadtest/k6_gateway_stress.js` compares direct mock-provider latency with gateway latency and injects a mid-run provider outage.

Main entry points: [`app/api/v1_chat.py`](https://github.com/dhananjaylab/llm-gateway/blob/main/app/api/v1_chat.py) (Chat API), [`app/main.py`](https://github.com/dhananjaylab/llm-gateway/blob/main/app/main.py) (FastAPI app), [`app/resilience/fallback.py`](https://github.com/dhananjaylab/llm-gateway/blob/main/app/resilience/fallback.py) (Fallback router), [`app/core/team_store.py`](https://github.com/dhananjaylab/llm-gateway/blob/main/app/core/team_store.py) (Team store)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_api["Gateway API"]
  node_main["FastAPI app<br/>[main.py]"]
  node_chat_api["Chat API<br/>HTTP handler<br/>[v1_chat.py]"]
  node_admin_api["Admin API<br/>HTTP handler<br/>[admin.py]"]
  node_schema["Unified schema<br/>request schema<br/>[schema.py]"]
end

subgraph group_control["Policy &amp; State"]
  node_config["Settings &amp; static config<br/>configuration<br/>[config.py]"]
  node_team_store[("Team store<br/>team state<br/>[team_store.py]")]
  node_auth_policy["Auth &amp; policy<br/>admission controls<br/>[auth.py]"]
  node_redis[("Redis<br/>state backend")]
  node_quota_budget["Quota &amp; budget control<br/>rate limiting<br/>[combined.py]"]
  node_pricing["Pricing calculator<br/>cost calculation<br/>[pricing.py]"]
end

subgraph group_execution["Routing &amp; Resilience"]
  node_registry["Provider registry<br/>target resolution<br/>[registry.py]"]
  node_fallback["Fallback router<br/>execution router<br/>[fallback.py]"]
  node_retry["Retry &amp; backoff<br/>resilience policy<br/>[retry.py]"]
  node_circuit["Circuit breaker<br/>resilience state<br/>[circuit_breaker.py]"]
end

subgraph group_providers["Provider Boundary"]
  node_adapters["Provider adapters<br/>protocol adapters<br/>[openai_adapter.py]"]
  node_mock_providers["Mock providers<br/>upstream service<br/>[main.py]"]
end

subgraph group_operations["Operating Stack"]
  node_observability["Metrics &amp; tracing<br/>instrumentation<br/>[metrics.py]"]
  node_compose{{"Operations stack<br/>container stack<br/>[docker-compose.yml]"}}
end

node_main -->|"mounts"| node_chat_api
node_main -->|"mounts"| node_admin_api
node_main -->|"loads"| node_config
node_main -->|"bootstraps"| node_team_store
node_main -->|"initializes"| node_observability
node_chat_api -->|"normalizes"| node_schema
node_chat_api -->|"authenticates and checks"| node_auth_policy
node_chat_api -->|"admits request"| node_quota_budget
node_chat_api -->|"resolves target"| node_registry
node_admin_api -->|"mutates teams"| node_team_store
node_config -->|"seeds configuration"| node_team_store
node_team_store -->|"persists in"| node_redis
node_quota_budget -->|"atomic Lua state"| node_redis
node_quota_budget -->|"calculates spend"| node_pricing
node_registry -->|"provider chain"| node_fallback
node_fallback -->|"retryable failures"| node_retry
node_fallback -->|"checks circuit"| node_circuit
node_circuit -->|"stores circuit state"| node_redis
node_fallback -->|"dispatches attempts"| node_adapters
node_adapters -->|"provider protocols"| node_mock_providers
node_chat_api -.->|"request telemetry"| node_observability
node_fallback -.->|"attempt telemetry"| node_observability
node_compose -->|"runs"| node_redis
node_compose -->|"scrapes and exports"| node_observability

click node_main "https://github.com/dhananjaylab/llm-gateway/blob/main/app/main.py"
click node_chat_api "https://github.com/dhananjaylab/llm-gateway/blob/main/app/api/v1_chat.py"
click node_admin_api "https://github.com/dhananjaylab/llm-gateway/blob/main/app/api/admin.py"
click node_schema "https://github.com/dhananjaylab/llm-gateway/blob/main/app/core/schema.py"
click node_config "https://github.com/dhananjaylab/llm-gateway/blob/main/app/core/config.py"
click node_team_store "https://github.com/dhananjaylab/llm-gateway/blob/main/app/core/team_store.py"
click node_auth_policy "https://github.com/dhananjaylab/llm-gateway/blob/main/app/core/auth.py"
click node_quota_budget "https://github.com/dhananjaylab/llm-gateway/blob/main/app/ratelimit/combined.py"
click node_pricing "https://github.com/dhananjaylab/llm-gateway/blob/main/app/core/pricing.py"
click node_registry "https://github.com/dhananjaylab/llm-gateway/blob/main/app/providers/registry.py"
click node_fallback "https://github.com/dhananjaylab/llm-gateway/blob/main/app/resilience/fallback.py"
click node_retry "https://github.com/dhananjaylab/llm-gateway/blob/main/app/resilience/retry.py"
click node_circuit "https://github.com/dhananjaylab/llm-gateway/blob/main/app/resilience/circuit_breaker.py"
click node_adapters "https://github.com/dhananjaylab/llm-gateway/blob/main/app/providers/openai_adapter.py"
click node_mock_providers "https://github.com/dhananjaylab/llm-gateway/blob/main/deploy/mock-providers/main.py"
click node_observability "https://github.com/dhananjaylab/llm-gateway/blob/main/app/observability/metrics.py"
click node_compose "https://github.com/dhananjaylab/llm-gateway/blob/main/docker-compose.yml"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_main,node_chat_api,node_admin_api,node_schema toneBlue
class node_config,node_team_store,node_auth_policy,node_redis,node_quota_budget,node_pricing toneAmber
class node_registry,node_fallback,node_retry,node_circuit toneMint
class node_adapters,node_mock_providers toneRose
class node_observability,node_compose toneIndigo
```

## Components

### Gateway API

- [FastAPI app](https://github.com/dhananjaylab/llm-gateway/blob/main/app/main.py): application · Builds the gateway and owns lifespan startup. · `app/main.py`
- [Chat API](https://github.com/dhananjaylab/llm-gateway/blob/main/app/api/v1_chat.py): HTTP handler · OpenAI-style chat completion entry point. · `app/api/v1_chat.py`
- [Admin API](https://github.com/dhananjaylab/llm-gateway/blob/main/app/api/admin.py): HTTP handler · Administrative configuration surface. · `app/api/admin.py`
- [Unified schema](https://github.com/dhananjaylab/llm-gateway/blob/main/app/core/schema.py): request schema · Client-facing normalized request and response contract. · `app/core/schema.py`

### Policy & State

- [Settings & static config](https://github.com/dhananjaylab/llm-gateway/blob/main/app/core/config.py): configuration · Loads team, tier, and pricing policy inputs. · `app/core/config.py`
- [Team store](https://github.com/dhananjaylab/llm-gateway/blob/main/app/core/team_store.py): team state · Persists runtime team mutations in Redis. · `app/core/team_store.py`
- [Auth & policy](https://github.com/dhananjaylab/llm-gateway/blob/main/app/core/auth.py): admission controls · Authenticates keys and enforces prompt and PII rules. · `app/core/auth.py`
- **Redis**: state backend · Shared state for teams, limits, budgets, and circuits.
- [Quota & budget control](https://github.com/dhananjaylab/llm-gateway/blob/main/app/ratelimit/combined.py): rate limiting · Atomically checks limits and reserves or reconciles spend. · `app/ratelimit/combined.py`
- [Pricing calculator](https://github.com/dhananjaylab/llm-gateway/blob/main/app/core/pricing.py): cost calculation · Calculates model usage cost from pricing policy. · `app/core/pricing.py`

### Routing & Resilience

- [Provider registry](https://github.com/dhananjaylab/llm-gateway/blob/main/app/providers/registry.py): target resolution · Resolves explicit provider models or tier chains. · `app/providers/registry.py`
- [Fallback router](https://github.com/dhananjaylab/llm-gateway/blob/main/app/resilience/fallback.py): execution router · Executes provider chains for standard and streaming completions. · `app/resilience/fallback.py`
- [Retry & backoff](https://github.com/dhananjaylab/llm-gateway/blob/main/app/resilience/retry.py): resilience policy · Classifies retryable failures and schedules retries. · `app/resilience/retry.py`
- [Circuit breaker](https://github.com/dhananjaylab/llm-gateway/blob/main/app/resilience/circuit_breaker.py): resilience state · Uses Redis-backed circuit state to isolate unhealthy providers. · `app/resilience/circuit_breaker.py`

### Provider Boundary

- [Provider adapters](https://github.com/dhananjaylab/llm-gateway/blob/main/app/providers/openai_adapter.py): protocol adapters · Translates OpenAI, Anthropic, Gemini, and Ollama protocols. · `app/providers/openai_adapter.py`
- [Mock providers](https://github.com/dhananjaylab/llm-gateway/blob/main/deploy/mock-providers/main.py): upstream service · Wire-compatible default upstream with chaos injection. · `deploy/mock-providers/main.py`

### Operating Stack

- [Metrics & tracing](https://github.com/dhananjaylab/llm-gateway/blob/main/app/observability/metrics.py): instrumentation · Per-app Prometheus metrics and OpenTelemetry spans. · `app/observability/metrics.py`
- [Operations stack](https://github.com/dhananjaylab/llm-gateway/blob/main/docker-compose.yml): container stack · Runs Redis, Prometheus, Grafana, Alertmanager, and Jaeger. · `docker-compose.yml`

## Connections

- FastAPI app → Chat API: mounts
- FastAPI app → Admin API: mounts
- FastAPI app → Settings & static config: loads
- FastAPI app → Team store: bootstraps
- FastAPI app → Metrics & tracing: initializes
- Chat API → Unified schema: normalizes
- Chat API → Auth & policy: authenticates and checks
- Chat API → Quota & budget control: admits request
- Chat API → Provider registry: resolves target
- Admin API → Team store: mutates teams
- Settings & static config → Team store: seeds configuration
- Team store → Redis: persists in
- Quota & budget control → Redis: atomic Lua state
- Quota & budget control → Pricing calculator: calculates spend
- Provider registry → Fallback router: provider chain
- Fallback router → Retry & backoff: retryable failures
- Fallback router → Circuit breaker: checks circuit
- Circuit breaker → Redis: stores circuit state
- Fallback router → Provider adapters: dispatches attempts
- Provider adapters → Mock providers: provider protocols
- Chat API → Metrics & tracing: request telemetry
- Fallback router → Metrics & tracing: attempt telemetry
- Operations stack → Redis: runs
- Operations stack → Metrics & tracing: scrapes and exports
