2407 Multi Tenant Applications
Multi-Tenant Applications
Introduction
What is Multi-Tenancy?
Tenant Analogy
Think of an apartment building:
- Multiple families (tenants) live in the same building
- They share infrastructure (electricity, water, internet)
- Each apartment is completely private
- One family cannot access another's apartment
- Building management oversees all apartments
Multi-tenant apps work the same way:
- Multiple companies share the same application
- They share infrastructure (servers, database, code)
- Each company's data is completely isolated
- One company cannot access another's data
- Super admins can manage all tenants
Why Build Multi-Tenant Apps?
For SaaS Providers
- Scalability - Serve many customers without creating separate apps
- Efficiency - Maintain one codebase for all customers
- Cost-Effective - Shared infrastructure reduces costs
- Easier Updates - Update once, all tenants benefit
- Centralized Management - Manage all customers from one place
For Customers
- Lower Cost - Shared infrastructure means lower subscription fees
- Faster Setup - Quick onboarding, no installation
- Automatic Updates - Always on latest version
- Reliable - Professional infrastructure management
Multi-Tenant vs. Single-Tenant
| Aspect | Multi-Tenant | Single-Tenant |
|---|---|---|
| Architecture | One app, shared database | Separate app per customer |
| Data Isolation | Logical (filters) | Physical (separate databases) |
| Scaling | Add users to shared system | Provision new instances |
| Updates | Update once for all | Update each instance |
| Customization | Limited per-tenant config | Full per-customer customization |
| Cost | Lower (shared resources) | Higher (dedicated resources) |
| Security | Must ensure isolation | Naturally isolated |
| Use Case | SaaS with many customers | Enterprise with unique needs |
Designing Multi-Tenant Architecture
Core Tenancy Structure
The Tenants Table
Create a table to represent each tenant (usually called "Companies", "Organizations", or "Accounts"):
- Go to Data Builder
- Create new table: "Companies"
- Add fields:
- Company Name (Text, required)
- Subdomain (Text, unique - e.g., "acme" for acme.yourapp.com)
- Status (Active, Trial, Suspended, Cancelled)
- Subscription Plan (Free, Basic, Pro, Enterprise)
- Created Date (Date/Time, auto-fill)
- User Limit (Number)
- Storage Limit (Number)
- Logo (File Upload, optional)
- Contact Email (Email)
Linking Users to Tenants
- Go to Users table
- Add field: "Company" (Connection to Companies table)
- Set as required
- Every user must belong to a company
Linking All Data Tables to Tenants
For every data table in your app:
- Add field: "Company" (Connection to Companies table)
- Set as required
- Enable "Auto-fill from logged in user's company" (if available) or use record rules
Data Isolation Strategy
Primary Filter on All Components
Every component that displays data must filter by company:
Filter:
Company = Logged In User's Company
Exception for Super Admins
Super admins can see all companies:
Filter Logic:
(Company = Logged In User's Company)
OR
(Role = Super Admin)
Role Structure
Tenant-Level Roles
Roles that exist within each tenant:
- Company Admin - Manages their company's account and users
- Company Manager - Manages operations within their company
- Company User - Standard user within company
- Company Guest - Limited access within company
Platform-Level Roles
Roles for managing the platform itself:
- Super Admin - Platform owner, sees all companies
- Platform Support - Can view all companies for support
Tenant Isolation Example
Scenario: Project Management SaaS
Tables:
- Companies
- Users (linked to Companies)
- Projects (linked to Companies)
- Tasks (linked to Companies and Projects)
- Files (linked to Companies and Tasks)
Company A:
- Users: Alice, Bob, Charlie
- Projects: Website Redesign, Mobile App
- Tasks: 50 tasks across projects
Company B:
- Users: David, Emma
- Projects: Marketing Campaign
- Tasks: 25 tasks
Isolation:
- Alice (Company A) sees only Company A's projects and tasks
- David (Company B) sees only Company B's projects and tasks
- Super Admin sees both companies
- Complete data separation
Implementing Multi-Tenancy
Step 1: Create Companies Table
Table: Companies
Fields:
- Company ID (Auto-increment, primary key)
- Company Name (Text, required)
- Subdomain (Text, unique)
- Status (Dropdown: Active, Trial, Suspended)
- Subscription Plan (Dropdown: Free, Basic, Pro)
- Created Date (Date/Time, auto-fill)
- User Limit (Number, default: 5)
- Logo (File Upload)
- Primary Contact (Connection to Users)
- Billing Email (Email)
Step 2: Link Users to Companies
Table: Users
Add Field:
- Company (Connection to Companies table)
- Connection Type: Many to One
- Required: Yes
- Display Field: Company Name
Step 3: Link Data Tables to Companies
For each data table:
Add Field:
- Company (Connection to Companies table)
- Required: Yes
- Auto-fill: Use record rule to auto-fill from logged-in user's company
Record Rule for Auto-Fill
- Go to table settings
- Add Record Rule
- Trigger: Before Insert
- Action: Update Field
- Field: Company
- Value: Logged In User's Company
Step 4: Filter All Components
For every table, details, form, chart, calendar component:
- Add filter: Company = Logged In User's Company
- OR: Role = Super Admin (for platform admins)
Step 5: Create Company Admin Pages
Company Settings Page
- Accessible to: Company Admin role
- Shows: Logged-in user's company details
- Allows editing: Company Name, Logo, Contact Info
- Cannot edit: Subscription Plan, Status (platform admin only)
Company User Management Page
- Accessible to: Company Admin
- Table showing: Users where Company = Logged In User's Company
- Actions: Add, Edit, Deactivate users within their company
- Cannot: Access users from other companies
Step 6: Create Platform Admin Pages
All Companies Page
- Accessible to: Super Admin only
- Table showing: All companies
- Columns: Company Name, Status, User Count, Created Date
- Actions: View, Edit, Suspend, Delete companies
Company Details (Platform Admin View)
- Accessible to: Super Admin
- Shows: Complete company information
- Includes: User list, subscription details, usage stats
- Actions: Change plan, suspend/activate, manage users
Step 7: Test Isolation
- Create test companies: Company A, Company B
- Create users for each company
- Create data for each company
- Log in as Company A user - verify only Company A data visible
- Log in as Company B user - verify only Company B data visible
- Try to access other company's data via URL manipulation
- Log in as Super Admin - verify all data visible
Tenant Administration
Company Admin Capabilities
User Management
Company admins can manage users within their company:
- View all company users
- Add new users (within user limit)
- Edit user details
- Deactivate users
- Cannot access users from other companies
- Cannot exceed their user limit
Implementation
- Create "Manage Users" page
- Permissions: Company Admin role
- Table Component:
- Data source: Users
- Filter: Company = Logged In User's Company
- Actions: Add, Edit, Deactivate
- Add validation: Check user count vs. limit before allowing new users
Company Settings
Company admins can update company profile:
- Company Name
- Logo
- Contact Information
- Preferences/Settings
Cannot modify:
- Subscription Plan (platform admin only)
- User Limits (platform admin only)
- Status (platform admin only)
- Billing (redirect to billing portal)
Usage Reports
Company admins see their company's usage:
- Number of users (X of Y limit)
- Storage used (X of Y limit)
- Active projects/records
- Activity logs
- Billing history
Platform Admin Capabilities
Company Management
Super admins can:
- View all companies
- Create new companies
- Edit any company
- Change subscription plans
- Set user/storage limits
- Suspend/activate companies
- Delete companies (carefully!)
Cross-Company Access
Super admins can access any company's data:
- For support purposes
- For troubleshooting
- For platform administration
- Should be logged and audited
Platform Analytics
Super admins see platform-wide metrics:
- Total companies
- Total users across all companies
- Companies by plan
- Growth metrics
- Usage statistics
- Revenue reports
Tenant Onboarding
Self-Service Signup
Signup Flow
- Company Information
- Company Name
- Subdomain (validate uniqueness)
- Industry/Type (optional)
- Admin Account
- Admin Name
- Password
- Plan Selection
- Choose subscription plan
- Show features/limits
- Trial vs. paid
- Payment (if not trial)
- Collect payment information
- Process initial payment
- Setup Complete
- Create company record
- Create admin user
- Send welcome email
- Redirect to onboarding
Implementation
Create public signup page with multi-step form:
- Form inserts into Companies table
- Record rule creates admin user automatically
- Links user to new company
- Assigns Company Admin role
- Sends welcome/onboarding email
Guided Onboarding
Initial Setup Wizard
After signup, guide new tenants through setup:
- Welcome - Introduction and overview
- Customize Profile - Add logo, company details
- Invite Team - Add additional users
- Import Data - Upload existing data (optional)
- Tour - Guided tour of features
- First Steps - Suggested initial tasks
Progress Tracking
- Add "Onboarding Progress" field to Companies table
- Track which steps completed
- Show progress bar
- Redirect to next step until complete
Trial Management
Trial Setup
- Add "Trial End Date" field to Companies
- Auto-calculate based on signup date (e.g., +14 days)
- Show "Days Remaining" in company dashboard
- Send reminder emails (7 days, 3 days, 1 day before expiration)
Trial Expiration
- Page rule checks Trial End Date
- If expired and no subscription: Redirect to "Upgrade Now" page
- Limit access until subscribed
- Don't delete data immediately (grace period)
Subscription and Billing
Subscription Plans
Plan Structure
Create Plans table:
Table: Subscription Plans
Fields:
- Plan Name (Starter, Pro, Enterprise)
- Price per Month (Number)
- User Limit (Number)
- Storage Limit (Number, GB)
- Features (Long Text, JSON list)
- Active (Yes/No)
Linking to Companies
- Companies table has "Current Plan" (connection to Plans)
- Track plan changes over time
- Apply limits based on plan
Enforcing Limits
User Limits
- Before adding user, check count
- Count: Users where Company = Logged In User's Company
- Compare to: Company's User Limit
- If at limit: Show error "You've reached your user limit. Upgrade to add more users."
Storage Limits
- Track file uploads per company
- Sum total file sizes where Company = X
- Compare to Storage Limit
- Block uploads if limit exceeded
- Show usage in company dashboard
Feature Limits
- Advanced features available only on higher plans
- Check plan before showing features
- Example: API access only on Pro+ plans
- Example: Custom branding only on Enterprise
Upgrade/Downgrade
Self-Service Upgrade
- Company admin clicks "Upgrade"
- Shows plan comparison
- Selects new plan
- Processes payment
- Updates company's plan
- New limits immediately available
Downgrade Handling
- Check if current usage exceeds new plan limits
- If over user limit: Require deactivating users first
- If over storage: Require deleting files first
- If using restricted features: Disable features
- Warn about limitations before downgrade
Payment Integration
Using Stripe
- Integrate Tadabase with Stripe
- Create customer in Stripe when company signs up
- Create subscription in Stripe
- Webhook updates when payment succeeds/fails
- Update company status based on payment status
Payment Failed
- Stripe webhook notifies of failed payment
- Update company status to "Payment Failed"
- Send email notification
- Show banner in app: "Update payment method"
- After X days: Suspend account
- After Y days: Cancel account (with data retention)
Multi-Tenant Security
Data Isolation Checklist
- ☐ Every data table has Company field
- ☐ Every component filters by Company
- ☐ Company field is required (cannot be empty)
- ☐ Company field auto-fills from logged-in user
- ☐ Users cannot change their own Company
- ☐ All page links include company context
- ☐ URL parameters validated for company
- ☐ API requests filtered by company
- ☐ Exports include only company data
- ☐ Search limited to company data
Common Security Risks
Risk 1: Missing Company Filter
What happens:
- Component doesn't filter by company
- Users see data from all companies
- Major security breach
Prevention:
- Create component template with company filter
- Review every component before launch
- Test thoroughly with multiple companies
Risk 2: URL Manipulation
What happens:
- User changes record ID in URL
- Accesses record from another company
Prevention:
- Page rules validate record belongs to user's company
- Redirect if validation fails
- Never trust URL parameters alone
Risk 3: Cross-Company Connections
What happens:
- User assigns task to user from another company
- Creates data leakage between companies
Prevention:
- Limit connection field options to same company
- Filter dropdown: Users where Company = Logged In User's Company
- Validate on server side
Risk 4: Export All Data
What happens:
- Export function exports all companies' data
- Massive data breach
Prevention:
- Exports respect company filter
- Limit export to Company Admins only
- Log all export activity
Testing Multi-Tenant Security
Test Cases
- Create two test companies with different data
- Log in as Company A user
- Verify only Company A data visible
- Try to access Company B record via URL
- Should be blocked or redirected
- Try to assign resources across companies
- Can user assign task to user from Company B?
- Should be prevented
- Test search
- Search for records from other company
- Should not appear in results
- Test exports
- Export data
- Verify only company's data included
- Test API (if enabled)
- API requests return only company data
- Cannot access other companies via API
Advanced Multi-Tenant Features
Per-Tenant Customization
Custom Branding
- Each company can upload logo
- Set brand colors
- Display in header and emails
- White-label experience
Implementation
- Add to Companies table:
- Logo (File Upload)
- Primary Color (Text, hex code)
- Secondary Color (Text, hex code)
- In header, display logged-in user's company logo
- Apply color theme dynamically
Custom Subdomains
Subdomain Structure
- Each company gets subdomain: companyname.yourapp.com
- Automatically route to their data
- Professional appearance
- Better organization
Implementation
- Companies table has "Subdomain" field (unique)
- Configure DNS wildcards (*.yourapp.com)
- Login page determines company from subdomain
- Auto-filters all data to that company
Usage Analytics
Company Dashboard
Show each company their usage:
- Number of users
- Storage used
- Number of records created
- Last login date
- Activity over time
Platform Dashboard
Show super admins overall metrics:
- Total companies
- Companies by plan
- Total users across platform
- Total storage used
- Growth trends
- Churn rate
Tenant Isolation Levels
Level 1: Basic Isolation
- All tables have Company field
- All components filter by company
- Suitable for most SaaS apps
Level 2: Enhanced Isolation
- Basic isolation PLUS
- Separate file storage per company
- Per-company encryption keys
- More complex but more secure
Level 3: Physical Isolation
- Each company has separate database
- Ultimate security
- More expensive
- Harder to maintain
- Usually not necessary in Tadabase
Multi-Tenant Best Practices
1. Plan from the Start
- Design for multi-tenancy from day one
- Harder to add later
- Affects entire architecture
- Think about isolation early
2. Consistent Naming
- Use same field name in all tables ("Company")
- Makes maintenance easier
- Reduces errors
- Clear to understand
3. Always Filter
- Never forget company filter
- Create component templates
- Review every component
- Test thoroughly
4. Super Admin Access
- Always include super admin override
- Needed for support and maintenance
- Log super admin activity
- Limit number of super admins
5. Enforce Limits
- Check limits before allowing actions
- Show clear error messages
- Prompt to upgrade
- Don't allow exceeding limits
6. Audit Everything
- Log company creation
- Log user additions
- Log plan changes
- Log cross-company access (super admin)
- Track usage metrics
7. Test Thoroughly
- Create multiple test companies
- Test isolation rigorously
- Try to break isolation
- Test every feature
- Have others test
8. Plan for Growth
- Consider performance at scale
- Index company field
- Optimize queries
- Monitor performance
Summary
- What multi-tenancy is - Single app serving multiple organizations
- Architecture design - Companies table, linking users and data
- Data isolation - Filtering by company, preventing cross-access
- Implementation steps - Building multi-tenant structure
- Tenant administration - Company admin and platform admin capabilities
- Tenant onboarding - Signup, trials, guided setup
- Subscriptions and billing - Plans, limits, payments
- Security considerations - Critical isolation requirements
- Advanced features - Branding, subdomains, analytics
- Best practices - Guidelines for successful multi-tenancy
Next: Phase 5 Summary and Project - Building a Multi-Tenant Application
Hands-On Exercise (To Be Added)
Exercise placeholders will include practical activities such as:
- Creating a Companies table structure
- Linking users and data to companies
- Implementing company filters
- Testing data isolation
- Creating company admin pages
- Building a tenant onboarding flow
Knowledge Check (To Be Added)
Quiz questions will test understanding of:
- What multi-tenancy is
- How to design multi-tenant architecture
- Implementing data isolation
- Security risks and prevention
- Company admin vs. platform admin
- Best practices for multi-tenancy
We'd love to hear your feedback.