Python

Building a Multi-Tenant SaaS Backend with FastAPI and PostgreSQL

Imagine you're building a project management platform. One company uses it to manage software development, another uses it to track marketing campaigns, and a…

D
DevByteTechnical Author
Published
19 min read4 views
Building a Multi-Tenant SaaS Backend with FastAPI and PostgreSQL

Imagine you're building a project management platform. One company uses it to manage software development, another uses it to track marketing campaigns, and a third uses it to organize internal operations.

All three companies use the same application, but their data must remain separate. A user from one company shouldn't be able to see another company's projects, team members, or billing information.

This is one of the main challenges when building a multi-tenant SaaS application.

Instead of deploying a separate backend and database for every customer, you can run a shared application that serves multiple customers while keeping their data isolated. This approach can reduce infrastructure costs, simplify deployments, and make it easier to maintain the product as the number of customers grows.

In this article, we'll build the foundation of a multi-tenant SaaS backend using FastAPI and PostgreSQL. We'll look at tenant identification, database design, authentication, tenant-aware queries, authorization, and some practical decisions you'll need to make before taking the application to production.

What Is Multi-Tenancy?

Multi-tenancy is an architecture in which a single application serves multiple customers, commonly called tenants.

A tenant might represent a company, an organization, a team, or an individual customer, depending on the product.

For example, consider a SaaS application with three organizations:

  • Acme Technologies: Uses the platform to manage software projects.

  • Bright Marketing: Uses it to manage marketing campaigns.

  • Nova Systems: Uses it to track internal tasks.

All three organizations access the same application, but each has its own users, projects, and settings.

The important part is that tenants share the application infrastructure without gaining access to one another's private data.

A typical request might look like this:

User logs in
    |
    v
Authentication is verified
    |
    v
User's organization is identified
    |
    v
Permission to access that organization is checked
    |
    v
Tenant-specific data is fetched from PostgreSQL
    |
    v
Response is returned

The application must enforce this separation consistently. Hiding another tenant's data in the frontend is not enough because someone could still call your API directly.

Choosing a Multi-Tenant Database Architecture

Before writing code, you need to decide how tenant data will be stored.

There are three common approaches.

1. Shared Database and Shared Tables

Every tenant uses the same database tables. Each tenant-owned record contains a tenant_id column.

For example:

id

tenant_id

project_name

1

101

Website Redesign

2

102

Marketing Dashboard

3

101

Mobile Application

Tenant 101 owns the first and third projects, while tenant 102 owns the second.

A query for tenant 101 would look like this:

SELECT *
FROM projects
WHERE tenant_id = 101;

This approach is relatively simple to operate and works well for many SaaS products.

Advantages:

  • Lower infrastructure costs.

  • Easier database migrations.

  • Simple onboarding for new tenants.

  • Efficient use of database connections.

  • Straightforward application deployment.

Disadvantages:

  • Every tenant-specific query must enforce isolation.

  • A missing tenant filter can expose data.

  • Very large tenants may compete for shared resources.

For many early-stage SaaS applications, this is a sensible starting point.

2. Separate Schema for Each Tenant

In this approach, tenants share one PostgreSQL database, but each tenant has its own schema.

For example:

PostgreSQL Database
    |
    |-- tenant_acme
    |      |-- users
    |      |-- projects
    |
    |-- tenant_bright
    |      |-- users
    |      |-- projects

This provides a degree of structural separation, but database migrations and tenant provisioning become more complicated as the number of tenants grows.

You also need to manage schema selection carefully. Simply changing the active schema based on an untrusted request parameter can introduce serious security problems.

3. Separate Database for Each Tenant

Every tenant has its own database.

SaaS Application
    |
    |-- Acme Database
    |-- Bright Database
    |-- Nova Database

This approach can make sense when customers require stronger operational isolation, dedicated infrastructure, or specific data residency arrangements.

However, managing database connections, backups, migrations, monitoring, and upgrades becomes more complex.

Which Approach Should You Choose?

For this tutorial, we'll use a shared PostgreSQL database with shared tables and a tenant_id column.

It offers a practical balance between simplicity, cost, and scalability.

