FullStack AI Hub
Studio
System Design · 07. Security
10 min
10 steps
Intermediate

Authorization & RBAC

Model roles, attribute policies, and Google Zanzibar relationship graphs cleanly without role explosion.

System Design07. SecurityLesson 2 of 3
10 minIntermediate10 steps

Authorization & RBAC

Model roles, attribute policies, and Google Zanzibar relationship graphs cleanly without role explosion.

Identity Check
Passed (u42)
Owner Check
Missing!
Cross-User Leak
200 OK (Data)
OWASP Rank
API1 Critical
Valid JWT (u42)AllowedWHERE id = 1099User #42AuthN MiddlewareInvoices APIInvoices DBBOLA / IDOR BugForgot AND owner_id = u42
Access Check / Request
Allowed (200 OK)
Policy / Tuple Sync
Denied (403 Forbidden)
IDOR / Unauthorized Leak
In This LessonStep 1 of 10
What You Will Master
  • ✓Separate Authentication from Authorization and prevent Broken Object-Level Authorization (IDOR)
  • ✓Model clean RBAC hierarchies and adopt ABAC + Policy-as-Code sidecars when roles explode
  • ✓Scale fine-grained document sharing using Google Zanzibar ReBAC tuple graphs and Leopard indexes
  • ✓Enforce defense-in-depth multi-tenant isolation with Row-Level Security and Least Privilege

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
RBAC (Role-Based)Admin dashboards, B2B org tiers (Viewer / Editor / Admin) with coarse permissionsCauses role explosion when rules depend on resource owner, region, or time
ABAC (OPA / Cedar Sidecar)Compliance rules combining user attributes, resource tags, region, and request contextHarder to answer "who can access document X?" without scanning policies
ReBAC (Google Zanzibar)Google Docs, GitHub repos, Slack channels with nested folders, teams, and per-object sharesRequires a dedicated low-latency tuple store + cache invalidation (Zookies)
Database Row-Level SecurityMulti-tenant SaaS defense-in-depth guaranteeing tenant A can never query tenant B rowsAdds query planner overhead if `tenant_id` is missing from composite indexes

Step-by-Step Architectural Breakdown (10 Steps)

Full architectural walkthrough transcript and state transitions for Authorization & RBAC.

STEP 01 · PROBLEMJump to step →

AuthN vs AuthZ & The Classic IDOR Bug

**Authentication (AuthN)** proves *who you are* (`user_id = 42`). **Authorization (AuthZ)** decides *what you are allowed to touch*. Mixing them up causes the #1 API vulnerability on the OWASP list: **Broken Object-Level Authorization (BOLA / IDOR)**.

User 42 logs in legitimately, receives a valid JWT, and simply edits the URL from `GET /invoices/1042` to `GET /invoices/1099`. Because the handler only checked `isAuthenticated()` and forgot to verify ownership, it returns another customer’s private invoice!

watch:Never rely on random UUIDs alone to prevent IDOR ("security through obscurity"). Every single data fetch must enforce an explicit authorization check.

AuthN vs AuthZIDOR / BOLAObject-Level CheckOWASP API1
STEP 02 · SOLUTIONJump to step →

Role-Based Access Control (RBAC)

**RBAC** decouples individual users from raw permissions through named **Roles** (`User → Role → Permission`). Instead of assigning `billing:refund` to 50 support agents individually, you assign them the `SupportLead` role.

Keep application code checking **permissions** (`can("invoices:refund")`) rather than role names (`if role === "admin"`). That way you can create custom roles later without editing a single line of business logic.

good:Golden RBAC rule: assign users to Roles, bind Roles to Permissions, and check Permissions—never hardcoded Role names—inside your API handlers.

RBACPermission ChecksRole Hierarchy401 vs 403
STEP 03 · PROBLEMJump to step →

When RBAC Breaks: Role Explosion

RBAC shines with 5–15 coarse roles—until Product asks for rules like: *"EU support managers can refund invoices under €500 during business hours, only for accounts in their assigned country."*

Encoding every combination of region × department × threshold × environment into static roles creates **Role Explosion** (`eu_de_support_tier2_under500_prod_editor`), producing hundreds of brittle roles nobody dares delete.

watch:If you find yourself naming roles with 3+ underscores encoding geography, amount limits, or ownership, you have outgrown pure RBAC.

Role ExplosionCombinatorial GrowthContext-Aware RulesStale Privileges
STEP 04 · SOLUTIONJump to step →

Attribute-Based Access Control (ABAC)

**ABAC** replaces hundreds of brittle roles with **declarative policies** evaluated over four dynamic attribute sets: **Subject** (`user.region = "EU"`), **Resource** (`invoice.amount < 500`), **Action** (`"refund"`), and **Environment** (`time ∈ business_hours`).

Now a single 5-line policy replaces 400 static roles—and automatically covers newly added regions or currencies without creating a single new role.

idea:Most production systems combine RBAC + ABAC: use RBAC for baseline job function (`SupportAgent`) and ABAC predicates for dynamic constraints (`amount <= 500 && region == resource.region`).

