Multi-Tenant Database Design: Single vs. Multiple DBs & The Role of a Master Database ๐Ÿค”๐Ÿ—๏ธ

Smit Patel
7 min readFeb 8, 2025

--

So, youโ€™re building a multi-tenant SaaS app and hit the big question:

โ€œShould I use a single database for all tenants or give each tenant their own database?โ€

Well, my friend, welcome to the battle of the architectures! ๐Ÿ† Letโ€™s break it down in a way that wonโ€™t make you want to run away from your own startup. ๐Ÿš€

Option 1: The โ€œOne Big Happy Familyโ€ Approach (Single Database) ๐Ÿ 

In this approach, all tenant data lives together in one database. You differentiate tenants using a Tenant ID column in every table. Itโ€™s like a huge apartment complex ๐Ÿข โ€” everyone has their own room, but they all share the same building.

โœ… Pros of Single Database:

โœ”๏ธ Cheaper to maintain โ€” One database means fewer resources and lower costs. ๐Ÿ’ฐ
โœ”๏ธ Easier to manage โ€” Schema updates apply to all tenants at once. No running migrations 50 times! ๐Ÿ˜…
โœ”๏ธ Simple connection pooling โ€” Since everything is in one DB, you donโ€™t need to manage 100+ connections.

โŒ Cons of Single Database:

โŒ Performance bottlenecks โ€” A high-traffic tenant can slow down everyone else. Itโ€™s like a noisy neighbor blasting music at 2 AM. ๐ŸŽธ๐Ÿ”Š
โŒ Security concerns โ€” If you mess up row-level security, one tenant might see anotherโ€™s data. ๐Ÿšจ
โŒ Scaling challenges โ€” As tenants grow, the database might become a slow-moving dinosaur. ๐Ÿฆ•

Who should choose this?
If youโ€™re just starting and want to keep things simple, go with this. But make sure to use
partitioning (by Tenant ID) for better performance!

Option 2: The โ€œEach Tenant Gets a Mansionโ€ Approach (Multiple Databases) ๐Ÿฐ

In this approach, each tenant gets their own separate database. Think of it like giving each customer their own private island. ๐Ÿ๏ธ

โœ… Pros of Multiple Databases:

โœ”๏ธ Better performance โ€” One noisy tenant wonโ€™t slow down the others. ๐ŸŽ๏ธ๐Ÿ’จ
โœ”๏ธ Stronger security โ€” No accidental data leaks because tenants donโ€™t share DBs. ๐Ÿ”’
โœ”๏ธ Easy backup & recovery โ€” If one tenantโ€™s DB crashes, others are safe. ๐Ÿš‘

โŒ Cons of Multiple Databases:

โŒ More expensive โ€” More databases = more resources = more money. ๐Ÿ’ธ
โŒ Harder schema updates โ€” Need to run migrations on every database. Annoying! ๐Ÿ˜ค
โŒ Connection pooling issues โ€” Managing 100+ DB connections can be a nightmare. ๐Ÿ˜จ

Who should choose this?
If you have
enterprise clients who need strong isolation and performance, this is the way to go.

Onboarding a New Tenant: The Right Way ๐Ÿš€

No matter which approach you choose, onboarding should be fast and automated. Hereโ€™s how you can handle it:

โœ… Single Database Approach:

  • Insert a new record in the tenants table with a unique tenant_id.
  • Ensure all queries filter data using tenant_id (use PostgreSQL Row-Level Security (RLS) to enforce this).

โœ… Multiple Database Approach:

  • Provision a new database dynamically when a new tenant signs up.
  • Use DB templates to auto-create schemas and indexes.
  • Store tenant DB details in a master database for easy lookup.

๐Ÿ”ฅ Pro Tip: Automate onboarding using Terraform, AWS Lambda, or Kubernetes operators to provision databases on demand!

What If a Tenant Grows Too Big? ๐Ÿ“ˆ

Ah, the best problem to have โ€” a tenant outgrowing your setup! But how do you move them to a bigger, better database without downtime?

Scenario 1: Single Database โ†’ Needs More Power โšก

โœ… Use partitioning by tenant ID (PostgreSQL pg_partman, MySQL sharding)
โœ… Scale up vertically (more CPU, memory) or add read replicas
โœ… Move high-traffic tenants to a separate table or schema

