Guides · App patterns
Multi-tenant B2B SaaS
Model organizations, memberships and invites in one schema without tenant_id columns, and shard the data by organization.
- API
- —
- In the schema
ext::napalm::root,ext::auth::Identity
What you’ll build#
You will build the data model of a B2B SaaS product covering organizations, members and roles, invitations and the workspaces and documents each organization owns. People create an organization, invite teammates, change roles and join through company sign-in. Every access rule lives in the schema so no query has to remember a tenant filter.
Required links toward Organization also preserve tenant row locality, enabling online horizontal scaling and regional residency across shards with zero schema or URL changes. You need a project and a sign-in method. Your first app and Sign-in for your app set up both.
Co-located tenant root trees
Required links toward Organization place memberships, invites, workspaces and documents onto one shard so tenant queries run locally without organization_id columns.
Online shard splits & regional residency
Split busy shards online or pin regulated customer roots into chosen regional shards via napalm placement keep behind one unchanged project URL.
Link organizations, members and roles#
On most databases, tenant isolation means an organization_id column on every table and a policy on each table that joins back to the organization. In Napalm, the links between your types do that work. A rule on a document reads .workspace.org.members. The same chain of links tells Napalm each row’s organization.
| Type | Belongs to | Description |
|---|---|---|
BillingPlan | Every shard | DescriptionThe plans on offer (starter, pro, enterprise). Every organization links to this small table, so Napalm copies it to each shard. |
Organization | Itself | DescriptionThe tenant. Every type below belongs to one organization. |
Membership | The organization | DescriptionOne person in one organization, as an Owner, an Admin or a Member. |
Invite | The organization | DescriptionAn address invited in a role. Valid for a week. |
Workspace | The organization | DescriptionA team’s space, read by members and managed by owners and admins. |
Document | The workspace’s organization | DescriptionWritten by members. A document can also be shared with a partner organization or with individual guests without moving. |
Write the whole schema#
using extension auth;using extension napalm;using future simple_scoping; module default { global caller := global ext::auth::ClientTokenIdentity; # The addresses the caller has confirmed, for the rules that go by address. global caller_emails := str_lower(( select ext::auth::EmailFactor filter .identity ?= global caller and exists .verified_at ).email); scalar type Role extending enum<Owner, Admin, Member>; type BillingPlan { annotation ext::napalm::root := 'reference'; required slug: str { constraint exclusive; }; required seat_limit: int32; access policy anyone_can_read allow select; } type Organization { required name: str; required slug: str { constraint exclusive; }; required plan: BillingPlan; # The issuer of the company's own sign-in, when it has one: whoever signs in through it may join. sso_issuer: str; multi members := .<org[is Membership]; multi invites := .<org[is Invite]; access policy member_can_read allow select using ((global caller in .members.identity) ?? false); access policy invited_can_read allow select using (exists ( select .invites filter .email in global caller_emails and .expires > datetime_of_statement() )); access policy company_sign_in_can_read allow select using (((global caller).issuer ?= .sso_issuer) ?? false); access policy signed_in_can_create allow insert using (exists global caller); access policy owner_can_manage allow update, delete using (exists ( select .members filter .identity ?= global caller and .role = Role.Owner )); } type Membership { required org: Organization { readonly := true; on target delete delete source; }; # Not required: a caller reads their own identity alone, so a coworker's reads as empty. identity: ext::auth::Identity; required role: Role { default := Role.Member; }; constraint exclusive on ((.org, .identity)); access policy coworker_can_read allow select using ((global caller in .org.members.identity) ?? false); access policy admin_can_manage allow insert, update, delete using (exists ( select .org.members filter .identity ?= global caller and .role in {Role.Owner, Role.Admin} )); # Whoever creates an organization is its first member, and its owner. access policy founder_can_join allow insert using ( .identity ?= global caller and .role = Role.Owner and not exists (select .org.members filter .id != __subject__.id) ); # Someone invited may add themselves, in the role the invite names and no other. access policy invited_can_join allow insert using ( .identity ?= global caller and exists ( select .org.invites filter .role = __subject__.role and .email in global caller_emails and .expires > datetime_of_statement() ) ); # So may someone signed in through the company's own sign-in, as a member. access policy company_sign_in_can_join allow insert using ( .identity ?= global caller and .role = Role.Member and (((global caller).issuer ?= .org.sso_issuer) ?? false) ); access policy member_can_leave allow delete using (.identity ?= global caller); } type Invite { required org: Organization { readonly := true; on target delete delete source; }; required email: str; required role: Role { default := Role.Member; }; required expires: datetime { default := datetime_of_statement() + <duration>'168 hours'; }; access policy admin_has_full_access allow all using (exists ( select .org.members filter .identity ?= global caller and .role in {Role.Owner, Role.Admin} )); access policy invited_can_read_and_use allow select, delete using (.email in global caller_emails); } type Workspace { required org: Organization { readonly := true; on target delete delete source; }; required name: str; access policy member_can_read allow select using ((global caller in .org.members.identity) ?? false); access policy admin_can_write allow insert, update, delete using (exists ( select .org.members filter .identity ?= global caller and .role in {Role.Owner, Role.Admin} )); } type Document { required workspace: Workspace { readonly := true; on target delete delete source; }; required author: Membership { annotation ext::napalm::root := 'none'; }; partner_org: Organization { annotation ext::napalm::root := 'none'; }; multi guest_viewers: ext::auth::Identity; required title: str; body: str { default := ''; }; access policy member_or_guest_can_read allow select using ( ((global caller in .workspace.org.members.identity) ?? false) or ((global caller in .partner_org.members.identity) ?? false) or ((global caller in .guest_viewers) ?? false) ); access policy member_can_create_and_edit allow insert, update using ( .workspace.org = .author.org and ((global caller in .workspace.org.members.identity) ?? false) ); access policy author_or_admin_can_delete allow delete using ( .author.identity ?= global caller or exists ( select .workspace.org.members filter .identity ?= global caller and .role in {Role.Owner, Role.Admin} ) ); }}Create an organization#
A new organization starts with zero members, so no admin exists yet to add the founder. The founder_can_join rule covers bootstrap creation by letting the caller insert an Owner membership when the organization has no existing members. Inserting the organization and initial membership in one atomic statement guarantees every organization starts with an owner.
with org := (insert Organization { name := <str>$name, slug := <str>$slug, plan := assert_single((select BillingPlan filter .slug = 'pro')), }), founder := (insert Membership { org := org, identity := assert_exists(global caller), role := Role.Owner, }),select org { id, slug }Invite and accept members#
An owner or an admin invites an address in a role. The email is a job queued in the same statement, so the email goes out if and only if the invite commits.
# No invite without its email queued, and no email for an invite that didn't commit.with invite := ( insert Invite { org := (select Organization filter .id = <uuid>$org), email := str_lower(<str>$email), role := <Role>$role, } ), email := ( insert ext::napalm::Job { query := 'sendInviteEmail', variables := <json>(invite := <str>invite.id), } ),select invite { id, email, role, expires }sendInviteEmail is an action. This query selects the email’s data, and your handler sends the email with a link to your app’s join page. Actions & background jobs has a complete handler.
# Selects invite fields for the email action, running under the sender's session.select Invite { id, email, role, org: { name } }filter .id = <uuid>$inviteBefore accepting, the invited person is not yet a member. Three rules admit the person by confirmed addresses (global caller_emails) so the invitee can view the invite, see the organization name and join with only the offered role.
# Accept a pending organization invite that has not expiredwith invite := assert_single(( select Invite filter .id = <uuid>$invite and .expires > datetime_of_statement() )), member := ( insert Membership { org := invite.org, identity := assert_exists(global caller), role := invite.role, } ), cleaned := (delete invite),select member { id, role, org: { id, name, slug },}Change roles and remove members#
Schema rules allow owners and admins to manage memberships and allow any member to leave an organization. The two deployed queries add the single cross-row invariant a per-row policy cannot express alone, ensuring an organization always keeps at least one owner.
# The last owner is left out by the filter, so demoting them changes nothing and answers no rows.update Membershipfilter .id = <uuid>$member and (.role != Role.Owner or count((select .org.members filter .role = Role.Owner)) > 1)set { role := <Role>$role }delete Membershipfilter .id = <uuid>$member and (.role != Role.Owner or count((select .org.members filter .role = Role.Owner)) > 1)Both queries return no rows when nothing changed. The app shows that result as “an organization needs an owner”. Run the project with napalm endpoint --passthrough keys, so a session can change a membership only through these deployed queries.
Track the current organization#
A person can belong to several organizations, so the app tracks the current organization. List the person’s organizations, keep the choice on the device and pass the choice to each query as a variable.
select Organization { id, name, slug, my_role := assert_single((select .members filter .identity ?= global caller)).role,}order by .name// src/useOrganization.tsimport { useState } from 'react'import { useMyOrganizations } from './generated/hooks' /** The organization the app is showing: the one last picked on this device, or the first. */export function useOrganization() { // Live, so an organization joined or left in another tab shows up here. const { rows } = useMyOrganizations() const [picked, setPicked] = useState(() => localStorage.getItem('organization')) const current = rows?.find((organization) => organization.id === picked) ?? rows?.[0] const pick = (id: string) => { localStorage.setItem('organization', id) setPicked(id) } return { organizations: rows, current, pick }}A query taking $org cannot read into another organization because the parameter only narrows rows already permitted by your access rules.
Add company sign-in#
When a customer wants employees to sign in through the company’s identity provider, add that provider to the project. The customer’s organization then names the provider’s issuer.
Each provider added to the main branch is an SSO connection. A connection costs $30 a month, charged by the day. The people who sign in through a connection are never counted.
# The company's identity provider, as one more way in to the projectnapalm sign-in provider acme-app oidc --slug acme \ --issuer-url https://login.acme.example --display-name "Acme" --client-id <client-id>Every identity records the sign-in issuer. With sso_issuer set on the organization, two rules let anyone from that issuer see the organization and join as a member without an invite.
# Allowed only for someone signed in through the issuer the organization names.insert Membership { org := (select Organization filter .slug = <str>$slug), identity := assert_exists(global caller),}unless conflict on (.org, .identity)Set sso_issuer to the provider’s issuer URL. Because sso_issuer is a property on Organization, only an owner can update it.
Avoid common rule mistakes#
- Rules return one bool
- An
access policy … using (…)must evaluate to exactly onebool. Compare a single link with?=. Wrap a test against a multi link in?? false, as in((global caller in .members.identity) ?? false). A signed-out caller then getsfalseinstead of an empty set. - Rules ignore other types’ rules
- Inside a rule, a link or subquery reads every row of the referenced type, including rows hidden from the caller. An invited person’s rule can therefore read invites, and a membership rule can inspect memberships without recursion.
- Rules read existing rows
- An
insertrule does not see sibling rows inserted in the same statement. Bootstrap creation therefore usesfounder_can_joinbecause no admin row exists yet. - Links can be forged
- A document’s author is a membership, and a person in two organizations has two memberships.
member_can_create_and_editchecks.workspace.org = .author.org. Without that check, a person could write into one organization with the membership from the other. - Sharing keeps placement
- A document can name a
partner_orgor individualguest_viewers, and the document’s read rule admits those viewers without moving the row. Both links carryext::napalm::root := 'none', keeping the document on the workspace organization’s shard.
Keep each organization’s rows together#
Roots in Napalm are places, not walls. Four schema clauses co-locate every organization’s memberships, invites, workspaces, documents and audit records on one shard without organization_id columns on nested tables.
Compiler-inferred placement root
Required single links toward Organization crown the tenant as a placement root so memberships, invites, workspaces and documents co-locate on one shard with clean UUID keys.
readonly := true- A membership, an invite, a workspace and a document each declare a required link toward
Organization, makingOrganizationa placeable root.readonlyfixes that link at insert time so rows never move between organizations and engines cache ID-to-root lookups permanently. on target delete delete source- Deleting an organization deletes every dependent row underneath that organization and marks the link as the cascading container in compiler tie-breaking.
ext::napalm::root := 'owner' | 'none'- Settles ownership when a type declares two or more
required singlelinks to project types, such asDocument(workspaceandauthor) or anAuditEvent(organdactor). ext::napalm::root := 'reference'- Replicates
BillingPlanacross every shard in one atomic commit so plan joins and seat-limit checks execute locally on each organization’s shard.
Disambiguating dual links to organizations, members and identities#
Multi-tenant records frequently point to both a tenant container and the user or member who acted. Extension types such as ext::auth::Identity never compete as project roots and replicate automatically when read by single-root policies, so Membership.identity needs no annotation. When a type links to two project types, such as an AuditEvent recording org: Organization, actor: Membership and identity: ext::auth::Identity, annotate org as 'owner' and actor as 'none'. Enforce .org = .actor.org in the insert policy so a member of two organizations cannot forge an actor link from the other organization.
type AuditEvent { required org: Organization { annotation ext::napalm::root := 'owner'; readonly := true; on target delete delete source; }; required actor: Membership { annotation ext::napalm::root := 'none'; readonly := true; }; # Not required: a caller reads their own identity alone, so another member's reads as empty. identity: ext::auth::Identity { readonly := true; }; required action: str; required created_at: datetime { default := datetime_of_statement(); readonly := true; }; access policy admin_can_read allow select using (exists ( select .org.members filter .identity ?= global caller and .role in {Role.Owner, Role.Admin} )); access policy actor_can_record allow insert using ( .org = .actor.org and .identity ?= global caller and .actor.identity ?= global caller );}Verify single-shard query plans before launch#
Before enabling horizontal placement, run napalm roots acme-app to inspect every deployed query’s inferred routing class and verify that customer-facing mutations stay strictly single-shard.
| Deployed query | Routing class in napalm roots | Shard execution behavior |
|---|---|---|
createOrganization | a new root (Organization) | Shard execution behaviorInserts the organization and founding Owner membership atomically on one bucket-owning shard. |
inviteMember | one root ($org) | Shard execution behaviorFilters Organization by .id = <uuid>$org, inserting the Invite and queueing the email Job on that organization’s shard. |
acceptInvite | one root ($invite’s root) | Shard execution behaviorResolves $invite to the owning Organization shard and runs the Membership insert and Invite delete in one local transaction. |
changeRole, removeMember | one root ($member’s root) | Shard execution behaviorResolves $member to the owning Organization shard so the last-owner count(.org.members) check and write execute locally. |
myOrganizations | reads across roots | Shard execution behaviorLists every organization holding a membership for the signed-in user, answered from a consolidated core copy once roots spread. |
joinOrganization | writes across roots when filtered by .slug | Shard execution behaviorFiltering Organization by .slug = <str>$slug inside an insert leaves the target shard unpinned once roots spread. Resolve the organization id on a read first and pass <uuid>$org so the write pins to one root. |
Split, move and restore by organization#
A project starts on one shard. When write volume or storage outgrows a single primary, enable placement, attach a core copy for cross-organization reads and split or move organizations across shards behind the same project URL while live traffic continues.
Consolidated core-copy sync
Data shards keep single-organization writes local while streaming committed rows to a read-only core copy for cross-tenant rollups.
Hot-tenant shard override
napalm placement move --root lifts a high-volume enterprise organization onto a dedicated shard online behind the same URL.
Per-root point-in-time recovery
napalm placement restore-root rewinds one customer organization to a past timestamp while neighboring tenants continue reading and writing.
# 1. Inspect inferred roots and verify each deployed query's shard routingnapalm roots acme-appnapalm schema push acme-app --plan # 2. Record each row's root and add a consolidated core copy for cross-org readsnapalm placement enable acme-app --waitnapalm core-copies add acme-app --wait # 3. Split load onto a second shard while live traffic continuesnapalm placement split acme-app --shard shard-0a1b2c3d4e --wait # 4. Isolate one large enterprise organization or pin an organization to Frankfurtnapalm placement move acme-app --root 0192c3f4-6b1a-7d8e-9f00-1a2b3c4d5e6f --shard shard-k3m9x2p7qa --waitnapalm placement keep acme-app 0192c3f4-6b1a-7d8e-9f00-1a2b3c4d5e6f --region fra --wait # 5. Rewind one organization to a past timestamp without touching other tenantsnapalm placement restore-root acme-app 0192c3f4-6b1a-7d8e-9f00-1a2b3c4d5e6f --to 2026-11-10T17:20:00Z --waitCross-organization billing and admin rollups on a core copy#
Customer sessions pass the active $org UUID from useOrganization, so workspace and document reads and writes route straight to one customer shard (primary for writes, causal replicas via Napalm-Bookmark for reads). Internal billing syncs, seat-overage audits and support dashboards need to query across every tenant without fanning out across customer primaries.
Provisioning a consolidated core copy (napalm core-copies add acme-app) streams committed rows from every data shard onto a dedicated read-only shard. Because Organization and Membership grant select only to members by default, add an explicit service-read policy (such as global role: str with access policy service_rollup allow select using (global role ?= 'service') bound through endpoint serviceGlobals), deploy the rollup query and call it with a --read-only service key.
# Aggregates every organization across shards on the consolidated core copy.select BillingPlan { slug, seat_limit, org_count := count(.<plan[is Organization]), total_seats := count(.<plan[is Organization].members), over_limit_orgs := ( select .<plan[is Organization] { id, slug, seats := count(.members), } filter count(.members) > __source__.seat_limit order by .slug ),}order by .slug# Issue a read-only service key for internal billing and admin jobsnapalm keys create acme-app --label billing-rollup --read-only --days 90 # Hide the cross-tenant rollup from user-facing CLI and MCP tool listsnapalm queries offer acme-app billingRollup --no-cli --no-agentsService keys for one organization’s servers#
When a customer’s backend integrates with your app over an API key, issue a scoped Napalm service key instead of maintaining a custom key table. Bind a schema global to the customer’s organization so your access rules filter rows automatically, pass --allow-query to restrict calls to the integration’s deployed queries and set --call-budget to cap daily requests (for example, 5,000 calls per day, returning 429 call_budget_reached once exhausted until 00:00 UTC).
# A global for the organization a service key belongs toglobal key_org: str; # In type Document, beside the other rulesaccess policy org_key_can_read allow select using (<str>.workspace.org.id ?= global key_org);# A key for one customer's servers: Globex's documents, through two deployed queries, 5,000 calls a daynapalm keys create acme-app --label globex-integration --read-only --days 90 \ --global default::key_org=<organization id> \ --allow-query listDocuments --allow-query getDocument \ --call-budget 5000/day # Count what the key reaches before you hand the key overnapalm keys reach acme-app <key-id>Each service key also inherits the branch’s serviceGlobals, so policies that check a service global still apply. Run napalm keys reach before sharing the credential to verify every readable type. To change the bound organization, allowed queries or daily budget later, issue a replacement key and revoke the previous credential.
Agents for one organization#
A user who belongs to several organizations can scope an agent connection to a single organization. Your consent page reads the allowed grant globals from GET / under the user’s session, prompts the user to pick an organization and passes that choice on the grant, where the value stays fixed for the life of the grant.
Because the user supplies that global value directly at consent time, Napalm does not verify membership in the named organization on its own. User-supplied grant globals must therefore only narrow access and never widen it. Pairing member_can_read with the deny policy below ensures the user can still read only permitted memberships while confining the agent to the chosen organization. Attach the same deny policy to every tenant-scoped type.
# The organization a person picked at consent for the agentglobal current_org: str; # In type Workspace, beside member_can_readaccess policy chosen_org deny all using ((<str>.org.id != global current_org) ?? false);# Let a person set current_org when the person lets an agent innapalm endpoint acme-app --grant-global default::current_org// On your consent page: the person picked the agent's organization from useOrganization.const answer = await fetch('https://acme.napalmdata.com/sign-in/agents/allow', { method: 'POST', headers: { Authorization: `Bearer ${session}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ request, isReadOnly: false, days: 30, globals: { 'default::current_org': organization.id }, }),})location.href = (await answer.json()).redirectToNever expose key_org as a user-settable grant global because org_key_can_read above is an allow policy that trusts key_org directly, which is safe only when org managers control the global. Grants held to one tenant shows how to audit rows exposed by a global on its own, and Test an agent’s grant exercises the deny policy with current_org set. Once a user connects an agent, napalm grants reach counts the rows reachable under that grant.
Check organizations and roles#
Create an organization as one person
createOrganizationreturns the new organization, andmyOrganizationslists the organization with the roleOwner. For anyone else, the list is empty.Invite a second person and accept as that person
Before accepting, the second person can see the organization’s name and nothing else. After accepting, the person is listed in the invite’s role. An attempt to join as an
Owneron anAdmininvite is refused.Try to remove the last owner
changeRoleandremoveMemberon the only owner return no rows. Make the second person an owner, and the same calls succeed.Check each person’s reach
napalm people reachcounts the rows one person can read and change, type by type.napalm explain-accessnames the rule that granted access to a given row.Verify root lineage and single-shard query routing
napalm rootsconfirmsOrganizationas a placeable root,BillingPlanasreferenceand every$org-scoped workspace or membership query asone rootbefore you enable placement.
Next#
Billing & payments puts these organizations on paid plans with seat limits and prepaid credits. Realtime & collaboration keeps a workspace’s lists live between members. Environments & going live lists the settings to lock down before customers arrive.