# System Architecture ## Overview Nexus is structured as a monolith-in-a-container: a single Docker image runs the FastAPI API server, two ARQ background worker processes, an embedded Redis instance (for pub/sub), and the compiled React frontend served as static files. This keeps deployment simple while maintaining clean internal separation between layers. ``` ┌─────────────────────────────────────────────────────────────┐ │ Docker Container │ │ │ │ ┌──────────────┐ ┌────────────────┐ ┌────────────────┐ │ │ │ Gunicorn │ │ ARQ Regular │ │ ARQ Heavy │ │ │ │ (4 uvicorn │ │ Worker │ │ Worker │ │ │ │ workers) │ │ (SLA, notify) │ │ (AI, embed) │ │ │ └──────┬───────┘ └───────┬────────┘ └───────┬────────┘ │ │ │ │ │ │ │ ┌──────▼──────────────────▼────────────────────▼────────┐ │ │ │ Local Redis (pub/sub, ephemeral) │ │ │ └───────────────────────────────────────────────────────┘ │ └──────────────────────────────┬──────────────────────────────┘ │ ┌─────────────────┼─────────────────┐ │ │ │ ┌───────▼──────┐ ┌───────▼──────┐ ┌──────▼───────┐ │ PostgreSQL │ │ Redis │ │ Ollama │ │ (Supabase/ │ │ (Upstash, │ │ (local, │ │ Neon) │ │ cloud) │ │ embeddings)│ └──────────────┘ └──────────────┘ └──────────────┘ ``` --- ## Layer responsibilities ### API layer (`api/v1/`) Twenty FastAPI router modules handle HTTP and WebSocket traffic. Each router depends on `core/deps.py` for JWT validation and workspace-context resolution. Business logic is delegated to the services layer or directly to SQLAlchemy queries for simple CRUD. Routers never import from one another. Key routers: | Router | Lines | Responsibility | |---|---|---| | `auth.py` | 554 | Registration, login, refresh, password reset, admin provisioning | | `tickets.py` | 267 | Ticket CRUD, status transitions, assignment | | `messages.py` | 352 | Thread messages, internal/public flagging | | `kb.py` | 1,213 | KB article CRUD, versioning, semantic search, bulk sync | | `nexus.py` | 607 | Master agent query interface (RBAC-isolated) | | `nexus_stream.py` | 222 | Streaming SSE responses for long AI operations | | `dashboard.py` | 487 | Workspace telemetry and AI-generated insights | | `reports.py` | 657 | SLA audit, personnel analytics, sentiment reports | | `websockets.py` | 85 | WebSocket upgrade and pub/sub subscription | ### Services layer (`services/`) Stateless async classes that encapsulate workspace-aware business logic. The `TicketService` handles hybrid search, role-based field sanitization (customers see different fields than staff), and telemetry aggregation. Services receive a `db: AsyncSession` via dependency injection and are the only layer that issues complex queries. ### Core infrastructure (`core/`) | Module | Purpose | |---|---| | `config.py` | Pydantic `BaseSettings`; all env var parsing with computed URL properties | | `database.py` | Two SQLAlchemy engine configs: `AsyncAdaptedQueuePool` (API, max 70) and `NullPool` (workers) | | `deps.py` | FastAPI dependencies — JWT decode, workspace-context resolution, role gate | | `security.py` | Password hashing (bcrypt), token generation, JTI-based revocation | | `cache.py` | L1 in-process LRU (2 048 entries) + L2 Redis + semantic vector cache | | `websockets.py` | Redis pub/sub manager; fanout to workspace and ticket-scoped channels | | `permissions.py` | Role-hierarchy helpers used by route guards and agent output masking | | `audit.py` | Append-only compliance log for sensitive actions | | `observability.py` | OpenTelemetry OTLP tracing instrumentation | ### Models (`models/`) Thirty SQLAlchemy models. All use UUID primary keys, UTC timestamps (`created_at`, `updated_at`), and a `deleted_at` soft-delete column. Key entities: ``` Workspace ──< UserWorkspace >── User │ ┌─────┴──────┐ Ticket NexusThread │ │ ┌──────┼────────┐ NexusInteraction Message Attachment Escalation │ Feedback Project ──< KBArticle ──< KBArticleChunk └──< KBArticleVersion └──< KnowledgeInsight WorkerJob NexusMemory NexusCheckpoint Notification ``` Search optimization on `Ticket` and `KBArticle`: - `TSVECTOR` computed column + GIN index for full-text search - `pgvector` column + HNSW index (768-dim) for semantic similarity - `content_hash` for deduplication --- ## Request lifecycle ``` Client │ ▼ Gunicorn/Uvicorn │ ▼ FastAPI middleware stack ├─ Security headers (HSTS, CSP, X-Frame-Options) ├─ CORS (workspace-domain aware) ├─ GZip compression └─ Trusted proxy (RFC-1918 forwarded headers) │ ▼ Router (api/v1/*.py) ├─ JWT decode → resolve workspace + role (core/deps.py) ├─ RBAC gate (core/permissions.py) │ ├─ [cache hit] → return L1/L2 cached response │ ├─ Service / direct DB query (AsyncSession) │ ├─ [side effects] → enqueue ARQ job (core/tasks.py) │ └─ Return Pydantic schema response ``` --- ## Caching strategy Three layers operate in order: 1. **L1 — in-process LRU** (`core/cache.py`): LRU dict with 2 048 slots. Zero-latency for hot read paths (workspace metadata, KB article headers). Invalidated on write within the same process; other Gunicorn workers invalidate on next L2 miss. 2. **L2 — Redis** (Upstash): Serialized JSON with configurable TTLs. Used for search results, dashboard telemetry, and KB chunk metadata. 3. **Semantic cache** (`core/cache.py`): Stores LLM response + embedding for recent queries. Incoming query is embedded and compared against cached embeddings via cosine similarity threshold (≥ 0.92). A cache hit bypasses the LLM entirely. Cache invalidation is write-through: mutations call `cache.invalidate(key)` which deletes from both L1 and L2. --- ## Real-time events (WebSocket pub/sub) ``` API write (e.g. new message) │ ▼ core/websockets.py ──publish──▶ Local Redis channel │ ┌────────▼────────┐ │ Subscriber loop │ (one per uvicorn worker) └────────┬────────┘ │ ┌─────────────┼─────────────┐ ▼ ▼ ▼ WS client 1 WS client 2 WS client N ``` Two channel namespaces: - `workspace:{workspace_id}` — workspace-wide events (ticket status, SLA alerts, insight ready) - `ticket:{ticket_id}` — thread-level events (new message, assignment change) Local Redis (not Upstash) is used for pub/sub because it requires a persistent TCP connection. Upstash's HTTP-based Redis does not support `SUBSCRIBE`. --- ## Background workers (ARQ) Two independent worker processes read from separate ARQ queues: **Regular worker** — high concurrency, sub-second jobs: - `monitor_sla_thresholds` (cron, every 5 min) - `notify_mentions` (on-demand) - `record_system_heartbeat` (cron, every 30 s) - `send_triple_notification` (on-demand, batch) **Heavy worker** — concurrency 1–2, 120 s timeout: - `auto_summarize_ticket` — dual LLM summaries (customer-facing + internal) - `index_kb_article` — chunk, embed, and HNSW-index a KB article - `crystallize_memory` — LLM summarization of long agent conversation histories - `generate_workspace_insights` — aggregate analytics → LLM narrative - `harvest_expertise_task` — extract structured knowledge from resolved tickets Job deduplication: a Redis-backed latch in `tasks/system.py` prevents the same job type from queuing twice for the same entity. --- ## Security model - **Transport**: TLS terminated at the reverse proxy (HF Spaces / Railway ingress). - **Auth**: JWT HS256 with access (60 min) + refresh (7 day) token pair. Logout stores the JTI in Redis with matching TTL (token blocklist). - **RBAC**: Roles resolved per-workspace from `UserWorkspace.role`. Six roles in hierarchy: `SUPERADMIN > SC_ADMIN > SC_LEAD > SC_AGENT > CUSTOMER_ADMIN > CUSTOMER_USER`. - **Workspace isolation**: All DB queries are scoped by `workspace_id` extracted from the JWT. Customers cannot read staff-internal fields (sanitized in `TicketService`). - **Agent output masking**: `agents/security.py` strips sensitive fields from LLM responses based on the requesting user's role before the response is returned. - **Input validation**: Pydantic schemas at every boundary; SQLAlchemy parameterized queries prevent SQL injection. - **Audit log**: `core/audit.py` appends an immutable record for sensitive operations. --- ## Further reading - [Hybrid search design](backend_insights/02_hybrid_search.md) - [Semantic caching](backend_insights/04_semantic_caching.md) - [Multi-tenant governance](backend_insights/05_multi_tenant_governance.md) - [Real-time sync](backend_insights/13_realtime_sync.md) - [DB schema design](backend_insights/11_db_schema_design.md) - [ARQ worker scaling](backend_insights/12_scaling_arq_workers.md) - [SLA enforcement](backend_insights/09_sla_enforcement.md)