Skip to the page

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
—

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 keep each tenant’s rows together on one shard, so you can split load online and pin regional residency without changing your schema or project URL. You need a project and a sign-in method. Your first app and Sign-in for your app set up both.

Grouped organization rows

Required links keep an organization and its child rows on one shard.

Online splits and residency

Split busy shards online or pin organizations to regions behind one 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.

TypeBelongs toDescription
BillingPlanEvery shardDescriptionSubscription tiers (starter, pro, enterprise). Every organization links to this small table, so Napalm replicates it across shards.
OrganizationPlacement rootDescriptionTop-level tenant record that owns every membership, invite, workspace and document below.
MembershipOrganizationDescriptionLinks one identity to one organization with role Owner, Admin or Member.
InviteOrganizationDescriptionPending email invitation for a specific role, valid for seven days.
WorkspaceOrganizationDescriptionTeam container readable by members and managed by owners and admins.
DocumentWorkspace organizationDescriptionAuthored by members and optionally shared with partner organizations or guests without moving shards.

Write the whole schema#

dbschema/default.gel
using extension auth;using extension napalm;using future simple_scoping; module default {  global caller := global ext::auth::ClientTokenIdentity;   # Verified email addresses owned by the current caller, used by invite policies.  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;    # Optional OIDC issuer URL allowing verified SSO users to read and join the organization.    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;    };    # Optional so coworkers can read Membership rows without reading each other's Identity.    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}      ));    # Allow the creator of a new organization to insert the initial Owner membership.    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)      );    # Allow an invited user with a matching verified email to join with the invited role.    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()        )      );    # Allow a user authenticated through the organization's OIDC issuer to join as 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.

dbschema/queries/createOrganization.edgeql
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#

Owners and admins invite teammates by email for a chosen role. Queueing the email job inside the same statement ensures the invitation email sends if and only if the invite row commits.

dbschema/queries/inviteMember.edgeql
# Insert the invite and enqueue its delivery email in one atomic transaction.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. The gatekeeper query below selects the invite fields, and your handler delivers the email with a link to your app’s join page. Actions & background jobs shows a complete handler.

dbschema/queries/sendInviteEmail.edgeql
# Select invite fields for the email action under the sender's session.select Invite { id, email, role, org: { name } }filter .id = <uuid>$invite

Before 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.

dbschema/queries/acceptInvite.edgeql
# 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 enforce the one cross-row invariant a per-row policy cannot express alone: every organization keeps at least one owner.

dbschema/queries/changeRole.edgeql
# Skip the update when the target member is the organization's only Owner.update Membershipfilter .id = <uuid>$member  and (.role != Role.Owner or count((select .org.members filter .role = Role.Owner)) > 1)set { role := <Role>$role }
dbschema/queries/removeMember.edgeql
delete Membershipfilter .id = <uuid>$member  and (.role != Role.Owner or count((select .org.members filter .role = Role.Owner)) > 1)

Both queries return zero rows when the target is the sole remaining owner, so the UI can explain that every organization needs at least one owner. Enable napalm endpoint --passthrough keys so sessions can modify memberships only through these deployed queries.

Track the current organization#

Users can belong to multiple organizations, so the client tracks the active selection locally and passes $org as a query variable.

dbschema/queries/myOrganizations.edgeql
select Organization {  id,  name,  slug,  my_role := assert_single((select .members filter .identity ?= global caller)).role,}order by .name
src/useOrganization.ts
// src/useOrganization.tsimport { useState } from 'react'import { useMyOrganizations } from './generated/hooks' /** Tracks the active organization across reloads and updates live when memberships change. */export function useOrganization() {  // Subscribes live so joining or leaving an organization in another tab updates immediately.  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#

Enterprise customers often sign in through an external OpenID Connect identity provider such as Okta or Microsoft Entra. Register the customer’s provider on the project and store its issuer URL on the customer’s Organization row.

Each OIDC provider on the main branch bills as an SSO connection at $30 per month, prorated daily and free of per-seat active-user fees.

Terminal
# Register the customer's OpenID Connect identity provider on 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.

dbschema/queries/joinOrganization.edgeql
# Insert a Member row when global caller matches the organization's sso_issuer.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 one bool. 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 gets false instead 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 insert rule does not see sibling rows inserted in the same statement. Bootstrap creation therefore uses founder_can_join because 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_edit checks .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 link to a partner_org or guest_viewers, and its read policy admits those viewers without moving the row. Marking both links ext::napalm::root := 'none' keeps the document on the workspace organization’s shard.

Keep each organization’s rows together#

Napalm infers placement roots automatically from required single links for any top-level owner type in a schema, whether that owner is an account, a workspace, a project or a customer tenant. In this B2B SaaS schema, Organization serves as that placement root.

Inferred placement roots

Required single links keep each organization’s child rows on one shard.

Roots determine shard placement rather than access boundaries. Four schema declarations keep every organization’s memberships, invites, workspaces, documents and audit events on one shard without adding organization_id columns to nested tables.

readonly := true
Memberships, invites, workspaces and documents each follow required single links up to Organization, so Napalm infers Organization as their root. Marking those links readonly fixes ownership at insert time so rows never move between roots 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 single links to project types, such as Document (workspace and author) or an AuditEvent (org and actor).
ext::napalm::root := 'reference'
Replicates BillingPlan across every shard in one atomic commit so plan joins and seat-limit checks execute locally on each organization’s shard.

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.

dbschema/default.gel
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;  };  # Optional so queries succeed when another member's Identity is hidden from the caller.  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 queryRouting class in napalm rootsShard execution behavior
createOrganizationa new root (Organization)Shard execution behaviorInserts the organization and founding Owner membership atomically on one shard.
inviteMemberone root ($org)Shard execution behaviorFilters Organization by .id = <uuid>$org so the Invite insert and email Job commit together on that organization’s shard.
acceptInviteone 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, removeMemberone 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.
myOrganizationsreads across rootsShard execution behaviorLists every organization holding a membership for the signed-in user, answered from a consolidated core copy once roots spread.
joinOrganizationwrites across roots when filtered by .slugShard 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 copies

