This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: openfga-subgraph-recursion-traversal-budget-standard

OpenFGA Zanzibar Subgraph Recursion Depth and Contextual Tuple Budget Standard

Enforces strict bounds on transitive relation closure depth and contextual tuple cardinality within OpenFGA authorization evaluations. Guarantees predictable sub-millisecond query latencies and prevents catastrophic graph expansion attacks in dense multi-tenant authorization topographies.

Prohibited Anti-Pattern: Unbounded Transitive Graph Traversal and Arbitrary Contextual Tuple Expansion Causing Zanzibar Engine Collapse

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Zanzibar Subgraph Recursion Depth and Contextual Tuple Budget Standard - Enforces strict bounds on transitive relation closure depth and contextual tuple cardinality within OpenFGA authorization evaluations. Guarantees predictable sub-millisecond query latencies and prevents catastrophic graph expansion attacks in dense multi-tenant authorization topographies.
globs: src/auth/**/*.ts, src/permissions/**/*.ts, src/services/authorization/**/*.ts, src/lib/openfga/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-subgraph-recursion-traversal-budget-standard"
---

# OpenFGA Zanzibar Subgraph Recursion Depth and Contextual Tuple Budget Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Transitive Graph Traversal and Arbitrary Contextual Tuple Expansion Causing Zanzibar Engine Collapse

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA Zanzibar Subgraph Recursion & Traversal Budget Standard. You must mandate strict limits on contextual tuple injection, enforce deterministic query timeouts via AbortSignal, bound transitive closure evaluation depth, and guarantee fail-closed semantics for all authorization checkpoints.

## Strict Guidelines
- Engineers MUST ALWAYS cap contextual tuples to an explicit cardinality ceiling (maximum 20 tuples) before forwarding checks to the OpenFGA evaluation engine.
- Engineers MUST NOT construct unindexed, deeply recursive hierarchical schemas (e.g., unbounded parent-folder nesting beyond 5 levels) without path materialization.
- Services MUST enforce strict client-side timeout deadlines (maximum 15 milliseconds) on OpenFGA API calls using AbortController/AbortSignal.
- Services MUST fail closed with an explicit AccessDenied error when OpenFGA returns evaluation budget exhaustion, cycle detection, or deadline cancellation errors.
- Components NEVER pass raw user-supplied hierarchy nodes directly into contextual tuples without structural deduplication, schema validation, and cycle verification.

## Bad vs Good Implementations
### Enforcing Contextual Tuple Budget, Recursion Deadlines, and Cycle Defense in OpenFGA Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad implementation accepts arbitrary array lengths for contextual tuples, triggering Zanzibar sub-graph query explosions and engine timeouts. It lacks a request-level AbortSignal deadline, has no traversal depth validation or cycle checks, and does not handle partial evaluation failures or engine budget exhaustion safely.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export class UnboundedAuthzService {
  constructor(private readonly fga: OpenFgaClient) {}

  // BAD: Accepts unbounded dynamic tuples, no query deadline, fails open or hangs on deep hierarchies
  async canAccessDocument(userId: string, docId: string, parentOrgIds: string[]): Promise<boolean> {
    // Dynamically builds contextual tuples for every parent org without cardinality limits
    const contextualTuples = parentOrgIds.map(orgId => ({
      user: `user:${userId}`,
      relation: 'member',
      object: `organization:${orgId}`
    }));

    const response = await this.fga.check({
      user: `user:${userId}`,
      relation: 'can_view',
      object: `document:${docId}`,
      contextualTuples
    });

    return Boolean(response.allowed);
  }
}
```

#### Production Standard (Correct)
> **Standard**: The good implementation enforces an invariant tuple budget ceiling (MAX_CONTEXTUAL_TUPLES = 20), deduplicates nodes to prevent cycle expansion, binds query execution to an AbortSignal timeout of 15ms, sanitizes identifier strings, and implements strict fail-closed authorization semantics on errors.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

export class BoundedAuthzService {
  private static readonly MAX_CONTEXTUAL_TUPLES = 20;
  private static readonly EVALUATION_TIMEOUT_MS = 15;

  constructor(private readonly fga: OpenFgaClient) {}

  async canAccessDocument(
    userId: string,
    docId: string,
    ancestorOrgs: readonly string[]
  ): Promise<boolean> {
    // Invariant: Bounded contextual tuple budget to avoid Zanzibar memory/recursion explosion
    if (ancestorOrgs.length > BoundedAuthzService.MAX_CONTEXTUAL_TUPLES) {
      throw new Error(`Contextual tuple budget exceeded: ${ancestorOrgs.length} > ${BoundedAuthzService.MAX_CONTEXTUAL_TUPLES}`);
    }

    // Invariant: Deduplicate and validate inputs to eliminate trivial recursion cycles
    const uniqueOrgs = [...new Set(ancestorOrgs)];
    const contextualTuples = uniqueOrgs.map((orgId) => ({
      user: `user:${encodeURIComponent(userId)}`,
      relation: 'member' as const,
      object: `organization:${encodeURIComponent(orgId)}`
    }));

    const payload: ClientCheckRequest = {
      user: `user:${encodeURIComponent(userId)}`,
      relation: 'can_view',
      object: `document:${encodeURIComponent(docId)}`,
      contextualTuples
    };

    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), BoundedAuthzService.EVALUATION_TIMEOUT_MS);

    try {
      const response = await this.fga.check(payload, {
        signal: controller.signal
      });
      return Boolean(response.allowed);
    } catch (error: unknown) {
      // Invariant: Fail closed on timeout, graph recursion limits, or engine cancellation
      return false;
    } finally {
      clearTimeout(timeoutId);
    }
  }
}
```

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 Subgraph Recursion Depth and Contextual Tuple Budget Standard

