# Lilith System Architecture

## Overview

Lilith employs a microservices architecture designed for scalability,
maintainability, and resilience. The system comprises 60+ services organized
into functional domains, connected through an API gateway and service mesh.

## Architecture Diagrams

### High-Level System Architecture

```
┌────────────────────────────────────────────────────────────────────────────┐
│                              CLIENTS                                        │
│                                                                            │
│   ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐   │
│   │ Web PWA  │  │ iOS App  │  │ Android  │  │ VR/XR    │  │ IoT/     │   │
│   │ (Next.js)│  │(R.Native)│  │(R.Native)│  │ (WebXR)  │  │ Biometric│   │
│   └────┬─────┘  └────┬─────┘  └────┬─────┘  └────┬─────┘  └────┬─────┘   │
└────────┼─────────────┼─────────────┼─────────────┼─────────────┼──────────┘
         │             │             │             │             │
         └─────────────┴──────┬──────┴─────────────┴─────────────┘
                              │
                              ▼
┌────────────────────────────────────────────────────────────────────────────┐
│                           EDGE LAYER                                        │
│  ┌─────────────────────────────────────────────────────────────────────┐  │
│  │                        CDN (CloudFront/Fastly)                       │  │
│  │              Static Assets • Media Delivery • Edge Caching           │  │
│  └─────────────────────────────────┬───────────────────────────────────┘  │
│                                    │                                       │
│  ┌─────────────────────────────────▼───────────────────────────────────┐  │
│  │                        API Gateway                                   │  │
│  │       WAF • Rate Limiting • JWT Verification • Request Routing       │  │
│  └─────────────────────────────────┬───────────────────────────────────┘  │
└────────────────────────────────────┼───────────────────────────────────────┘
                                     │
                                     ▼
┌────────────────────────────────────────────────────────────────────────────┐
│                     BACKEND-FOR-FRONTEND (BFF)                             │
│                                                                            │
│  ┌────────────────────────────────────────────────────────────────────┐   │
│  │                         BFF Service                                 │   │
│  │   • Request Aggregation    • Response Shaping    • A/B Experiments │   │
│  │   • Client Versioning      • Error Normalization • Correlation IDs │   │
│  └────────────────────────────────┬───────────────────────────────────┘   │
└───────────────────────────────────┼────────────────────────────────────────┘
                                    │
         ┌──────────────────────────┼──────────────────────────┐
         │                          │                          │
         ▼                          ▼                          ▼
┌─────────────────┐      ┌─────────────────┐      ┌─────────────────┐
│  CORE SERVICES  │      │   AI SERVICES   │      │ MEDIA SERVICES  │
├─────────────────┤      ├─────────────────┤      ├─────────────────┤
│ • Auth          │      │ • AI Orchestr.  │      │ • TTS (Chatter) │
│ • Content       │      │ • RAG Pipeline  │      │ • STT (Whisper) │
│ • Conversation  │      │ • Knowledge     │      │ • Media Store   │
│ • Notification  │      │ • Vector DB     │      │ • Voice Pipeline│
│ • Moderation    │      │ • Ingestion     │      │ • WebRTC SFU    │
│ • User Prefs    │      │ • Embeddings    │      │ • Audio Handoff │
│ • Progress Sync │      │ • Multi-Agent   │      │ • Spatial Audio │
└────────┬────────┘      └────────┬────────┘      └────────┬────────┘
         │                        │                        │
         └────────────────────────┼────────────────────────┘
                                  │
                                  ▼
┌────────────────────────────────────────────────────────────────────────────┐
│                         SERVICE MESH (ISTIO)                               │
│              mTLS • Circuit Breakers • Retries • Load Balancing            │
└────────────────────────────────┬───────────────────────────────────────────┘
                                 │
         ┌───────────────────────┼───────────────────────┐
         ▼                       ▼                       ▼
┌─────────────────┐   ┌─────────────────┐   ┌─────────────────┐
│  BLOCKCHAIN     │   │  METAVERSE      │   │  CONSCIOUSNESS  │
├─────────────────┤   ├─────────────────┤   ├─────────────────┤
│ • Smart Contrs  │   │ • World Engine  │   │ • Biometric     │
│ • Wallet        │   │ • Avatar System │   │ • Brainwave     │
│ • IPFS Gateway  │   │ • Physics       │   │ • Dream Tracker │
│ • DeFi          │   │ • Multiplayer   │   │ • Energy Map    │
│ • Token         │   │ • Spatial Audio │   │ • Group Consc.  │
└────────┬────────┘   └────────┬────────┘   └────────┬────────┘
         │                     │                     │
         └─────────────────────┼─────────────────────┘
                               │
                               ▼
┌────────────────────────────────────────────────────────────────────────────┐
│                          DATA LAYER                                        │
│                                                                            │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐      │
│  │  PostgreSQL │  │  Vector DB  │  │    Neo4j    │  │  S3/Object  │      │
│  │  (Primary)  │  │  (Milvus)   │  │  (Graph)    │  │  (Media)    │      │
│  └─────────────┘  └─────────────┘  └─────────────┘  └─────────────┘      │
│                                                                            │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐      │
│  │    Redis    │  │   Kafka     │  │ TimescaleDB │  │  Arweave    │      │
│  │  (Cache)    │  │  (Events)   │  │ (Biometric) │  │  (Permanent)│      │
│  └─────────────┘  └─────────────┘  └─────────────┘  └─────────────┘      │
└────────────────────────────────────────────────────────────────────────────┘
```