You can always introduce dedicated databases for selected enterprise customers later if your architecture and business requirements justify it.


Step 1: Set Up the FastAPI Project

Let's start with a basic project structure.

saas-backend/
├── app/
│   ├── __init__.py
│   ├── main.py
│   ├── database.py
│   ├── models.py
│   ├── schemas.py
│   ├── dependencies.py
│   └── routes/
│       ├── __init__.py
│       ├── tenants.py
│       └── projects.py
├── .env
├── requirements.txt
└── alembic.ini

We'll use FastAPI for the API layer, SQLAlchemy for database operations, and PostgreSQL as the database.

Install the required dependencies:

pip install fastapi "uvicorn[standard]" sqlalchemy \
psycopg[binary] pydantic-settings alembic pyjwt \
pwdlib[argon2]

These packages provide the foundation for API development, database access, configuration management, migrations, JWT authentication, and password hashing.

For a real application, you should also pin dependency versions and use a lockfile or another reproducible dependency-management process.

Configure the Environment

Create a .env file:

DATABASE_URL=postgresql+psycopg://postgres:password@localhost:5432/saas_db
JWT_SECRET=replace-with-a-long-random-secret
JWT_ALGORITHM=HS256

Use a strong, randomly generated secret in development and production. Never commit real secrets to Git.

Now create app/database.py:

from pydantic_settings import BaseSettings, SettingsConfigDict
from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, sessionmaker


class Settings(BaseSettings):
    database_url: str
    jwt_secret: str
    jwt_algorithm: str = "HS256"

    model_config = SettingsConfigDict(
        env_file=".env",
        extra="ignore",
    )


settings = Settings()

engine = create_engine(
    settings.database_url,
    pool_pre_ping=True,
)

SessionLocal = sessionmaker(
    bind=engine,
    autoflush=False,
    expire_on_commit=False,
)


class Base(DeclarativeBase):
    pass


def get_db():
    with SessionLocal() as db:
        yield db

The get_db() dependency provides a database session for each request that needs one.

Using a context manager helps ensure that the session is closed after the request finishes. SQLAlchemy manages transactions separately, so we'll explicitly commit or roll back write operations where appropriate.

For a production application, you'll also want to configure connection pooling based on your database limits and expected traffic.

Step 2: Design the Tenant-Aware Database Models

Let's create three core models:

  • Tenant: Represents an organization.

  • User: Represents an individual user.

  • Project: Represents a project owned by an organization.

A user may belong to more than one organization, so we'll model organization membership separately rather than assuming every user has exactly one tenant.

This is a useful design decision because many SaaS applications eventually need to support consultants, contractors, or employees who work with multiple organizations.

Create app/models.py:

from sqlalchemy import (
    Boolean,
    ForeignKey,
    String,
    UniqueConstraint,
)
from sqlalchemy.orm import Mapped, mapped_column

from app.database import Base


class Tenant(Base):
    __tablename__ = "tenants"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(150), nullable=False)
    slug: Mapped[str] = mapped_column(
        String(100),
        unique=True,
        nullable=False,
    )
    is_active: Mapped[bool] = mapped_column(
        Boolean,
        default=True,
        nullable=False,
    )


class User(Base):
    __tablename__ = "users"

    id: Mapped[int] = mapped_column(primary_key=True)
    email: Mapped[str] = mapped_column(
        String(255),
        unique=True,
        nullable=False,
        index=True,
    )
    hashed_password: Mapped[str] = mapped_column(
        String(255),
        nullable=False,
    )
    is_active: Mapped[bool] = mapped_column(
        Boolean,
        default=True,
        nullable=False,
    )


class Membership(Base):
    __tablename__ = "memberships"

    __table_args__ = (
        UniqueConstraint(
            "tenant_id",
            "user_id",
            name="uq_membership_tenant_user",
        ),
    )

    id: Mapped[int] = mapped_column(primary_key=True)

    tenant_id: Mapped[int] = mapped_column(
        ForeignKey("tenants.id"),
        nullable=False,
        index=True,
    )

    user_id: Mapped[int] = mapped_column(
        ForeignKey("users.id"),
        nullable=False,
        index=True,
    )

    role: Mapped[str] = mapped_column(
        String(30),
        default="member",
        nullable=False,
    )


