# santanuhxx/inferx architecture

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

- Interactive diagram: https://gitdiagram.com/santanuhxx/inferx
- Repository: https://github.com/santanuhxx/inferx

## Overview

#### Purpose and Entry Point
InferX is a FastAPI service for extracting pooled embeddings from selected hidden layers of Hugging Face transformer models. The runtime entry point is `app/main.py`, which creates the HTTP app, manages startup/shutdown, installs middleware, and exposes API and Prometheus routes. Configuration is environment-driven through `app/config.py`.

#### HTTP Boundary and Request Policy
REST endpoints are split between authentication and inference/status APIs:
- `app/api/auth.py` handles token issuance, refresh, and identity.
- `app/api/routes.py` serves encoding, health, layer discovery, and usage statistics.
- `app/api/dependencies.py` composes authenticated-user and rate-limit checks before protected inference routes.
- `app/schemas/request.py` and `app/schemas/response.py` define the Pydantic API contract, including text/batch/layer validation and embedding metadata.

The API boundary validates requests before model work and returns embeddings, selected layer, shape, and timing rather than model-native tensors.

#### Security and Traffic Controls
JWT/OAuth2 credential handling, password verification, and token verification are centralized in `app/security/auth_backend.py`. Per-user sliding-window request limits are enforced by `app/security/rate_limiter.py`, invoked through API dependencies. Application-level request IDs and response compression are provided by `app/middleware/request_id.py` and `app/middleware/compression.py`; CORS is configured at application assembly time in `app/main.py`.

#### Model Lifecycle and Extraction
`app/models/model_loader.py` owns loading and unloading the configured Hugging Face model and tokenizer, choosing CUDA when available/configured and falling back to CPU. The core extraction stage in `app/inference/layer_extractor.py` tokenizes text, runs the model with hidden states enabled, selects the requested/default final layer, mean-pools token representations, and optionally normalizes vectors. `app/inference/batch_processor.py` splits larger valid requests into configured inference batches.

Model identity and supported-model/VRAM metadata are represented by `app/models/model_registry.py`. This boundary isolates framework-specific PyTorch/Transformers operations from HTTP routing.

#### Cache-First Inference Flow
`app/inference/inference_engine.py` coordinates the primary encode path: derive/cache lookup per request input, return a hit when available, otherwise invoke layer extraction and persist the result. `app/cache/embedding_cache.py` implements embedding-key generation and TTL-backed storage; `app/cache/redis_client.py` owns Redis connectivity. Redis is both the embedding-cache service and Celery broker, making its availability material to low-latency cached inference and async work.

#### Persistence, Metrics, and Background Work
SQLite/SQLAlchemy persistence is initialized through `app/db/database.py`; request/user/model entities and analytics queries live in `app/db/models.py` and `app/db/crud.py`. The request path records latency and cache outcomes for aggregate and per-user stats.

Prometheus instruments requests, inference latency, cache counters, and GPU memory in `app/monitoring/metrics.py`; structured application logging is configured by `app/monitoring/logging_config.py`. Optional asynchronous batch encoding and cleanup tasks are defined in `app/tasks/background_jobs.py` and registered against Celery/Redis in `app/tasks/celery_app.py`.

#### Deployment Topology
The service runs on Python 3.10+ with FastAPI/Uvicorn, PyTorch, and Hugging Face Transformers. It needs a locally loaded/downloaded Hugging Face-compatible model, optionally an NVIDIA CUDA environment. Docker deployment is defined in `docker/Dockerfile`; the multi-service stack in `docker/docker-compose.yaml` includes InferX, Redis, Prometheus (scrape settings: `configs/prometheus.yml`), and Grafana. Startup initializes the database, connects Redis, then loads the model; shutdown unloads it and releases GPU resources.

