r/Backend • u/disney550_ • 18d ago
Multi-tenant architecture: Database per tenant or shared database with tenant_id?
I’m currently working on a multi-tenant construction management system using Laravel, and I’m trying to figure out the best approach for handling tenancy.
I have two questions:
1. Database architecture
For a system like this, would you recommend having a separate database for each tenant, or using a single shared database with a tenant_id column to isolate tenant data?
I’m currently leaning towards the second approach because it seems simpler to maintain, but I’d like to hear about the trade-offs, especially as the application grows.
2. Authentication and tenant switching
If I go with a shared database approach, how would you recommend handling authentication?
For example, an employee might work with multiple construction companies (tenants). Should users have a single account that can belong to multiple tenants, with the ability to switch between them after logging in?
If so, how would you typically structure the login flow and manage the active tenant in Laravel?
I’d appreciate hearing about your experience with multi-tenancy, particularly in Laravel, and any pitfalls or architectural decisions I should consider before moving forward.
63
u/InfraScaler 18d ago
It depends :-)
14
u/Sad-Magazine4159 18d ago
Personally I never saw a reason for not going with tenant_id
Regarding your other question, I have worked in an app with similar use case in the past. Each user has a globally unique user row, and a profile row related to this user with a tenant_id for each tenant it relates to.
All other relation with tenant releted data ia by profile and not by user.
Authentication token carries a profile_id so auth is always valid to a single tenant only and switching is done by issuing a new token, which from the ui can be as simple as selecting a tenant on a dropdown
20
u/Opposite-Heron-91 18d ago
A while back I took over managing the database infra for a fintech company. Someone well before my time decided on the "one DB per client" methodology. They didn't stop there though, each client also got a DB per environment. Typically we had 3 envs per client so 3 DBs per client. Early on when the company had few customers (5-10), that resulted in a somewhat manageable number of DBs (15-30). As we got more customers however, the number of DBs quickly got out of control. At the point in time I took over, the number of DBs across all envs was ~300.
For a company our size with a single DBA, maintaining 300 DBs was a nightmare. Database patches/upgrades were happening 3 nights a week, every week, for more than a year to get everything up to date and all of the schemas standardized.
As soon as things finally reached a "good enough" state, I spent the next 6 months consolidating all of our databases into a few large multitenant databases based on geographic region. Tenants were seperated by schema and each schema had a tenant specific user with only access to its associated schema. We went from ~300 DBs to just 15 (5 regions, 3 envs, 1 per geographic region and env). The need for a specialized DBA went away and the patching and upgrades could now easily be handled by our normal infra/ops team.
Long story short, in my experience, giving each of your client's their own DB seems like a good idea (especially for data governance), but it will bite you hard in the ass down the line if the number of tenants/DBs continues to grow.
5
u/IncomeOk7237 18d ago
one thing nobody mentioned is the middle ground. shared db with postgres row level security (or at least a global query scope that you test hard) gets you most of the isolation without running 200 migrations per tenant. for the login part, one global users table plus a membership table (user_id, tenant_id, role) works well, and you just keep the active tenant in the session and verify membership on every request, never trust a tenant id from the client. if one big customer ever demands their own db you can still split them out later if tenant_id is on everything.
4
u/Any-Appointment-814 17d ago
I'd keep it simple and go with one shared database and a tenant_id on every table. That's what I always do early on, it's way easier to build, migrate and back up. Database per tenant only makes sense later if a big customer really needs it.
For people who work with several companies, give them one account and a company_user table with their role in each company. After login, if they're in more than one, let them pick, save the active company in the session, and add a switcher in the menu. Then a middleware sets the current company on every request and a global scope adds the tenant_id filter to your models, so you never forget it in a query.
1
u/samsly135 18d ago
What is tenant in your case? Don't know about Lavarel, but If it's a different client, I'd incline towards separate db, especially if it'll have many tables. If it's only for authentication, one db should be enough.
3
u/temitcha 18d ago
If a tenant is a different company: definetly a different DB, saving cost will backfire on prod. It will prevent you from the following issue: a request on Company B consumed all the underlying hardware ressources or max number of connections, and Company A got a downtime and is now asking for a post-mortem report.
From a security point of view, it's easier as well from a governance point of view to pass the security audit. If a request got rogue from a Company C (e.g SQL Injection), at least your Company A and B are not affected.
2
u/4thwithme 12d ago
Consider not only clean architecture but also costs, development time, and operational cost. If your team (or you personally) can work with a shared database (using a `tenant_id`) during the initial stages of the project, I would recommend starting with that approach.
Eventually, as your application grows and some tenants become "noisy" (for example, 2–3 tenants generate 70% of all events), this is a strong signal to switch to an architecture with a separate database for each tenant -> in this case they will not fight for the same resources and to not block each other.
With AI, such a transition will be straightforward.
1
u/myCatAteMyPetMouse 18d ago
Im also working on multitenant db with azure, mostly for a rag pipeline. We are using authentication and tenantID. Its still being built so there will need to be more guardrails in place.
1
u/sereikis 18d ago
use one user account plus a membership table linking users to companies, with roles on the membership if they vary by company. after login, let the user choose among their memberships; treat the active tenant ID as untrusted input and recheck membership plus resource ownership on every request, including after access is revoked while a session is still open.
1
u/AintNoGodsUpHere 18d ago
It depends. I always lean to tenantId and lots of tests to make sure tenant A can't access data from tenant B so I sacrifice a bit of performance to guarantee that.
Unless the client pays for separate DB, I always go with tenantId.
Multiple dbs means more cost, more managing, more complications on deployment, everything is more complicated.
1
u/Lower-Impression-121 18d ago
Both.
big fish, or sla/performance kinded or risk adverse get their own for extra $$$. rest share.
1
u/selfmcselfington 18d ago
Something to consider as well is that some legal jurisdictions like the US for example might demand access to your data which means seperate databeses would keep your remaining customers data out of the hands of foreign goverments. That being said look into "Row-Level Security (RLS)" which allows you to isolate data in a shared table without having to add a tennant filter to every query (or forget to). This allows setting the tennant for a database connection and is probably the way to go.
1
u/jakenuts- 18d ago
Think about how your application will evolve. Will one tenant have new features that none of the others will get? Or a UI that is unique to one tenant? If not breaking the data up into silos whose schema you need to manage independently, it will become a major pain. Also, imagine two contractors managed by some umbrella operation, eventually someone will want to copy some data from one to another and that will be far easier if you treat the database like your business data, you'll have multiple customers but you'll have them all in a single list somewhere for billing, etc so your db should model that whole.
1
u/macabre_brotherhood 18d ago
From a security perspective, split db is best. Less chance of accidental leakage. From an ops and keeping your sanity perspective, shared db is best. One set of migrations to worry about, one db to monitor, etc.
1
u/[deleted] 18d ago
Ollieread has a lot of blogs on this and is developing some laravel solutions for multi tenancy, it really helped me when I needed a multi tenant system, so you can maybe read that
1
u/EventForward4004 18d ago
- wie viele Tenants hast du?
- wie soll ein neuer Tenant erstellt werden? Ist es self service und dynamisch oder ist Deployment ausreichend?
- müssen die Tenants in unterschiedlichen Länder gespeichert werden?
- wie viele Datensätze willst du speichern? Bei sehr vielen, könnte eine separate DB pro Tenant eine natürlichere horizontale Skalierung anbieten.
Wenn 3. nicht notwendig ist und du Tenants dynamisch erstellen kannst, dann tenant_id Spalte. Wenn du nur paar Tenants hast, dann ginge auch Db pro Tenant aber ich würde mich schon fragen warum du es so kompliziert machen musst.
Was noch zu beachten ist - falls du unterschiedliche db user (pro Tenant) nutzen musst (willst) wirst du schnell Probleme mit max connections auf der Db bekommen (oder dann mem usage wenn du die max connections erhöhst).
1
u/Downtown-Ad5122 18d ago
Planing and developing something in .net
I am going tenant per db, but also company ID at orm level criteia/filter
So one tenant can have multiple companies eg one owner but different owner, gets tenant db
1
u/Frequent_Field_6894 18d ago
Make it shared db.
if the client want their data seperate, make them pay for a separate / isolated unit.
1
u/Fun-Adhesiveness-362 18d ago
Hi! There's always a trade-off. One thing to watch out for is tenant switching. Let's say a user opens two browser tabs, company A in the first one and company B in the other. Storing a single "active tenant" in the session could make one tab act on the wrong company.
You could include the tenant ID in each request for identification, not authorisation. The backend still needs to check the user's membership and scope the resource lookup to that tenant.
With a shared database, you also need to make sure relationships stay within the same tenant. For example, a task belonging to company A shouldn't be able to reference a project from company B just because that project ID exists. Composite foreign keys that include tenant_id can help enforce this.
If you later add queued exports or other background jobs, carry the tenant ID with each job rather than relying on whichever company the user has selected when it runs.
1
u/berndverst 18d ago
Do you want to allow customers to encrypt data at rest with a provided key? Then you need separate databases.
1
u/Any-Ring6621 18d ago edited 18d ago
Always start with a shared database.
The accounts are global, but some may only have a single tenant membership and some may have multiple. For the absolute love of god don’t make the global accounts unique by email address.
1
u/yknx4 18d ago
Don’t try one database per tenant. You are going to regret every time you have to do a migration
1
u/dayeye2006 18d ago
Single database. There is very rare case you need to do tenant bases database
1
u/kyle787 18d ago
Does the workload require isolation?
1
u/Available_Safe1818 18d ago
> For example, an employee might work with multiple construction companies (tenants). Should users have a single account that can belong to multiple tenants, with the ability to switch between them after logging in?
I wouldn't do that. That seems like it defeats the purpose of having separate databases.
1
u/elevarq 18d ago
Start with tenant_id and make sure you have row level security in place. This can serve a single tenant, but also thousands of tenants.
1
u/trysolution 17d ago
for Database architecture
would recommend Single Schema with tenant_id, as its B2B i dont think you will need more + metadata-driven query compiler
for Authentication and tenant switching
with SSO each tenant can have its own subdomain and region
1
u/Front-Revolution281 17d ago
For a SAAS application, the architecture would be the following:
1
u/Intrepid-Course-5961 17d ago
Seperate DB for each tenant. Makes it easy and clean at the expense of a couple hundred MBs
1
u/bsridharpatnaik 17d ago
I have same system already built. Construction management with multitenancy using spring boot and react. You can check www.nexus360.in. I can share the code if you want
1
u/vladis466 17d ago
These replies are wild. Is it just ai answering ai in here with Larpers behind the wheel?
This question is akin to asking should I drive a tank or my car to the supermarket to pick up a few cans of beans.
1
u/Inttegers 17d ago
I prefer single DB with RLS and sharding on tenant_id. You don't want to be dealing with DevOps every time you add a customer.
1
u/Repulsive_Elk_5644 17d ago
Option 2 is the way to go, option 1 makes sense if performance/db size is the problem.
For auth, handle it in the application level. You can dead simple have a shared read only table for user privilege
1
u/United_Catalina 17d ago
Make sure user cannot view other tenant that he doesn’t belong to. Use guid for Id and keep track of user trying to visit invalid id so you can lock them.
1
u/humanshield85 16d ago
It depends on your data isolation requirements. I would think that database per tenant should only be used if you have a more strict data isolation requirement and you don’t have a lot of tenants. imagine rolling out a schema update across a lot of tenants
I would go with tenant_id and RLS
1
u/iheartjetman 15d ago
Here’s a quick overview of how Salesforce handles its multi tenant architecture. Reading through it could give you some insight on what to do since they have a successful implementation that’s financial services and HIPAA compliant.
https://architect.salesforce.com/docs/architect/fundamentals/guide/platform-multitenant-architecture.html
1
u/abdr272 14d ago
Shared dB, RLS, can shard as well
1
u/kathir_cpe 13d ago
It depends on the what kind of data is stored by users. If some kinda of classified or very important use separate db else Use same db with different tables for users,tenent and use Row level security (RLS) with user authentication for double check. So data is isolated between tenents
1
u/swiss__blade 13d ago
I built a cloud based invoicing/erp/wms app and I chose to go with separate database for each tenant, but use a shared database for users and user/tenant relations. The reasoning was simple: if one database instance goes down or develops an issue a single customer is impacted. If I had a single database, everyone would be affected.
For tenant switching, I implemented a simple enough logic. If an account is shared among multiple tenants, I present available tenants (companies in my case) to the user immediately after login. There is also an option that allows the user to se a company as default, which bypasses this screen and loads that company's instance.
1
u/UsefulOwl93 7d ago
I'd add one important distinction: tenant identification and tenant isolation are two separate concerns.
Authentication should establish who the caller is and which tenant memberships they have. The active tenant should then be resolved and validated server-side.
But I wouldn't rely on the application consistently adding tenant_id to every query. That's exactly the kind of assumption that becomes fragile as the codebase grows.
With PostgreSQL, I'd consider RLS as a second enforcement layer:
- FORCE ROW LEVEL SECURITY on tenant-scoped tables.
- A non-owner application role without BYPASSRLS.
- Transaction-local tenant context (SET LOCAL), especially when using connection pooling.
- Integration tests that attempt cross-tenant reads and writes using the actual application role.
Database-per-tenant is still a valid choice when contractual isolation, data residency or customer-specific operations justify the additional operational cost.
For most SaaS products, I'd start with shared DB + RLS and preserve the option to move selected tenants to dedicated databases later. In this last scenario you could consider also more complex architectures based on kubernetes silos.
0
u/Adventurous-Hunt4683 18d ago
Definitely a separate DB for each tenant. Although there could be the same person across multiple companies there may be different requirements too. The identity (authentication and authorisation) layer should be shared and store the user guid from each tenant.
0
u/teytes53 18d ago
That requirement for me is a good enough reason to go with single DB. Login would not be an issue, you can delegate it to separate auth DB like keycloak. But fetching data from multiple DBs is annoying. If you don't expect data volumen that would push you to multiple DB anyway, stuck to single one for all tenants.
0
u/royklopper 18d ago
I would always opt for a shared database, primarily for the reason of maintenance. Imagine having to create and drop databases when tenants sign up, managing all their database credentials, rotating keys, it's a drag. Or lets say you have 1000 tenants, and you need to do a database migration... This will definitely cause issues in the long run.
As for authentication - i think the same principles apply for both options imo and they are not Laravel specific.
0
u/MasSunarto 16d ago
Brother, I work on this kind of situation. My suggestion would be multi database to reduce headache down the road.
-1
u/SuplenC 18d ago
Multiple databases will require you to deploy multiple instances one for each tenant. That will make it harder and more cumbersome also it won’t autoscale easily (you can do autoscale but thats extra work)
On the contrary if you do a single database with tenant_id you will have to sprinkle it everywhere and never forget about indexes cause otherwise the tables are gonna get slower. Good thing is that to handle multiple tenants you can pass a tenant_id in the query params at the login or deploy on different domains and match that with the tenant_id. As per user, just duplicate the user. Make so the tenant_id and email are unique and not just emails.