### Request Flow - Chat Interaction

```
┌──────┐     ┌─────────┐     ┌─────┐     ┌──────────────┐     ┌─────────┐
│Client│────>│API Gate │────>│ BFF │────>│Conversation  │────>│   AI    │
└──────┘     └─────────┘     └─────┘     │   Service    │     │ Service │
                                         └──────────────┘     └────┬────┘
                                                                   │
     ┌─────────────────────────────────────────────────────────────┘
     │
     ▼
┌─────────┐     ┌─────────┐     ┌─────────┐     ┌─────────┐
│   RAG   │────>│Knowledge│────>│ Vector  │────>│   LLM   │
│Pipeline │     │  Graph  │     │   DB    │     │Provider │
└─────────┘     └─────────┘     └─────────┘     └────┬────┘
                                                     │
     ┌───────────────────────────────────────────────┘
     │
     ▼
┌─────────┐     ┌─────────┐     ┌─────────┐
│Moderator│────>│   TTS   │────>│  Client │
│ Service │     │ Service │     │(SSE/WS) │
└─────────┘     └─────────┘     └─────────┘
```

### Multi-Agent AI Architecture

```
                         ┌─────────────────┐
                         │  User Request   │
                         └────────┬────────┘
                                  │
                                  ▼
                    ┌─────────────────────────┐
                    │    Intent Classifier    │
                    │   (Query Understanding) │
                    └────────────┬────────────┘
                                 │
                                 ▼
                    ┌─────────────────────────┐
                    │     Agent Selector      │
                    │  (Route to Specialists) │
                    └────────────┬────────────┘
                                 │
         ┌───────────────────────┼───────────────────────┐
         │                       │                       │
         ▼                       ▼                       ▼
┌─────────────────┐   ┌─────────────────┐   ┌─────────────────┐
│  LIBRARIAN AI   │   │   TEACHER AI    │   │   SAFETY AI     │
│                 │   │                 │   │                 │
│ • Query Planning│   │ • Instruction   │   │ • Moderation    │
│ • Source Search │   │ • Style/Tone    │   │ • Policy Check  │
│ • Citation Mgmt │   │ • Adaptation    │   │ • Content Filter│
│ • Fact Retrieval│   │ • Persona Voice │   │ • Age Gating    │
└────────┬────────┘   └────────┬────────┘   └────────┬────────┘
         │                     │                     │
         └─────────────────────┼─────────────────────┘
                               │
                               ▼
                  ┌─────────────────────────┐
                  │   Response Synthesis    │
                  │  (Merge Agent Outputs)  │
                  └────────────┬────────────┘
                               │
                               ▼
                  ┌─────────────────────────┐
                  │   Multi-Modal Output    │
                  │ (Text/Voice/3D/Energy)  │
                  └─────────────────────────┘
```

## Service Catalog

### Core Platform Services (17 Production-Ready)

| Service              | Port | Description                              | Tests |
| -------------------- | ---- | ---------------------------------------- | ----- |
| **auth**             | 8001 | JWT, OAuth2, MFA, RBAC, Web3 wallet auth | 505   |
| **bff**              | 8000 | Backend-for-Frontend aggregation         | 284   |
| **content**          | 8002 | Encyclopedia, courses, versioning        | 263   |
| **conversation**     | 8003 | Thread/message store, SSE streaming      | 155   |
| **ai**               | 8004 | Multi-agent orchestration, RAG pipeline  | 1,078 |
| **media**            | 8005 | Metadata, packaging, signed URLs         | 340   |
| **notification**     | 8006 | Push, email, multi-channel               | 60    |
| **moderation**       | 8007 | Content filtering, safety checks         | 74    |
| **rag**              | 8008 | Retrieval augmented generation           | 175   |
| **knowledge**        | 8009 | Knowledge graph management               | 82    |
| **stt**              | 8010 | Speech-to-text (Whisper-class)           | 57    |
| **tts**              | 8011 | Text-to-speech with SSML                 | 133   |
| **ingestion**        | 8012 | Content pipeline, OCR                    | 57    |
| **anonymization**    | 8013 | Privacy pipelines                        | 87    |
| **data-governance**  | 8014 | GDPR/CCPA compliance                     | 84    |
| **user-preferences** | 8015 | Preferences management                   | 69    |
| **offline**          | 8016 | Offline data layer                       | 41    |

