# Architecture

> Understanding the system design and technical decisions behind Izri

## 📋 Overview

Izri is built as a modern, scalable monorepo application using TypeScript, React Router, Hono, tRPC, and Python. This section covers the architectural decisions, technology choices, and system design patterns used throughout the project.

## 🎯 Architectural Goals

The architecture is designed with these principles:

- **Type Safety**: End-to-end type safety from database to frontend
- **Modularity**: Clear separation of concerns with workspace packages
- **Scalability**: Easy to add new features and scale services
- **Developer Experience**: Fast builds, hot reload, and great tooling
- **Maintainability**: Clean code structure and comprehensive documentation
- **Performance**: Optimized for speed with caching and parallel builds

## 📚 Documentation Pages

### [System Overview](./overview.md)

**Essential reading for all developers**

High-level architecture covering:

- Overall system design
- Service interactions
- Data flow diagram
- Key components
- Communication patterns

### [Technology Stack](./technology-stack.md)

**Complete technology reference**

Detailed breakdown of all technologies:

- Frontend technologies (React Router, Tailwind, etc.)
- Backend technologies (Hono, tRPC, Drizzle)
- Infrastructure (Docker, PostgreSQL, Redis)
- Development tools (Turbo, pnpm, TypeScript)
- Why each technology was chosen

### [Monorepo Structure](./monorepo-structure.md)

**Understanding the codebase organization**

In-depth explanation of:

- Workspace organization
- Package dependencies
- Build orchestration
- Code sharing patterns
- Import strategies

### [Data Flow](./data-flow.md)

**How data moves through the system**

Comprehensive data flow documentation:

- Request/response lifecycle
- Database operations
- State management
- Caching strategies
- Error propagation

### [Design Decisions](./design-decisions.md)

**Key architectural and engineering decisions**

Historical record of important decisions:

- Why React Router over Next.js
- Why tRPC over REST
- Why Drizzle over Prisma
- Authentication strategy
- Database schema design
- API structure
- Deployment approach

## 🏗️ Architecture at a Glance

```
┌─────────────────────────────────────────────────────────────────┐
│                         User's Browser                          │
└────────────────────────────┬────────────────────────────────────┘
                             │
                             ├─ HTTP/WebSocket
                             │
┌────────────────────────────▼────────────────────────────────────┐
│                     React Router Web App                        │
│                    (apps/web - Port 5173)                       │
│                                                                  │
│  ┌─────────────┐  ┌──────────────┐  ┌──────────────────────┐  │
│  │   Routes    │  │  Components  │  │   tRPC Client        │  │
│  │  (Pages)    │  │   (UI)       │  │ (Type-safe API)      │  │
│  └─────────────┘  └──────────────┘  └──────────────────────┘  │
└────────────────────────────┬────────────────────────────────────┘
                             │
                             ├─ tRPC over HTTP
                             │
┌────────────────────────────▼────────────────────────────────────┐
│                    Hono + tRPC API Server                       │
│                    (apps/api - Port 4000)                       │
│                                                                  │
│  ┌─────────────┐  ┌──────────────┐  ┌──────────────────────┐  │
│  │   Routers   │  │   Context    │  │   Middleware         │  │
│  │  (tRPC)     │  │  (Auth, DB)  │  │ (Logging, Auth)      │  │
│  └─────────────┘  └──────────────┘  └──────────────────────┘  │
└────────┬───────────────────────────────────────────┬────────────┘
         │                                           │
         ├─ Drizzle ORM                             ├─ HTTP
         │                                           │
┌────────▼──────────────┐               ┌───────────▼─────────────┐
│   PostgreSQL 15       │               │   Python AI Service     │
│   (Port 5433/5432)    │               │   (Port 8000)           │
│                       │               │                         │
│  ┌─────────────────┐  │               │  ┌──────────────────┐  │
│  │  Tables         │  │               │  │  FastAPI         │  │
│  │  - users        │  │               │  │  - Analysis      │  │
│  │  - projects     │  │               │  │  - Test Gen      │  │
│  │  - test_runs    │  │               │  │  - AI Models     │  │
│  │  - orgs         │  │               │  └──────────────────┘  │
│  └─────────────────┘  │               └─────────────────────────┘
└───────────────────────┘
         │
         ├─ Redis Cache (Port 6379)
         │
┌────────▼──────────────┐
│     Redis Server      │
│   (Session, Cache)    │
└───────────────────────┘
```

## 🔧 Core Technologies

