NewCode CLOUD — 20% off your first month on all cloud VPSClaim

Building Multi-Tenant SaaS on Hong Kong VPS: Architecture Guide (2026)

· 6 min read

Multi-tenancy — where one application instance serves multiple customer organisations, each with isolated data — is the foundation of SaaS business models. Architecting it correctly from the start determines how well you can scale, how isolated your customers’ data is, and how you handle onboarding and offboarding. This guide covers the three multi-tenancy patterns and how to implement them on a Hong Kong VPS with CN2 GIA routing serving Asia-Pacific business customers.


The Three Multi-Tenancy Patterns

Pattern 1: Schema-Per-Tenant (PostgreSQL)

Each tenant gets a dedicated PostgreSQL schema within one database. Tables are namespaced: tenant_abc.users, tenant_xyz.users. Same database server, completely isolated data.

Pros: Simple backup/restore per tenant; schema migrations can be applied tenant-by-tenant; easy to move heavy tenants to a dedicated server
Cons: Cross-tenant analytics require schema-switching; PostgreSQL limits schemas per database
Best for: B2B SaaS with 10–1,000 tenants where data isolation is a sales requirement

Pattern 2: Shared Tables with Tenant ID

All tenants share tables; every row has a tenant_id column. Row-level security enforces isolation at the database layer.

Pros: Simplest to implement; efficient database space; easy cross-tenant reporting
Cons: Strict discipline required to always filter by tenant_id; harder to move a tenant to a dedicated server
Best for: Consumer SaaS or B2B with thousands of small tenants

Pattern 3: Database-Per-Tenant

Each tenant gets a completely separate database (or even a separate PostgreSQL instance).

Pros: Maximum isolation; easy per-tenant backup, migration, and deletion; can run on different servers
Cons: Connection pool management becomes complex; expensive at many tenants
Best for: Enterprise SaaS where each customer is large and requires dedicated infrastructure SLAs


Implementation: Schema-Per-Tenant with PostgreSQL

Database Setup

<code">-- Base schema migration function
CREATE OR REPLACE FUNCTION create_tenant_schema(tenant_slug TEXT)
RETURNS void AS $$
DECLARE
    schema_name TEXT := 'tenant_' || tenant_slug;
