# Architecture Overview

AdTlas is built using a modular Django architecture with microservices principles, designed for scalability, maintainability, and security.

## 🏗️ System Architecture

### High-Level Architecture

```
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│     Client      │    │     NGINX       │    │     Django      │
│   (Browser)     │◄──►│  Reverse Proxy  │◄──►│   Application   │
│                 │    │                 │    │                 │
└─────────────────┘    └─────────────────┘    └─────────────────┘
                                                        │
                                                        ▼
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   PostgreSQL    │    │      Redis      │    │     Celery      │
│    Database     │◄──►│   Cache/Queue   │◄──►│    Workers      │
│                 │    │                 │    │                 │
└─────────────────┘    └─────────────────┘    └─────────────────┘
                                                        │
                                                        ▼
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   Prometheus    │    │     Grafana     │    │   Celery Beat   │
│   Monitoring    │◄──►│   Dashboard     │    │   Scheduler     │
│                 │    │                 │    │                 │
└─────────────────┘    └─────────────────┘    └─────────────────┘
```

### Component Overview

| Component | Purpose | Technology |
|-----------|---------|------------|
| **Web Server** | Serve static files, reverse proxy | NGINX |
| **Application Server** | Django application | Gunicorn + Django |
| **Database** | Primary data storage | PostgreSQL |
| **Cache/Queue** | Caching and task queue | Redis |
| **Task Workers** | Async task processing | Celery |
| **Task Scheduler** | Periodic task scheduling | Celery Beat |
| **Monitoring** | Metrics collection | Prometheus |
| **Visualization** | Metrics dashboard | Grafana |

## 📦 Application Structure

### Django Apps Architecture

```
apps/
├── accounts/           # User management and authentication
│   ├── models.py       # User, Role, UserProfile models
│   ├── admin.py        # Admin interface configuration
│   ├── middleware.py   # Authentication middleware
│   └── signals.py      # User-related signals
│
├── authentification/   # Authentication views and forms
│   ├── views.py        # Login, register, password reset views
│   ├── forms.py        # Authentication forms
│   └── urls.py         # Authentication URL patterns
│
├── activities/         # Activity logging and audit trails
│   ├── models.py       # Activity, AuditLog, SecurityEvent models
│   ├── views.py        # Activity viewing and filtering
│   ├── middleware.py   # Activity logging middleware
│   └── signals.py      # Activity tracking signals
│
├── notifications/      # Notification system
│   ├── models.py       # Notification models
│   ├── services.py     # Notification business logic
│   ├── tasks.py        # Celery tasks for async notifications
│   └── views.py        # Notification management views
│
├── core/              # Shared utilities and base classes
│   ├── models.py      # Abstract base models
│   ├── utils.py       # Utility functions
│   └── views.py       # Base view classes
│
└── dashboard/         # Main dashboard interface
    ├── views.py       # Dashboard views
    └── templates/     # Dashboard templates
```

### Design Patterns

#### 1. **Model-View-Template (MVT)**
- **Models**: Data layer with business logic
- **Views**: Class-based views for request handling
- **Templates**: Presentation layer with Django templates

#### 2. **Repository Pattern**
- Service classes encapsulate business logic
- Models focus on data representation
- Clear separation of concerns

#### 3. **Observer Pattern**
- Django signals for loose coupling
- Event-driven architecture for notifications
- Activity logging through signals

#### 4. **Strategy Pattern**
- Configurable authentication backends
- Multiple notification delivery methods
- Pluggable middleware components

## 🔐 Security Architecture

### Authentication & Authorization

```
┌─────────────────┐
│   User Request  │
└─────────┬───────┘
          │
          ▼
┌─────────────────┐
│  Authentication │
│   Middleware    │
└─────────┬───────┘
          │
          ▼
┌─────────────────┐
│   Permission    │
│   Checking      │
└─────────┬───────┘
          │
          ▼
┌─────────────────┐
│   View Access   │
│    Control      │
└─────────────────┘
```

### Security Layers

1. **Network Security**
   - NGINX reverse proxy
   - SSL/TLS termination
   - Rate limiting

2. **Application Security**
   - CSRF protection
   - XSS prevention
   - SQL injection protection
   - Input validation

3. **Authentication Security**
   - Email-based authentication
   - Password strength requirements
   - Account lockout mechanisms
   - Session management

4. **Authorization Security**
   - Role-based access control (RBAC)
   - Permission-based access
   - Resource-level permissions

## 📊 Data Architecture

### Database Design Principles

1. **Normalization**: Proper database normalization to reduce redundancy
2. **Indexing**: Strategic indexing for performance optimization
3. **Constraints**: Foreign key and check constraints for data integrity
4. **Soft Deletes**: Soft delete pattern for data recovery
5. **Audit Trail**: Comprehensive activity logging

### Key Relationships

```
User ──┬── UserProfile (1:1)
       ├── UserRole (1:M) ── Role (M:1)
       ├── Activity (1:M)
       ├── Notification (1:M)
       └── AuditLog (1:M)

Role ── Permission (M:M)

Notification ── NotificationType (M:1)
             ── NotificationTemplate (M:1)

Activity ── ActivityType (M:1)
```

## 🚀 Performance Architecture

### Caching Strategy

1. **Database Query Caching**
   - Redis for query result caching
   - Cache invalidation strategies
   - Cache warming for critical data

2. **Session Caching**
   - Redis-based session storage
   - Distributed session management

3. **Template Caching**
   - Fragment caching for expensive operations
   - Template-level caching

### Async Processing

1. **Celery Tasks**
   - Email notifications
   - Report generation
   - Data processing
   - Cleanup operations

2. **Task Queues**
   - Priority-based task queuing
   - Retry mechanisms
   - Dead letter queues

## 📈 Monitoring Architecture

### Metrics Collection

```
Django App ──► Prometheus ──► Grafana
    │              │
    ▼              ▼
Celery ────────► Alerts
    │
    ▼
PostgreSQL
    │
    ▼
  Redis
```

### Key Metrics

1. **Application Metrics**
   - Request/response times
   - Error rates
   - User activity

2. **Infrastructure Metrics**
   - CPU/Memory usage
   - Database performance
   - Queue lengths

3. **Business Metrics**
   - User registrations
   - Login success rates
   - Feature usage

## 🔧 Configuration Management

### Environment-based Configuration

```
config/
├── settings/
│   ├── base.py      # Common settings
│   ├── dev.py       # Development settings
│   ├── prod.py      # Production settings
│   └── test.py      # Testing settings
└── .env             # Environment variables
```

### Configuration Principles

1. **12-Factor App**: Environment-based configuration
2. **Security**: Sensitive data in environment variables
3. **Flexibility**: Easy environment switching
4. **Validation**: Configuration validation on startup

## 🐳 Containerization Architecture

### Docker Services

```yaml
services:
  web:        # Django application
  nginx:      # Reverse proxy
  postgres:   # Database
  redis:      # Cache/Queue
  celery:     # Task workers
  celery-beat: # Task scheduler
  prometheus: # Monitoring
  grafana:    # Visualization
```

### Container Benefits

1. **Consistency**: Same environment across dev/staging/prod
2. **Scalability**: Easy horizontal scaling
3. **Isolation**: Service isolation and security
4. **Deployment**: Simplified deployment process

---

**Next**: [Database Schema](database.md) | [Security Guide](security.md)