The user wants a system design for "multi-tenant data isolation and security". This is a classic system design problem.
1. Deconstruct the Request:
- Core Concept: Multi-tenancy (MT).
- Key Requirements: Data Isolation (keeping tenant A's data away from tenant B) and Security (Authentication, Authorization, Encryption, Auditing).
- Goal: Design a system. This means I need to cover architecture, database strategies, access control, and infrastructure.
2. Identify the Levels of Isolation (The "Spectrum"):
Multi-tenancy isn't binary. It's a tradeoff between cost/efficiency and isolation/security.
- Level 1: Separate Silo (Highest Isolation, Highest Cost): Dedicated infrastructure per tenant.
- Level 2: Shared Infrastructure, Separate Instances (Middle Ground): Shared hardware/cluster, but separate application instances or database servers.
- Level 3: Shared Application, Separate Databases (Logical Isolation): One app codebase, but
db_tenant_a, db_tenant_b.
- Level 4: Shared Application, Shared Database, Separate Schemas (Schema Isolation): One DB,
tenant_a.users, tenant_b.users.
- Level 5: Shared All (Row-Level Security / Discriminator Column): One table,
tenant_id column. (Lowest Cost, Highest Risk if buggy).
3. Structure the System Design:
A good system design answer should be structured logically:
- Introduction/High-Level Architecture: What are we building?
- Approaches to Data Isolation (The Database Layer): This is the most critical part.
- Access Control & Security (The Application Layer): How do we know who is who?
- Infrastructure & Networking: Network isolation.
- Encryption: Data at rest and in transit.
- Operational Considerations: Migration, backups, logging.
- Recommendation/Trade-offs: When to use what.
4. Flesh out each section:
-
Database Strategies (The Meat):
- Approach A: Database per Tenant. Good for strict compliance (GDPR/HIPAA). Easy backups per tenant. High operational overhead.
- Approach B: Schema per Tenant. Good middle ground. Moderate isolation. Connection pooling becomes tricky (pg_bouncer). Migration scripts need to run against N schemas.
- Approach C: Row-Level Security (RLS) / Shared Table. Most efficient. Scalable. Requires
tenant_id on every query. Risk of data leakage (the "uber leak" scenario).
- Hybrid: Critical tenants get their own DB, freemium users share tables.
-
Application/Security Layer:
- Authentication (AuthN): Identity Provider (IdP) is best. JWTs containing
tenant_id or a lookup service.
- Authorization (AuthZ): RBAC (Role-Based Access Control) or ABAC (Attribute-Based). Crucial: The "Tenant Context". How does the code know which tenant it's serving?
- Middleware: Intercept requests -> Validate JWT -> Extract
tenant_id -> Set context (ThreadLocal or Context object) -> Pass to DB.
-
Row-Level Security (RLS) Implementation (Deep Dive):
- Even if we use
tenant_id in code, the DB should verify it.
- Postgres RLS is the gold standard example here.
SET app.current_tenant = 'id' -> Policy checks tenant_id = current_setting('app.current_tenant').
-
Infrastructure/Network:
- VPCs.
- K8s Namespaces (if using K8s).
- API Gateways (Rate limiting per tenant).
-
Encryption:
- At Rest: Key management (KMS). Should tenants have separate keys? (Key per tenant vs Global key).
- In Transit: TLS 1.3.
- Application-Level Encryption (ALE): Encrypt sensitive fields before hitting DB. Tenant holds key (Zero Trust).
-
Observability & Auditing:
- Logs must include
tenant_id.
- Audit trails (who changed what and when).
5. Refine and Polish:
- Visuals: Describe a diagram (Request flow).
- Trade-offs: Explicitly state the pros/cons of the approaches. The interviewer/user wants to see I understand the costs.
- Security pitfalls: Mention SQL injection (classic bypass), IDOR (Insecure Direct Object References).
6. Draft the Content (Self-Correction during drafting):
- Correction: Initially, I thought about just putting
tenant_id in the query. But that relies on developers never making a mistake. I must emphasize DB-level RLS as a safety net.
- Refinement: Don't forget tenant onboarding. How do we provision a new tenant? Automation (Terraform/Helm/DB Migrations).
7. Final Output Structure:
- Executive Summary: Definition of Tenancy.
- Architectural Approaches (The 3 Tiers): Isolation levels.
- Data Isolation Strategy (Deep Dive): DB per Tenant vs. Schema vs. Row.
- Security Architecture: IAM, Context Propagation, RLS.
- Encryption & Key Management.
- Operational Concerns: Backups, Migrations, Throttling.
- Summary Table/Decision Matrix.
(Proceeding to generate the response based on this structure.)
Designing a multi-tenant system requires balancing cost efficiency (sharing resources) with strict isolation (guaranteeing privacy and performance).
Below is a comprehensive system design for data isolation and security, categorized by Compute, Database, Application Logic, and Infrastructure.
1. High-Level Architecture: The "Spectrum of Isolation"
Before diving into specifics, you must choose your deployment model. There are three standard patterns:
- Silo (Isolated): Separate infrastructure per tenant. (Highest security, highest cost).
- Pool (Shared): Everyone shares the same DB and App. (Lowest cost, highest risk).
- Bridge (Hybrid): Shared app compute, but isolated databases. (The "Goldilocks" standard for modern SaaS).
Recommended Approach: We will design a Bridge/Pool Hybrid system. This uses a shared application layer for efficiency but offers pluggable strategies for data isolation based on tenant tier (e.g., Enterprise tenants get their own DB, Free tenants share a table).
2. Data Isolation Strategies (The Storage Layer)
This is the most critical component. There are three main ways to structure the data:
A. Row-Level Security (RLS) / Discriminator Column (Shared Pool)
- Concept: All tenants share the same tables. A column (e.g.,
tenant_id) identifies ownership.
- Pros: Zero overhead for adding new tenants. Easy maintenance (one schema to update).
- Cons: Risk of data leakage (e.g., a developer forgets the
WHERE clause).
- Mitigation: Use Database-Level RLS (e.g., PostgreSQL RLS). The database enforces isolation, not the application code.
- Mechanism: The app sets a session variable (e.g.,
SET app.current_tenant = '123'). The database policy automatically appends WHERE tenant_id = '123' to every query, even if the developer forgets it.
B. Schema Separation (Shared Instance)
- Concept: One database instance, but each tenant has their own schema (namespace).
- Pros: Good logical isolation; easy to backup/restore specific tenants.
- Cons: Connection pooling is complex (you must set the search path per connection). Migrations take longer as they must run against N schemas.
C. Database Per Tenant (Silo)
- Concept: Each tenant gets a physically distinct database instance (or a dedicated server).
- Pros: Ultimate isolation. Performance of one tenant cannot impact another (Noisy Neighbor problem solved). Compliance friendly (GDPR data residency).
- Cons: High operational overhead. Expensive.
Design Decision:
Implement a Routing Layer.
- Tier 1 (Standard): Uses Row-Level Security (Shared DB).
- Tier 2 (Enterprise): Uses Dedicated Database.
3. Application Security Architecture
A. Tenant Context Injection
Every request entering the system must be "tagged" with the tenant context immediately.
- Authentication: User logs in via Identity Provider (IdP) (e.g., Auth0, Cognito, or Internal IAM).
- Token: The JWT (JSON Web Token) contains a custom claim:
https://myapp.com/tenant_id.
- Middleware:
- Intercepts the request.
- Validates the JWT signature.
- Extracts
tenant_id.
- Verifies the user belongs to that tenant (prevents IDOR/spoofing).
- Injects
tenant_id into the Thread Context (e.g., Java ThreadLocal, Node.js Async Local Storage) so it is accessible to all downstream DB calls without passing it manually through every function.
B. The "Sharding" Router
If implementing the Hybrid model, your Data Access Layer (DAL) needs a router.
- Function:
getDataSource(tenant_id)
- Logic:
- Look up tenant configuration in a lightweight "Control Plane" database.
- If config says "Dedicated", return connection to
tenant-prod-db.
- If config says "Shared", return connection to
shared-pool-db.
4. Infrastructure & Network Security
A. Network Segmentation
- mTLS (Mutual TLS): Encrypt traffic between services (East-West traffic) and verify identity.
- VPCs: Use separate VPCs or Subnets for high-security tenants if utilizing the "Silo" model.
B. Encryption
- At Rest: Encrypt database disks (AES-256).
- In Transit: TLS 1.3 mandatory.
- Application-Level Encryption (ALE): For highly sensitive fields (SSN, Tax ID), encrypt the data before it hits the database using a Key Management Service (KMS).
- Key Hierarchy: Use a different Data Encryption Key (DEK) for every tenant.
- Envelope Encryption: The DEK is encrypted by a Master Key (MK) stored in a Hardware Security Module (HSM) or AWS KMS.
C. The "Noisy Neighbor" Prevention (Performance Isolation)
Security isn't just about privacy; it's about availability.
- Rate Limiting: Implement quotas per
tenant_id, not just per IP address. If Tenant A spams the API, they should be throttled without affecting Tenant B.
- Resource Governance: In shared databases, use features like PostgreSQL
work_mem limits or AWS RDS "Resource Groups" to prevent one tenant's heavy query from consuming 100% CPU.
5. Operational Security (Humans & Access)
A. Audit Logging
Log who did what to which tenant's data.
- Logs must be immutable.
- Logs should capture the
tenant_id context.
- Alert on anomalies (e.g., An admin exporting 100% of a tenant's user data).
B. "Break Glass" / Impersonation
Support engineers sometimes need to view a tenant's data to debug issues.
- Do not give engineers direct DB access.
- Design: Build an internal "Super Admin" portal that requires MFA and explicit justification to "Login as Tenant." All actions during this session are recorded on video or detailed text logs.
C. Zero Standing Privileges
Database credentials used by the application should have the minimum permissions required.
- The App role should generally not have
DROP TABLE permissions.
- Use separate roles for Schema Migrations vs. Runtime App usage.
Summary Diagram Logic
If you were to draw this, the flow would look like this:
- Request: User sends API request + JWT.
- Gateway: Validates SSL, checks WAF (Web App Firewall).
- App Middleware:
- Verifies JWT.
- Extracts
tenant_id.
- Checks Redis cache for tenant config (Are they paid? Are they suspended? Do they have a dedicated DB?).
- Data Router:
- Determines correct DB connection based on config.
- Opens connection.
- (If Shared DB) Runs
SET app.current_tenant = 'id'.
- Database:
- Executes query.
- (If RLS enabled) Database automatically filters data.
- Returns rows.
- Response: JSON returned to user.