Main entry points: [`app/main.py`](https://github.com/santanuhxx/inferx/blob/main/app/main.py) (FastAPI app lifecycle), [`app/inference/inference_engine.py`](https://github.com/santanuhxx/inferx/blob/main/app/inference/inference_engine.py) (Cache-first inference engine), [`app/api/routes.py`](https://github.com/santanuhxx/inferx/blob/main/app/api/routes.py) (Inference & status API), [`app/cache/redis_client.py`](https://github.com/santanuhxx/inferx/blob/main/app/cache/redis_client.py) (Redis)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_http["HTTP API"]
  node_main["FastAPI app lifecycle<br/>application entry<br/>[main.py]"]
  node_config["Environment config<br/>configuration<br/>[config.py]"]
  node_auth_api["Auth API<br/>REST routes<br/>[auth.py]"]
  node_inference_api["Inference &amp; status API<br/>REST routes<br/>[routes.py]"]
  node_api_policy["Auth and rate-limit policy<br/>route dependencies<br/>[dependencies.py]"]
  node_api_contract["Embedding API contract<br/>Pydantic schemas<br/>[request.py]"]
  node_security["JWT credential backend<br/>security service<br/>[auth_backend.py]"]
  node_rate_limiter["Per-user rate limiter<br/>sliding-window limiter<br/>[rate_limiter.py]"]
end

subgraph group_inference["Inference Runtime"]
  node_inference_engine["Cache-first inference engine<br/>inference coordinator"]
  node_batch_processor["Inference batch processor<br/>batching<br/>[batch_processor.py]"]
  node_extractor["Hidden-layer extractor<br/>PyTorch/Transformers extraction<br/>[layer_extractor.py]"]
  node_model_loader["Model and tokenizer lifecycle<br/>model loader<br/>[model_loader.py]"]
  node_model_registry["Supported model registry<br/>model metadata<br/>[model_registry.py]"]
end

subgraph group_state["State &amp; Observability"]
  node_embedding_cache["Embedding cache<br/>TTL cache<br/>[embedding_cache.py]"]
  node_redis[("Redis<br/>cache and broker<br/>[redis_client.py]")]
  node_database[("SQLite analytics store<br/>SQLAlchemy persistence<br/>[database.py]")]
  node_metrics["Prometheus metrics<br/>instrumentation<br/>[metrics.py]"]
end

subgraph group_async["Background Work"]
  node_celery["Celery background jobs<br/>async worker<br/>[celery_app.py]"]
end

subgraph group_deploy["Deployment"]
  node_compose["Docker service stack<br/>deployment topology"]
end

node_main -->|"reads"| node_config
node_main -->|"mounts"| node_auth_api
node_main -->|"mounts"| node_inference_api
node_main -->|"startup / shutdown"| node_model_loader
node_main -->|"connects"| node_redis
node_main -->|"initializes"| node_database
node_auth_api -->|"issues and verifies tokens"| node_security
node_inference_api -->|"protects encode routes"| node_api_policy
node_inference_api -->|"validates request / response"| node_api_contract
node_api_policy -->|"authenticates user"| node_security
node_api_policy -->|"enforces limits"| node_rate_limiter
node_inference_api -->|"encodes validated input"| node_inference_engine
node_inference_engine -->|"lookup then store"| node_embedding_cache
node_embedding_cache -->|"uses TTL storage"| node_redis
node_inference_engine -->|"miss path"| node_batch_processor
node_batch_processor -->|"submits batches"| node_extractor
node_extractor -->|"uses loaded model"| node_model_loader
node_model_loader -->|"selects model metadata"| node_model_registry
node_inference_engine -->|"records request outcomes"| node_database
node_inference_engine -->|"emits latency and cache metrics"| node_metrics
node_celery -->|"broker"| node_redis
node_compose -->|"runs service"| node_main
node_compose -->|"runs dependency"| node_redis
node_compose -.->|"Prometheus scrapes"| node_metrics

click node_main "https://github.com/santanuhxx/inferx/blob/main/app/main.py"
click node_config "https://github.com/santanuhxx/inferx/blob/main/app/config.py"
click node_auth_api "https://github.com/santanuhxx/inferx/blob/main/app/api/auth.py"
click node_inference_api "https://github.com/santanuhxx/inferx/blob/main/app/api/routes.py"
click node_api_policy "https://github.com/santanuhxx/inferx/blob/main/app/api/dependencies.py"
click node_api_contract "https://github.com/santanuhxx/inferx/blob/main/app/schemas/request.py"
click node_security "https://github.com/santanuhxx/inferx/blob/main/app/security/auth_backend.py"
click node_rate_limiter "https://github.com/santanuhxx/inferx/blob/main/app/security/rate_limiter.py"
click node_inference_engine "https://github.com/santanuhxx/inferx/blob/main/app/inference/inference_engine.py"
click node_batch_processor "https://github.com/santanuhxx/inferx/blob/main/app/inference/batch_processor.py"
click node_extractor "https://github.com/santanuhxx/inferx/blob/main/app/inference/layer_extractor.py"
click node_model_loader "https://github.com/santanuhxx/inferx/blob/main/app/models/model_loader.py"
click node_model_registry "https://github.com/santanuhxx/inferx/blob/main/app/models/model_registry.py"
click node_embedding_cache "https://github.com/santanuhxx/inferx/blob/main/app/cache/embedding_cache.py"
click node_redis "https://github.com/santanuhxx/inferx/blob/main/app/cache/redis_client.py"
click node_database "https://github.com/santanuhxx/inferx/blob/main/app/db/database.py"
click node_metrics "https://github.com/santanuhxx/inferx/blob/main/app/monitoring/metrics.py"
click node_celery "https://github.com/santanuhxx/inferx/blob/main/app/tasks/celery_app.py"
click node_compose "https://github.com/santanuhxx/inferx/blob/main/docker/docker-compose.yaml"

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_config,node_auth_api,node_inference_api,node_api_policy,node_api_contract,node_security,node_rate_limiter toneBlue
class node_inference_engine,node_batch_processor,node_extractor,node_model_loader,node_model_registry toneAmber
class node_embedding_cache,node_redis,node_database,node_metrics toneMint
class node_celery toneRose
class node_compose toneIndigo
```

## Components

### HTTP API

- [FastAPI app lifecycle](https://github.com/santanuhxx/inferx/blob/main/app/main.py): application entry · Starts dependencies, installs middleware, and exposes routes. · `app/main.py`
- [Environment config](https://github.com/santanuhxx/inferx/blob/main/app/config.py): configuration · `app/config.py`
- [Auth API](https://github.com/santanuhxx/inferx/blob/main/app/api/auth.py): REST routes · `app/api/auth.py`
- [Inference & status API](https://github.com/santanuhxx/inferx/blob/main/app/api/routes.py): REST routes · `app/api/routes.py`
- [Auth and rate-limit policy](https://github.com/santanuhxx/inferx/blob/main/app/api/dependencies.py): route dependencies · `app/api/dependencies.py`
- [Embedding API contract](https://github.com/santanuhxx/inferx/blob/main/app/schemas/request.py): Pydantic schemas · Validates text, batches, layers, and response metadata. · `app/schemas/request.py`
- [JWT credential backend](https://github.com/santanuhxx/inferx/blob/main/app/security/auth_backend.py): security service · `app/security/auth_backend.py`
- [Per-user rate limiter](https://github.com/santanuhxx/inferx/blob/main/app/security/rate_limiter.py): sliding-window limiter · `app/security/rate_limiter.py`

### Inference Runtime

- [Cache-first inference engine](https://github.com/santanuhxx/inferx/blob/main/app/inference/inference_engine.py): inference coordinator · `app/inference/inference_engine.py`
- [Inference batch processor](https://github.com/santanuhxx/inferx/blob/main/app/inference/batch_processor.py): batching · `app/inference/batch_processor.py`
- [Hidden-layer extractor](https://github.com/santanuhxx/inferx/blob/main/app/inference/layer_extractor.py): PyTorch/Transformers extraction · Tokenizes, selects a hidden layer, mean-pools, and normalizes vectors. · `app/inference/layer_extractor.py`
- [Model and tokenizer lifecycle](https://github.com/santanuhxx/inferx/blob/main/app/models/model_loader.py): model loader · Loads on CUDA when available and unloads on shutdown. · `app/models/model_loader.py`
- [Supported model registry](https://github.com/santanuhxx/inferx/blob/main/app/models/model_registry.py): model metadata · `app/models/model_registry.py`

### State & Observability

- [Embedding cache](https://github.com/santanuhxx/inferx/blob/main/app/cache/embedding_cache.py): TTL cache · Generates keys and persists cached embedding results. · `app/cache/embedding_cache.py`
- [Redis](https://github.com/santanuhxx/inferx/blob/main/app/cache/redis_client.py): cache and broker · Shared embedding cache and Celery broker. · `app/cache/redis_client.py`
- [SQLite analytics store](https://github.com/santanuhxx/inferx/blob/main/app/db/database.py): SQLAlchemy persistence · Stores request, user, model, and usage data. · `app/db/database.py`
- [Prometheus metrics](https://github.com/santanuhxx/inferx/blob/main/app/monitoring/metrics.py): instrumentation · Tracks requests, latency, cache outcomes, and GPU memory. · `app/monitoring/metrics.py`

### Background Work

- [Celery background jobs](https://github.com/santanuhxx/inferx/blob/main/app/tasks/celery_app.py): async worker · Runs optional batch encoding and cleanup tasks. · `app/tasks/celery_app.py`

### Deployment

- [Docker service stack](https://github.com/santanuhxx/inferx/blob/main/docker/docker-compose.yaml): deployment topology · Runs InferX with Redis, Prometheus, and Grafana. · `docker/docker-compose.yaml`

## Connections

- FastAPI app lifecycle → Environment config: reads
- FastAPI app lifecycle → Auth API: mounts
- FastAPI app lifecycle → Inference & status API: mounts
- FastAPI app lifecycle → Model and tokenizer lifecycle: startup / shutdown
- FastAPI app lifecycle → Redis: connects
- FastAPI app lifecycle → SQLite analytics store: initializes
- Auth API → JWT credential backend: issues and verifies tokens
- Inference & status API → Auth and rate-limit policy: protects encode routes
- Inference & status API → Embedding API contract: validates request / response
- Auth and rate-limit policy → JWT credential backend: authenticates user
- Auth and rate-limit policy → Per-user rate limiter: enforces limits
- Inference & status API → Cache-first inference engine: encodes validated input
- Cache-first inference engine → Embedding cache: lookup then store
- Embedding cache → Redis: uses TTL storage
- Cache-first inference engine → Inference batch processor: miss path
- Inference batch processor → Hidden-layer extractor: submits batches
- Hidden-layer extractor → Model and tokenizer lifecycle: uses loaded model
- Model and tokenizer lifecycle → Supported model registry: selects model metadata
- Cache-first inference engine → SQLite analytics store: records request outcomes
- Cache-first inference engine → Prometheus metrics: emits latency and cache metrics
- Celery background jobs → Redis: broker
- Docker service stack → FastAPI app lifecycle: runs service
- Docker service stack → Redis: runs dependency
- Docker service stack → Prometheus metrics: Prometheus scrapes