### Metaverse Services

| Service              | Description                          |
| -------------------- | ------------------------------------ |
| **metaverse**        | World engine, environment management |
| **avatar-cosmetic**  | Character customization              |
| **sacred-space**     | Sacred environment templates         |
| **sacred-art**       | Spiritual artwork management         |
| **sacred-music**     | Meditation music generation          |
| **group-meditation** | Synchronized sessions                |

### Blockchain Services

| Service                | Description                 |
| ---------------------- | --------------------------- |
| **blockchain**         | Smart contract interactions |
| **native-token**       | $LILITH token operations    |
| **cross-chain-bridge** | Multi-chain bridging        |
| **dao-governance**     | DAO voting and proposals    |
| **defi-integration**   | Staking, yield farming      |
| **ipfs-integration**   | Decentralized storage       |

### Consciousness Tech Services

| Service                   | Description                |
| ------------------------- | -------------------------- |
| **biometric**             | EEG, HRV, GSR processing   |
| **meditation-experience** | Session management         |
| **meditation-generation** | AI-generated meditations   |
| **spiritual-embeddings**  | Tradition-specific vectors |
| **spiritual-guidance**    | Personalized guidance      |

## Data Flow Patterns

### 1. Synchronous Request-Response

Used for: Chat, API queries, authentication

```
Client → API Gateway → BFF → Service → Database → Response
```

### 2. Server-Sent Events (SSE)

Used for: Chat token streaming, real-time updates

```
Client ←─SSE─ BFF ←─SSE─ AI Service ←─Token─ LLM
```

### 3. WebSocket

Used for: Voice chat, metaverse sync, real-time collaboration

```
Client ←─WS─ WebRTC SFU ←─WS─ Voice Pipeline
```

### 4. Event-Driven (Async)

Used for: Notifications, content processing, analytics

```
Service → Kafka → Consumer Service → Action
```

### 5. Batch Processing

Used for: Lecture generation, embedding updates, reports

```
Scheduler → Job Queue → Worker → Storage
```

## Infrastructure

### Kubernetes Deployment

```
┌────────────────────────────────────────────────────────────────┐
│                    KUBERNETES CLUSTER                          │
│                                                                │
│  ┌────────────────────────────────────────────────────────┐   │
│  │                   ISTIO SERVICE MESH                    │   │
│  │              mTLS • Traffic Management • Observability  │   │
│  └────────────────────────────────────────────────────────┘   │
│                                                                │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐        │
│  │  Namespace:  │  │  Namespace:  │  │  Namespace:  │        │
│  │   lilith-    │  │   lilith-    │  │   lilith-    │        │
│  │    core      │  │     ai       │  │    media     │        │
│  │              │  │              │  │              │        │
│  │ • auth       │  │ • ai         │  │ • tts        │        │
│  │ • bff        │  │ • rag        │  │ • stt        │        │
│  │ • content    │  │ • knowledge  │  │ • media      │        │
│  │ • convers.   │  │ • vectordb   │  │ • webrtc     │        │
│  └──────────────┘  └──────────────┘  └──────────────┘        │
│                                                                │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐        │
│  │  Namespace:  │  │  Namespace:  │  │  Namespace:  │        │
│  │   lilith-    │  │   lilith-    │  │   lilith-    │        │
│  │    data      │  │   infra      │  │  monitoring  │        │
│  │              │  │              │  │              │        │
│  │ • postgres   │  │ • redis      │  │ • prometheus │        │
│  │ • neo4j      │  │ • kafka      │  │ • grafana    │        │
│  │ • milvus     │  │ • vault      │  │ • jaeger     │        │
│  └──────────────┘  └──────────────┘  └──────────────┘        │
└────────────────────────────────────────────────────────────────┘
```

### GitOps with ArgoCD

```
┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│    Git      │────>│   ArgoCD    │────>│ Kubernetes  │
│ Repository  │     │   (GitOps)  │     │   Cluster   │
└─────────────┘     └─────────────┘     └─────────────┘
       │                   │                   │
       │                   ▼                   │
       │         ┌─────────────────┐           │
       │         │ App-of-Apps     │           │
       │         │ Pattern         │           │
       │         └─────────────────┘           │
       │                   │                   │
       ▼                   ▼                   ▼
┌──────────────────────────────────────────────────┐
│  deploy/argocd/app-of-apps.yaml                  │
│  deploy/helm/lilith-service/                     │
│  deploy/terraform/                               │
└──────────────────────────────────────────────────┘
```

### Terraform Modules

