This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-recursive-graph-evaluation-budget-guardrail-production-standard

OpenFGA Graph Evaluation Budget, Depth Limiting, and Cycle-Detection Standard

Unbounded recursive relation evaluation in fine-grained authorization (ReBAC) graphs induces algorithmic denial-of-service, goroutine/thread starvation, and cascading microservice failures. This standard mandates explicit evaluation budgets, hard relation traversal depth limits, visited-node cycle detection invariants, and deterministic context deadline timeouts across all OpenFGA client dispatchers and schema models.

Prohibited Anti-Pattern: Unconstrained recursive graph resolution and circular relation self-nesting without traversal ceilings or context timeouts.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Graph Evaluation Budget, Depth Limiting, and Cycle-Detection Standard - Unbounded recursive relation evaluation in fine-grained authorization (ReBAC) graphs induces algorithmic denial-of-service, goroutine/thread starvation, and cascading microservice failures. This standard mandates explicit evaluation budgets, hard relation traversal depth limits, visited-node cycle detection invariants, and deterministic context deadline timeouts across all OpenFGA client dispatchers and schema models.
globs: src/authz/**/*.ts, src/permissions/**/*.ts, src/fga/**/*.ts, src/lib/openfga/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-recursive-graph-evaluation-budget-guardrail-production-standard"
---

# OpenFGA Graph Evaluation Budget, Depth Limiting, and Cycle-Detection Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unconstrained recursive graph resolution and circular relation self-nesting without traversal ceilings or context timeouts.

## System Constraints
You are a Principal Security Architect specializing in Fine-Grained Authorization (ReBAC) and OpenFGA engine safety. You must mandate strict recursion depth limits, evaluation budget ceilings, memoized cycle-breaker sets, and non-negotiable context deadline propagation across all authorization query flows. Reject any OpenFGA queries, schema definitions, or custom resolvers that permit unbounded recursive relation expansion or omit deterministic timeout controls.

## Strict Guidelines
- Engineers MUST ALWAYS enforce an explicit execution budget using an AbortSignal with a strict deadline (<= 250ms for synchronous authz checks) when calling OpenFGA check, expand, or list-objects APIs.
- Engineers MUST NOT define self-referencing or mutually recursive schema relations (e.g., 'folder:parent' or 'group:member') without specifying bounded traversal guards or validating against circular tuple graphs at write time.
- Code MUST initialize OpenFGA clients with explicit maxRetries (<= 2), retryBackoffLimitMs, and deterministic circuit breakers to prevent thread exhaustion during engine backpressure.
- Services evaluating multi-hop or dynamic authorization paths MUST maintain an in-memory visited-node set (cycle breaker) and an explicit maxDepth limit (default: 5) to short-circuit cyclic paths.
- Tuple ingestion pipelines MUST validate that relationship tuples (e.g., parent_folder, nested_group) do not introduce directed cycles before committing tuples to the OpenFGA datastore.

## Bad vs Good Implementations
### Unbounded OpenFGA Check Execution vs. Bounded Deadline Evaluation with Traversal Budget

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The check call is completely unbounded. If the folder hierarchy contains a cycle or spans dozens of nested levels, OpenFGA engine workers will spin on graph resolution until connection timeouts trigger, consuming server-side goroutines and starving connection pools.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

const fga = new OpenFgaClient({
  apiUrl: process.env.FGA_API_URL!,
  storeId: process.env.FGA_STORE_ID!,
});

// ANTI-PATTERN: No timeout budget, no context cancellation, vulnerability to graph DoS
export async function canAccessFolder(userId: string, folderId: string): Promise<boolean> {
  const response = await fga.check({
    user: `user:${userId}`,
    relation: 'can_read',
    object: `folder:${folderId}`,
  });
  return response.allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: Enforces an explicit evaluation budget (250ms) using AbortController, binds client retry parameters to prevent storm cascades, and defensively fails closed with a budget-exceeded security alert upon deadline exhaustion.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

const fga = new OpenFgaClient({
  apiUrl: process.env.FGA_API_URL!,
  storeId: process.env.FGA_STORE_ID!,
  maxRetries: 2,
  retryParams: { maxRetryInterval: 100 },
});

const DEFAULT_AUTHZ_TIMEOUT_MS = 250;

// PRODUCTION INVARIANT: Bounded evaluation budget with deterministic deadline and abort signal
export async function canAccessFolder(
  userId: string,
  folderId: string,
  timeoutMs = DEFAULT_AUTHZ_TIMEOUT_MS
): Promise<boolean> {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), timeoutMs);

  const payload: ClientCheckRequest = {
    user: `user:${userId}`,
    relation: 'can_read',
    object: `folder:${folderId}`,
    contextualTuples: [],
  };

  try {
    const response = await fga.check(payload, {
      signal: controller.signal,
    });
    return Boolean(response.allowed);
  } catch (error: unknown) {
    if (error instanceof Error && error.name === 'AbortError') {
      throw new Error(`Authz evaluation budget exceeded (${timeoutMs}ms) for folder:${folderId}`);
    }
    throw error;
  } finally {
    clearTimeout(timer);
  }
}
```

### Cyclic Tuple Ingestion vs. Invariant Cycle-Breaker Pre-Validation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly writing hierarchical relations without ancestor cycle detection permits cycles (A -> B -> C -> A). When an OpenFGA query resolves transitive 'can_read' relations via 'parent', it triggers infinite loops or high-depth engine thread exhaustion.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

// ANTI-PATTERN: Direct tuple insertion allows circular parent-child graph cycles
export async function setParentFolder(fga: OpenFgaClient, childId: string, parentId: string) {
  await fga.writeTuples([{
    user: `folder:${parentId}`,
    relation: 'parent',
    object: `folder:${childId}`,
  }]);
}
```

