How to design a multi tenant mysql database
In MySQL I prefer to use a single database for all tenants. I restrict access to the data by using a separate database user for each tenant that only has access to views that only show rows that belong to that tenant.
This can be done by:
- Add a tenant_id column to every table
- Use a trigger to populate the tenant_id with the current database username on insert
- Create a view for each table where tenant_id = current_database_username
- Only use the views in your application
- Connect to the database using the tenant specific username
I've fully documented this in a blog post: https://opensource.io/it/mysql-multi-tenant/
The simple way is: for each shared table, add a column says SEGMENT_ID. Assigned proper SEGMENT_ID to each customer. Then create views for each customer base on the SEGMENT_ID, These views will keep data separated from each customers. With this method, information can be shared, make it simple for both operation & development (stored procedure can also be shared) simple.
There are several approaches to multi-tenant databases. For discussion, they're usually broken into three categories.
- One database per tenant.
- Shared database, one schema per tenant.
- Shared database, shared schema. A tenant identifier (tenant key) associates every row with the right tenant.
MSDN has a good article on the pros and cons of each design, and examples of implementations.
Microsoft has apparently taken down the pages I referred to, but they are on on archive.org. Links have been changed to point there.
For reference, this is the original link for the second article