# nithinvikas-av/llm_gateway architecture

> Architecture diagram of the GitHub repository nithinvikas-av/llm_gateway, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-05-28). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/nithinvikas-av/llm_gateway
- Repository: https://github.com/nithinvikas-av/llm_gateway

## Overview

1. **System shape**
   - This repo is a 4-part LLM gateway: a React frontend, a FastAPI backend, PostgreSQL for persistent data, and Redis for short-lived rate-limit counters.
   - `docker-compose.yml` is the local integration boundary; it runs all four services together.

2. **Frontend boundary**
   - The UI lives under `frontend/src` and is organized by page and shared component layers.
   - Entry flow starts at `frontend/src/main.jsx` → `App.jsx`, with routes for login, dashboard, keys, users, and a playground.
   - The frontend does not hold business logic; it mainly calls backend APIs through `frontend/src/api/*` and stores auth state in `frontend/src/store/authStore.js`.

3. **Authentication flow**
   - Google OAuth is the first trust boundary: `backend/app/api/auth.py` handles login and callback.
   - After OAuth, the backend issues a JWT; the frontend uses that token for subsequent protected requests.
   - Authorization is role-based (`admin` vs `employee`) and enforced in backend dependencies, not in the UI alone.

4. **Backend API surface**
   - Route handlers are split by concern in `backend/app/api/`: `auth.py`, `keys.py`, `gateway.py`, `users.py`, and `usage.py`.
   - These routes are thin controllers; they delegate real work to services under `backend/app/services/`.
   - `backend/main.py` is the FastAPI entry point and likely wires the routers, middleware, and docs exposure.

5. **Business logic layer**
   - `key_service.py` manages provider key storage/retrieval and encryption concerns.
   - `gateway_service.py` is the request proxy to external LLM providers and is the main enforcement point for gateway policy.
   - `rate_limiter.py` uses Redis to enforce per-key/request quotas.
   - `usage_service.py` records token, request, and cost usage for analytics and billing-style reporting.

6. **Persistence model**
   - SQLAlchemy models in `backend/app/models/` define the persistent domain:
     - `user.py`
     - `provider_key.py`
     - `universal_key.py`
     - `key_permission.py`
     - `usage_log.py`
   - Alembic migrations under `backend/alembic/versions/` control schema evolution; the project expects migrations to create and update the tables.

7. **Data ownership and key management**
   - Provider API keys are stored per user per provider in `provider_keys`; the raw secret is never stored, only encrypted material plus IV.
   - `universal_keys` are the keys employees use to access the gateway; they map back to the owning user and are indexed by hash for lookup.
   - `key_permissions` attaches per-universal-key policy such as allowed models, RPM, token budget, and cost caps.

8. **Gateway request flow**
   - A client request enters the frontend or direct API, authenticates with a JWT, then reaches `backend/app/api/gateway.py`.
   - The gateway checks permissions and rate limits, resolves the caller’s universal key, fetches the owning provider credential, and forwards the request to the selected LLM provider.
   - The response path also feeds usage accounting so every call becomes an auditable record.

9. **Redis and quota enforcement**
   - Redis is a non-persistent control plane used for counters and rate-limit state.
   - This keeps quota checks fast and separate from the durable PostgreSQL audit trail.
   - The architecture therefore splits “enforcement now” in Redis from “record forever” in PostgreSQL.

10. **Security and cryptography**
   - `backend/app/core/security.py` centralizes JWT creation/verification and symmetric encryption/decryption for stored provider keys.
   - `backend/app/core/dependencies.py` is the enforcement layer for authenticated user context and admin-only access.
   - `backend/app/core/config.py` and `backend/app/core/redis_client.py` externalize secrets and infra connections from business code.

11. **Reporting and auditability**
   - `usage_logs` is append-only by design and is the source of truth for auditing, analytics, and cost tracking.
   - The dashboard and usage endpoints read from this history rather than from transient runtime state.
   - This makes the system suitable for both operational monitoring and governance.

12. **Deployment and delivery**
   - Each tier has its own Dockerfile, and `docker-compose.yml` is the local orchestration layer.
   - `.github/workflows/deploy.yml` and `railway.toml` indicate deployment automation to Railway-style infrastructure.
   - `backend/.env example` and the root README show that secrets, OAuth credentials, DB URLs, and Redis settings are expected as environment configuration, not code.