```
deploy/terraform/
├── modules/
│   ├── kubernetes/          # EKS/GKE cluster
│   ├── networking/          # VPC, subnets, security groups
│   ├── databases/           # RDS, ElastiCache, managed DBs
│   ├── storage/             # S3, EFS, persistent volumes
│   ├── monitoring/          # CloudWatch, Prometheus stack
│   └── security/            # IAM, KMS, secrets management
├── environments/
│   ├── dev/
│   ├── staging/
│   └── production/
└── main.tf
```

## Security Architecture

### Authentication Flow

```
┌──────┐     ┌─────────────┐     ┌──────────┐     ┌──────────┐
│Client│────>│ API Gateway │────>│   Auth   │────>│  Vault   │
│      │<────│ (JWT Verify)│<────│ Service  │<────│  (KMS)   │
└──────┘     └─────────────┘     └──────────┘     └──────────┘
   │                                   │
   │         ┌──────────────────────────┘
   │         │
   │         ▼
   │   ┌──────────┐     ┌──────────┐
   │   │ Session  │────>│ PostgreSQL│
   │   │ Store    │     │  (Users)  │
   │   └──────────┘     └──────────┘
   │
   ▼
┌────────────────────────────────────────────┐
│             JWT Token                       │
│  {                                         │
│    "sub": "user_id",                       │
│    "iat": 1234567890,                      │
│    "exp": 1234571490,                      │
│    "roles": ["user", "premium"],           │
│    "permissions": ["chat:read", "..."]     │
│  }                                         │
└────────────────────────────────────────────┘
```

### Security Layers

| Layer              | Security Measures                                  |
| ------------------ | -------------------------------------------------- |
| **Edge**           | WAF, DDoS protection, rate limiting, bot detection |
| **Transport**      | TLS 1.3, mTLS between services                     |
| **Authentication** | JWT (short TTL), OAuth2, WebAuthn MFA              |
| **Authorization**  | RBAC/ABAC, service-to-service auth                 |
| **Data**           | AES-256 encryption, field-level encryption         |
| **Secrets**        | Vault/KMS, envelope encryption, rotation           |

## Observability Stack

### Metrics, Logging, Tracing

```
┌────────────────────────────────────────────────────────────────┐
│                      OBSERVABILITY                             │
│                                                                │
│  ┌────────────────┐  ┌────────────────┐  ┌────────────────┐  │
│  │   PROMETHEUS   │  │    GRAFANA     │  │    JAEGER      │  │
│  │    (Metrics)   │  │  (Dashboards)  │  │   (Tracing)    │  │
│  └───────┬────────┘  └───────┬────────┘  └───────┬────────┘  │
│          │                   │                   │            │
│          └───────────────────┼───────────────────┘            │
│                              │                                │
│  ┌────────────────┐  ┌──────┴──────┐  ┌────────────────┐     │
│  │  FLUENTD/      │  │   LOKI      │  │  ALERTMANAGER  │     │
│  │  FLUENTBIT     │──│  (Logs)     │  │   (Alerts)     │     │
│  └────────────────┘  └─────────────┘  └────────────────┘     │
└────────────────────────────────────────────────────────────────┘
```

### Key Metrics

| Category       | Metrics                                            |
| -------------- | -------------------------------------------------- |
| **Latency**    | p50/p95 response times, TTS first-byte             |
| **Throughput** | RPS, concurrent users, message volume              |
| **Errors**     | Error rates, 4xx/5xx counts, circuit breaker trips |
| **Resources**  | CPU, memory, GPU utilization, connection pools     |
| **Business**   | DAU, chat sessions, completion rates               |

## Scaling Strategy

### Horizontal Pod Autoscaling

```yaml
# Example HPA configuration
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: ai-service-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: ai-service
  minReplicas: 3
  maxReplicas: 50
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70
    - type: Pods
      pods:
        metric:
          name: requests_per_second
        target:
          type: AverageValue
          averageValue: 100
```

### Scale Targets

| Service          | Min Pods | Max Pods | Scale Metric     |
| ---------------- | -------- | -------- | ---------------- |
| **bff**          | 3        | 100      | CPU, RPS         |
| **ai**           | 5        | 50       | Queue depth, GPU |
| **tts**          | 3        | 30       | GPU, queue       |
| **conversation** | 3        | 50       | Connections      |

## Related Documentation

- **Detailed Service Docs**: `../services/<service>/README.md`
- **OpenAPI Specification**: `../openapi/openapi.yaml`
- **Helm Charts**: `../deploy/helm/`
- **Terraform Modules**: `../deploy/terraform/`
- **ADR on Microservices**:
  [decisions/adr-0001-microservices-architecture.md](./decisions/adr-0001-microservices-architecture.md)

---

_For operational procedures, see [operations.md](./operations.md)_
