I thought I'd write about a topic that I feel many people need, but don't know about.
And that is multi-tenancy.
Multi-tenancy is the ability to provide your application to multiple customers, with separate data, without having to host an instance for each customer.
Say you have built an e-commerce platform. Your database has tables for users, orders, products, ordered products, product variants, invoices etc.
You want to let multiple businesses use this platform. You want them to have separate orders, products and all the other things.
You can do two things.
Multi-tenancy comes in two flavors.
tenant_idcolumn and you use
WHEREclauses to scope the data to the current tenant.
Single-database tenancy comes with more code complexity. You have to keep the scoping in mind at all times. Some backend frameworks, like Laravel, let you add "global scopes" that automatically apply these WHERE clauses to your queries, but there are still edge cases when you need to be mindful of the data scoping.
Multi-database tenancy comes with more devops complexity. If you implement tenancy right, you don't need to think about the data scoping at all - you can just switch the database connection before your application's code (controllers in MVC frameworks) is reached. However, you will have to maintain multiple databases - such as running migrations for each one separately, which means slower deployments.
But, one devops upside of multi-database tenancy is that you likely won't EVER have to think about database sharding. Your data is already sharded in a way. Single-DB tenancy can result in one massive database that would need sharding.
There's a lot of misconception about the multi-database approach. People often that it's somehow very complex. They often say "for most apps, it's not needed". But that assumes that it's somehow more work to use multi-database tenancy.
Personally, I'm a fan of it because it lets me write my code as if tenancy weren't a thing and then just have logic that switches the database to the correct tenant based on hostname, before my application code is reached.
But multi-database tenancy comes with one big disadvantage: sharing data between tenants can be a pain. There are three scenarios here:
So my recommendation is that if you want a comfortable coding experience and don't need a lot of shared data between tenants, use multi-database tenancy. If you just need to scope a part of the database to a tenant, but otherwise have a lot of "global" data, use single-database tenancy.
If you're using Laravel, you can look into my package: https://tenancyforlaravel.com/
It's focused on providing as much out-of-the-box functionality as possible and making you ship very quickly.
That's the reason I'm writing this article. Maintaining a multi-tenancy package for a year and a half, I have a lot of experience with this and wanted to share this concept with the people who aren't that familiar with it.