#### Production Standard (Correct)
> **Standard**: Implements an explicit cycle-breaker guard and maximum hierarchy depth ceiling (10 levels) using a memoized visited-node set before persisting the relation, preventing cyclic graph vulnerabilities at the ingestion layer.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

const MAX_HIERARCHY_DEPTH = 10;

// PRODUCTION INVARIANT: Cycle-breaker validation and traversal depth ceiling prior to tuple persistence
export async function setParentFolder(
  fga: OpenFgaClient,
  childId: string,
  newParentId: string
): Promise<void> {
  if (childId === newParentId) {
    throw new Error('Self-referencing cycle detected: childId equals parentId');
  }

  // Check if child is an ancestor of newParentId to prevent circular graph creation
  let current: string | undefined = newParentId;
  const visited = new Set<string>([childId]);
  let depth = 0;

  while (current && depth < MAX_HIERARCHY_DEPTH) {
    visited.add(current);
    depth++;

    const res = await fga.read({
      object: `folder:${current}`,
      relation: 'parent',
    });

    const parentTuple = res.tuples?.[0];
    if (!parentTuple) break;

    const nextParentId = parentTuple.key.user.replace('folder:', '');
    if (visited.has(nextParentId)) {
      throw new Error(`Cycle detected or depth limit (${MAX_HIERARCHY_DEPTH}) reached in folder hierarchy`);
    }
    current = nextParentId;
  }

  await fga.write({
    writes: [{
      user: `folder:${newParentId}`,
      relation: 'parent',
      object: `folder:${childId}`,
    }],
  });
}
```

Recommended Agent Skills (askills.dev)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Graph Evaluation Budget, Depth Limiting, and Cycle-Detection Standard

OpenFGA Graph Evaluation Budget, Depth Limiting, and Cycle-Detection Standard defines an industrial-grade behavioral standard for security engineering. Unbounded recursive relation evaluation in fine-grained authorization (ReBAC) graphs induces algorithmic denial-of-service, goroutine/thread starvation, and cascading microservice failures. This standard mandates explicit evaluation budgets, hard relation traversal depth limits, visited-node cycle detection invariants, and deterministic context deadline timeouts across all OpenFGA client dispatchers and schema models. 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: Unconstrained recursive graph resolution and circular relation self-nesting without traversal ceilings or context timeouts. 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 DriftUnconstrained recursive graph resolution and circular relation self-nesting without traversal ceilings or context timeouts.Critical
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 enforce an explicit execution budget using an AbortSignal with a strict deadline (<= 250ms for synchronous authz checks) when calling OpenFGA check, expand, or list-objects APIs.

Engineers MUST ALWAYS enforce an explicit execution budget using an AbortSignal with a strict deadline (<= 250ms for synchronous authz checks) when calling OpenFGA check, expand, or list-objects APIs.

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 define self-referencing or mutually recursive schema relations (e.g., 'folder

Engineers MUST NOT define self-referencing or mutually recursive schema relations (e.g., 'folder:parent' or 'group:member') without specifying bounded traversal guards or validating against circular tuple graphs at write time.

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

Code MUST initialize OpenFGA clients with explicit maxRetries (<= 2), retryBackoffLimitMs, and deterministic circuit breakers to prevent thread exhaustion during engine backpressure.

Code MUST initialize OpenFGA clients with explicit maxRetries (<= 2), retryBackoffLimitMs, and deterministic circuit breakers to prevent thread exhaustion during engine backpressure.

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 evaluating multi-hop or dynamic authorization paths MUST maintain an in-memory visited-node set (cycle breaker) and an explicit maxDepth limit (default

Services evaluating multi-hop or dynamic authorization paths MUST maintain an in-memory visited-node set (cycle breaker) and an explicit maxDepth limit (default: 5) to short-circuit cyclic paths.

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

Tuple ingestion pipelines MUST validate that relationship tuples (e.g., parent_folder, nested_group) do not introduce directed cycles before committing tuples to the OpenFGA datastore.

Tuple ingestion pipelines MUST validate that relationship tuples (e.g., parent_folder, nested_group) do not introduce directed cycles before committing tuples to the OpenFGA datastore.

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 Graph Evaluation Budget, Depth Limiting, and Cycle-Detection Standard critical for AI coding assistants?

Unbounded recursive relation evaluation in fine-grained authorization (ReBAC) graphs induces algorithmic denial-of-service, goroutine/thread starvation, and cascading microservice failures. This standard mandates explicit evaluation budgets, hard relation traversal depth limits, visited-node cycle detection invariants, and deterministic context deadline timeouts across all OpenFGA client dispatchers and schema models. 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 (Unconstrained recursive graph resolution and circular relation self-nesting without traversal ceilings or context timeouts.) 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