Scenario 2: Move a Tenant to a New DB Cluster ๐Ÿ—๏ธ

1๏ธโƒฃ Create a new database in a high-performance cluster (AWS RDS, Azure SQL, etc.).
2๏ธโƒฃ Migrate data using tools like pg_dump, MySQL replication, or CDC (Change Data Capture).
3๏ธโƒฃ Update routing to point tenant queries to the new database.
4๏ธโƒฃ Test & switch without downtime (use a feature flag for gradual rollout).

๐Ÿ”ฅ Pro Tip: Use a Database Proxy Layer (like ProxySQL or PgBouncer) to route tenants dynamically without changing application logic!

But waitโ€ฆ how do we manage all these tenants efficiently? ๐Ÿคฏ

๐Ÿ‘‰ Enter the Master Database! ๐Ÿ†

What is a Master Database? ๐Ÿง

A master database is a central registry that keeps track of all tenants and their database details. Think of it as the control tower of your multi-tenant system. ๐Ÿ›ซ

๐Ÿ”น In a Single DB approach, it stores tenant metadata (name, domain, plan, settings, etc.).
๐Ÿ”น In a Multiple DB approach, it also stores database connection details (hostname, credentials, region, etc.).

Master Database Schema Example:

CREATE TABLE tenants (
id SERIAL PRIMARY KEY,
tenant_name VARCHAR(255) NOT NULL,
tenant_domain VARCHAR(255) UNIQUE NOT NULL,
db_host VARCHAR(255), -- Only needed for multiple DB setup
db_name VARCHAR(255),
db_user VARCHAR(255),
db_password TEXT, -- Should be encrypted!
created_at TIMESTAMP DEFAULT NOW()
);

Now, every time a user logs in or accesses the system, your app looks up the tenant in the master database and connects to the right DB. ๐Ÿ”„

How Does the Master Database Help? ๐Ÿคฉ

1๏ธโƒฃ Easy Tenant Management ๐ŸŽ›๏ธ

โœ”๏ธ Store tenant details, subscription plans, and settings in one place.
โœ”๏ธ Quickly activate, suspend, or delete tenants.

2๏ธโƒฃ Dynamic Database Routing ๐Ÿš€

๐Ÿ”€ When a request comes in, look up the master DB to get the right database details.

Example in Node.js (Express + PostgreSQL):

const pool = new Pool({ connectionString: MASTER_DB_URL });

async function getTenantDB(tenantDomain) {
const res = await pool.query("SELECT * FROM tenants WHERE tenant_domain = $1", [tenantDomain]);
if (!res.rows.length) throw new Error("Tenant not found");

return new Pool({
host: res.rows[0].db_host,
database: res.rows[0].db_name,
user: res.rows[0].db_user,
password: decrypt(res.rows[0].db_password), // Always encrypt credentials
});
}

Now, your app can dynamically connect to the right tenant DB based on the request.

3๏ธโƒฃ Smooth Onboarding ๐Ÿ—๏ธ

When a new tenant signs up, your system:
โœ… Creates an entry in the master database.
โœ… Assigns them to an existing shared DB OR provisions a new DB (if using multiple DBs).
โœ… Returns database credentials for dynamic connection handling.

4๏ธโƒฃ Moving a Tenant to a High-Performance DB ๐ŸŽ๏ธ๐Ÿ’จ

๐Ÿ’ก Imagine a tenant suddenly becomes a huge enterprise customer with massive traffic.

You can move them to a dedicated high-CPU DB cluster and update the master database:

UPDATE tenants 
SET db_host = 'new-high-performance-db.com', db_name = 'tenant_bigcorp'
WHERE tenant_name = 'BigCorp';

Boom! ๐ŸŽ‰ No downtime, no app code changes โ€” just an update in the master database!

Security Best Practices for a Master Database ๐Ÿ”’

โŒ Never store DB passwords in plaintext โ†’ Use encryption (AES, Vault, AWS Secrets Manager)
โŒ Donโ€™t expose DB credentials to frontend โ†’ Always fetch from the backend
โœ… Use caching (Redis, Memcached) to reduce master DB queries

Master DB & High Availability Strategy๐ŸŒ

So, weโ€™ve established that the Master Database is the brain of a multi-tenant system. ๐Ÿง  It keeps track of tenant information, routes requests to the correct database, and enables smooth onboarding.

