Designing a Graph-Based Authorization Service and Zero-Downtime Migration
System DesignModel answerLast updated
Design a scalable graph database schema for user-resource authorization (ReBAC) and plan a zero-downtime migration strategy from a legacy relational system.
Context
Your organization is replacing an existing legacy authorization system (stored in a SQL database) with a Relationship-Based Access Control (ReBAC) service backed by a graph database.
The access model must support:
- Direct user-to-resource permissions.
- Indirect permissions via nested user groups (groups containing other groups).
- Resource hierarchies (e.g., Organization $\rightarrow$ Folder $\rightarrow$ Document) where access to a parent node grants inherited access to child nodes.
- Multiple permission levels (
read,write,admin). - Explicit permission revocations/denials that take precedence over granted inherited access.
Requirements
Part 1: Architecture & Graph Schema
- Define the graph schema (node types, edge types, properties, and indexes).
- Explain how authorization queries are evaluated:
check_permission(user_id, resource_id, required_permission)$\rightarrow$booleanlist_accessible_resources(user_id, permission)$\rightarrow$List<resource_id>
- Detail how explicit denials, nested groups, and inheritance are handled in traversals while avoiding unbounded path explosion.
Part 2: Performance & Scalability
- Design a caching strategy to meet strict latency targets ($< 10\text{ ms}$ for $p99$ access checks) under a read-heavy workload ($100,000\text{ read queries/sec}$ vs. $500\text{ permission updates/sec}$).
- Describe invalidation strategies for cached decisions when deep nested hierarchies or high-degree nodes ("supergroups" or root folders) change.
- Address graph partitioning (sharding) strategies to prevent cross-machine traversal bottlenecks.
Part 3: Zero-Downtime Migration Strategy
- Outline a step-by-step migration plan from the legacy relational database to the graph database without service downtime.
- Detail dual-writing, data reconciliation, shadow reading, and fallback/rollback mechanisms.
Hints
Hint 1
Consider how directed edges represent group membership versus resource containment. Standardize edge direction to make traversals single-directional (e.g., User -> Group -> Resource vs Resource -> Group -> User).
Hint 2
Think about how explicit DENY nodes or properties alter traversal semantics. A breadth-first search (BFS) or depth-first search (DFS) must process denials before resolving granted access.
Hint 3
For high-scale caching, caching individual edge operations vs. caching fully resolved reachability decisions (e.g., bitsets or path tokens) has major trade-offs during cache invalidation.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
High-Level Architecture Overview
To support fine-grained, deep-hierarchy access checks at scale, we use a dedicated Authorization Engine backed by a distributed graph database (e.g., AWS Neptune, Neo4j, or custom engines like Google Zanzibar).
[ Client Application ]
│
▼
[ API Gateway / Authz Service ] ──(Read-Through)──► [ Distributed Redis Cache ]
│ │ (Miss)
│ ▼
└───────────► [ Graph Query Engine ] ◄───────────────┘
│
▼
[ Graph DB Cluster ]
Part 1: Graph Schema & Access Traversals
1. Schema Design
Nodes (Vertices)
User:id,created_atGroup:id,name,typeResource:id,resource_type(e.g.,folder,document),owner_id
Edges (Relationships)
MEMBER_OF:(User|Group) -> Group- Properties:
added_at
- Properties:
PARENT_OF:Resource -> Resource- Properties:
created_at
- Properties:
HAS_PERMISSION:(User|Group) -> Resource- Properties:
role(admin,write,read),effect(ALLOW,DENY),expiry_timestamp
- Properties:
Indexes
- Primary Key indexes on all Node
ids. - Outgoing adjacency index on
HAS_PERMISSIONandMEMBER_OF. - Incoming adjacency index on
PARENT_OF.
2. Evaluating check_permission(User, Resource, Action)
A user has permission to a target resource if there exists an ALLOW path from User to Resource (directly, via group membership, or via parent resource inheritance) AND there is no explicit DENY override.
Traversal Logic
- Find Expand User Sets: Traversal outwards from
UserviaMEMBER_OF*to collect all effective principal IDs $P = { \text{User}, \text{Group}_1, \text{Group}_2, \dots }$. - Find Target Hierarchies: Traversal upwards from target
ResourceviaPARENT_OF*to collect all ancestor resource IDs $R = { \text{Resource}, \text{ParentFolder}, \text{RootFolder} }$. - Evaluate Edges: Search for any edge between any $p \in P$ and any $r \in R$.
- Denial Resolution:
- If any
DENYedge forActionexists between $p \in P$ and $r \in R$ at a node level equal to or closer to the target resource than anALLOW, evaluate toFALSE. - If an
ALLOWpath with validrole($\text{Admin} \ge \text{Write} \ge \text{Read}$) exists and is not denied, evaluate toTRUE.
- If any
(User: Alice) ──MEMBER_OF──► (Group: Engineers)
│
HAS_PERMISSION
(role: WRITE, effect: ALLOW)
│
▼
(Document: D1) ◄────PARENT_OF──── (Folder: F1)
Handling Unbounded Traversal & Cycles
- Cycle Detection: Maintain a
visitedset during BFS to prevent infinite loops in cyclic group memberships. - Max Depth Constraint: Set a strict max traversal depth (e.g., 10 steps for groups, 15 steps for resources). Any paths exceeding this limit raise an alert and default to safe failure (
FALSE).
3. Evaluating list_accessible_resources(User, Action)
- Traversal outward to find all groups $P$ of
User. - Find all direct
HAS_PERMISSIONedges from any $p \in P$. - Traverse downstream via
PARENT_OF*to collect all child and descendant resources. - Filter out any descendants that carry a direct
DENYedge forUseror any of $P$.
Part 2: Scalability & Performance
1. Performance Profile
- Read Throughput: $100,000\text{ QPS}$
- Write Throughput: $500\text{ QPS}$
- Latency Target: $p99 < 10\text{ ms}$
Direct multi-hop graph traversals at high concurrency can cause unacceptable latency spikes ($50\text{–}200\text{ ms}$). To maintain sub-10ms $p99$, an aggressive caching strategy is required.
2. Multi-Level Caching & Invalidation
+-------------------------------------------------------------+
| Local In-Memory Cache |
| (L1: Guava / Caffeine, TTL: 5-10s) |
+-------------------------------------------------------------+
│ (Miss)
▼
+-------------------------------------------------------------+
| Distributed Redis Cache |
| (L2: Key-Value / Bitmaps, TTL: 1 hour) |
+-------------------------------------------------------------+
│ (Miss)
▼
+-------------------------------------------------------------+
| Graph Database Read Replicas |
+-------------------------------------------------------------+
Cache Strategy: Check Decision Caching
- Key:
authz:{user_id}:{resource_id}:{action}$\rightarrow$ Value:true/false(or short-lived token). - Cache Invalidation on Graph Mutations:
- Permission updates produce CDC (Change Data Capture) events via Kafka/Debezium.
- An invalidation worker reads Kafka events:
- Direct Grant/Revoke: Invalidate direct
(user, resource)keys. - Group Membership Change: Traversing downstream to invalidate all members' decision entries can cause a "stampede" if a large group changes.
- Direct Grant/Revoke: Invalidate direct
Mitigating Invalidation Stampedes (Supergroups / High-Degree Nodes)
- Denormalized Authorization Index (Zanzibar-style Tuple Change Vectors):
- Assign a Zookeeper / Etcd Sequence Version to each Group and Resource hierarchy.
- Store group versions in a fast KV store. Include the snapshot version in the cache key:
authz:{user_id}:{resource_id}:{action}:v={group_version}_{resource_version} - When a group’s structure changes, increment
group_version. All associated cache keys automatically miss lazily without requiring massive batch invalidation.
3. Graph Partitioning (Sharding)
Graph databases suffer when traversals cross shard boundaries.
Partitioning Strategy
- Partition by Organization / Tenant ID: Authorization graphs naturally form disjoint subgraphs around top-level enterprise tenants. All users, groups, and resources belonging to
Tenant_Areside on the same database shard. - Cross-Tenant Sharing: For cross-tenant sharing, store shared links as explicit cross-shard references. Traversal defaults to local evaluation first, making RPC calls across shards only when explicit external edges are identified.
Part 3: Zero-Downtime Migration Strategy
Migrating permission evaluations from a relational model to a graph model without downtime requires a 4-Phase Migration Strategy.
[ Phase 1: Dual Write ] ──► [ Phase 2: Shadow Read ] ──► [ Phase 3: Primary Read ] ──► [ Phase 4: Deprecation ]
Phase 1: Backfill & Dual Writing
- Historical Migration:
- Write an ETL pipeline (Apache Spark / Flink) to dump SQL relational tables (
users,roles,permissions,resource_hierarchy) into nodes and edges. - Bulk-insert into the Graph DB using batch API imports.
- Write an ETL pipeline (Apache Spark / Flink) to dump SQL relational tables (
- Dual-Writing:
- Update the permission mutation service to write to both databases:
- Primary: Legacy SQL DB
- Secondary: Graph DB (asynchronous via CDC/Kafka to prevent graph latency from blocking writes).
- Update the permission mutation service to write to both databases:
┌──────────────┐
│ Write Request│
└──────┬───────┘
│
▼
┌───────────────────┐
│ Write Service API │
└─────────┬─────────┘
│
┌─────────────┴─────────────┐
▼ (Sync Transaction) ▼ (Async CDC Event)
┌──────────────┐ ┌──────────────┐
│ Legacy SQL │ │ Kafka Queue │
└──────────────┘ └──────┬───────┘
│
▼
┌──────────────┐
│ Graph Writer │
└──────┬───────┘
│
▼
┌──────────────┐
│ Graph DB │
└──────────────┘
Phase 2: Shadow Reading & Reconciliation
- Shadow Traffic Execution:
- All authorization checks target the legacy SQL system to return the live result.
- An asynchronous task (or service wrapper) duplicates the check against the Graph Authz service in the background.
- Reconciliation & Metrics:
- Compare outputs of
Legacy_ResultvsGraph_Result. - Log discrepancies to an error queue for investigation (e.g., edge cases in group inheritance or nested denial rules).
- Track performance targets: Verify latency profiles under actual production load.
- Compare outputs of
- Data Verification Worker:
- Run a continuous background job comparing random samples of access decisions between SQL and Graph DB until agreement reaches 99.999%.
Phase 3: Staged Cutover (Graph as Primary Read)
- Feature Flag Rollout:
- Use dynamic configuration (e.g., LaunchDarkly) to switch read traffic to the Graph DB by percentage:
1% -> 5% -> 25% -> 50% -> 100%.
- Use dynamic configuration (e.g., LaunchDarkly) to switch read traffic to the Graph DB by percentage:
- Fallback / Rollback Path:
- If latency spikes or error rates exceed $0.01%$, immediately toggle the feature flag back to $0%$ to route reads to SQL.
- Dual-writing remains active throughout this phase so SQL data remains completely up to date.
┌────────────────────┐
│ Read Authz Request │
└─────────┬──────────┘
│
▼
┌───────────────────────────┐
│ Dynamic Feature Switch │
└─────┬───────────────┬─────┘
X% │ │ (100-X)%
▼ ▼
┌──────────────────┐ ┌──────────────────┐
│ Graph DB Service│ │ Legacy SQL System│
└──────────────────┘ └──────────────────┘
Phase 4: Primary Write Switch & Legacy Deprecation
- Switch write primary: Writes now go synchronously to the Graph DB first.
- Reverse CDC pipeline: Write changes asynchronously from Graph DB back to Legacy SQL (for safety window of 1-2 weeks).
- Deprecate legacy SQL sync and decommission legacy permission tables.
Common Pitfalls & Anti-Patterns
- Naïve Graph Traversals Without Limits: Running unbounded graph traversals in real-time queries can cause execution timeouts when traversing supergroups containing $100,000+$ members.
- Invalidating Entire Caches on High-Degree Node Edits: Purging millions of entries when a root folder changes can cause cache stampedes. Use versioned keys or lazy evaluation instead.
- Migrating Reads Before Verifying Dual-Write Consistency: Cutting over traffic without a shadow-reading and automatic reconciliation pipeline leads to silent permission leaks or broken access controls.