# ananya-ys/churnguard-ai architecture

> Architecture diagram of the GitHub repository ananya-ys/churnguard-ai, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-06-13). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/ananya-ys/churnguard-ai
- Repository: https://github.com/ananya-ys/churnguard-ai

## Overview

1. **Overall shape**
   - ChurnGuard AI is a split full-stack system: a **React/Vite frontend** and a **FastAPI backend**.
   - The backend owns all business logic, persistence, ML inference, background jobs, and auth.
   - Runtime dependencies are **PostgreSQL** for durable state, **Redis** for Celery broker/cache-style coordination, and **Celery workers** for asynchronous ML tasks.

2. **Frontend boundary**
   - The frontend is a single-page app built with **React 18** and served through **nginx** in production.
   - UI routes map to a few product areas: **Dashboard**, **Predict**, **Batch Upload**, **Models**, **Jobs**, and **Login**.
   - All API access is centralized in `src/api.js`, so the frontend is a thin client and does not contain domain logic.

3. **HTTP/API layer in the backend**
   - FastAPI routes live under `backend/app/api/v1/endpoints/`.
   - The API is organized by domain: `auth`, `predict`, `upload`, `jobs`, `models`, `experiments`, `ab_tests`, `drift`, `metrics`, `audit_logs`, `health`, and `explain`.
   - `router.py` assembles the versioned API surface, while middleware and error handlers in `app/core/` provide shared cross-cutting behavior.

4. **Backend internal layering**
   - The backend uses a clean separation:
     - **API endpoints**: request/response translation
     - **Services**: business rules and orchestration
     - **Repositories**: database access
     - **ORM models**: SQLAlchemy entities
     - **Schemas**: Pydantic contracts
   - This layering makes the backend easy to diagram as a pipeline from HTTP → service logic → repository/DB, with ML and task execution branching off where needed.

5. **Authentication and security**
   - Auth is handled by `auth_service`, `dependencies/auth.py`, and security helpers in `core/security.py`.
   - The system uses **JWT-based auth** and **Argon2** password hashing.
   - RBAC is present in tests and likely enforced through dependencies/middleware, so authenticated identity is a first-class concern across the API.

6. **Core application state**
   - Persistent entities include **users**, **model versions**, **prediction jobs**, **drift reports**, **experiments**, **A/B tests**, and **audit logs**.
   - These map to SQLAlchemy models and dedicated repositories, indicating that most product features are stored and queried from PostgreSQL rather than computed on the fly.
   - Alembic migrations define the schema evolution, with `0001_initial_schema` and `0002_phases_1_6` showing the system has grown in phases.

7. **Prediction and ML inference path**
   - Online prediction is handled by `predict_service` and the ML package under `app/ml/`.
   - The ML subsystem includes a **pipeline singleton**, **explainer**, **training script**, and a prebuilt artifact store (`app/ml/artifacts/v1.pkl`).
   - The expected flow is: frontend submits features → FastAPI validates input → prediction service loads the active model → result is returned and likely logged/audited.

8. **Batch processing and asynchronous jobs**
   - Batch uploads do not appear to run inline; they create a **prediction job** and are processed asynchronously.
   - Celery tasks in `app/tasks/` cover `batch_predict`, `drift_check`, `retrain`, and the worker entrypoint.
   - Redis acts as the coordination layer for these jobs, while PostgreSQL stores job state and results for the Jobs UI to poll.

9. **Drift, retraining, and model lifecycle**
   - The architecture includes explicit support for **model drift detection** and **retraining**.
   - `drift_service`, `drift_repository`, and `tasks/drift_check.py` indicate scheduled or triggered monitoring of prediction quality/data shift.
   - `model_service` and the Models UI support model registration and promotion, so model lifecycle is a managed backend workflow rather than a manual file swap.

10. **Experiments and A/B tests**
    - There are dedicated subsystems for **experiments** and **A/B testing**, with services, repositories, and API endpoints for both.
    - This suggests the platform can compare model variants or controlled rollout strategies, storing outcomes in the database and exposing them through the API.
    - These features sit beside the main inference path, not inside it, which is important for diagramming feature experimentation as an orthogonal capability.

11. **Observability and auditability**
    - The backend includes **metrics**, **logging**, **audit logs**, and a `health` endpoint.
    - Prometheus and Grafana provisioning under `infra/` show a real monitoring stack rather than ad hoc logs.
    - Audit logs are a separate persisted domain, which implies user actions and model operations are meant to be traceable.