13. **Notable repo-specific boundary**
   - The repo is intentionally split between UI, API, persistence, and policy enforcement; the gateway service is the central integration point where auth, RBAC, quotas, encryption, and provider proxying all meet.
   - `Universal_Chat.py` and `secret-key.py` appear to be auxiliary/top-level scripts rather than core runtime surfaces, so they are not part of the primary application architecture.

Main entry points: [`backend/main.py`](https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/main.py) (FastAPI app), [`backend/app/api/gateway.py`](https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/api/gateway.py) (Gateway API), [`docker-compose.yml`](https://github.com/nithinvikas-av/llm_gateway/blob/main/docker-compose.yml) (Compose), [`backend/app/services/gateway_service.py`](https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/services/gateway_service.py) (Gateway service)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_frontend["Frontend"]
  node_frontend_main["App entry<br/>react entry<br/>[main.jsx]"]
  node_frontend_app["Routes<br/>react shell<br/>[App.jsx]"]
  node_frontend_pages["Pages"]
  node_frontend_api["API client<br/>client layer"]
  node_auth_store["Auth store<br/>state<br/>[authStore.js]"]
end

subgraph group_backend["Backend"]
  node_backend_main["FastAPI app<br/>api entry<br/>[main.py]"]
  node_api_auth["Auth API<br/>route<br/>[auth.py]"]
  node_api_gateway["Gateway API<br/>route<br/>[gateway.py]"]
  node_api_keys["Keys API<br/>route<br/>[keys.py]"]
  node_api_users["Users API<br/>route<br/>[users.py]"]
  node_api_usage["Usage API<br/>route<br/>[usage.py]"]
  node_security{{"Security<br/>crypto/auth<br/>[security.py]"}}
  node_dependencies{{"Deps<br/>auth guard<br/>[dependencies.py]"}}
  node_key_service["Key service<br/>[key_service.py]"]
  node_gateway_service["Gateway service<br/>[gateway_service.py]"]
  node_rate_limiter["Rate limiter<br/>redis control<br/>[rate_limiter.py]"]
  node_usage_service["Usage service<br/>[usage_service.py]"]
end

subgraph group_data["Data layer"]
  node_models[("Domain models<br/>sqlalchemy models")]
  node_migrations["Migrations<br/>schema evolution"]
  node_postgres[("PostgreSQL<br/>persistent store")]
  node_redis[("Redis<br/>ephemeral store")]
end

subgraph group_delivery["Delivery"]
  node_docker_compose["Compose<br/>orchestration<br/>[docker-compose.yml]"]
  node_deploy["Deploy<br/>delivery<br/>[deploy.yml]"]
end

node_docker_compose -->|"runs"| node_frontend_main
node_docker_compose -->|"runs"| node_backend_main
node_docker_compose -->|"includes"| node_postgres
node_docker_compose -->|"includes"| node_redis
node_frontend_main -->|"boots"| node_frontend_app
node_frontend_app -->|"routes"| node_frontend_pages
node_frontend_pages -->|"calls"| node_frontend_api
node_frontend_app -->|"reads"| node_auth_store
node_frontend_api -->|"requests"| node_backend_main
node_backend_main -->|"mounts"| node_api_auth
node_backend_main -->|"mounts"| node_api_gateway
node_backend_main -->|"mounts"| node_api_keys
node_backend_main -->|"mounts"| node_api_users
node_backend_main -->|"mounts"| node_api_usage
node_api_auth -->|"issues JWTs"| node_security
node_api_auth -->|"guards"| node_dependencies
node_api_gateway -->|"authorizes"| node_dependencies
node_api_gateway -->|"delegates"| node_gateway_service
node_api_gateway -->|"limits"| node_rate_limiter
node_api_gateway -->|"records"| node_usage_service
node_api_keys -->|"delegates"| node_key_service
node_api_keys -->|"authorizes"| node_dependencies
node_api_users -->|"authorizes"| node_dependencies
node_api_usage -->|"queries"| node_usage_service
node_key_service -->|"encrypts"| node_security
node_key_service -->|"persists"| node_models
node_gateway_service -->|"resolves keys"| node_key_service
node_gateway_service -->|"consults"| node_rate_limiter
node_gateway_service -->|"emits usage"| node_usage_service
node_usage_service -->|"writes logs"| node_models
node_models -->|"maps to"| node_postgres
node_migrations -->|"evolves"| node_models
node_rate_limiter -->|"stores counters"| node_redis
node_deploy -->|"deploys"| node_backend_main
node_deploy -->|"deploys"| node_frontend_main
node_deploy -.->|"mirrors"| node_docker_compose

click node_docker_compose "https://github.com/nithinvikas-av/llm_gateway/blob/main/docker-compose.yml"
click node_frontend_main "https://github.com/nithinvikas-av/llm_gateway/blob/main/frontend/src/main.jsx"
click node_frontend_app "https://github.com/nithinvikas-av/llm_gateway/blob/main/frontend/src/App.jsx"
click node_frontend_pages "https://github.com/nithinvikas-av/llm_gateway/tree/main/frontend/src/pages"
click node_frontend_api "https://github.com/nithinvikas-av/llm_gateway/tree/main/frontend/src/api"
click node_auth_store "https://github.com/nithinvikas-av/llm_gateway/blob/main/frontend/src/store/authStore.js"
click node_backend_main "https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/main.py"
click node_api_auth "https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/api/auth.py"
click node_api_gateway "https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/api/gateway.py"
click node_api_keys "https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/api/keys.py"
click node_api_users "https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/api/users.py"
click node_api_usage "https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/api/usage.py"
click node_security "https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/core/security.py"
click node_dependencies "https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/core/dependencies.py"
click node_key_service "https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/services/key_service.py"
click node_gateway_service "https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/services/gateway_service.py"
click node_rate_limiter "https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/services/rate_limiter.py"
click node_usage_service "https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/services/usage_service.py"
click node_models "https://github.com/nithinvikas-av/llm_gateway/tree/main/backend/app/models"
click node_migrations "https://github.com/nithinvikas-av/llm_gateway/tree/main/backend/alembic/versions"
click node_deploy "https://github.com/nithinvikas-av/llm_gateway/blob/main/.github/workflows/deploy.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_frontend_main,node_frontend_app,node_frontend_pages,node_frontend_api,node_auth_store toneBlue
class node_backend_main,node_api_auth,node_api_gateway,node_api_keys,node_api_users,node_api_usage,node_security,node_dependencies,node_key_service,node_gateway_service,node_rate_limiter,node_usage_service toneAmber
class node_models,node_migrations,node_postgres,node_redis toneMint
class node_docker_compose,node_deploy toneRose
```

## Components

### Frontend

React UI and client-side state/API access

- [App entry](https://github.com/nithinvikas-av/llm_gateway/blob/main/frontend/src/main.jsx): react entry · Bootstraps the frontend application · `frontend/src/main.jsx`
- [Routes](https://github.com/nithinvikas-av/llm_gateway/blob/main/frontend/src/App.jsx): react shell · Top-level app shell and route composition · `frontend/src/App.jsx`
- [Pages](https://github.com/nithinvikas-av/llm_gateway/tree/main/frontend/src/pages): ui pages · Login, dashboard, keys, users, and playground screens · `frontend/src/pages`
- [API client](https://github.com/nithinvikas-av/llm_gateway/tree/main/frontend/src/api): client layer · Browser-side API wrappers for auth, gateway, keys, usage, and users · `frontend/src/api`
- [Auth store](https://github.com/nithinvikas-av/llm_gateway/blob/main/frontend/src/store/authStore.js): state · Client auth and token state · `frontend/src/store/authStore.js`

### Backend

FastAPI gateway, services, and domain logic

- [FastAPI app](https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/main.py): api entry · Backend application entry point and router wiring · `backend/main.py`
- [Auth API](https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/api/auth.py): route · Google OAuth login and callback handling · `backend/app/api/auth.py`
- [Gateway API](https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/api/gateway.py): route · LLM request proxy and policy enforcement endpoint · `backend/app/api/gateway.py`
- [Keys API](https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/api/keys.py): route · Provider and universal key management endpoints · `backend/app/api/keys.py`
- [Users API](https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/api/users.py): route · User administration endpoints · `backend/app/api/users.py`
- [Usage API](https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/api/usage.py): route · Usage and reporting endpoints · `backend/app/api/usage.py`
- [Security](https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/core/security.py): crypto/auth · JWT handling and symmetric encryption for stored secrets · `backend/app/core/security.py`
- [Deps](https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/core/dependencies.py): auth guard · Authenticated user context and admin-only access dependencies · `backend/app/core/dependencies.py`
- [Key service](https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/services/key_service.py): service · Provider key storage, retrieval, and encryption workflow · `backend/app/services/key_service.py`
- [Gateway service](https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/services/gateway_service.py): service · Core request proxy, policy checks, and provider forwarding · `backend/app/services/gateway_service.py`
- [Rate limiter](https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/services/rate_limiter.py): redis control · Redis-backed per-key and per-request quota enforcement · `backend/app/services/rate_limiter.py`
- [Usage service](https://github.com/nithinvikas-av/llm_gateway/blob/main/backend/app/services/usage_service.py): service · Token, request, and cost accounting · `backend/app/services/usage_service.py`

### Data layer

Persistent PostgreSQL models and Redis control-plane state

- [Domain models](https://github.com/nithinvikas-av/llm_gateway/tree/main/backend/app/models): sqlalchemy models · User, key, permission, and usage persistence model set · `backend/app/models`
- [Migrations](https://github.com/nithinvikas-av/llm_gateway/tree/main/backend/alembic/versions): schema evolution · Alembic schema history and table evolution · `backend/alembic/versions`
- **PostgreSQL**: persistent store · Durable audit trail and domain data store
- **Redis**: ephemeral store · Short-lived quota counters and rate-limit state

### Delivery

Containerization and deployment automation

- [Compose](https://github.com/nithinvikas-av/llm_gateway/blob/main/docker-compose.yml): orchestration · Local integration boundary for frontend, backend, PostgreSQL, and Redis · `docker-compose.yml`
- [Deploy](https://github.com/nithinvikas-av/llm_gateway/blob/main/.github/workflows/deploy.yml): delivery · CI/CD and infrastructure configuration · `.github/workflows/deploy.yml`

## Connections

- Compose → App entry: runs · Local stack brings up the UI
- Compose → FastAPI app: runs · Local stack brings up the API
- Compose → PostgreSQL: includes · Local stack includes persistent database
- Compose → Redis: includes · Local stack includes quota store
- App entry → Routes: boots · Application entry mounts the route shell
- Routes → Pages: routes · Shell dispatches to page views
- Pages → API client: calls · Pages use API wrappers for backend communication
- Routes → Auth store: reads · App shell consumes auth state
- API client → FastAPI app: requests · Browser client talks to the API server
- FastAPI app → Auth API: mounts · Main app wires auth routes
- FastAPI app → Gateway API: mounts · Main app wires gateway routes
- FastAPI app → Keys API: mounts · Main app wires key management routes
- FastAPI app → Users API: mounts · Main app wires admin/user routes
- FastAPI app → Usage API: mounts · Main app wires reporting routes
- Auth API → Security: issues JWTs · OAuth login results in signed tokens
- Auth API → Deps: guards · Auth routes rely on request context helpers
- Gateway API → Deps: authorizes · Gateway enforces authenticated and role-based access
- Gateway API → Gateway service: delegates · Route handler hands off proxy logic
- Gateway API → Rate limiter: limits · Gateway checks quotas before forwarding
- Gateway API → Usage service: records · Gateway emits usage accounting after requests
- Keys API → Key service: delegates · Key endpoints use service layer for storage and crypto
- Keys API → Deps: authorizes · Key routes are protected by user context and roles
- Users API → Deps: authorizes · User admin routes require privileged access
- Usage API → Usage service: queries · Usage endpoints read accounting history
- Key service → Security: encrypts · Provider secrets are protected before persistence
- Key service → Domain models: persists · Key service works through ORM models
- Gateway service → Key service: resolves keys · Gateway fetches provider credentials for forwarding
- Gateway service → Rate limiter: consults · Gateway service enforces request policy through Redis state
- Gateway service → Usage service: emits usage · Gateway service contributes accounting records
- Usage service → Domain models: writes logs · Accounting is stored as durable usage history
- Domain models → PostgreSQL: maps to · ORM entities are backed by PostgreSQL
- Migrations → Domain models: evolves · Alembic schema tracks the domain model set
- Rate limiter → Redis: stores counters · Quota state lives in Redis rather than PostgreSQL
- Deploy → FastAPI app: deploys · Deployment automation targets the API service
- Deploy → App entry: deploys · Deployment automation targets the frontend service
- Deploy → Compose: mirrors · Infra config reflects the local composed stack
