HomeBlogHow to Build a SaaS Application...

Engineering Guide · 9 min read · May 27, 2026

How to Build a SaaS Application with Team and Permission Management

Most early-stage SaaS startups break authorization the moment a user joins a second workspace or a customer asks for custom roles. This guide details a production-tested schema and security model for workspace memberships, invite token flows, permission caching, and billing seat-limit enforcement.

Author
Smit Desai
Published
May 27, 2026
Read time
9 min read
Topic
SaaS Engineering
Services
Custom Web · Mobile Apps · All Services

Single-user SaaS prototypes are forgiving: user_id owns everything, login resolves one account, and authorization is a simple ownership check. The moment you sell to B2B teams, every assumption breaks.

An agency consultant needs access to four client workspaces using a single login. An enterprise buyer refuses to sign unless finance can view invoices without accessing production API keys. And your billing code suddenly has to decide whether pending email invitations count toward a workspace's 5-seat Starter limit.

Building team and permission management cleanly from the start prevents painful authorization rewrites—and security leaks—after launch.


1. Separate Identity (users) from Workspace Access (memberships)

The most common rookie mistake in SaaS data modeling is placing workspace_id and role directly on the users table. That design forces users to maintain separate email addresses for every team they join and guarantees a schema migration later.

Model global authentication (users) separately from workspace participation (workspace_memberships).

