Multi-Tenant SaaS on Cloudflare D1
Adapting the shared-database multi-tenancy pattern for edge SQLite with Drizzle ORM and SvelteKit.
A few weeks ago, an insightful post on Reddit caught our attention discussing multi-tenant database design for SaaS. The core thesis was simple but profound:
The database design choices you make early on determine everything downstream — RBAC, billing, audit logging, even your test suite… The core decision: shared database with
org_id. Every table that belongs to a tenant gets anorg_idcolumn. Every service call filters by it. No exceptions. And never let users pick theirorg_id— re-derive it from the authenticated session.
Coming from Postgres where Row-Level Security (RLS) is often hailed as the ultimate safety net, we asked ourselves: How does this pattern translate to edge-first serverless architectures running on Cloudflare D1 (SQLite), Drizzle ORM, and SvelteKit?
Here is what we learned, the anti-patterns we had to dismantle, and the elegant architecture we arrived at for isitfun.
1. The Edge Reality: SQLite Has No Native RLS
In Postgres, you can attach ENABLE ROW LEVEL SECURITY and write policies based on current_setting('app.current_org_id').
In Cloudflare D1 (distributed SQLite at the edge), there is no native Row-Level Security. Your application layer and service guards are the security perimeter.
If an endpoint queries WHERE project_id = ? without asserting that the calling user has access to the organization that owns that project, you have an authorization vulnerability.
To implement the Reddit post’s philosophy reliably, we established a strict rule: Zero ad-hoc queries in route handlers. Every access check must flow through a centralized, auditable authorization guard.
The Guard Pattern (auth-guard.ts)
Instead of repeating permissions logic in every endpoint, we built reusable guards that verify ownership and role hierarchy before returning the scoped entity:
// apps/api/src/lib/auth-guard.ts
export type OrgRole = 'owner' | 'admin' | 'member';
const ROLE_HIERARCHY: Record<OrgRole, number> = {
viewer: 10,
member: 20,
editor: 20,
admin: 30,
owner: 40
};
export async function requireOrgAccess(
db: DrizzleClient,
orgId: string,
user: { id: string; role?: string },
minRole: OrgRole = 'member'
): Promise<OrgAccessResult> {
const org = await db
.select()
.from(schema.organizations)
.where(eq(schema.organizations.id, orgId))
.get();
if (!org) {
throw new AuthGuardError(404, 'Organization not found');
}
// Global platform admin override
if (user.role === 'admin') {
return { organization: org, membershipRole: 'owner' };
}
// Tenant membership verification
const membership = await db
.select()
.from(schema.organizationMemberships)
.where(
and(
eq(schema.organizationMemberships.organizationId, orgId),
eq(schema.organizationMemberships.userId, user.id)
)
)
.get();
if (!membership) {
throw new AuthGuardError(403, 'Forbidden: Not a member of this workspace');
}
if (ROLE_HIERARCHY[membership.role] < ROLE_HIERARCHY[minRole]) {
throw new AuthGuardError(403, `Forbidden: Requires ${minRole} privileges`);
}
return { organization: org, membershipRole: membership.role };
} Because these guards throw a strongly-typed AuthGuardError, route handlers stay remarkably lean:
// apps/api/src/routes/billing/billing.ts
billingRouter.post('/checkout/org/:id', async (c) => {
const user = c.get('user')!;
const orgId = c.req.param('id');
const db = createD1Client(c.env.DB);
// One line enforces authentication, existence, and RBAC
await requireOrgAccess(db, orgId, user, 'admin');
// Proceed with Creem checkout session creation...
}); 2. The Trap of Null Organization IDs (and How We Escaped It)
When building multi-tenant apps, the most common architecture trap is the bifurcation between “Personal” and “Team” projects.
Early on, it is tempting to design the schema like this:
- If a project belongs to an individual:
organization_idisNULL, anduser_idpoints to the owner. - If a project belongs to a team:
organization_idis populated.
Why this breaks down
- Query Complexity: Every dashboard query becomes an awkward union or
ORcondition:
WHERE (user_id = ? AND organization_id IS NULL)
OR (organization_id IN (SELECT organization_id FROM memberships WHERE user_id = ?)) - Index Degradation: SQLite query planners struggle with complex
ORclauses across nullable foreign keys. - Downstream Chaos: Features like audit logging, billing tiers, API keys, and storage quotas must constantly check
if (project.organizationId) { ... } else { ... }.
The Solution: First-Class Personal Workspaces
We refactored our schema so that every single tenant is an organization:
// packages/db/src/schema/orgs.ts
export const organizations = sqliteTable(
'organizations',
{
id: text('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
name: text('name').notNull(),
ownerId: text('owner_id').notNull().references(() => user.id, { onDelete: 'cascade' }),
type: text('type').$type<'personal' | 'team'>().notNull().default('team'),
tier: text('tier').$type<'free' | 'pro' | 'team'>().default('free'),
creemSubscriptionId: text('creem_subscription_id'),
createdAt: integer('created_at', { mode: 'timestamp' }).notNull().$defaultFn(() => new Date())
},
(table) => [
index('org_owner_type_idx').on(table.ownerId, table.type)
]
); When a user registers:
- Better Auth provisions the
userrecord. - The system automatically creates a personal organization (
type: 'personal') whereownerId = user.id. - Every project created by the user is tied to an
organization_id.
The Enforced Invariants:
- Personal Workspaces: Members cannot be invited, and the owner cannot “leave” their personal workspace.
if (org.type === 'personal') { return c.json({ error: 'Cannot invite members to a personal workspace.' }, 400); } - Team Workspaces: Support full member invitations, role promotions (
member->admin), Creem per-seat billing, and ownership transfers.
Now, all projects, quotas, and audit logs are 100% uniformly scoped to an organization_id.
3. High-Performance Edge Indexing
On Cloudflare D1, read latency is minimal (usually single-digit milliseconds), but you must optimize your queries to avoid full table scans.
We added targeted composite indexes on our relational tables:
// Organization owner & type lookup (fetch user's personal org instantly)
index('org_owner_type_idx').on(table.ownerId, table.type)
// Organization membership lookup (verify user in org in O(1))
index('org_mem_org_user_idx').on(table.organizationId, table.userId) With Drizzle ORM and D1, queries compile down to prepared statements that execute with zero overhead across Cloudflare’s edge network.
4. Key Takeaways
- Re-derive tenant identity on every request: Never trust client-supplied
org_idwithout validating that the authenticated session holds the required role within that tenant. - Eliminate NULL tenants: Treat personal accounts as single-user organizations (
type: 'personal'). Your database schema, query pipelines, and mental model will become vastly simpler. - Use Guard Helpers over Raw Queries: Encapsulate authorization logic in robust helpers like
requireOrgAccess()andrequireProjectAccess(). They serve as an impenetrable defense in depth, even in SQLite environments lacking database-level RLS.