Data shards stream committed rows to a core copy for cross-organization reads.

Dedicated tenant shards

Move a high-volume organization onto a dedicated shard while live traffic continues.

Per-tenant point-in-time restore

Rewind one organization to an earlier timestamp without affecting other organizations.

Run the commands below to inspect root routing, enable placement and split, move or restore individual organizations.

Terminal
# 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 --wait

Cross-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 the owning 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 organization without fanning out across data shards.

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.

dbschema/queries/billingRollup.edgeql
# 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
Terminal
# 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-agents

Service 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).

dbschema/default.gel
# Holds the organization UUID bound to a customer service keyglobal key_org: str; # Inside type Document alongside member policiesaccess policy org_key_can_read  allow select  using (<str>.workspace.org.id ?= global key_org);
Terminal
# Issue a customer-scoped service key restricted to two deployed queries and 5,000 calls per 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 # Audit every row the key can reach before sharing the credentialnapalm 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 /sign-in/agents/request 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.

dbschema/default.gel
# Holds the organization UUID selected on the user's agent consent screenglobal current_org: str; # Inside type Workspace alongside member_can_readaccess policy chosen_org  deny all  using ((<str>.org.id != global current_org) ?? false);
Terminal
# Allow user sessions to bind current_org on an AgentGrantnapalm endpoint acme-app --grant-global default::current_org
Consent page
// Bind the user's selected organization onto the agent grant at consent time.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()).redirectTo

Never 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. Scoping grants with consent globals 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#

  1. Create an organization as one person

    createOrganization returns the new organization, and myOrganizations lists the organization with the role Owner. For anyone else, the list is empty.

  2. 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 Owner on an Admin invite is refused.

  3. Try to remove the last owner

    changeRole and removeMember on the only owner return no rows. Make the second person an owner, and the same calls succeed.

  4. Check each person’s reach

    napalm people reach counts the rows a user can read or write on each type, and napalm explain-access names the policy that granted access to a specific row.

  5. Verify root lineage and single-shard query routing

    napalm roots confirms Organization as a placeable root, BillingPlan as reference and every $org-scoped workspace or membership query as one root before you enable placement.

Next steps#

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.

Type a word or two to search every docs page.