Every B2B SaaS startup begins with the simplest multi-tenant architecture: a single PostgreSQL database where every table includes a tenant_id column.
This model is clean, cheap, and productive—until an enterprise customer with 50,000 active employees signs an annual contract. Suddenly:
- That single tenant consumes 80% of database buffer cache.
- Large analytic queries executed by the enterprise customer spike CPU, causing 500 errors for smaller tenants.
- Regulatory mandates (HIPAA or CJIS) require physical data residency isolation that a shared database cannot legally satisfy.
Here is the sharding playbook we deploy for enterprise-grade SaaS systems.
Sharding Architectures: Hash vs Directory Routing
Incoming Tenant Request (Tenant: 'enterprise-corp')
│
▼
[Tenant Directory Service] (Cached in Redis)
Returns: Shard_04 (Dedicated AWS r6i Instance)
│
▼
[Database Connection Pooler for Shard_04]
│
▼
[PostgreSQL Shard_04 Primary]
Directory-Based Routing in TypeScript
export class TenantConnectionManager {
private shardPools: Map<string, Pool> = new Map();
public async getPoolForTenant(tenantId: string): Promise<Pool> {
const shardKey = await this.resolveTenantShard(tenantId);
let pool = this.shardPools.get(shardKey);
if (!pool) {
pool = new Pool({ connectionString: process.env[`DATABASE_URL_${shardKey}`] });
this.shardPools.set(shardKey, pool);
}
return pool;
}
private async resolveTenantShard(tenantId: string): Promise<string> {
// Check Redis metadata directory with sub-millisecond lookup
const cachedShard = await redis.get(`tenant_shard:${tenantId}`);
if (cachedShard) return cachedShard;
const row = await controlPlaneDb.query(
"SELECT shard_id FROM tenant_registry WHERE id = $1",
[tenantId]
);
return row.rows[0].shard_id;
}
}
By decoupling tenant IDs from physical servers via a directory layer, large enterprise accounts can be migrated to dedicated database instances live with zero downtime.



