# Telegram SaaS Platform — Architecture Overview

## 1. High-Level Architecture

The platform is designed as a **Modular Monolith with Distributed Workers**:
- **Gateway / API Process (`apps.api`)**: FastAPI application handling REST endpoints, authentication, tenant resolution, RBAC validation, and webhook dispatching.
- **Telegram Runtime Process (`apps.telegram`)**: Aiogram 3 engine running webhooks and handlers, dynamically loading tenant bot tokens.
- **Background Worker (`apps.worker`)**: Celery workers consuming tasks from RabbitMQ/Redis for notifications, broadcasts, AI generations, analytics ingestion, and payment webhooks.
- **Scheduler (`apps.scheduler`)**: Celery beat for recurring tasks (usage counters reset, subscription renewals, token cleanup).

```
                      +-----------------------------+
                      |       Nginx / Gateway       |
                      +--------------+--------------+
                                     |
               +---------------------+---------------------+
               |                                           |
      +--------v--------+                         +--------v--------+
      |  FastAPI (API)  |                         | Telegram Engine |
      +--------+--------+                         +--------+--------+
               |                                           |
               +---------------------+---------------------+
                                     |
               +---------------------+---------------------+
               |                     |                     |
      +--------v--------+   +--------v--------+   +--------v--------+
      |   PostgreSQL    |   |      Redis      |   | RabbitMQ/Celery |
      | (Asyncpg + RLS) |   | (Cache + Locks) |   | (Async Workers) |
      +-----------------+   +-----------------+   +-----------------+
```

## 2. Multi-Tenancy Design

- **Shared Database, Isolated Data**: All tenants share the relational database, but every entity belongs strictly to a `tenant_id`.
- **Tenant Context**: Python's `contextvars` propagates `current_tenant_id` throughout async request lifecycles.
- **API Resolution**: Authenticated endpoints inspect `X-Tenant-ID` header, verifying tenant membership and RBAC permissions before executing any logic.
- **Cache Isolation**: Redis keys are prefixed with `tenant:{tenant_id}:{key}`.
- **Encryption**: Telegram bot tokens and third-party API keys are encrypted at rest with AES-256-GCM using authenticated encryption.
