# stark-sk/carverse architecture

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

- Interactive diagram: https://gitdiagram.com/stark-sk/carverse
- Repository: https://github.com/stark-sk/carverse

## Overview

1. **Overall shape**
   - This repository is a **containerized microservices backend** for an AI automotive marketplace.
   - The system is centered on a **FastAPI gateway** (`services/api`) backed by **PostgreSQL**, **Redis**, **PgBouncer**, and several specialized AI services (`ml`, `vision`, `voice`, `llm`), with **n8n** handling cross-service automation.

2. **Primary entry point: the API gateway**
   - `services/api` is the main synchronous interface for clients.
   - It owns the marketplace/domain surface: **auth, users, listings, appointments, transactions, community, events, webhooks, health, and DLQ**.
   - Most user-facing flows terminate here, and this service orchestrates calls to the other services rather than embedding model logic itself.

3. **Persistent state and access pattern**
   - **PostgreSQL** is the system of record for application data and also hosts **pgvector** for embedding storage.
   - **PgBouncer** sits in front of Postgres for transaction pooling; application services use the pooled path, while migrations/init scripts target Postgres directly.
   - **Redis** is used for ephemeral coordination: sessions, locks, debounce/cache behavior, and idempotency-related patterns.

4. **AI/ML service boundary**
   - `services/ml` is the shared inference/training service for marketplace intelligence.
   - It covers **collaborative filtering, NCF recommendations, pricing, NLP moderation/analyzing, fraud scanning, and forecasting**.
   - The README indicates model lifecycle tracking via **MLflow**, so this service is both an online inference endpoint and a model-training/registry integration point.

5. **Computer vision and voice are separate specialist services**
   - `services/vision` encapsulates **damage detection** using YOLOv8-style logic and returns analysis results to the main application.
   - `services/voice` handles the **voice car finder** pipeline: speech-to-text, entity extraction, and safe search over allowed vehicle makes.
   - These are isolated from the API gateway, which keeps the core app thin and makes the AI capabilities independently deployable.

6. **Conversational/agentic layer**
   - `services/llm` provides an **AI negotiation agent**.
   - The README notes this is **feature-flagged**, which means it is present as an optional subsystem rather than a hard dependency of the base marketplace flow.
   - Architecturally, it sits alongside the other AI services as an auxiliary decision/interaction engine.

7. **n8n as the automation and batch backbone**
   - `n8n/workflows` contains the canonical workflow definitions for the platform’s background automation.
   - These workflows cover recommendation fanout, price prediction, damage detection, voice finder, community NLP, chat agent, market forecast, moderation, and self-learning.
   - n8n is used for **cron jobs, async fanout, batch processing, polling, and workflow glue** between application events and downstream intelligence tasks.

8. **Eventing and feedback loops**
   - The API emits or forwards events to support the **self-learning loop** and community workflows.
   - A notable pattern is **HMAC-signed outbound webhooks** from the app to n8n, which keeps workflow ingestion authenticated and decouples user actions from workflow completion.
   - The “self-learning” architecture depends on anchoring events in the database and then fanning them out for multiple signals rather than doing synchronous heavy processing in the request path.

9. **Security and trust boundaries**
   - Security is enforced at multiple layers: **HMAC webhook verification**, **Redis-backed opaque sessions**, **service-to-service JWTs**, and **parameterized SQL only**.
   - The API includes middleware for **signature verification** and **security headers**.
   - The voice search path is specifically hardened with allowlist-based search constraints, reflecting a boundary where natural-language input could otherwise become an injection vector.

10. **Schema and lifecycle management**
   - Database structure is defined by a combination of **initialization scripts** (`db/init`) and **versioned migrations** (`db/migrations`).
   - The init scripts set up roles, extensions, tables, indexes, grants, and domain-specific seed data; migrations evolve the schema through phases, including performance, partitioning, config, renaming, FX rates, and search indexing.
   - This indicates the database schema is a core architectural artifact, not just an implementation detail.

