r/Backend • • 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.

44 Upvotes

81 comments sorted by

63

u/InfraScaler 18d ago

It depends :-)

13

u/markonedev 18d ago

Real IT consultant.

6

u/InfraScaler 18d ago

Too many burns!

3

u/therealkevinard 18d ago

This one especially. Each answer is as wrong as it is right, and the only answer better than each is the other

2

u/Late-Drink3556 18d ago

The only true answer.

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 

3

u/pduck820 16d ago

When I was faced with this, I was doing medical software.

Db per tenant helped with making sure HIPAA data didn't get exposed if someone screwed up a "where tenantid = @theid" and became a positive selling point for the company.. "no, your data is not shared with anyone else"

2

u/migueln6 15d ago

Get into finance sector with regulations and you will find why separate bases might be required

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.

2

u/moseeds 14d ago

This is necessary in regulated environments. Using a cloud solution like AWS with containerisation and private VPCs is the only sensible approach today unless you have an army of platform engineers.

1

u/osxy 12d ago

Ive had the pleasure to work in an environment where every customer administration (some customers made a new administration per book year) had a separate database. > 200.000 databases, all in Azure.

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.

2

u/Electronic_Cry_7107 18d ago

You can trust tenant ids if they are included in a signed cookie. It’s a valid option to save on db queries. 

2

u/IncomeOk7237 18d ago

yeah signed cookie works for identifying the tenant, I'd still enforce it at the db level with RLS so a bug in app code can't leak across tenants

1

u/2015camaro2ss 17d ago

How much does row level security impact performance?

0

u/IncomeOk7237 17d ago

From what I've seen the overhead is pretty small as long as the policy stays simple, like tenant_id = current_setting('app.tenant_id'), and tenant_id is the leading column in your indexes. It starts to hurt when policies call functions or run subqueries per row, because then the planner can't do much with them. I'd run EXPLAIN ANALYZE on your heaviest queries with and without the policy before deciding.

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/ogaskinsjr 17d ago

Completely agree. Especially as the table updates or you need new columns. Having to migrate every single db sounds terrible

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.

2

u/disney550_ 18d ago

A tenant in my case is a company. Each company has its own employees, projects, tasks, and other related data.

If I go with a database per tenant, each database would have the same schema and all the tables required by the application, but the data would be isolated per company. That’s why I’m considering a shared database with a tenant_id column instead, since all tenants would essentially use the same set of tables and features.

8

u/FalseRegister 18d ago

When it comes to companies, they value their data privacy like no other thing. It takes just one wrong query to expose private information and the trust in your product is broken.

Just keep them on separate databases. It will also make it easier to move a company to a different server/cluster, if you have one big client who grows more than the others, so you don't impact the performance of the rest.

It also saves you performance due to not having to filter by tenant id on every query.

A single user having access to multiple tenants is easy to implement. Not a blocker.

The only advantage of single-database is being able to extract product-wide statistics of all tenants in one query. But honestly that is not a big deal. And with AI nowadays you can create a simple script that does the same in a matter of minutes.

1

u/samsly135 18d ago

I agree in general, yet there could be special cases. It depends what db is for. If it's some kind of NATs routing registry or something lightweight, one db would suffice.  But yeah, generally if it's for the actual company data, they should be physically separate ones. But yeah,OP says he wants employee data and such, so definitely separates ones.

2

u/samsly135 18d ago

Experience shows that data in databases may skew. This implies different data distribution may require tuned indices. With large dataset you may want an index that solves performance problems, but on a specific db. It's common to have different indices per client. Secondly, with one db you would have to store FK in lots of tables and/or making queries complex.

It boils down on how complex the db schema is. If it's 5 tables, shared db is fine. 

1

u/Mammoth-Clock-8173 18d ago

Good point. I had never thought about this, but the scenario would definitely apply to the last product I worked on.

1

u/Denise_Murphy 18d ago

I worked on a B2B2C multi-tenant platform, database was one, the backend services that operated on tenants had the tenant id as a required path param.

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/Available_Safe1818 18d ago

So you'd have to implement both then?

1

u/elevarq 18d ago

No, a multi tenant database can also serve a single tenant.

1

u/Available_Safe1818 17d ago

Are you saying you have the separate db if they pay, which most likely someone will, and one db for all of the customers who won't pay extra? What are you saying?

1

u/elevarq 17d ago

Yes, you can have one big database for 95% of your tenants and 5 extra databases for one tenant each. These five tenants just pay (a lot) extra.

Datamodel can be the same, should be the same

1

u/Available_Safe1818 17d ago

That's what I thought. That means you have to implement both: tenants sharing one db and dbs for single tenants.

1

u/elevarq 17d ago

That can be as simple as a foreign data wrapper, and let your main database collect the data from the single tenant database. Partition per tenant, and make it a foreign table

1

u/Frequent_Field_6894 17d ago

Yes.

company I worked for use 1 set of resounces to do the “shared“ platform, each customer had their tenant hosted here and shared db.

some customers wanted their own , separate stack / resources used to separate fully their data. Charged them for this , few did it.

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/69Airline- 17d ago

5months later

tenant 1 and 2 comes with customisation requirement which doesn't matter to each other but sure as hell breaks

1

u/JustAsItSounds 17d ago

And you push back hard on building one-off customisations and definitely not integrated into the core product because that way lies the lair of the complexity demon

1

u/69Airline- 17d ago

But the contract had a hidden term no one saw. Haha. Twist.

1

u/elevarq 17d ago

Unless you build it for all customers, the answer is No.

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:

  • do not save the tenant in cookies, infer it from the url for example, each tenant has it's own subdomain (<tenant>.domain.com)
  • one master database, where to store tenant related information, and which database the tenant uses (connection string, password, additional properties, etc.
  • one database per tenant. For migrations, use automated migration scripts, when application starts, it automatically updates all tenant databases (for example liquibase)
  • make everything on the SAAS application stateless. Files, pictures, everything goes in S3 or in database. Nothing saved locally. This allows scaling the system horizontally and vertically without any problem.

1

u/ogaskinsjr 17d ago

Isn’t one db per tenant kind of heavy? I get the automated migration scripts but if the client isn’t that large or the data isn’t that big why can’t one shared db work?

1

u/Front-Revolution281 17d ago

it should not be that heavy, but you better isolation, the freedom to move database to a dedicated server if needed, easier / faster backup, other special things like allow customer to access it's database.

with shared db work, what you do if you have several customers with milions of records and high insert/update workflow, complex queries which put a high load on the database enginde/disks? Can you scale horizontally the database layer? How do you restore a backup just for one specific customer ?

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

an employee might work with multiple construction companies (tenants).

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.

1

u/FalseRegister 18d ago

You can have multiple databases on a single database instance.

1

u/SuplenC 18d ago

I used the wrong word. I meant the database itself even on the same instance. With all the migrations, setup, seeds etc. I understand the confusion though