This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: openfga-zanzibar-rebac-guardrails

OpenFGA Zanzibar ReBAC Invariants & High-Throughput Verification

Enforces deterministic graph evaluation and zero-divergence tuple synchronization in OpenFGA Zanzibar architectures. Mandates batch evaluations or ListObjects over iterative Check calls, strict transactional outbox delivery for tuple mutations, and explicit authorization model version pinning.

Prohibited Anti-Pattern: N+1 Iterative Graph Checks and Direct Dual-Write Tuple Divergence

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Zanzibar ReBAC Invariants & High-Throughput Verification - Enforces deterministic graph evaluation and zero-divergence tuple synchronization in OpenFGA Zanzibar architectures. Mandates batch evaluations or ListObjects over iterative Check calls, strict transactional outbox delivery for tuple mutations, and explicit authorization model version pinning.
globs: src/authz/**/*.{ts,js,go}, src/services/**/*.{ts,js,go}, src/repositories/**/*.{ts,js,go}, src/api/**/*.{ts,js,go}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-zanzibar-rebac-guardrails"
---

# OpenFGA Zanzibar ReBAC Invariants & High-Throughput Verification

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: N+1 Iterative Graph Checks and Direct Dual-Write Tuple Divergence

## System Constraints
You are a Principal Engineer enforcing OpenFGA Zanzibar Relationship-Based Authorization Graph architecture. Mandate deterministic sub-millisecond evaluation patterns, strict separation of entity writes via Transactional Outbox, prevention of N+1 Check anti-patterns via ListObjects or BatchCheck, and absolute model immutability.

## Strict Guidelines
- Engineers MUST ALWAYS pin explicit `authorization_model_id` values across all API calls to prevent schema race conditions during active model migrations.
- Engineers MUST NOT execute sequential `fgaClient.check()` calls within iteration loops; evaluations over collections MUST use `listObjects`, `listUsers`, or `batchCheck`.
- Services MUST synchronize relationship tuples with the primary operational datastore via the Transactional Outbox pattern or CDC pipeline, NEVER via uncoordinated inline dual writes.
- Code SHOULD leverage `contextual_tuples` to evaluate uncommitted or ephemeral state within the current request context without persisting high-churn temporary tuples.
- Components NEVER store derived or computed permissions inside application database rows; permissions MUST remain derived dynamically from Zanzibar graph relationship traversals.

## Bad vs Good Implementations
### Document Filtering via OpenFGA ReBAC Graph

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Iterative Check calls produce N+1 network requests, degrading latency from sub-millisecond to seconds while saturating graph evaluation workers. The missing authorization_model_id causes dynamic lookups that introduce race conditions during model deployment.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

interface Document { id: string; title: string; }

// ANTI-PATTERN: N+1 sequential checks with dual-write risk and unpinned model
export async function getAuthorizedDocuments(
  fga: OpenFgaClient,
  userId: string,
  documents: Document[]
): Promise<Document[]> {
  const allowedDocs: Document[] = [];
  
  // Sequential network I/O per record destroys throughput and causes Zanzibar engine throttling
  for (const doc of documents) {
    const response = await fga.check({
      user: `user:${userId}`,
      relation: 'viewer',
      object: `document:${doc.id}`,
    });
    if (response.allowed) {
      allowedDocs.push(doc);
    }
  }
  return allowedDocs;
}
```

#### Production Standard (Correct)
> **Standard**: Resolves access in a single O(1) graph traversal using `listObjects`. Explicitly pins the schema with `authorization_model_id`, injects ephemeral state via `contextual_tuples`, and applies database-level filtering against returned identity vectors.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { prisma } from '../infrastructure/db';

interface FetchAuthorizedDocsInput {
  fga: OpenFgaClient;
  modelId: string;
  userId: string;
  orgId: string;
  userRoleInContext?: string;
}

// PRODUCTION INVARIANT: Set-based ListObjects evaluation with model pinning and contextual tuples
export async function getAuthorizedDocuments({
  fga,
  modelId,
  userId,
  orgId,
  userRoleInContext,
}: FetchAuthorizedDocsInput) {
  const contextualTuples = userRoleInContext ? [{
    user: `user:${userId}`,
    relation: userRoleInContext,
    object: `organization:${orgId}`,
  }] : [];

  // Single graph traversal returns all accessible object IDs
  const { objects } = await fga.listObjects({
    authorization_model_id: modelId,
    user: `user:${userId}`,
    relation: 'viewer',
    type: 'document',
    contextual_tuples: contextualTuples,
  });

  const documentIds = objects.map((obj) => obj.replace('document:', ''));
  if (documentIds.length === 0) return [];

  return prisma.document.findMany({
    where: { id: { in: documentIds }, orgId },
  });
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Zanzibar ReBAC Invariants & High-Throughput Verification

OpenFGA Zanzibar ReBAC Invariants & High-Throughput Verification defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic graph evaluation and zero-divergence tuple synchronization in OpenFGA Zanzibar architectures. Mandates batch evaluations or ListObjects over iterative Check calls, strict transactional outbox delivery for tuple mutations, and explicit authorization model version pinning. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: N+1 Iterative Graph Checks and Direct Dual-Write Tuple Divergence Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftN+1 Iterative Graph Checks and Direct Dual-Write Tuple DivergenceCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS pin explicit `authorization_model_id` values across all API calls to prevent schema race conditions during active model migrations.

Engineers MUST ALWAYS pin explicit `authorization_model_id` values across all API calls to prevent schema race conditions during active model migrations.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT execute sequential `fgaClient.check()` calls within iteration loops

Engineers MUST NOT execute sequential `fgaClient.check()` calls within iteration loops; evaluations over collections MUST use `listObjects`, `listUsers`, or `batchCheck`.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Services MUST synchronize relationship tuples with the primary operational datastore via the Transactional Outbox pattern or CDC pipeline, NEVER via uncoordinated inline dual writes.

Services MUST synchronize relationship tuples with the primary operational datastore via the Transactional Outbox pattern or CDC pipeline, NEVER via uncoordinated inline dual writes.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Code SHOULD leverage `contextual_tuples` to evaluate uncommitted or ephemeral state within the current request context without persisting high-churn temporary tuples.

Code SHOULD leverage `contextual_tuples` to evaluate uncommitted or ephemeral state within the current request context without persisting high-churn temporary tuples.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER store derived or computed permissions inside application database rows

Components NEVER store derived or computed permissions inside application database rows; permissions MUST remain derived dynamically from Zanzibar graph relationship traversals.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is OpenFGA Zanzibar ReBAC Invariants & High-Throughput Verification critical for AI coding assistants?

Enforces deterministic graph evaluation and zero-divergence tuple synchronization in OpenFGA Zanzibar architectures. Mandates batch evaluations or ListObjects over iterative Check calls, strict transactional outbox delivery for tuple mutations, and explicit authorization model version pinning. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (N+1 Iterative Graph Checks and Direct Dual-Write Tuple Divergence) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

OpenFGA