12. **Deployment and orchestration**
    - `docker-compose.yml` is the main local orchestrator: PostgreSQL, Redis, migrations, FastAPI app, Celery worker/beat, Flower, and the React frontend.
    - The frontend container uses nginx to serve static assets and proxy API traffic.
    - The backend uses Docker and Alembic; CI is defined in GitHub Actions, and the repo includes deployment guidance for cloud hosting.

13. **Testing and verification**
    - The backend has layered tests: **unit**, **integration**, **security**, **concurrency**, and **smoke**.
    - This mirrors the architecture: business logic can be tested independently from the HTTP layer, while auth and concurrency are verified where the system is stateful and async.
    - CI is therefore likely validating the full pipeline from API behavior to model/infrastructure assumptions.

14. **How to draw the main data flows**
    - Primary synchronous flow: **Browser → Frontend → FastAPI endpoint → Service → Repository → PostgreSQL / ML pipeline → response**.
    - Primary asynchronous flow: **Frontend upload/API request → job record in PostgreSQL → Celery task via Redis → worker processes batch/drift/retrain → results persisted back to PostgreSQL**.
    - Monitoring flow: **app metrics/logs → Prometheus/Grafana**, with audit logs stored in the database for domain-level traceability.

Main entry points: [`backend/app/api/v1/endpoints`](https://github.com/ananya-ys/churnguard-ai/tree/main/backend/app/api/v1/endpoints) (API Endpoints), [`backend/app/core`](https://github.com/ananya-ys/churnguard-ai/tree/main/backend/app/core) (Core), [`backend/app/tasks`](https://github.com/ananya-ys/churnguard-ai/tree/main/backend/app/tasks) (Celery Tasks), [`frontend/src/App.jsx`](https://github.com/ananya-ys/churnguard-ai/blob/main/frontend/src/App.jsx) (React App)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_frontend["Frontend"]
  node_browser(("Browser<br/>client"))
  node_spa["React App<br/>react/vite SPA<br/>[App.jsx]"]
  node_api_client["API Client<br/>http client<br/>[api.js]"]
  node_nginx["Nginx<br/>static server<br/>[nginx.conf]"]
end

subgraph group_backend["Backend"]
  node_router["API Router<br/>[router.py]"]
  node_endpoints["API Endpoints<br/>HTTP handlers"]
  node_core["Core<br/>cross-cutting"]
  node_auth_service["Auth Service<br/>security service<br/>[auth_service.py]"]
  node_predict_service["Predict Service<br/>inference service<br/>[predict_service.py]"]
  node_batch_service["Batch Service<br/>job service<br/>[batch_service.py]"]
  node_model_service["Model Service<br/>model lifecycle<br/>[model_service.py]"]
  node_drift_service["Drift Service<br/>monitoring service<br/>[drift_service.py]"]
  node_experiment_service["Experiment Service"]
  node_repositories["Repositories<br/>db access"]
  node_schemas["Schemas<br/>contracts"]
  node_orm_models[("ORM Models<br/>sqlalchemy entities")]
  node_ml_pipeline["ML Pipeline<br/>inference core<br/>[pipeline.py]"]
  node_tasks["Celery Tasks<br/>async jobs"]
end

subgraph group_runtime["Runtime"]
  node_postgres[("PostgreSQL<br/>database")]
  node_redis[("Redis<br/>broker/cache")]
end

subgraph group_ops["Ops"]
  node_prometheus["Prometheus<br/>metrics<br/>[prometheus.yml]"]
  node_grafana["Grafana<br/>dashboards<br/>[churnguard.json]"]
end

node_browser -->|"uses"| node_nginx
node_nginx -->|"serves"| node_spa
node_spa -->|"calls"| node_api_client
node_api_client -->|"HTTP"| node_router
node_router -->|"routes"| node_endpoints
node_endpoints -->|"validates"| node_schemas
node_endpoints -->|"auth"| node_auth_service
node_endpoints -->|"predict"| node_predict_service
node_endpoints -->|"jobs"| node_batch_service
node_endpoints -->|"models"| node_model_service
node_endpoints -->|"drift"| node_drift_service
node_endpoints -->|"experiments"| node_experiment_service
node_auth_service -->|"security"| node_core
node_predict_service -->|"infer"| node_ml_pipeline
node_batch_service -->|"enqueue"| node_tasks
node_drift_service -->|"schedule"| node_tasks
node_tasks -->|"broker"| node_redis
node_tasks -->|"persist"| node_postgres
node_repositories -->|"reads/writes"| node_postgres
node_orm_models -->|"maps to"| node_postgres
node_core -->|"db"| node_postgres
node_core -->|"cache/broker"| node_redis
node_core -->|"metrics"| node_prometheus
node_prometheus -->|"visualizes"| node_grafana

click node_spa "https://github.com/ananya-ys/churnguard-ai/blob/main/frontend/src/App.jsx"
click node_api_client "https://github.com/ananya-ys/churnguard-ai/blob/main/frontend/src/api.js"
click node_nginx "https://github.com/ananya-ys/churnguard-ai/blob/main/frontend/nginx.conf"
click node_router "https://github.com/ananya-ys/churnguard-ai/blob/main/backend/app/api/v1/router.py"
click node_endpoints "https://github.com/ananya-ys/churnguard-ai/tree/main/backend/app/api/v1/endpoints"
click node_core "https://github.com/ananya-ys/churnguard-ai/tree/main/backend/app/core"
click node_auth_service "https://github.com/ananya-ys/churnguard-ai/blob/main/backend/app/services/auth_service.py"
click node_predict_service "https://github.com/ananya-ys/churnguard-ai/blob/main/backend/app/services/predict_service.py"
click node_batch_service "https://github.com/ananya-ys/churnguard-ai/blob/main/backend/app/services/batch_service.py"
click node_model_service "https://github.com/ananya-ys/churnguard-ai/blob/main/backend/app/services/model_service.py"
click node_drift_service "https://github.com/ananya-ys/churnguard-ai/blob/main/backend/app/services/drift_service.py"
click node_experiment_service "https://github.com/ananya-ys/churnguard-ai/blob/main/backend/app/services/experiment_service.py"
click node_repositories "https://github.com/ananya-ys/churnguard-ai/tree/main/backend/app/repositories"
click node_schemas "https://github.com/ananya-ys/churnguard-ai/tree/main/backend/app/schemas"
click node_orm_models "https://github.com/ananya-ys/churnguard-ai/tree/main/backend/app/models"
click node_ml_pipeline "https://github.com/ananya-ys/churnguard-ai/blob/main/backend/app/ml/pipeline.py"
click node_tasks "https://github.com/ananya-ys/churnguard-ai/tree/main/backend/app/tasks"
click node_prometheus "https://github.com/ananya-ys/churnguard-ai/blob/main/infra/prometheus/prometheus.yml"
click node_grafana "https://github.com/ananya-ys/churnguard-ai/blob/main/infra/grafana/dashboards/churnguard.json"

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_browser,node_spa,node_api_client,node_nginx toneBlue
class node_router,node_endpoints,node_core,node_auth_service,node_predict_service,node_batch_service,node_model_service,node_drift_service,node_experiment_service,node_repositories,node_schemas,node_orm_models,node_ml_pipeline,node_tasks toneAmber
class node_postgres,node_redis toneMint
class node_prometheus,node_grafana toneRose
```

## Components

### Frontend

React/Vite SPA served by nginx in production.

- **Browser**: client · End user entrypoint for the SPA.
- [React App](https://github.com/ananya-ys/churnguard-ai/blob/main/frontend/src/App.jsx): react/vite SPA · Single-page frontend with product pages and shared layout. · `frontend/src/App.jsx`
- [API Client](https://github.com/ananya-ys/churnguard-ai/blob/main/frontend/src/api.js): http client · Centralized frontend API access layer. · `frontend/src/api.js`
- [Nginx](https://github.com/ananya-ys/churnguard-ai/blob/main/frontend/nginx.conf): static server · Serves the built frontend and fronts the app in production. · `frontend/nginx.conf`

### Backend

FastAPI application with layered business logic and persistence.

- [API Router](https://github.com/ananya-ys/churnguard-ai/blob/main/backend/app/api/v1/router.py): FastAPI router · Assembles the versioned HTTP surface. · `backend/app/api/v1/router.py`
- [API Endpoints](https://github.com/ananya-ys/churnguard-ai/tree/main/backend/app/api/v1/endpoints): HTTP handlers · Domain routes for auth, predict, upload, jobs, models, experiments, drift, metrics, audit, health, and explain. · `backend/app/api/v1/endpoints`
- [Core](https://github.com/ananya-ys/churnguard-ai/tree/main/backend/app/core): cross-cutting · Shared config, database, middleware, errors, logging, metrics, cache, and security helpers. · `backend/app/core`
- [Auth Service](https://github.com/ananya-ys/churnguard-ai/blob/main/backend/app/services/auth_service.py): security service · JWT auth, password hashing, and user identity handling. · `backend/app/services/auth_service.py`
- [Predict Service](https://github.com/ananya-ys/churnguard-ai/blob/main/backend/app/services/predict_service.py): inference service · Online prediction orchestration and model invocation. · `backend/app/services/predict_service.py`
- [Batch Service](https://github.com/ananya-ys/churnguard-ai/blob/main/backend/app/services/batch_service.py): job service · Creates and coordinates asynchronous batch prediction work. · `backend/app/services/batch_service.py`
- [Model Service](https://github.com/ananya-ys/churnguard-ai/blob/main/backend/app/services/model_service.py): model lifecycle · Manages model registration, promotion, and active version selection. · `backend/app/services/model_service.py`
- [Drift Service](https://github.com/ananya-ys/churnguard-ai/blob/main/backend/app/services/drift_service.py): monitoring service · Detects drift and coordinates monitoring workflows. · `backend/app/services/drift_service.py`
- [Experiment Service](https://github.com/ananya-ys/churnguard-ai/blob/main/backend/app/services/experiment_service.py): experiment service · Handles experiments and A/B test orchestration. · `backend/app/services/experiment_service.py`
- [Repositories](https://github.com/ananya-ys/churnguard-ai/tree/main/backend/app/repositories): db access · Persistence layer for users, jobs, models, drift reports, experiments, AB tests, and audit logs. · `backend/app/repositories`
- [Schemas](https://github.com/ananya-ys/churnguard-ai/tree/main/backend/app/schemas): contracts · Pydantic request and response models. · `backend/app/schemas`
- [ORM Models](https://github.com/ananya-ys/churnguard-ai/tree/main/backend/app/models): sqlalchemy entities · Persistent domain entities mapped to PostgreSQL. · `backend/app/models`
- [ML Pipeline](https://github.com/ananya-ys/churnguard-ai/blob/main/backend/app/ml/pipeline.py): inference core · Model pipeline, explainer, training, and stored artifact loading. · `backend/app/ml/pipeline.py`
- [Celery Tasks](https://github.com/ananya-ys/churnguard-ai/tree/main/backend/app/tasks): async jobs · Background workers for batch prediction, drift checks, and retraining. · `backend/app/tasks`

### Runtime

External state and async infrastructure used by the app.

- **PostgreSQL**: database · Durable storage for users, jobs, models, experiments, drift reports, and logs.
- **Redis**: broker/cache · Celery broker and coordination store.

### Ops

Monitoring and deployment tooling.

- [Prometheus](https://github.com/ananya-ys/churnguard-ai/blob/main/infra/prometheus/prometheus.yml): metrics · Collects application and infrastructure metrics. · `infra/prometheus/prometheus.yml`
- [Grafana](https://github.com/ananya-ys/churnguard-ai/blob/main/infra/grafana/dashboards/churnguard.json): dashboards · Operational dashboards and visualization. · `infra/grafana/dashboards/churnguard.json`

## Connections

- Browser → Nginx: uses · Users access the frontend through production serving.
- Nginx → React App: serves · Nginx serves the compiled React app.
- React App → API Client: calls · UI actions use the centralized API client.
- API Client → API Router: HTTP · Frontend API requests hit the versioned backend surface.
- API Router → API Endpoints: routes · Router assembles domain endpoints.
- API Endpoints → Schemas: validates · Endpoints use request and response contracts.
- API Endpoints → Auth Service: auth · Authentication routes and dependencies delegate to the auth service.
- API Endpoints → Predict Service: predict · Online prediction requests flow into the inference service.
- API Endpoints → Batch Service: jobs · Batch upload and job routes create async work.
- API Endpoints → Model Service: models · Model management routes call the model lifecycle service.
- API Endpoints → Drift Service: drift · Drift routes expose monitoring workflows.
- API Endpoints → Experiment Service: experiments · Experiment and A/B test routes use the experiment service.
- Auth Service → Core: security · Auth depends on shared security and error handling.
- Predict Service → ML Pipeline: infer · Prediction service loads and executes the ML pipeline.
- Batch Service → Celery Tasks: enqueue · Batch requests schedule asynchronous tasks.
- Drift Service → Celery Tasks: schedule · Drift monitoring can be executed by background workers.
- Celery Tasks → Redis: broker · Celery uses Redis for coordination and delivery.
- Celery Tasks → PostgreSQL: persist · Workers write outcomes and job state back to the database.
- Repositories → PostgreSQL: reads/writes · Repositories encapsulate PostgreSQL access.
- ORM Models → PostgreSQL: maps to · ORM entities represent durable database rows.
- Core → PostgreSQL: db · Shared database session and config support persistence.
- Core → Redis: cache/broker · Shared cache and queue coordination live here.
- Core → Prometheus: metrics · Application metrics are exposed for scraping.
- Prometheus → Grafana: visualizes · Grafana dashboards consume Prometheus metrics.