| Layer | Technology | Purpose |
|-------|-----------|---------|
| **Frontend** | React Router v7 | Modern React framework with SSR |
| **UI Library** | shadcn/ui + Tailwind | Beautiful, accessible components |
| **API Protocol** | tRPC | Type-safe API without code generation |
| **HTTP Server** | Hono | Fast, lightweight web framework |
| **Database ORM** | Drizzle ORM | TypeScript-first ORM |
| **Database** | PostgreSQL 15 | Robust relational database |
| **Cache** | Redis 7 | In-memory data store |
| **AI Service** | FastAPI | Python async web framework |
| **Package Manager** | pnpm | Fast, efficient package manager |
| **Build Tool** | Turbo | Monorepo build system |
| **Type System** | TypeScript | Static type checking |

## 🎨 Design Patterns

### 1. Monorepo Architecture

- **Pattern**: pnpm workspaces + Turbo
- **Benefits**: Code sharing, consistent tooling, atomic changes
- **Implementation**: See [Monorepo Structure](./monorepo-structure.md)

### 2. Type-Safe API

- **Pattern**: tRPC with shared types
- **Benefits**: End-to-end type safety, no code generation needed
- **Implementation**: See [Data Flow](./data-flow.md)

### 3. Repository Pattern

- **Pattern**: Database access through Drizzle queries
- **Benefits**: Testable, maintainable, type-safe database access
- **Implementation**: See [Design Decisions](./design-decisions.md)

### 4. Provider Pattern

- **Pattern**: React Context for cross-cutting concerns
- **Benefits**: Clean dependency injection, easy testing
- **Implementation**: See Frontend docs

### 5. Middleware Chain

- **Pattern**: Hono middleware for request processing
- **Benefits**: Reusable logic, clear separation of concerns
- **Implementation**: See Backend docs

## 📊 System Characteristics

### Performance

- **Build Time**: ~20s full build (with Turbo cache: <5s)
- **Hot Reload**: <100ms for most changes
- **API Response**: <50ms for cached queries
- **Database Queries**: <10ms average
- **Frontend Bundle**: <500KB gzipped

### Scalability

- **Horizontal**: API and AI services can scale independently
- **Vertical**: Database connection pooling supports high concurrency
- **Caching**: Redis caching reduces database load
- **Build**: Turbo caching speeds up CI/CD

### Reliability

- **Type Safety**: Catches errors at compile time
- **Database Transactions**: ACID compliance
- **Error Handling**: Comprehensive error boundaries
- **Logging**: Structured logging with Pino
- **Observability**: OpenTelemetry support

## 🔐 Security Architecture

### Authentication

- OAuth 2.0 with GitHub (primary)
- Credentials-based fallback
- API token support for programmatic access
- Session management with secure cookies

### Data Protection

- PostgreSQL with encrypted connections
- Environment variable management
- Input validation with Zod
- SQL injection protection (parameterized queries)
- XSS protection (React's built-in escaping)

### API Security

- CORS configuration
- Rate limiting (planned)
- Request validation
- Authentication middleware
- Authorization checks

## 🚀 Deployment Architecture

### Development

- Docker Compose for local infrastructure
- Hot reload for all services
- Drizzle Studio for database inspection
- Structured logging

### Production (Planned)

- Containerized services
- Load balancing
- Database replication
- Redis clustering
- CDN for static assets
- Log aggregation
- Monitoring and alerts

## 📖 Deep Dive Guides

### For New Developers

Start with these in order:

1. [System Overview](./overview.md) - Big picture understanding
2. [Technology Stack](./technology-stack.md) - What we use and why
3. [Monorepo Structure](./monorepo-structure.md) - Code organization

### For Experienced Developers

Focus on these:

1. [Design Decisions](./design-decisions.md) - Why things are the way they are
2. [Data Flow](./data-flow.md) - How everything connects
3. Backend/Frontend specific docs for implementation details

## 🎓 Learning Path

```
Start Here: System Overview
     ↓
Technology Stack (understand the tools)
     ↓
Monorepo Structure (navigate the code)
     ↓
Data Flow (understand communication)
     ↓
Design Decisions (learn the "why")
     ↓
Implementation Guides (Frontend/Backend docs)
```

## 🔗 Related Documentation

- **Frontend Architecture**: [Frontend Documentation](../frontend/README.md)
- **Backend Architecture**: [Backend Documentation](../backend/README.md)
- **Package Design**: [Packages Documentation](../packages/README.md)
- **Deployment**: [Deployment Documentation](../deployment/README.md)

## 🤝 Contributing to Architecture

When proposing architectural changes:

1. Document the decision in [Design Decisions](./design-decisions.md)
2. Update affected diagrams and documentation
3. Discuss in PR with the team
4. Consider impact on all packages
5. Update this README if needed

---

*Ready to dive deep? Start with [System Overview](./overview.md) →*