OpenFGA Zanzibar Subgraph Recursion Depth and Contextual Tuple Budget Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict bounds on transitive relation closure depth and contextual tuple cardinality within OpenFGA authorization evaluations. Guarantees predictable sub-millisecond query latencies and prevents catastrophic graph expansion attacks in dense multi-tenant authorization topographies. 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: Unbounded Transitive Graph Traversal and Arbitrary Contextual Tuple Expansion Causing Zanzibar Engine Collapse 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 DriftUnbounded Transitive Graph Traversal and Arbitrary Contextual Tuple Expansion Causing Zanzibar Engine CollapseCritical
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 cap contextual tuples to an explicit cardinality ceiling (maximum 20 tuples) before forwarding checks to the OpenFGA evaluation engine.

Engineers MUST ALWAYS cap contextual tuples to an explicit cardinality ceiling (maximum 20 tuples) before forwarding checks to the OpenFGA evaluation engine.

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 construct unindexed, deeply recursive hierarchical schemas (e.g., unbounded parent-folder nesting beyond 5 levels) without path materialization.

Engineers MUST NOT construct unindexed, deeply recursive hierarchical schemas (e.g., unbounded parent-folder nesting beyond 5 levels) without path materialization.

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 enforce strict client-side timeout deadlines (maximum 15 milliseconds) on OpenFGA API calls using AbortController/AbortSignal.

Services MUST enforce strict client-side timeout deadlines (maximum 15 milliseconds) on OpenFGA API calls using AbortController/AbortSignal.

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

Services MUST fail closed with an explicit AccessDenied error when OpenFGA returns evaluation budget exhaustion, cycle detection, or deadline cancellation errors.

Services MUST fail closed with an explicit AccessDenied error when OpenFGA returns evaluation budget exhaustion, cycle detection, or deadline cancellation errors.

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 pass raw user-supplied hierarchy nodes directly into contextual tuples without structural deduplication, schema validation, and cycle verification.

Components NEVER pass raw user-supplied hierarchy nodes directly into contextual tuples without structural deduplication, schema validation, and cycle verification.

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 Subgraph Recursion Depth and Contextual Tuple Budget Standard critical for AI coding assistants?

Enforces strict bounds on transitive relation closure depth and contextual tuple cardinality within OpenFGA authorization evaluations. Guarantees predictable sub-millisecond query latencies and prevents catastrophic graph expansion attacks in dense multi-tenant authorization topographies. 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 (Unbounded Transitive Graph Traversal and Arbitrary Contextual Tuple Expansion Causing Zanzibar Engine Collapse) 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