django-boundary

Scalable row-level multi-tenancy for Django with PostgreSQL Row Level Security.
Who Is This For?
django-boundary is for Django projects that serve multiple tenants from a
single database. If your users belong to organisations, workspaces, teams,
schools, clinics, clubs, or any other entity that should only see its own
data, boundary handles the isolation.
Common use cases
SaaS platforms: Each customer (organisation, workspace, account) is a
tenant. Their data is isolated at the ORM and database level. New tenants are
provisioned via management command; no schema migrations required.
Marketplace platforms: Sellers, venues, or merchants each have their own
tenant. Products, orders, and analytics are scoped per-tenant. Platform-wide
reporting uses the unscoped manager.
Education / healthcare / government: Schools, clinics, or departments are
tenants. Data residency requirements are met via regional routing (e.g. UK data
stays in UK database, EU data in EU database).
Agency or white-label products: Each client gets their own tenant, resolved
by subdomain (client-a.app.com) or JWT claim from the auth provider.
Internal tools: Departments or business units are tenants, resolved via
session or header. STRICT_MODE catches accidental cross-department data
exposure during development.
What boundary does not do
- Authentication, session management or login. That is your own auth
stack. boundary's resolvers read an already-authenticated request; they
never authenticate one.
- Membership, RBAC or authorisation. Resolving a tenant is not
authorising a caller against it. Your project, or
icv-tenants for ICV
ecosystem consumers, owns that check.
- Providing the tenant domain model itself. You define your own tenant
model and point
BOUNDARY_TENANT_MODEL at it, or use the bundled
AbstractTenant convenience base.
- Non-PostgreSQL Row Level Security. The ORM filtering layer works on
any Django-supported database, but RLS enforcement requires PostgreSQL
14+, with no database-level backstop elsewhere. The RLS migration
operations are a logged no-op there rather than an error, so the same
migration files run on a SQLite development database.
- Cross-region data migration. Moving a tenant's data from one regional
database to another is your own operational tooling.
- Frontend, API or Django admin components. You wire your own admin and
views to use the
unscoped manager or tenant-filtered querysets.
When NOT to use boundary
- Single-tenant apps: no need for isolation machinery.
- Schema-per-tenant: use django-tenants instead (different trade-offs at scale).
Features
- Automatic ORM filtering: queries are scoped to the active tenant by default
- PostgreSQL RLS: database-level enforcement as a second layer of defence
- Async-native: context propagation via
contextvars, works with sync and async Django
- Pluggable resolvers: subdomain, header, JWT claim, session, or custom
- Strict mode: raises on unscoped queries (default: on), catches data leaks at development time
- Regional routing: route queries to geographically distinct databases for data residency compliance
- Celery integration: tenant context propagated via task headers, restored on workers
- Management commands: provision, deprovision (with NDJSON export), scoped run, run-all with parallelism
- Test utilities:
set_tenant(), TenantTestMixin, tenant_factory()
- System checks: validates configuration at startup
- Optional LEAKPROOF RLS functions: opt-in planner optimisation (off by default so RLS migrations run on managed Postgres)
- Zero assumptions: no opinion on auth, URL structure, or domain model
Installation
pip install django-boundary
Add to INSTALLED_APPS:
INSTALLED_APPS = [
...
"boundary",
...
]
Quick Start
1. Define your tenant model
# tenants/models.py
from boundary.models import AbstractTenant
class Organisation(AbstractTenant):
# Inherits: name, slug, region, is_active, created_at, updated_at
plan = models.CharField(max_length=50, default="free")
2. Configure settings
# settings.py
BOUNDARY_TENANT_MODEL = "tenants.Organisation"
BOUNDARY_STRICT_MODE = True # default: raises on unscoped queries
# Resolver chain: first match wins.
# For public-facing apps, SubdomainResolver should be first.
BOUNDARY_RESOLVERS = [
"boundary.resolvers.SubdomainResolver",
]
3. Add middleware
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"boundary.middleware.TenantMiddleware", # before session/auth
"django.contrib.sessions.middleware.SessionMiddleware",
...
]
4. Make models tenant-scoped
# bookings/models.py
from boundary.models import TenantModel
class Booking(TenantModel):
court = models.IntegerField()
start_time = models.DateTimeField()
Booking.objects.all() now automatically filters by the active tenant.
Creating a booking auto-populates the tenant field from context. That is
the ORM layer. Add the database layer before you ship.
5. Turn on Row Level Security (PostgreSQL)
Write the migration by hand, in the app owning the model
(python manage.py makemigrations bookings --empty --name rls):
from boundary.migrations_ops import CreateTenantPolicy, EnableRLS
operations = [
EnableRLS("Booking"),
CreateTenantPolicy("Booking"),
]
Apply it, then confirm python manage.py check reports neither
boundary.E006 nor boundary.W003. Connect as a NOSUPERUSER NOBYPASSRLS
role: superusers and BYPASSRLS roles are exempt from every policy, so the
layer exists but enforces nothing for them.
The same migration runs on SQLite. EnableRLS, CreateTenantPolicy and
DropTenantPolicy apply on PostgreSQL and are a logged no-op on any other
backend: one logger.info line each on the boundary.migrations logger
naming the operation, the model, the alias and the vendor, then no DDL and no
error. So you write this migration once and run it unchanged against a SQLite
development database and a PostgreSQL production one, with no backend
conditional and no router. Your model keeps its ORM-layer tenant filtering on
SQLite; it is the RLS layer, and only that, which is absent there.
AdoptTenantApp is the one operation that still refuses off PostgreSQL,
because an adopted table has no ORM layer beneath the policy and would be
left with no isolation at all rather than reduced isolation. See
Add RLS policies with migrations
for the migrating-role caveats and verification.
Example Configurations
SaaS with subdomain routing
Each customer gets a subdomain: acme.app.com, globex.app.com.
# models.py
class Workspace(AbstractTenant):
plan = models.CharField(max_length=20, default="starter")
max_users = models.IntegerField(default=5)
class Project(TenantModel):
name = models.CharField(max_length=200)
class Task(TenantModel):
project = models.ForeignKey(Project, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
completed = models.BooleanField(default=False)
# settings.py
BOUNDARY_TENANT_MODEL = "core.Workspace"
BOUNDARY_RESOLVERS = ["boundary.resolvers.SubdomainResolver"]
# In a view: no tenant filtering needed, it's automatic
def dashboard(request):
projects = Project.objects.all() # only this workspace's projects
tasks = Task.objects.filter(completed=False) # only this workspace's tasks
return render(request, "dashboard.html", {"projects": projects, "tasks": tasks})
API with JWT-based tenancy
A React/mobile frontend sends a JWT containing the tenant ID. Useful for
single-page apps where subdomains aren't practical.
# settings.py
BOUNDARY_TENANT_MODEL = "accounts.Account"
BOUNDARY_RESOLVERS = [
"boundary.resolvers.JWTClaimResolver", # reads tenant_id from JWT
]
BOUNDARY_JWT_CLAIM = "org_id" # custom claim name
The JWT is validated by your auth middleware (DRF, django-allauth, etc.).
Boundary only reads the claim; it never validates signatures.
Marketplace with seller isolation
Sellers manage their own products, orders, and inventory. Platform admins
see everything via the unscoped manager.
class Seller(AbstractTenant):
contact_email = models.EmailField()
stripe_account_id = models.CharField(max_length=100, blank=True)
class Product(TenantModel):
name = models.CharField(max_length=200)
price = models.DecimalField(max_digits=10, decimal_places=2)
class Order(TenantModel):
product = models.ForeignKey(Product, on_delete=models.PROTECT)
quantity = models.IntegerField()
# settings.py
BOUNDARY_TENANT_MODEL = "sellers.Seller"
BOUNDARY_RESOLVERS = [
"boundary.resolvers.HeaderResolver", # internal API, trusted clients
]
# Seller's view: only sees their own products
def my_products(request):
return Product.objects.all()
# Admin analytics: sees all sellers
def platform_revenue():
return Order.unscoped.aggregate(total=Sum("product__price"))
Multi-region with data residency
UK customer data must stay in the UK database; EU data in the EU database.
# settings.py
BOUNDARY_TENANT_MODEL = "orgs.Organisation"
BOUNDARY_REGIONS = {
"uk": {"ENGINE": "django.db.backends.postgresql", "HOST": "uk.db.example.com", ...},
"eu-west": {"ENGINE": "django.db.backends.postgresql", "HOST": "eu.db.example.com", ...},
"us-east": {"ENGINE": "django.db.backends.postgresql", "HOST": "us.db.example.com", ...},
}
DATABASE_ROUTERS = ["boundary.routing.RegionalRouter"]
# Tenant has region="uk": all queries automatically hit the UK database
with TenantContext.using(uk_tenant):
Patient.objects.create(name="Smith", nhs_number="123") # stored in UK DB
# Platform-wide reporting across all regions
from boundary.routing import all_regions
with all_regions() as aliases:
for alias in aliases:
count = Patient.objects.using(alias).count()
print(f"{alias}: {count} patients")
Internal tool with session-based switching
Staff users switch between departments via a dropdown. The selected
department is stored in the session.
# settings.py
BOUNDARY_TENANT_MODEL = "departments.Department"
BOUNDARY_REQUIRED = False # allow unauthenticated pages
BOUNDARY_RESOLVERS = [
"boundary.resolvers.SessionResolver",
]
# Switch department view
def switch_department(request, dept_id):
dept = Department.objects.get(pk=dept_id)
request.session["boundary_tenant_id"] = str(dept.pk)
return redirect("dashboard")
How It Works
Architecture
HTTP Request / Celery Task / Management Command
|
v
RESOLUTION LAYER: TenantMiddleware + pluggable Resolvers
|
v
CONTEXT LAYER: TenantContext (ContextVar + DB session variable)
|
v
ORM LAYER: TenantManager auto-filters every queryset
|
v
ROUTING LAYER (optional): RegionalRouter per-tenant DB alias
|
v
DATABASE LAYER: PostgreSQL RLS policies (defence in depth)
Every layer below RESOLUTION LAYER faithfully enforces isolation for
whichever tenant was resolved. None of them ask whether the caller is
allowed to act as that tenant: that is what RESOLUTION LAYER decides, and
for a client-controlled resolver (HeaderResolver, JWTClaimResolver) it
decides purely from what the client sent. boundary's isolation guarantee is
"every layer scopes to the resolved tenant correctly", not "the resolved
tenant is the one this caller is allowed to see". Closing that second gap
(authenticating the caller, then checking their membership of the resolved
tenant) is the consumer's responsibility; see
Resolvers and
Enforce membership after resolution.
Defence in Depth
Two independent layers enforce tenant isolation:
- ORM layer:
TenantManager filters every queryset by the active tenant.
This catches standard Django ORM usage.
- PostgreSQL RLS: Row Level Security policies enforce isolation at the
database level, catching raw SQL, third-party packages, and ORM bugs.
A bug in one layer is caught by the other. This RLS layer only exists for
models with their own tenant column (TenantMixin / make_tenant_mixin).
Relation-scoped (path-scoped) models built with make_tenant_path_mixin are
protected at the ORM layer only: see
Scope a model through a relation
for the exact contract before relying on RLS to catch direct SQL against one.
Models
AbstractTenant
Convenience base for your tenant model. Provides common fields:
| Field |
Type |
Description |
name |
CharField(200) |
Tenant name |
slug |
SlugField(unique) |
URL-safe identifier |
region |
CharField(50) |
Regional routing key (blank if single-region) |
is_active |
BooleanField |
Inactive tenants are rejected by middleware (403) |
created_at |
DateTimeField |
Auto-set on creation |
updated_at |
DateTimeField |
Auto-set on save |
TenantModel / TenantMixin
Base class for tenant-scoped data models. Adds:
tenant ForeignKey to your tenant model (CASCADE, non-nullable)
objects: TenantManager that auto-filters by active tenant
unscoped: plain Manager for cross-tenant operations (admin, analytics)
class Booking(TenantModel):
court = models.IntegerField()
Auto-populate on save: When no tenant is set explicitly,
TenantModel.save() reads from TenantContext automatically.
Bulk operations:
bulk_create(): auto-populates tenant on objects where tenant_id is None
bulk_update(): validates all objects belong to the active tenant
Custom FK Field Names: make_tenant_mixin()
If your domain uses a different name for the tenant relationship (e.g.
merchant, organisation, workspace), use the factory instead of
TenantMixin:
from boundary.models import make_tenant_mixin
MerchantMixin = make_tenant_mixin("merchant")
class Product(MerchantMixin):
sku = models.CharField(max_length=50)
# Product.merchant is the FK: auto-filtering, auto-populate, bulk ops all work
# Product.objects.all() : filters by active tenant via the "merchant" field
# product.merchant : returns the tenant instance
The factory accepts the same FK options as Django's ForeignKey:
make_tenant_mixin(
"merchant",
on_delete=models.PROTECT, # default: CASCADE
related_name="products", # default: "%(app_label)s_%(class)s_set"
db_index=True, # default: True
null=False, # default: False
)