Full-stack web application for Telegram management - Frontend: Vue 3 + Vben Admin - Backend: NestJS - Features: User management, group broadcast, statistics 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
6.4 KiB
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:
- Subdomain:
acme.app.com→ tenant: acme - Custom Domain:
app.acme.com→ tenant: acme - Header:
X-Tenant-Idfor API access - URL Parameter:
?tenant=acmefor multi-tenant admin - User Association: From authenticated user's tenant
Implementation
1. Tenant Middleware
// Automatically adds tenant context to all requests
app.use(tenantMiddleware);
app.use(allowCrossTenant); // For superadmin access
2. Model Updates
All models now include tenantId:
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 tenantPATCH /api/v1/tenants/current/settings- Update settingsPATCH /api/v1/tenants/current/branding- Update brandingGET /api/v1/tenants/current/usage- Get usage statistics
Superadmin Routes
GET /api/v1/tenants- List all tenantsPATCH /api/v1/tenants/:id- Update any tenantDELETE /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 userscampaigns: Maximum number of campaignsmessagesPerMonth: Monthly message limittelegramAccounts: Number of Telegram accountsstorage: Storage quota in bytesapiCallsPerHour: API rate limitingwebhooks: Number of webhookscustomIntegrations: Enable/disable custom integrations
Usage Tracking
The system tracks usage in real-time:
// 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
-
Backup your data before migration
-
Run migration script:
node scripts/migrate-to-multitenant.js -
Update environment variables:
DEFAULT_TENANT_SLUG=default ENABLE_MULTI_TENANT=true -
Test tenant isolation:
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
- Always include tenantId in queries
- Use tenant middleware for automatic filtering
- Test with multiple tenants in development
- Validate tenant limits before operations
Production
- Monitor tenant usage regularly
- Set up alerts for limit approaching
- Implement proper backup strategies per tenant
- Use custom domains for enterprise tenants
Performance
- Ensure all queries use tenant indexes
- Monitor slow queries per tenant
- Implement caching strategies
- Use read replicas for analytics
Troubleshooting
Common Issues
-
"Tenant not found" error
- Check tenant slug/domain configuration
- Verify tenant status is active
- Check subdomain DNS settings
-
Data visible across tenants
- Ensure tenantId is in all queries
- Check model indexes
- Verify middleware is applied
-
Performance degradation
- Check compound index usage
- Monitor per-tenant query patterns
- Consider sharding large tenants
Debug Mode
Enable tenant debug logging:
// In development
process.env.TENANT_DEBUG = 'true';
This logs all tenant resolution and filtering operations.
Future Enhancements
- Tenant Sharding: Distribute large tenants across databases
- Tenant Templates: Pre-configured tenant setups
- Tenant Marketplace: Share templates/workflows between tenants
- Advanced Analytics: Cross-tenant analytics for superadmin
- Automated Scaling: Dynamic resource allocation based on usage