class Project(Base):
    __tablename__ = "projects"

    __table_args__ = (
        UniqueConstraint(
            "tenant_id",
            "name",
            name="uq_project_tenant_name",
        ),
    )

    id: Mapped[int] = mapped_column(primary_key=True)

    tenant_id: Mapped[int] = mapped_column(
        ForeignKey("tenants.id"),
        nullable=False,
        index=True,
    )

    name: Mapped[str] = mapped_column(
        String(200),
        nullable=False,
    )

    description: Mapped[str | None] = mapped_column(
        String(1000),
        nullable=True,
    )

Notice that User doesn't have a tenant_id column.

Instead, the Membership table connects users to organizations and stores their roles.

For example:

user_id

tenant_id

role

1

101

owner

1

102

member

2

101

admin

User 1 belongs to two organizations with different roles.

This gives us flexibility without creating separate user accounts for every organization.

The Project model includes tenant_id because every project belongs to one organization.

The unique constraint on (tenant_id, name) allows two different organizations to create projects with the same name while preventing duplicate project names within one organization.

For an existing production database, use Alembic migrations to create and modify these tables rather than relying on Base.metadata.create_all() at application startup.

Step 3: Understand Tenant Identification

One important question remains: how does the backend know which tenant a request belongs to?

There are several common options.

Subdomain-based identification:

acme.example.com/projects
bright.example.com/projects

Request header:

X-Tenant-ID: 101

Organization-specific URL:

/api/tenants/101/projects

Each approach has trade-offs.

For this tutorial, we'll use a tenant ID in the URL to keep the example easy to follow.

However, the tenant ID supplied by the client is only a request to access an organization. It is not proof that the user is authorized to access it.

Never trust a tenant ID simply because it appears in a URL, header, or request body.

The backend must verify that the authenticated user belongs to the requested tenant and has the required permissions.

Step 4: Authenticate Users and Verify Membership

Authentication answers one question:

Who is making this request?

Authorization answers a different question:

What is this user allowed to do?

In a multi-tenant application, you need both.

A user might be authenticated successfully but still have no permission to access a particular organization's data.

We'll use JWT authentication as the example. A production login endpoint should verify a password against its stored password hash and issue a signed token.

Here's a simplified token-generation function using PyJWT:

from datetime import datetime, timedelta, timezone

import jwt

from app.database import settings


def create_access_token(user_id: int) -> str:
    now = datetime.now(timezone.utc)

    payload = {
        "sub": str(user_id),
        "iat": now,
        "exp": now + timedelta(minutes=15),
    }

    return jwt.encode(
        payload,
        settings.jwt_secret,
        algorithm=settings.jwt_algorithm,
    )

The token identifies the user. It doesn't automatically grant access to every organization.

Keeping the access token relatively short-lived limits the impact of a leaked token. You should also consider refresh-token rotation, token revocation strategies, and secure client-side token storage based on your application.

Next, we'll create a dependency that validates the token and loads the authenticated user.

Create app/dependencies.py:

from typing import Annotated

import jwt
from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from jwt.exceptions import InvalidTokenError
from sqlalchemy import select
from sqlalchemy.orm import Session

from app.database import get_db, settings
from app.models import Membership, Tenant, User


oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")


