Architecture

Building Multi-Tenant SaaS: Domain-Based Tenant Resolution Strategies

Explore different approaches to tenant resolution in multi-tenant SaaS applications, focusing on domain-based strategies for better user experience and scalability.

August 27, 2025
9 min read
Domainly Team

Understanding Multi-Tenancy

Multi-tenancy is an architectural pattern where a single instance of software serves multiple customers (tenants), with each tenant's data isolated and invisible to other tenants. In the context of SaaS applications, this approach maximizes resource efficiency while maintaining strong isolation between customers.

Why Domain-Based Tenancy?

  • • Better user experience and branding
  • • Simplified tenant identification
  • • Natural security boundaries
  • • SEO benefits for customers
  • • White-label capabilities
  • • Intuitive URL structure

Tenant Resolution Strategies

Before diving into domain-based approaches, let's understand the different strategies for tenant resolution and their trade-offs.

1. Subdomain-Based Resolution

tenant1.yourapp.com, tenant2.yourapp.com

Pros:

  • • Simple to implement
  • • Easy wildcard SSL certificates
  • • Clear tenant separation

Cons:

  • • Limited branding flexibility
  • • Not white-label friendly
  • • SEO benefits go to main domain

2. Custom Domain Resolution

app.tenant1.com, dashboard.tenant2.org

Pros:

  • • Full branding control
  • • White-label capabilities
  • • SEO benefits for customers
  • • Professional appearance

Cons:

  • • Complex SSL management
  • • Domain verification required
  • • More infrastructure complexity

3. Path-Based Resolution

yourapp.com/tenant1, yourapp.com/tenant2

Pros:

  • • Simple infrastructure
  • • Single SSL certificate
  • • Easy to implement

Cons:

  • • Poor user experience
  • • No branding benefits
  • • Confusing URL structure

Domain-Based Architecture Implementation

Implementing domain-based tenant resolution requires careful consideration of several architectural components working together seamlessly.

Domain-to-Tenant Mapping

Store the relationship between domains and tenants in your database:

CREATE TABLE domains (
  id UUID PRIMARY KEY,
  domain_name VARCHAR(255) UNIQUE NOT NULL,
  tenant_id UUID NOT NULL,
  status VARCHAR(20) DEFAULT 'pending',
  verified_at TIMESTAMP,
  created_at TIMESTAMP DEFAULT NOW(),
  
  FOREIGN KEY (tenant_id) REFERENCES tenants(id),
  INDEX idx_domain_lookup (domain_name, status)
);

Tenant Resolution Middleware

Implement middleware to resolve tenants from incoming requests:

// Express.js middleware example
const tenantResolver = async (req, res, next) => {
  const hostname = req.get('host');
  
  // Check cache first
  let tenant = await redis.get(`tenant:${hostname}`);
  
  if (!tenant) {
    // Lookup in database
    const domain = await Domain.findOne({
      where: { 
        domain_name: hostname, 
        status: 'verified' 
      },
      include: ['tenant']
    });
    
    if (!domain) {
      return res.status(404).json({ 
        error: 'Domain not found' 
      });
    }
    
    tenant = domain.tenant;
    
    // Cache for 5 minutes
    await redis.setex(`tenant:${hostname}`, 300, 
      JSON.stringify(tenant));
  }
  
  req.tenant = tenant;
  next();
};

Performance Optimization Strategies

Domain-based tenant resolution can introduce latency if not properly optimized. Here are key strategies to maintain high performance at scale.

Caching Strategies

  • Redis Cache: Cache domain-to-tenant mappings with appropriate TTL
  • Application Cache: Use in-memory cache for frequently accessed mappings
  • CDN Edge Caching: Cache tenant context at edge locations

Database Optimization

  • • Optimize domain lookup queries with proper indexing
  • • Use read replicas for tenant resolution queries
  • • Implement connection pooling for database efficiency
  • • Consider domain-based database sharding for massive scale

Data Isolation Patterns

Once you've resolved the tenant, you need to ensure proper data isolation. Here are the main patterns for multi-tenant data architecture.

1. Shared Database, Shared Schema

All tenants share the same database and schema, with tenant_id in every table.

-- Every query must include tenant_id
SELECT * FROM users 
WHERE tenant_id = ? AND active = true;

-- Use Row Level Security (PostgreSQL)
CREATE POLICY tenant_isolation ON users
  USING (tenant_id = current_setting('app.tenant_id')::UUID);
Pros: Cost-effective, easy maintenance
Cons: Data leakage risk, limited customization

2. Shared Database, Separate Schemas

Each tenant gets their own schema within a shared database.

-- Set schema based on tenant
SET search_path = tenant_123, public;

-- All queries automatically use tenant schema
SELECT * FROM users WHERE active = true;
Pros: Better isolation, tenant customization
Cons: Schema management complexity

3. Separate Databases

Each tenant gets their own dedicated database.

// Dynamic database connection
const dbConfig = {
  host: 'localhost',
  database: `tenant_${tenant.id}`,
  user: 'app_user',
  password: process.env.DB_PASSWORD
};

const connection = await pg.connect(dbConfig);
Pros: Complete isolation, compliance
Cons: Higher costs, operational complexity

Scaling Considerations

As your multi-tenant SaaS grows, you'll need to consider various scaling strategies to maintain performance and reliability.

Horizontal Scaling Strategies

Tenant-Based Sharding

Distribute tenants across multiple database instances based on tenant ID or domain hash.

Geographic Distribution

Route tenants to regional data centers based on their primary geographic location.

Microservices Architecture

Break down your application into tenant-aware microservices for independent scaling.

Security Best Practices

Security in multi-tenant applications requires special attention to prevent data leakage and ensure proper tenant isolation.

Critical Security Measures

  • • Always validate tenant context in every request
  • • Use database-level security policies when possible
  • • Implement comprehensive audit logging
  • • Regular security audits and penetration testing
  • • Encrypt data at rest and in transit
  • • Implement proper access controls and RBAC

Conclusion

Building a successful multi-tenant SaaS with domain-based tenant resolution requires careful planning of your architecture, performance optimization, and security measures. While it adds complexity compared to simpler approaches, the benefits in terms of user experience, branding flexibility, and scalability make it worthwhile for many applications.

The key is to start with a solid foundation, implement proper caching and optimization from the beginning, and plan for scale. Remember that the choice between data isolation patterns should be based on your specific requirements for security, compliance, and operational complexity.

Ready to build multi-tenant SaaS?

Domainly provides all the infrastructure you need for domain-based multi-tenant SaaS applications. Focus on building features while we handle domain management, SSL certificates, and tenant resolution at scale.