BEGIN
    EXECUTE format('CREATE SCHEMA IF NOT EXISTS %I', schema_name);

    -- Create tenant tables within the schema
    EXECUTE format('
        CREATE TABLE IF NOT EXISTS %I.users (
            id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
            email TEXT UNIQUE NOT NULL,
            name TEXT NOT NULL,
            role TEXT DEFAULT ''member'',
            created_at TIMESTAMPTZ DEFAULT NOW()
        )', schema_name);

    EXECUTE format('
        CREATE TABLE IF NOT EXISTS %I.projects (
            id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
            name TEXT NOT NULL,
            owner_id UUID REFERENCES %I.users(id),
            created_at TIMESTAMPTZ DEFAULT NOW()
        )', schema_name, schema_name);

    -- Add more tenant tables here
    RAISE NOTICE 'Created schema for tenant: %', tenant_slug;
END;
$$ LANGUAGE plpgsql;

-- Global tenants registry
CREATE TABLE public.tenants (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    slug TEXT UNIQUE NOT NULL,
    name TEXT NOT NULL,
    plan TEXT DEFAULT 'starter',
    status TEXT DEFAULT 'active',
    db_schema TEXT GENERATED ALWAYS AS ('tenant_' || slug) STORED,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

Tenant Provisioning Service (Node.js)

<code"># src/services/tenants.js
const { pool } = require('../db');

async function provisionTenant({ name, slug, ownerEmail }) {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');

    // Register tenant
    const { rows: [tenant] } = await client.query(
      `INSERT INTO public.tenants (name, slug) VALUES ($1, $2) RETURNING *`,
      [name, slug]
    );

    // Create schema and tables
    await client.query(`SELECT create_tenant_schema($1)`, [slug]);

    // Set search path and create admin user
    await client.query(`SET search_path TO tenant_${slug}`);
    await client.query(
      `INSERT INTO users (email, name, role) VALUES ($1, $2, 'admin')`,
      [ownerEmail, name + ' Admin']
    );

    await client.query('COMMIT');
    return tenant;
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release();
  }
}

async function deleteTenant(slug) {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');
    await client.query(`DROP SCHEMA IF EXISTS tenant_${slug} CASCADE`);
    await client.query(`DELETE FROM public.tenants WHERE slug = $1`, [slug]);
    await client.query('COMMIT');
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release();
  }
}

Tenant Context Middleware

<code"># Express middleware — identify tenant from subdomain and set schema
const tenantMiddleware = async (req, res, next) => {
  const host = req.hostname;
  const subdomain = host.split('.')[0];

  if (subdomain === 'app' || subdomain === 'www') {
    return next(); // Public routes
  }

  try {
    const { rows } = await pool.query(
      `SELECT * FROM public.tenants WHERE slug = $1 AND status = 'active'`,
      [subdomain]
    );

    if (!rows.length) {
      return res.status(404).json({ error: 'Tenant not found' });
    }

    req.tenant = rows[0];
    req.schemaName = `tenant_${subdomain}`;

    // Middleware to auto-set schema on each DB query
    req.db = {
      query: async (sql, params) => {
        const client = await pool.connect();
        try {
          await client.query(`SET search_path TO ${req.schemaName}`);
          return client.query(sql, params);
        } finally {
          client.release();
        }
      }
    };

    next();
  } catch (err) {
    next(err);
  }
};

Subdomain Routing with Nginx

<code">cat > /etc/nginx/sites-available/saas << 'EOF'
# Wildcard subdomain — all tenant subdomains routed to the same app
server {
    listen 443 ssl http2;
    server_name ~^(?[^.]+)\.yoursaas\.com$;

    ssl_certificate /etc/letsencrypt/live/yoursaas.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yoursaas.com/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Tenant $tenant;    # Pass tenant slug as header
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

# Main marketing site
server {
    listen 443 ssl http2;
    server_name yoursaas.com www.yoursaas.com;

    ssl_certificate /etc/letsencrypt/live/yoursaas.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yoursaas.com/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
    }
}
EOF

Wildcard SSL Certificate

<code"># Wildcard cert for *.yoursaas.com — requires DNS challenge
certbot certonly \
  --dns-cloudflare \
  --dns-cloudflare-credentials /root/.cloudflare.ini \
  -d yoursaas.com \
  -d "*.yoursaas.com" \
  --preferred-challenges dns-01

Tenant-Aware Background Jobs

<code"># Celery / BullMQ jobs must carry tenant context
# In job data, always include tenant_slug

# Node.js with BullMQ:
await emailQueue.add('send-welcome', {
  tenant_slug: 'acme-corp',   // Always pass tenant context
  user_email: 'user@acme.com',
  template: 'welcome'
});

// In the worker:
worker.on('job', async (job) => {
  const { tenant_slug, user_email, template } = job.data;

  // Set schema for this job
  await db.query(`SET search_path TO tenant_${tenant_slug}`);

  // All subsequent queries scoped to this tenant
  const user = await db.query(
    `SELECT * FROM users WHERE email = $1`, [user_email]
  );
  await sendEmail(user.rows[0], template);
});

Tenant Onboarding Flow

<code"># Automated onboarding endpoint
app.post('/api/tenants/signup', async (req, res) => {
  const { company_name, admin_email, plan } = req.body;

  // Generate URL-safe slug from company name
  const slug = company_name
    .toLowerCase()
    .replace(/[^a-z0-9]/g, '-')
    .replace(/-+/g, '-')
    .slice(0, 30);

  // Check slug availability
  const { rows } = await pool.query(
    'SELECT id FROM public.tenants WHERE slug = $1', [slug]
  );
  if (rows.length) {
    return res.status(409).json({ error: 'Company name already taken' });
  }

  // Provision tenant (schema + admin user)
  const tenant = await provisionTenant({
    name: company_name,
    slug,
    ownerEmail: admin_email
  });

  // Send welcome email with login URL
  await sendEmail(admin_email, 'welcome', {
    loginUrl: `https://${slug}.yoursaas.com/login`,
    companyName: company_name
  });

  res.status(201).json({
    tenant_id: tenant.id,
    dashboard_url: `https://${slug}.yoursaas.com`
  });
});

Per-Tenant Rate Limiting

<code"># Rate limit per tenant (not per IP) — prevents one large tenant from degrading others
const tenantRateLimit = rateLimit({
  windowMs: 60 * 1000,
  max: (req) => {
    // Different limits per plan
    const limits = { starter: 100, pro: 1000, enterprise: 10000 };
    return limits[req.tenant?.plan] || 100;
  },
  keyGenerator: (req) => req.tenant?.slug || req.ip,
  message: { error: 'API rate limit exceeded for your plan' }
});

Scaling: Moving Heavy Tenants to Dedicated Hardware

Schema-per-tenant makes it straightforward to move a heavy enterprise tenant to a dedicated Server.HK Hong Kong VPS or dedicated server:

<code"># 1. Dump just the tenant's schema
pg_dump --schema=tenant_enterprise_corp \
  -h 127.0.0.1 -U postgres myapp_db | gzip > enterprise_corp.sql.gz

# 2. Restore on dedicated server
scp enterprise_corp.sql.gz root@DEDICATED_SERVER_IP:/tmp/
ssh root@DEDICATED_SERVER_IP \
  "gunzip -c /tmp/enterprise_corp.sql.gz | psql -U postgres myapp_db"

# 3. Update tenant record to point to new database
UPDATE public.tenants
SET dedicated_db_host = 'DEDICATED_SERVER_IP'
WHERE slug = 'enterprise-corp';

# 4. Tenant middleware reads dedicated_db_host and connects accordingly

Conclusion

Multi-tenant SaaS on a Hong Kong VPS is a practical architecture for Asia-Pacific B2B startups — schema-per-tenant PostgreSQL provides strong data isolation with manageable operational complexity, wildcard subdomain routing via Nginx handles tenant-specific URLs, and CN2 GIA routing ensures all tenants (and their mainland Chinese end users) access the application at consistent low latency. The architecture scales cleanly: light tenants share VPS infrastructure, heavy enterprise tenants migrate to dedicated hardware when needed, all on the same provider.

Build your SaaS: Browse Server.HK Hong Kong VPS plans — start with a 4–8 GB VPS for your multi-tenant application; add dedicated servers for enterprise tenants as you grow.

Related articles

More in VPS & ServersServer setup guides