BUTโ€ฆ what happens if the Master DB goes down? ๐Ÿ˜ฑ

๐Ÿ’€ No master DB = No tenant routing = Full system outage!

This is where High Availability (HA) comes into play! Letโ€™s explore how to keep the master DB reliable, scalable, and always online. ๐Ÿš€

๐Ÿšจ The Problem: Master DB Downtime Kills Everything

Since all tenant requests must first query the master DB to determine where their data lives, even a few minutes of downtime can:
โŒ Prevent logins & API requests ๐Ÿ˜จ
โŒ Block new tenant onboarding ๐Ÿšซ
โŒ Impact all tenants (single or multi-DB setup) โš ๏ธ

โœ… Solution: Master-Slave (Read Replicas) Setup

The best way to avoid downtime is to use a Primary-Replica (Master-Slave) strategy.

๐Ÿ”น Master DB (Primary): Handles write operations (e.g., tenant creation, updates).
๐Ÿ”น Replica DBs (Slaves): Handle read operations (e.g., tenant lookups).

๐Ÿ’ก This ensures that even if the master goes down, read requests still work!

How It Works:

1๏ธโƒฃ Writes go to the master DB
2๏ธโƒฃ Read requests are distributed across replicas
3๏ธโƒฃ Failover Mechanism: If the master DB crashes, a replica automatically takes over as the new master.

๐Ÿ”ฅ Master-Replica Setup in AWS RDS (Example)

If youโ€™re using AWS RDS for PostgreSQL/MySQL, setting up replication is easy:
โœ”๏ธ Enable Read Replicas
โœ”๏ธ Use Multi-AZ deployment for auto-failover
โœ”๏ธ Route reads to replicas, writes to the primary

๐Ÿ› ๏ธ What If the Master DB Crashes?

If the master DB goes down, you need a failover strategy:

โœ… Database Failover System (AWS RDS Multi-AZ, Google Cloud SQL HA)
โœ… Automated Health Checks (Detect downtime in seconds)
โœ… DNS-Based Failover (Route traffic to the new master)
โœ… Heartbeat Monitoring (Check DB health every few seconds)

๐Ÿ’ก Pro Tip: Use PgBouncer (PostgreSQL) or ProxySQL (MySQL) to handle failovers seamlessly!

๐ŸŒ Global Multi-Region High Availability ๐ŸŒ

For large-scale SaaS apps, consider multi-region replication:

๐ŸŒ Master in US-East โ†’ Replicas in EU, Asia ๐ŸŒ
๐Ÿ”ฅ Load Balancer automatically directs traffic to the nearest healthy DB.

โœ… Protects against regional failures
โœ… Improves performance for global users
โœ… Disaster Recovery Ready

Final Thoughts ๐Ÿ’ก

Thereโ€™s no perfect answer, just trade-offs. Choose wisely based on your budget, security needs, and scalability goals. ๐Ÿš€

โœ… Start small โ†’ Use a single DB with strong indexing & partitioning.
โœ… Plan for scale โ†’ Be ready to move big tenants to their own DBs.
โœ… Automate onboarding โ†’ Because who likes manual work? ๐Ÿ˜†

A master database is the backbone of a scalable multi-tenant system. It makes onboarding, routing, and scaling seamless.

The Master Database is the core of a multi-tenant system. If it fails, your entire app is in trouble.

๐Ÿš€ How to ensure high availability?
โœ… Use Master-Replica Setup for read scaling
โœ… Implement Failover & Automatic Recovery
โœ… Optimize Query Routing (Reads โ†’ Replica, Writes โ†’ Master)
โœ… Consider Global Multi-Region Setup for maximum uptime

By implementing these strategies, your multi-tenant SaaS will stay online โ€” even when things go wrong! ๐ŸŽ‰

Whatโ€™s your take? Have you ever switched from single to multi-DB (or vice versa)? Share your war stories in the comments! ๐Ÿ—๏ธ๐Ÿ˜†

Have you ever faced a Master DB failure? How did you handle it? Drop your experience in the comments! ๐Ÿš€

What do you think? Have you built a multi-tenant system before? Letโ€™s chat in the comments! ๐Ÿš€

--

--

Smit Patel
Smit Patel

Written by Smit Patel

Passionate about crafting efficient and scalable solutions to solve complex problems. Follow me for practical tips and deep dives into cutting-edge technologies

No responses yet