# Multi-Tenant Architecture This document describes the multi-tenant implementation for the Telegram Marketing Intelligence Agent System. ## Overview The system supports full multi-tenant isolation, allowing multiple organizations to use the same instance while keeping their data completely separated. ## Architecture ### Tenant Model Each tenant has: - **Basic Information**: Name, slug, domain - **Plan & Limits**: Subscription plan with resource limits - **Usage Tracking**: Real-time usage monitoring - **Billing**: Integrated billing and payment tracking - **Settings**: Customizable preferences per tenant - **Branding**: White-label support for enterprise plans - **Features**: Plan-based feature toggles - **Compliance**: GDPR and data retention settings ### Data Isolation All data models include a `tenantId` field that ensures complete data isolation: - MongoDB models use compound indexes with tenantId - Sequelize models use foreign key references - All queries automatically filter by current tenant ### Tenant Context The tenant context is determined through multiple methods: 1. **Subdomain**: `acme.app.com` → tenant: acme 2. **Custom Domain**: `app.acme.com` → tenant: acme 3. **Header**: `X-Tenant-Id` for API access 4. **URL Parameter**: `?tenant=acme` for multi-tenant admin 5. **User Association**: From authenticated user's tenant ## Implementation ### 1. Tenant Middleware ```javascript // Automatically adds tenant context to all requests app.use(tenantMiddleware); app.use(allowCrossTenant); // For superadmin access ``` ### 2. Model Updates All models now include tenantId: ```javascript const schema = new Schema({ tenantId: { type: ObjectId, ref: 'Tenant', required: true, index: true }, // ... other fields }); ``` ### 3. API Routes #### Public Routes - `POST /api/v1/tenants/signup` - Create new tenant #### Tenant Routes (Authenticated) - `GET /api/v1/tenants/current` - Get current tenant - `PATCH /api/v1/tenants/current/settings` - Update settings - `PATCH /api/v1/tenants/current/branding` - Update branding - `GET /api/v1/tenants/current/usage` - Get usage statistics #### Superadmin Routes - `GET /api/v1/tenants` - List all tenants - `PATCH /api/v1/tenants/:id` - Update any tenant - `DELETE /api/v1/tenants/:id` - Delete tenant ### 4. Frontend Components #### Tenant Settings - Location: `/dashboard/tenant/settings` - Features: - General settings (timezone, language, currency) - Security settings (2FA, SSO) - Branding (logo, colors, custom CSS) - Usage monitoring and limits - Compliance configuration #### Tenant Management (Superadmin) - Location: `/dashboard/tenants` - Features: - List all tenants with filtering - Edit tenant plans and limits - Suspend/activate tenants - Login as tenant - Delete tenants ## Plans & Features ### Free Plan - 5 users - 10 campaigns - 1,000 messages/month - Basic analytics - Community support ### Starter Plan ($29/month) - 20 users - 50 campaigns - 10,000 messages/month - Automation - API access - Email support ### Professional Plan ($99/month) - 100 users - 200 campaigns - 50,000 messages/month - A/B testing - Custom reports - Multi-language - Priority support ### Enterprise Plan (Custom) - Unlimited everything - White-label branding - AI suggestions - SLA guarantee - Dedicated support ## Resource Limits Each tenant has configurable limits: - `users`: Maximum number of users - `campaigns`: Maximum number of campaigns - `messagesPerMonth`: Monthly message limit - `telegramAccounts`: Number of Telegram accounts - `storage`: Storage quota in bytes - `apiCallsPerHour`: API rate limiting - `webhooks`: Number of webhooks - `customIntegrations`: Enable/disable custom integrations ## Usage Tracking The system tracks usage in real-time: ```javascript // Check limit before operation if (!tenant.checkLimit('campaigns')) { throw new Error('Campaign limit exceeded'); } // Increment usage after successful operation await tenant.incrementUsage('campaigns'); // Monthly reset for message limits await tenant.resetMonthlyUsage(); ``` ## Security Considerations ### Tenant Isolation - All database queries include tenant filtering - Compound indexes ensure query performance - Cross-tenant access blocked except for superadmin ### Authentication - Users belong to a single tenant - Tenant context included in JWT tokens - API keys scoped to tenant ### Compliance - Per-tenant GDPR settings - Configurable data retention - IP whitelisting support - Audit logging per tenant ## Migration Guide ### For Existing Installations 1. **Backup your data** before migration 2. **Run migration script**: ```bash node scripts/migrate-to-multitenant.js ``` 3. **Update environment variables**: ```env DEFAULT_TENANT_SLUG=default ENABLE_MULTI_TENANT=true ``` 4. **Test tenant isolation**: ```bash npm run test:multitenant ``` ### For New Installations Multi-tenancy is enabled by default. The first user signup creates a new tenant automatically. ## Best Practices ### Development 1. Always include tenantId in queries 2. Use tenant middleware for automatic filtering 3. Test with multiple tenants in development 4. Validate tenant limits before operations ### Production 1. Monitor tenant usage regularly 2. Set up alerts for limit approaching 3. Implement proper backup strategies per tenant 4. Use custom domains for enterprise tenants ### Performance 1. Ensure all queries use tenant indexes 2. Monitor slow queries per tenant 3. Implement caching strategies 4. Use read replicas for analytics ## Troubleshooting ### Common Issues 1. **"Tenant not found" error** - Check tenant slug/domain configuration - Verify tenant status is active - Check subdomain DNS settings 2. **Data visible across tenants** - Ensure tenantId is in all queries - Check model indexes - Verify middleware is applied 3. **Performance degradation** - Check compound index usage - Monitor per-tenant query patterns - Consider sharding large tenants ### Debug Mode Enable tenant debug logging: ```javascript // In development process.env.TENANT_DEBUG = 'true'; ``` This logs all tenant resolution and filtering operations. ## Future Enhancements 1. **Tenant Sharding**: Distribute large tenants across databases 2. **Tenant Templates**: Pre-configured tenant setups 3. **Tenant Marketplace**: Share templates/workflows between tenants 4. **Advanced Analytics**: Cross-tenant analytics for superadmin 5. **Automated Scaling**: Dynamic resource allocation based on usage