def get_current_user(
    token: Annotated[str, Depends(oauth2_scheme)],
    db: Annotated[Session, Depends(get_db)],
) -> User:
    credentials_exception = HTTPException(
        status_code=401,
        detail="Invalid authentication credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )

    try:
        payload = jwt.decode(
            token,
            settings.jwt_secret,
            algorithms=[settings.jwt_algorithm],
        )

        subject = payload.get("sub")

        if not subject:
            raise credentials_exception

        user_id = int(subject)

    except (InvalidTokenError, ValueError, TypeError):
        raise credentials_exception

    user = db.get(User, user_id)

    if not user or not user.is_active:
        raise credentials_exception

    return user


def get_current_tenant(
    tenant_id: int,
    current_user: Annotated[User, Depends(get_current_user)],
    db: Annotated[Session, Depends(get_db)],
) -> Tenant:
    membership = db.scalar(
        select(Membership).where(
            Membership.tenant_id == tenant_id,
            Membership.user_id == current_user.id,
        )
    )

    if not membership:
        raise HTTPException(
            status_code=404,
            detail="Tenant not found",
        )

    tenant = db.get(Tenant, tenant_id)

    if not tenant or not tenant.is_active:
        raise HTTPException(
            status_code=404,
            detail="Tenant not found",
        )

    return tenant

The get_current_user() dependency verifies the JWT and retrieves the corresponding user.

The get_current_tenant() dependency then checks whether that user has a membership in the requested organization.

Returning a generic 404 when the user doesn't have access can help avoid revealing whether a particular organization exists. Your application may choose a different response policy, but it should do so consistently.

One important detail: The token creation function above is only a token-generation example. You'll still need a login endpoint that verifies the user's password using a secure password-hashing library such as Argon2 before issuing the token.

You should also validate that JWT claims have the expected types and handle malformed claims without exposing internal errors.

Step 5: Build Tenant-Aware API Endpoints

Now let's create an endpoint that lists projects for an organization.

A common mistake is to fetch all projects and filter them in application code.

For example, this is not a good approach:

projects = db.scalars(
    select(Project)
).all()

tenant_projects = [
    project
    for project in projects
    if project.tenant_id == tenant_id
]

This loads records belonging to every organization before filtering them. Apart from being inefficient, it creates unnecessary opportunities for accidental data exposure.

Instead, apply the tenant filter directly to the database query.

Create app/routes/projects.py:

from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import select
from sqlalchemy.orm import Session

from app.database import get_db
from app.dependencies import get_current_tenant
from app.models import Project, Tenant


router = APIRouter(
    prefix="/tenants/{tenant_id}/projects",
    tags=["Projects"],
)


class ProjectCreate(BaseModel):
    name: str = Field(min_length=1, max_length=200)
    description: str | None = Field(
        default=None,
        max_length=1000,
    )


class ProjectResponse(BaseModel):
    id: int
    name: str
    description: str | None

    model_config = ConfigDict(from_attributes=True)


@router.post("", response_model=ProjectResponse, status_code=201)
def create_project(
    tenant: Annotated[Tenant, Depends(get_current_tenant)],
    payload: ProjectCreate,
    db: Annotated[Session, Depends(get_db)],
):
    project = Project(
        tenant_id=tenant.id,
        name=payload.name.strip(),
        description=payload.description,
    )

    db.add(project)

    try:
        db.commit()
        db.refresh(project)

    except Exception:
        db.rollback()
        raise

    return project


@router.get("", response_model=list[ProjectResponse])
def list_projects(
    tenant: Annotated[Tenant, Depends(get_current_tenant)],
    db: Annotated[Session, Depends(get_db)],
):
    statement = (
        select(Project)
        .where(Project.tenant_id == tenant.id)
        .order_by(Project.id.desc())
    )

    return list(db.scalars(statement).all())


@router.get("/{project_id}", response_model=ProjectResponse)
def get_project(
    project_id: int,
    tenant: Annotated[Tenant, Depends(get_current_tenant)],
    db: Annotated[Session, Depends(get_db)],
):
    statement = select(Project).where(
        Project.id == project_id,
        Project.tenant_id == tenant.id,
    )

    project = db.scalar(statement)

    if not project:
        raise HTTPException(
            status_code=404,
            detail="Project not found",
        )

    return project

There are two important details in this implementation.

First, every endpoint obtains the tenant through get_current_tenant(). This ensures that the user is authenticated and belongs to the requested organization.

Second, the project queries include the tenant condition:

.where(
    Project.id == project_id,
    Project.tenant_id == tenant.id,
)

Even if a user guesses the ID of another organization's project, the query won't return it.

When creating a project, we also set tenant_id from the verified tenant object instead of accepting it from the request body.

This prevents clients from creating records under arbitrary tenant IDs.

What About Updating and Deleting Records?

The same principle applies to every operation.

For example, a tenant-aware update query should look like this:

statement = select(Project).where(
    Project.id == project_id,
    Project.tenant_id == tenant.id,
)

project = db.scalar(statement)

if not project:
    raise HTTPException(
        status_code=404,
        detail="Project not found",
    )

project.name = payload.name.strip()

db.commit()
db.refresh(project)

The tenant condition must remain part of the database query.

Don't fetch a project using only its ID and assume that authentication alone makes it safe to modify.

Step 6: Add Role-Based Access Control

Membership checks tell us whether a user belongs to an organization. They don't tell us what that user can do.

For example, an organization might have these roles:

Role

Permissions

Owner

Manage organization, members, billing, and projects

Admin

Manage members and projects

Member

Create and update permitted projects

Viewer

Read permitted project information

The exact permissions depend on your product.

Let's add a reusable dependency that checks membership roles.

In app/dependencies.py, add:

from collections.abc import Callable

from fastapi import HTTPException


def require_tenant_roles(
    *allowed_roles: str,
) -> Callable:
    def dependency(
        tenant_id: int,
        current_user: Annotated[
            User,
            Depends(get_current_user),
        ],
        db: Annotated[
            Session,
            Depends(get_db),
        ],
    ) -> Tenant:
        membership = db.scalar(
            select(Membership).where(
                Membership.tenant_id == tenant_id,
                Membership.user_id == current_user.id,
            )
        )

        if not membership:
            raise HTTPException(
                status_code=404,
                detail="Tenant not found",
            )

        tenant = db.get(Tenant, tenant_id)

        if not tenant or not tenant.is_active:
            raise HTTPException(
                status_code=404,
                detail="Tenant not found",
            )

        if membership.role not in allowed_roles:
            raise HTTPException(
                status_code=403,
                detail="Insufficient permissions",
            )

        return tenant

    return dependency

Now an endpoint that should only be available to owners and administrators can use:

@router.delete("/{project_id}")
def delete_project(
    project_id: int,
    tenant: Annotated[
        Tenant,
        Depends(require_tenant_roles("owner", "admin")),
    ],
    db: Annotated[Session, Depends(get_db)],
):
    statement = select(Project).where(
        Project.id == project_id,
        Project.tenant_id == tenant.id,
    )

    project = db.scalar(statement)

    if not project:
        raise HTTPException(
            status_code=404,
            detail="Project not found",
        )

    db.delete(project)
    db.commit()

    return {"message": "Project deleted successfully"}

The endpoint checks both organization membership and role permissions before deleting the project.

For larger systems, you may eventually want a more flexible permission model instead of hard-coded role names. But a small, clearly defined role system is often a good starting point.

Step 7: Register the Routes

Create app/main.py:

from fastapi import FastAPI

from app.routes.projects import router as projects_router


app = FastAPI(
    title="Multi-Tenant SaaS API",
    version="1.0.0",
)

app.include_router(projects_router)


@app.get("/health")
def health_check():
    return {"status": "ok"}

Run the application:

uvicorn app.main:app --reload

FastAPI automatically generates interactive API documentation.

Open the /docs endpoint on your local server to inspect the routes and test requests.

Before testing the project endpoints, you'll need to create database tables and seed or register a tenant, a user, and a membership. You'll also need a working login endpoint to issue the JWT used by protected routes.

The examples so far demonstrate the core architecture rather than a complete, ready-to-deploy authentication system.


Step 8: Strengthen Tenant Isolation at the Database Level

Application-level filters are necessary, but a missed filter can still create a serious security issue.

This is where PostgreSQL Row-Level Security (RLS) becomes useful.

RLS allows PostgreSQL to restrict which rows a database role can read or modify.

For example, suppose the projects table contains a tenant_id column. You can enable RLS and create a policy that compares each row's tenant ID with the tenant ID associated with the current database session.

First, enable RLS:

ALTER TABLE projects ENABLE ROW LEVEL SECURITY;

ALTER TABLE projects FORCE ROW LEVEL SECURITY;

Then create a policy:

CREATE POLICY tenant_isolation_policy
ON projects
USING (
    tenant_id = current_setting('app.current_tenant_id', true)::integer
)
WITH CHECK (
    tenant_id = current_setting('app.current_tenant_id', true)::integer
);

The policy restricts which project rows are visible and which rows can be inserted or updated.

However, the application must set the tenant context correctly for every transaction.

For example, with SQLAlchemy, you could set a transaction-local PostgreSQL setting after verifying the user's tenant membership:

from sqlalchemy import text
from sqlalchemy.orm import Session


def set_tenant_context(
    db: Session,
    tenant_id: int,
) -> None:
    db.execute(
        text(
            "SELECT set_config("
            "'app.current_tenant_id', :tenant_id, true)"
        ),
        {"tenant_id": str(tenant_id)},
    )

The third argument to set_config() is true, which makes the setting transaction-local.

You must call this function inside the transaction that performs tenant-scoped queries, after authorization has succeeded.

Important: PostgreSQL RLS is not automatically secure simply because you enable it. The application must manage transaction boundaries and tenant context correctly. Connection pooling, background jobs, and queries executed outside the expected transaction need particular attention.

Also, table owners and roles with special privileges can bypass RLS in certain circumstances. Use a dedicated application database role without unnecessary privileges, and understand the behavior of FORCE ROW LEVEL SECURITY before deploying this pattern.

RLS is a valuable additional protection, but it doesn't replace application-level authorization.

For a multi-tenant SaaS application handling sensitive customer data, using both application-level tenant checks and carefully configured database policies can provide stronger defense in depth.

Step 9: Handle Database Migrations Properly

Your application will change as the product grows.

You might add billing plans, subscription status, invitation tokens, audit logs, or tenant-specific settings. Managing these changes manually becomes difficult once multiple developers and environments are involved.

That's why database migrations matter.

Install Alembic if you haven't already:

pip install alembic

Initialize it:

alembic init migrations

Configure Alembic to use your SQLAlchemy metadata and database settings, then generate an initial migration:

alembic revision --autogenerate -m "create tenant models"

Review the generated migration before applying it:

alembic upgrade head

Autogenerated migrations aren't guaranteed to capture every intended database change correctly, so always inspect them.

For a production SaaS application, run migrations through a controlled deployment process. Avoid having every application worker attempt to run schema migrations when it starts.

If you later switch from shared tables to a separate-schema or separate-database strategy for selected customers, migration management becomes even more important.

Step 10: Think About Performance and Scaling

A shared-table architecture is convenient, but the database needs to be designed for tenant-scoped access from the beginning.

Add the Right Indexes

Suppose your application frequently loads projects belonging to a tenant.

A basic index on tenant_id helps PostgreSQL locate the relevant records:

CREATE INDEX idx_projects_tenant_id
ON projects (tenant_id);

If most queries filter by tenant and sort by project ID, a composite index might be more useful:

CREATE INDEX idx_projects_tenant_id_id
ON projects (tenant_id, id DESC);

Whether this index improves performance depends on the actual query plan and workload. Use EXPLAIN ANALYZE with representative data before adding indexes indiscriminately.

Paginate Large Result Sets

Avoid returning every project in a large organization.

Instead, support pagination:

@router.get("")
def list_projects(
    tenant: Annotated[Tenant, Depends(get_current_tenant)],
    db: Annotated[Session, Depends(get_db)],
    limit: int = 20,
    offset: int = 0,
):
    limit = max(1, min(limit, 100))
    offset = max(0, offset)

    statement = (
        select(Project)
        .where(Project.tenant_id == tenant.id)
        .order_by(Project.id.desc())
        .limit(limit)
        .offset(offset)
    )

    return list(db.scalars(statement).all())

This example uses offset pagination because it's easy to understand and implement.

For tables containing millions of records, cursor-based pagination is often more efficient and provides more predictable results as data changes.

Use Redis Carefully

Redis can help cache frequently requested information, such as tenant settings or feature flags.

However, tenant-specific cache keys must include the tenant identity.

For example:

tenant:101:settings
tenant:102:settings

A cache key such as settings could accidentally return one organization's configuration to another organization.

The same concern applies to cached API responses, background-job results, and distributed locks.

Prevent One Tenant From Consuming All Resources

In a shared environment, a single tenant might generate significantly more traffic than everyone else.

Consider implementing:

  • Rate limits per tenant and per user.

  • Request timeouts.

  • Query and pagination limits.

  • Usage tracking.

  • Background processing for expensive jobs.

  • Monitoring for unusually high traffic.

  • Subscription-based usage limits where appropriate.

These controls help protect the entire service from noisy-neighbor problems.


Step 11: Test Tenant Isolation

Tenant isolation should be treated as a security requirement, not merely a feature.

Imagine two organizations, Acme and Bright. Both have their own projects.

Your tests should confirm that a user from Acme cannot access Bright's projects, even when they know a project ID.

A simplified test using FastAPI's test client might look like this:

def test_tenant_cannot_access_another_tenant_project(
    client,
    acme_token,
    bright_project_id,
):
    response = client.get(
        f"/tenants/1/projects/{bright_project_id}",
        headers={
            "Authorization": f"Bearer {acme_token}",
        },
    )

    assert response.status_code == 404

This example assumes that the fixtures create an Acme user, issue a valid token, and create a project owned by Bright. The IDs must be configured consistently in the test database.

You should also test the following scenarios:

  1. An unauthenticated user cannot access protected endpoints.

  2. A user cannot access a tenant they don't belong to.

  3. A member cannot perform owner-only actions.

  4. A project cannot be created under an arbitrary tenant ID.

  5. A user cannot update or delete another tenant's project.

  6. Tenant-specific cache entries never leak across organizations.

  7. Background jobs cannot accidentally process another tenant's records.

  8. Disabled users and inactive tenants cannot access protected resources.

Test both successful access and denied access.

For stronger assurance, consider property-based tests that generate different combinations of users, tenants, memberships, and resources. The goal is to verify that changing a resource's tenant never grants unauthorized access.

Common Mistakes to Avoid

There are several mistakes that can create problems as your SaaS application grows.

Trusting the tenant ID sent by the client: A tenant ID is a selector, not an authorization mechanism. Verify membership on the server.

Forgetting tenant filters: A query that retrieves records using only a resource ID can expose another organization's data. Include the tenant condition in every tenant-scoped read and write.

Relying only on frontend restrictions: Hiding buttons or organization data in React doesn't secure your API. Authorization must happen on the backend.

Ignoring background jobs: Scheduled tasks, report generation, email delivery, and queue consumers need the same tenant isolation rules as HTTP endpoints.

Using incomplete cache keys: Tenant-specific data must be isolated in Redis and other caching layers.

Giving the application database role excessive privileges: Restrict database permissions and understand how those privileges interact with PostgreSQL RLS.

Making every user an organization administrator: Membership roles should reflect what users actually need to do. Apply least-privilege access by default.

Skipping audit logs: For sensitive actions, record who performed the action, which tenant was affected, what changed, and when it happened. Avoid logging passwords, access tokens, or unnecessary personal information.

Ignoring tenant lifecycle management: Tenant creation, suspension, subscription expiration, data export, and deletion all need defined workflows.

These details might not matter much in a small prototype, but they become increasingly important when paying customers depend on your platform.

Conclusion

Building a multi-tenant SaaS backend with FastAPI and PostgreSQL is not just about adding a tenant_id column to every table. The real challenge is ensuring that authentication, authorization, database queries, caching, background jobs, and operational processes all respect tenant boundaries.

A shared database with tenant-aware tables is a practical starting point for many SaaS products. It keeps infrastructure manageable while allowing the application to serve multiple organizations from one codebase.

As the product grows, you can strengthen isolation with PostgreSQL Row-Level Security, add role-based access control, improve query performance with appropriate indexes, and introduce tenant-specific limits to prevent one customer from affecting everyone else.

My recommendation is to start with a clear tenant model, centralized authorization checks, and automated isolation tests. Get those fundamentals right before adding complex infrastructure.

It's much easier to build these protections into your application from the beginning than to retrofit them after customers are already depending on your service.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