ABACSubject AttributesResource AttributesPolicy Engine
STEP 05 · TECHNIQUEJump to step →

Policy-as-Code Sidecars (OPA & Cedar)

Calling a single remote AuthZ microservice on every internal RPC adds network latency and creates a global single point of failure. Instead, deploy **Open Policy Agent (OPA)** or **AWS Cedar** as a **localhost sidecar** (or in-process library) beside every service.

Policies live in Git, pass unit tests in CI, and publish as signed **policy bundles** synced every 15 seconds. Every service evaluates authorization in **< 0.5 ms over loopback**—even if the central policy control plane goes offline.

good:Decoupling policy execution (localhost sidecar) from policy authoring (Git + CI bundle server) gives you sub-millisecond speed AND centralized security audits.

OPA / RegoAWS CedarPolicy-as-CodeSidecar Pattern
STEP 06 · PROBLEMJump to step →

The Fine-Grained Sharing Problem

Now imagine building **Google Drive, Notion, or GitHub**. Alice is a member of `Team:Backend`, which is nested inside `Group:Engineering`, which has `editor` access to `Folder:Q4-Plans`, which contains `Doc:Roadmap`!

Neither RBAC nor stateless ABAC can answer *"Can Alice edit `Doc:Roadmap`?"*—because the answer depends on traversing an arbitrarily deep **graph of relationships** across users, groups, folders, and individual shared objects.

watch:Running recursive SQL `WITH RECURSIVE` CTEs across 50M permission rows on every document open turns your primary database into a smoking crater.

Hierarchical SharingTransitive PermissionsRecursive JoinsGraph Traversal
STEP 07 · SOLUTIONJump to step →

Relationship-Based Access Control (Google Zanzibar)

Google solved global collaborative permissions across Drive, YouTube, and Calendar with **Zanzibar** (inspired open-source engines: **SpiceDB, OpenFGA, Ory Keto**). Every permission fact is stored as a tiny **Relationship Tuple**: `(object, relation, subject)`.

A centralized AuthZ graph service answers `Check(doc:roadmap, edit, user:alice)` by walking typed schema rules (`editor` implies `viewer`, `parent.editor` inherits down) across specialized tuple shards in single-digit milliseconds.

good:One universal tuple model (`doc:42#viewer@user:alice`, `folder:9#parent@doc:42`) powers RBAC, org hierarchies, AND per-document sharing in a single engine.

ReBACGoogle ZanzibarRelation TuplesOpenFGA / SpiceDB
STEP 08 · TECHNIQUEJump to step →

Scaling ReBAC: Leopard Indexes & Zookie Tokens

At 10 million checks/sec, two hard distributed bugs appear: (1) deeply nested groups take too many graph hops, and (2) **The New Enemy Problem**—Alice removes Bob from `Doc:Secret`, then writes a sensitive sentence, but Bob reads it anyway because a **stale cache** still thinks Bob is a viewer!

Zanzibar solves both: **Leopard** precomputes flattened transitive group sets in RAM for O(1) intersection, while **Zookies** (opaque consistency timestamps stored alongside the doc) force AuthZ checks to evaluate at a snapshot **at least as fresh as the document’s last permission change**.

idea:Zookies give you bounded staleness for fast caching (99% cache hits) while mathematically preventing the New Enemy bug on freshly revoked documents.

New Enemy ProblemZookie TokenLeopard IndexConsistent Caching
STEP 09 · TECHNIQUEJump to step →

Multi-Tenant Isolation & Least Privilege

In B2B SaaS, a single missing `WHERE tenant_id = ?` in one new microservice endpoint can leak data across rival enterprises. Defense-in-depth pushes tenant isolation **all the way down into PostgreSQL Row-Level Security (RLS)**.

Every request sets `SET LOCAL app.tenant_id = $1` on the DB transaction from the verified token. Even if an application engineer forgets the `WHERE` clause, the database engine itself refuses to return or mutate rows belonging to any other tenant.

good:Pair PostgreSQL RLS with **Least Privilege** service credentials: your analytics reader gets `SELECT` on a read replica, never superuser `DROP TABLE` rights on the primary.

Row-Level SecurityMulti-Tenant IsolationLeast PrivilegeDefense-in-Depth
STEP 10 · RECAPJump to step →

Choosing Your Authorization Architecture

Start simple and evolve deliberately: begin with **RBAC** checking permission strings, add **ABAC / OPA sidecars** when rules depend on region/amount/time, and adopt **Zanzibar ReBAC** when users share individual nested resources across teams.

Backstop every tier with **PostgreSQL Row-Level Security** and **Least Privilege** service scopes so a single application bug can never leak cross-tenant data.

good:Default Deny everywhere: if an AuthZ engine times out or a policy returns undefined, fail closed with `403 Forbidden`—never fail open!

Default DenyRBAC + ABAC + ReBACOPA SidecarsPostgreSQL RLS

Related Production Deep-Dives & Simulators

Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.