# SwarmCare Production Architecture

## System Overview

```
                                    +------------------+
                                    |   Load Balancer  |
                                    |    (Traefik)     |
                                    +--------+---------+
                                             |
              +------------------------------+------------------------------+
              |                              |                              |
    +---------v---------+         +----------v----------+        +----------v----------+
    |   SwarmCare UI    |         |   SwarmCare API     |        |   Monitoring        |
    |   (Next.js)       |         |   (FastAPI)         |        |   (Prometheus)      |
    |   Port: 3000      |         |   Port: 8001        |        |   Port: 9090        |
    +---------+---------+         +----------+----------+        +---------------------+
              |                              |
              |                   +----------+----------+
              |                   |                     |
              |          +--------v--------+   +--------v--------+
              |          |     Redis       |   |     Neo4j       |
              |          |   (Cache)       |   | (Knowledge Graph)|
              |          |   Port: 6379    |   |   Port: 7474     |
              |          +-----------------+   +-----------------+
              |
              +---> All API calls go through FastAPI
```

## Knowledge Graph Architecture

### Node Clusters
1. **Patient Cluster** - Demographics, identifiers, risk scores
2. **Clinical Cluster** - Conditions, diagnoses, procedures
3. **Medication Cluster** - Drugs, prescriptions, adherence
4. **Diagnostic Cluster** - Labs, imaging, vitals
5. **Provider Cluster** - Physicians, care teams, facilities
6. **Temporal Cluster** - Encounters, timelines, episodes

### Edge Types (Relationships)
- `HAS_CONDITION` - Patient -> Condition
- `TAKES_MEDICATION` - Patient -> Medication
- `HAS_LAB_RESULT` - Patient -> LabResult
- `HAS_IMAGING` - Patient -> ImagingReport
- `TREATED_BY` - Patient -> Provider
- `INDICATES` - Condition -> Medication (treatment)
- `CONTRAINDICATES` - Medication -> Condition
- `INTERACTS_WITH` - Medication -> Medication
- `CODED_AS` - Entity -> OntologyCode (SNOMED, ICD-10, etc.)

### Property Clusters (Indexed)
- **Ontology Properties**: snomed_ct, icd10, rxnorm, loinc, cpt, ndc
- **Temporal Properties**: onset_date, recorded_date, effective_date
- **Status Properties**: status, severity, priority
- **Metric Properties**: risk_score, confidence, value

## Ontology Mapping

| Domain | Ontology | Purpose |
|--------|----------|---------|
| Diagnoses | SNOMED CT | Clinical terminology |
| Diagnoses | ICD-10-CM | Billing codes |
| Medications | RxNorm | Drug normalization |
| Medications | NDC | Product identification |
| Medications | ATC | Therapeutic classification |
| Labs | LOINC | Lab test codes |
| Procedures | CPT | Procedure codes |
| Procedures | HCPCS | Healthcare services |
| Concepts | UMLS | Concept unification |
| Literature | MeSH | Medical subject headings |
| Phenotypes | HPO | Human phenotype |
| Genetics | OMIM | Genetic disorders |
| Radiology | RadLex | Imaging terminology |

## Response Time Optimization

### Redis Caching Strategy
1. **L1 Cache (Hot)**: Patient summaries, active alerts - TTL: 60s
2. **L2 Cache (Warm)**: Full patient data, care plans - TTL: 300s
3. **L3 Cache (Cold)**: Historical data, analytics - TTL: 3600s

### Query Optimization
- Neo4j indexes on all ontology codes
- Composite indexes for common query patterns
- Query result caching in Redis
- Connection pooling for all databases

## EHR Document Aggregation

```python
EHR_Document = {
    "patient": Patient,
    "demographics": Demographics,
    "conditions": [Condition],      # ICD-10, SNOMED
    "medications": [Medication],    # RxNorm, NDC
    "allergies": [Allergy],         # SNOMED
    "lab_results": [LabResult],     # LOINC
    "vital_signs": [VitalSign],     # LOINC
    "imaging_reports": [Imaging],   # RadLex
    "procedures": [Procedure],      # CPT, HCPCS
    "encounters": [Encounter],
    "care_plans": [CarePlan],
    "providers": [Provider],        # NPI
    "insurance": [Coverage],
    "knowledge_graph": KnowledgeGraph
}
```

## Docker Services

| Service | Image | Port | Purpose |
|---------|-------|------|---------|
| swarmcare-ui | node:20-alpine | 3000 | Frontend |
| swarmcare-api | python:3.11-slim | 8001 | Backend API |
| neo4j | neo4j:5.15-community | 7474, 7687 | Knowledge Graph |
| redis | redis:7-alpine | 6379 | Caching |
| prometheus | prom/prometheus | 9090 | Metrics |
| grafana | grafana/grafana | 3001 | Dashboards |

## Tracking & Monitoring

1. **API Metrics**: Response times, error rates, throughput
2. **Cache Metrics**: Hit/miss ratio, memory usage
3. **Graph Metrics**: Query times, node/edge counts
4. **Business Metrics**: Patients processed, alerts generated
