3
votes

I'm trying to build a Multi tenant SaaS application, and i know there are multiple approaches to that, but i picked the multi-database one i think it would fit most.

so I create a db for each tenant and store a table of tenants in the main db and connect users to their respective db based on the subdomain.

now my issue here is where to store the users, in the main db? or the tenant db, storing the users in the main db is going to make it difficult to get user related models in other db's, but storing it inside tenants db would make it difficult to authenticate on all users ...

also what's the best scenario?

  1. authenticate, get jwt token.
  2. send token with each request.
  3. on each request validate token, check subdomain, connect to respective tenant db, execute request.

is this a good approach? what should I do with the users table issue? ThnQ

2
"storing it inside tenants db would make it difficult to authenticate on all users" Why would you want to do that? - Alex Howansky
maybe I didn't make that clear ... if I store it in tenants db, when the user log's in the first time without specifying which tenant. how would I know which db to authenticate from? - Sherif
Either make them specify the tenant explicitly by using userids that look like emails (e.g., [email protected]) or implicitly determine the tenant by looking at the domain name that served the request. In either case, you want your userids to be unique within each tenant, not unique across all of them. I.e., if somebody sets up the userid bob within tenant #1, that shouldn't prevent somebody else from using the userid bob within tenant #2. - Alex Howansky
I know you're using multiple databases but if you decide to switch to single database, I'd suggest looking at Landlord which is great for saas platforms. Just a thought, good luck. - camelCase

2 Answers

0
votes

I can offer third option. Have user both in tenant and main db. You can then create procedure to update main db when user changes in tenant db (or vice versa).

Also, I don't know models in Laravel, but MySQL doesn't have problem with cross database JOINs.

0
votes

Good option will be to keep users in tenant database. As you are distinguishing your tenant based on sub-domain, you can tell your authentication system to query sub-domain specific database.

Sharing flow of authentication

  1. User hits the sub-domain to login for application
  2. User credentials will be sent to application
  3. Before passing credentials to authentication, decide database for user authentication based on sub-domain from which user came.
  4. Pass database name, user credentials to authentication system
  5. Authentication system query specific database and authenticate user
  6. Generate session