CREATE TABLE workspaces (
    id          UUID PRIMARY KEY,
    name        VARCHAR(120) NOT NULL,
    plan_code   VARCHAR(40) NOT NULL DEFAULT 'starter',
    seat_limit  INT NOT NULL DEFAULT 5,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE workspace_memberships (
    id            UUID PRIMARY KEY,
    workspace_id  UUID NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
    user_id       UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    role_key      VARCHAR(40) NOT NULL,   -- 'owner', 'admin', 'editor', 'viewer'
    status        VARCHAR(20) NOT NULL DEFAULT 'active', -- 'active', 'suspended'
    joined_at     TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (workspace_id, user_id)
);

CREATE INDEX idx_memberships_user ON workspace_memberships (user_id, status);

Notice two critical behaviors this enables immediately:

  • One person can hold owner in their own company workspace and viewer in a partner's workspace without duplicating credentials.
  • Suspending a contractor (status = 'suspended') revokes access to that workspace instantly without deleting their global account or breaking foreign keys on historical activity logs.

2. Check Granular Permissions, Never Role Names

Even if your launch UI only offers three preset roles (Owner, Admin, Member), never scatter if ($member->role === 'admin') across controllers or UI components.

When a customer inevitably asks for a "Billing Manager" role—or custom per-seat toggles—hardcoded role-name checks force you to audit every endpoint in the codebase. Instead, map roles to explicit resource.action permission strings and check capabilities everywhere.

final class PermissionMatrix
{
    public const ROLE_PERMISSIONS = [
        'owner' => ['*'],
        'admin' => [
            'members.invite', 'members.remove',
            'projects.create', 'projects.edit', 'projects.delete',
            'billing.view',
        ],
        'editor' => [
            'projects.create', 'projects.edit',
        ],
        'viewer' => [
            'projects.view',
        ],
    ];

    public static function allows(string $roleKey, string $permission): bool
    {
        $granted = self::ROLE_PERMISSIONS[$roleKey] ?? [];

        return in_array('*', $granted, true)
            || in_array($permission, $granted, true);
    }
}

When you later introduce custom database-backed roles or per-user overrides on an Enterprise plan, only PermissionMatrix::allows() changes—every route guard and policy remains untouched.

Comparing Permission Models as You Scale

Permission Pattern Implementation Effort Runtime Query Cost Ideal Stage
Static Role-to-Permission Map Low; zero extra DB joins Sub-millisecond in-memory lookup Seed / MVP startups
DB-Backed Custom Roles + Redis Cache Moderate; role editor UI + invalidation Fast cached set lookup (~1ms) Growth B2B SaaS (mid-market buyers)
Resource-Level ACL / ABAC High; per-folder or per-record rules Requires scoped policy tables & indexes Complex document/data governance platforms

3. Secure the Team Invitation Lifecycle

Team invitation flows are a frequent target for account-takeover bugs and seat-limit bypasses. Lock down four edge cases from day one:

  1. Hash invite tokens at rest: Generate a 32-byte cryptographically random token, email the raw token once, and store only SHA-256(token) in workspace_invitations. If database backups ever leak, unaccepted invites remain unusable.
  2. Bind acceptance to the invited email (or explicit verify flow): Never let an already logged-in user userA@evil.com accept an invite token issued for cfo@acme.com simply by clicking a leaked link. Require matching email verification or explicit workspace transfer rules.
  3. Prevent privilege escalation on invite: An Admin must never be allowed to invite a new Owner or assign permissions higher than they personally hold.
  4. Protect the last owner: Block any DELETE /members/{id} or role-downgrade request that would leave a workspace with zero active owner rows.

4. Enforce Seat Limits Atomically with Billing State

If your pricing charges per seat or caps team size by tier, enforce limits on the server—including pending invitations—inside a row-level lock so concurrent invite requests cannot overshoot the cap.

BEGIN;

SELECT seat_limit
FROM workspaces
WHERE id = $1
FOR UPDATE;

SELECT
    (SELECT COUNT(*) FROM workspace_memberships WHERE workspace_id = $1 AND status = 'active')
  + (SELECT COUNT(*) FROM workspace_invitations WHERE workspace_id = $1 AND accepted_at IS NULL AND expires_at > NOW())
AS occupied_seats;

-- Application aborts with 402/422 if occupied_seats >= seat_limit; otherwise inserts invitation
COMMIT;

Sync seat_limit reliably from verified Stripe Billing subscription webhooks (never from frontend checkout return URLs). If you want to see how webhook-driven entitlement state machines work reliably in production, check our case study on web subscriptions for SaaS and our broader multi-tenant SaaS architecture guide.


5. Cache Permissions Safely Without Stale Access Leaks

Looking up roles and custom permissions on every API call adds latency, yet aggressive caching creates an ugly security bug: an admin revokes a fired employee's access, and the employee keeps calling API endpoints for 15 minutes until the cache expires.

Solve both cleanly using versioned cache keys or short-lived session invalidation:

  • Store a monotonically increasing auth_version integer on workspace_memberships (or in Redis per (workspace_id, user_id)).
  • Include auth_version inside the permission cache key: perm:v{version}:{workspace_id}:{user_id}.
  • Increment auth_version inside the same transaction whenever a role changes, a member is suspended, or a workspace plan downgrades.

Revocation takes effect on the very next HTTP request, with zero stale-cache window and zero manual DEL race conditions.


6. Ship Audit Visibility Customers Expect

B2B buyers—especially CTOs and compliance leads—expect to see who changed permissions and when. Log four events out of the box:

  • member.invited and member.invite_revoked
  • member.role_changed (capturing old_role, new_role, actor_id)
  • member.removed or member.suspended
  • workspace.ownership_transferred

Exposing a clean, read-only "Security & Team Activity" log in workspace settings immediately raises enterprise trust without adding heavy engineering scope.


Ship Your SaaS Team Layer Right the First Time

Authorization and team billing are foundational infrastructure—getting them wrong early creates security exposure and weeks of painful refactoring right when enterprise prospects show interest.

At SmitDev, we build custom web application development platforms and multi-tenant B2B SaaS products for startups globally across the US, UK, Europe, UAE, Australia, and Singapore. Across 170+ shipped engagements, our focus is clean, tested architecture shipped quickly—either at $55/day (8–9 hours of dedicated engineering) or $1,999/month dedicated delivery, or scoped up front via Launch Consulting.

Building a team-based SaaS product and want a rock-solid permission and billing foundation? Let's discuss your project and map out your schema and launch milestones.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Custom Web & SaaS

Custom Web Application Development

Production Laravel, Next.js, API, and multi-tenant SaaS systems engineered end to end at $55/day (8–9 hrs) or $1,999/mo.

Comparison · Buyer Guide

SmitDev vs Software Agencies

See side-by-side economics, senior code ownership, and onboarding speed vs traditional dev shops and marketplaces.

01 — Frequently asked questions

saas engineering

Why shouldn't I store a user's role directly on the users table in a SaaS?

Storing role on the users table breaks as soon as one email address belongs to multiple workspaces—such as an agency consultant who is Admin in Workspace A and Viewer in Workspace B. Always store roles on a workspace_memberships join table.

Should a B2B SaaS start with RBAC or full custom permissions?

Start with 3 to 4 fixed Role-Based Access Control (RBAC) roles mapped to granular permission keys in code (like invoices.export or members.invite). Because checks already evaluate permission keys rather than role names, you can unlock custom Enterprise roles later without rewriting authorization checks.

How do you prevent race conditions when enforcing paid seat limits on team invites?

Count both active members and pending invitations inside a database transaction locked on the workspace row (SELECT ... FOR UPDATE), and enforce the plan seat cap right before inserting a new invitation or accepting a join token.

Can SmitDev architect and build team management and billing for our startup MVP?

Yes. Across 170+ shipped case studies, SmitDev builds complete B2B SaaS foundations—including multi-tenant RBAC, secure invites, SSO readiness, and Stripe seat billing—at $55/day or $1,999/month dedicated delivery.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.