Hi everyone,
I’m building a collaborative text editor SaaS with Phoenix, similar to Notion, where users can create teams and invite others. I’m facing a challenge with managing multi-tenancy and specifically, how to reliably determine the current team (tenant) for a user across sessions.
Here’s a breakdown of my setup and the issue:
- Database Structure:
- I have a
users
table and ateams
table. - Each user must belong to at least one team (their default team, created during onboarding).
- Users can belong to multiple teams.
- I have a
- Current Flow:
- During onboarding, a default team is created for the new user.
- I’m considering storing the user’s currently selected team (tenant) in the session.
- On subsequent requests, I would retrieve the team from the session for context.
- The Problem:
- When a user logs out and back in, the
phx.gen.auth
functionality renews the session, causing the selected team to be lost. - This results in queries failing, as the application can’t determine the correct tenant.
- When a user logs out and back in, the
- Potential Solution (and Concerns):
- I’ve considered storing the user’s current team selection in the database.
- However, I’m unsure if this is a good practice and how to best structure the database to support this.
- I am unsure of the best way to handle the setting and retreival of the users current selected team.
My Questions:
- What are the best practices for managing multi-tenancy in a Phoenix application, specifically for handling user team selection across sessions?
- Is storing the current team selection in the database a viable approach? If so, what is the best way to implement it?
- Are there other strategies that people have used to solve this problem?
I understand this is more of an architectural question than a Phoenix-specific one and it’s probably a very common solved problem, but it’s my first application with this architecture and I’d greatly appreciate any insights or guidance you can offer.