11. **Operational envelope**
   - The repository is built for **Docker Compose**-based local/staging deployment, with explicit service ports and startup ordering.
   - `load_tests` and `scripts` provide operational validation, including buyer/seller/community scenarios and performance monitoring for Redis/PgBouncer.
   - The docs emphasize readiness checks, boot/runbooks, and launch validation, so the architecture is meant to be reproducible and testable end-to-end.

12. **How to draw the main diagram**
   - Put **clients** on the left, **API gateway** in the center, and branch from it to:
     - **Postgres via PgBouncer** for durable state,
     - **Redis** for sessions/locks/cache,
     - **ML / vision / voice / llm** for specialized AI calls,
     - **n8n** for asynchronous automation and batch workflows.
   - Show **MLflow** as a supporting registry for the ML service, and show **webhooks between API and n8n** as an asynchronous feedback path.
   - The key architectural theme is: **synchronous marketplace control in the API, specialized AI behind service boundaries, and background intelligence/automation through n8n**.

Main entry points: [`services/api/app/main.py`](https://github.com/stark-sk/carverse/blob/main/services/api/app/main.py) (API App), [`n8n/workflows`](https://github.com/stark-sk/carverse/tree/main/n8n/workflows) (n8n Workflows), [`load_tests`](https://github.com/stark-sk/carverse/tree/main/load_tests) (Load Tests), [`services/ml/app/main.py`](https://github.com/stark-sk/carverse/blob/main/services/ml/app/main.py) (ML Service)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_api["API Gateway"]
  node_api_main["API App<br/>FastAPI entry<br/>[main.py]"]
  node_api_routers["Domain Routers<br/>HTTP routes<br/>[__init__.py]"]
  node_api_services["App Services<br/>domain logic<br/>[__init__.py]"]
  node_api_mw["Middleware<br/>security layer<br/>[__init__.py]"]
  node_api_db[("DB Access<br/>postgres adapter<br/>[db.py]")]
end

subgraph group_ai["AI Services"]
  node_ml["ML Service<br/>inference service<br/>[main.py]"]
  node_vision["Vision Service<br/>cv service<br/>[main.py]"]
  node_voice["Voice Service<br/>speech pipeline<br/>[main.py]"]
  node_llm["LLM Agent<br/>negotiation agent<br/>[main.py]"]
  node_mlflow[("MLflow<br/>model registry")]
end

subgraph group_data["Data Layer"]
  node_postgres[("PostgreSQL<br/>system of record")]
  node_pgbouncer[("PgBouncer<br/>pooling proxy")]
  node_redis[("Redis<br/>ephemeral state")]
  node_db_init["DB Init<br/>bootstrap scripts"]
  node_db_migrations["Migrations<br/>schema evolution"]
end

subgraph group_automation["Automation"]
  node_n8n["n8n Workflows<br/>automation engine"]
  node_webhooks["Webhooks<br/>async boundary<br/>[webhooks.py]"]
end

subgraph group_ops["Operations"]
  node_load_tests["Load Tests<br/>validation suite"]
end

node_clients(("Clients<br/>external actors"))

node_clients -->|"requests"| node_api_main
node_api_main -->|"routes"| node_api_routers
node_api_main -->|"orchestrates"| node_api_services
node_api_main -->|"guards"| node_api_mw
node_api_main -->|"queries"| node_api_db
node_api_db -->|"pooled path"| node_pgbouncer
node_pgbouncer -->|"transactions"| node_postgres
node_db_init -->|"bootstrap"| node_postgres
node_db_migrations -->|"evolve schema"| node_postgres
node_api_main -->|"sessions/cache"| node_redis
node_api_main -->|"inference calls"| node_ml
node_api_main -->|"image analysis"| node_vision
node_api_main -->|"voice search"| node_voice
node_api_main -->|"optional agent"| node_llm
node_ml -->|"tracks models"| node_mlflow
node_api_main -->|"emits events"| node_webhooks
node_webhooks -->|"ingests"| node_n8n
node_api_services -->|"fanout"| node_webhooks
node_n8n -->|"batch jobs"| node_ml
node_n8n -->|"damage workflow"| node_vision
node_n8n -->|"voice workflow"| node_voice
node_n8n -->|"chat agent"| node_llm
node_n8n -->|"signals"| node_postgres
node_load_tests -->|"validates"| node_api_main
node_load_tests -->|"monitors"| node_pgbouncer
node_load_tests -->|"monitors"| node_redis

click node_api_main "https://github.com/stark-sk/carverse/blob/main/services/api/app/main.py"
click node_api_routers "https://github.com/stark-sk/carverse/blob/main/services/api/app/routers/__init__.py"
click node_api_services "https://github.com/stark-sk/carverse/blob/main/services/api/app/services/__init__.py"
click node_api_mw "https://github.com/stark-sk/carverse/blob/main/services/api/app/middleware/__init__.py"
click node_api_db "https://github.com/stark-sk/carverse/blob/main/services/api/app/db.py"
click node_ml "https://github.com/stark-sk/carverse/blob/main/services/ml/app/main.py"
click node_vision "https://github.com/stark-sk/carverse/blob/main/services/vision/app/main.py"
click node_voice "https://github.com/stark-sk/carverse/blob/main/services/voice/app/main.py"
click node_llm "https://github.com/stark-sk/carverse/blob/main/services/llm/app/main.py"
click node_n8n "https://github.com/stark-sk/carverse/tree/main/n8n/workflows"
click node_webhooks "https://github.com/stark-sk/carverse/blob/main/services/api/app/routers/webhooks.py"
click node_db_init "https://github.com/stark-sk/carverse/tree/main/db/init"
click node_db_migrations "https://github.com/stark-sk/carverse/tree/main/db/migrations"
click node_load_tests "https://github.com/stark-sk/carverse/tree/main/load_tests"

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_api_main,node_api_routers,node_api_services,node_api_mw,node_api_db toneBlue
class node_ml,node_vision,node_voice,node_llm,node_mlflow toneAmber
class node_postgres,node_pgbouncer,node_redis,node_db_init,node_db_migrations toneMint
class node_n8n,node_webhooks toneRose
class node_load_tests toneIndigo
class node_clients toneNeutral
```

## Components

### API Gateway

FastAPI marketplace control plane and domain orchestration.

- [API App](https://github.com/stark-sk/carverse/blob/main/services/api/app/main.py): FastAPI entry · Main synchronous gateway for marketplace requests. · `services/api/app/main.py`
- [Domain Routers](https://github.com/stark-sk/carverse/blob/main/services/api/app/routers/__init__.py): HTTP routes · Auth, users, listings, appointments, transactions, community, events, webhooks, health, and DLQ surfaces. · `services/api/app/routers/__init__.py`
- [App Services](https://github.com/stark-sk/carverse/blob/main/services/api/app/services/__init__.py): domain logic · Session, OTP, reminders, trust, events, notifications, buffering, and DLQ support. · `services/api/app/services/__init__.py`
- [Middleware](https://github.com/stark-sk/carverse/blob/main/services/api/app/middleware/__init__.py): security layer · HMAC verification and security headers for trust boundaries. · `services/api/app/middleware/__init__.py`
- [DB Access](https://github.com/stark-sk/carverse/blob/main/services/api/app/db.py): postgres adapter · Database connectivity used by the API layer. · `services/api/app/db.py`

### AI Services

Specialized inference services split by modality and task.

- [ML Service](https://github.com/stark-sk/carverse/blob/main/services/ml/app/main.py): inference service · Recommendations, pricing, NLP, fraud, and forecasting with tracking. · `services/ml/app/main.py`
- [Vision Service](https://github.com/stark-sk/carverse/blob/main/services/vision/app/main.py): cv service · Damage detection and image analysis. · `services/vision/app/main.py`
- [Voice Service](https://github.com/stark-sk/carverse/blob/main/services/voice/app/main.py): speech pipeline · Speech-to-text, entity extraction, and safe vehicle search. · `services/voice/app/main.py`
- [LLM Agent](https://github.com/stark-sk/carverse/blob/main/services/llm/app/main.py): negotiation agent · Feature-flagged conversational negotiation subsystem. · `services/llm/app/main.py`
- **MLflow**: model registry · Model lifecycle and tracking support for the ML service.

### Data Layer

Durable storage and access-path components.

- **PostgreSQL**: system of record · Primary durable datastore, including pgvector-backed embeddings.
- **PgBouncer**: pooling proxy · Transaction pooling front end for application connections.
- **Redis**: ephemeral state · Sessions, locks, cache/debounce, and idempotency-related coordination.
- [DB Init](https://github.com/stark-sk/carverse/tree/main/db/init): bootstrap scripts · Roles, extensions, tables, indexes, grants, and seed data. · `db/init`
- [Migrations](https://github.com/stark-sk/carverse/tree/main/db/migrations): schema evolution · Versioned schema and performance changes over time. · `db/migrations`

### Automation

n8n workflow backbone for async fanout and batch jobs.

- [n8n Workflows](https://github.com/stark-sk/carverse/tree/main/n8n/workflows): automation engine · Cron, async fanout, polling, and batch workflow orchestration. · `n8n/workflows`
- [Webhooks](https://github.com/stark-sk/carverse/blob/main/services/api/app/routers/webhooks.py): async boundary · HMAC-signed outbound event path into workflow automation. · `services/api/app/routers/webhooks.py`

### Operations

Deployment, testing, and validation support.

- [Load Tests](https://github.com/stark-sk/carverse/tree/main/load_tests): validation suite · Scenario and resource monitoring for operational verification. · `load_tests`

### Other components

- **Clients**: external actors · Marketplace users and external callers consuming the API.

## Connections

- Clients → API App: requests · Client traffic enters the FastAPI gateway.
- API App → Domain Routers: routes · Main app dispatches into domain routers.
- API App → App Services: orchestrates · Gateway coordinates domain workflows through service helpers.
- API App → Middleware: guards · Requests pass through signature and header middleware.
- API App → DB Access: queries · API uses the database adapter for persistence access.
- DB Access → PgBouncer: pooled path · Application traffic goes through PgBouncer.
- PgBouncer → PostgreSQL: transactions · PgBouncer forwards pooled connections to PostgreSQL.
- DB Init → PostgreSQL: bootstrap · Initialization scripts prepare the database directly.
- Migrations → PostgreSQL: evolve schema · Migrations apply versioned database changes.
- API App → Redis: sessions/cache · Redis supports ephemeral coordination and session state.
- API App → ML Service: inference calls · Marketplace flows invoke ML capabilities when needed.
- API App → Vision Service: image analysis · API forwards damage-analysis requests to vision.
- API App → Voice Service: voice search · API delegates car-finder speech workflows to voice.
- API App → LLM Agent: optional agent · Negotiation agent is available as a feature-flagged subsystem.
- ML Service → MLflow: tracks models · ML service integrates with model lifecycle tracking.
- API App → Webhooks: emits events · The API sends authenticated outbound webhook events.
- Webhooks → n8n Workflows: ingests · Workflow automation consumes signed webhook payloads.
- App Services → Webhooks: fanout · Event buffering and notifications drive async workflow triggers.
- n8n Workflows → ML Service: batch jobs · Workflows coordinate recommendation, pricing, forecasting, and moderation tasks.
- n8n Workflows → Vision Service: damage workflow · Workflow automation triggers image analysis pipelines.
- n8n Workflows → Voice Service: voice workflow · Workflows support the voice-finder pipeline.
- n8n Workflows → LLM Agent: chat agent · Workflows can route conversational tasks to the agent.
- n8n Workflows → PostgreSQL: signals · Background automation reads and updates anchored application data.
- Load Tests → API App: validates · Operational scenarios exercise the API path.
- Load Tests → PgBouncer: monitors · Performance checks cover connection pooling behavior.
- Load Tests → Redis: monitors · Performance checks cover Redis coordination behavior.
