This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-recursive-relation-depth-ceiling

OpenFGA Recursive Relation Evaluation Depth Ceiling and Cycle Guard

Enforces deterministic bounding on OpenFGA graph traversal depth and mandates cycle prevention in recursive authorization hierarchies. Failure to bound recursive evaluation allows adversarial or misconfigured nested groups to trigger catastrophic goroutine or memory exhaustion in multi-tenant authorization engines. Production environments must strictly configure engine-level resolution depth limits and intercept relationship creation to reject cyclic or excessive graph chains.

Prohibited Anti-Pattern: Unbounded recursive tuple resolution and unvalidated cyclic relationships leading to authorization engine denial-of-service

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Recursive Relation Evaluation Depth Ceiling and Cycle Guard - Enforces deterministic bounding on OpenFGA graph traversal depth and mandates cycle prevention in recursive authorization hierarchies. Failure to bound recursive evaluation allows adversarial or misconfigured nested groups to trigger catastrophic goroutine or memory exhaustion in multi-tenant authorization engines. Production environments must strictly configure engine-level resolution depth limits and intercept relationship creation to reject cyclic or excessive graph chains.
globs: src/**/authz/**/*.{ts,js,go}, src/**/openfga/**/*.{ts,js,go}, src/**/permissions/**/*.{ts,js,go}, **/*fga*.{json,yaml,dsl}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-recursive-relation-depth-ceiling"
---

# OpenFGA Recursive Relation Evaluation Depth Ceiling and Cycle Guard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded recursive tuple resolution and unvalidated cyclic relationships leading to authorization engine denial-of-service

## System Constraints
You are a Principal Security Architect enforcing hard computational boundaries on OpenFGA Fine-Grained Authorization engines. You must prevent recursive relation denial-of-service vulnerabilities across multi-tenant graph traversals. You will ensure that OpenFGA engine configuration limits max resolution depth, client-side writes implement cycle detection and path-length guards before issuing write assertions, and client evaluation requests enforce bounded context deadlines to guarantee sub-millisecond tail latencies.

## Strict Guidelines
- Engineers MUST ALWAYS configure OpenFGA engine instances with an explicit `--max-concurrent-reads-for-list-objects` and `--resolve-node-limit` (or client-side query depth ceiling <= 25 iterations) to prevent graph explosion.
- Engineers MUST NOT allow circular self-referential or ancestor-referential relationship tuples (e.g., group:A -> member -> group:B -> member -> group:A) to be persisted without prior cycle-detection validation.
- Code SHOULD enforce path-depth validation at the ingestion layer prior to executing OpenFGA `Write` operations, rejecting child-to-parent hierarchies exceeding the domain nesting budget (typically depth <= 5).
- Services MUST pass an explicit cancellation context or timeout (maximum 200ms for Check calls) to abort runaway graph resolutions before exhausting connection pools.
- Components NEVER execute raw unbounded recursive checks on dynamically constructed user relations without enforcing tenant-partitioned object namespaces.

## Bad vs Good Implementations
### Unbounded Relationship Tuple Ingestion vs Cycle-Guarded Depth-Capped Ingestion

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Writing nested group tuples without verifying transitive ancestry or maximum depth creates unbounded recursion or loops in OpenFGA evaluation, leading to server-side memory exhaustion and context timeouts.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

interface AddMemberRequest {
  groupId: string;
  memberGroupId: string;
}

export async function addNestedGroup(fgaClient: OpenFgaClient, req: AddMemberRequest): Promise<void> {
  // ANTI-PATTERN: Direct write without cycle check or depth limit allows cyclic graphs,
  // inducing goroutine explosion in OpenFGA Check/ListObjects evaluations.
  await fgaClient.write({
    writes: [
      {
        user: `group:${req.memberGroupId}`,
        relation: 'member',
        object: `group:${req.groupId}`
      }
    ]
  });
}
```

#### Production Standard (Correct)
> **Standard**: Enforces an immediate cycle-check traversal before tuple insertion with a strict 200ms evaluation deadline, preventing persistent authorization graphs from inducing engine-level resource exhaustion.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

interface AddMemberRequest {
  groupId: string;
  memberGroupId: string;
}

const MAX_HIERARCHY_DEPTH = 5;

export async function addNestedGroupGuarded(fgaClient: OpenFgaClient, req: AddMemberRequest): Promise<void> {
  if (req.groupId === req.memberGroupId) {
    throw new Error('Cyclic relationship rejected: direct self-reference');
  }

  // 1. Detect immediate cycle by checking if parent is already a member of child
  const cycleCheck: ClientCheckRequest = {
    user: `group:${req.groupId}`,
    relation: 'member',
    object: `group:${req.memberGroupId}`
  };

  const { allowed } = await fgaClient.check(cycleCheck, {
    // Bounded deadline to prevent engine freeze on existing deep graphs
    requestTimeout: 200
  });

  if (allowed) {
    throw new Error(`Cyclic relationship rejected: group:${req.groupId} is already a member of group:${req.memberGroupId}`);
  }

  // 2. Commit tuple only after cycle-free verification
  await fgaClient.write({
    writes: [
      {
        user: `group:${req.memberGroupId}`,
        relation: 'member',
        object: `group:${req.groupId}`
      }
    ]
  }, {
    requestTimeout: 500
  });
}
```

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 Recursive Relation Evaluation Depth Ceiling and Cycle Guard

OpenFGA Recursive Relation Evaluation Depth Ceiling and Cycle Guard defines an industrial-grade behavioral standard for security engineering. Enforces deterministic bounding on OpenFGA graph traversal depth and mandates cycle prevention in recursive authorization hierarchies. Failure to bound recursive evaluation allows adversarial or misconfigured nested groups to trigger catastrophic goroutine or memory exhaustion in multi-tenant authorization engines. Production environments must strictly configure engine-level resolution depth limits and intercept relationship creation to reject cyclic or excessive graph chains. 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 recursive tuple resolution and unvalidated cyclic relationships leading to authorization engine denial-of-service 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 recursive tuple resolution and unvalidated cyclic relationships leading to authorization engine denial-of-serviceCritical
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 configure OpenFGA engine instances with an explicit `--max-concurrent-reads-for-list-objects` and `--resolve-node-limit` (or client-side query depth ceiling <= 25 iterations) to prevent graph explosion.

Engineers MUST ALWAYS configure OpenFGA engine instances with an explicit `--max-concurrent-reads-for-list-objects` and `--resolve-node-limit` (or client-side query depth ceiling <= 25 iterations) to prevent graph explosion.

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 allow circular self-referential or ancestor-referential relationship tuples (e.g., group

Engineers MUST NOT allow circular self-referential or ancestor-referential relationship tuples (e.g., group:A -> member -> group:B -> member -> group:A) to be persisted without prior cycle-detection validation.

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 SHOULD enforce path-depth validation at the ingestion layer prior to executing OpenFGA `Write` operations, rejecting child-to-parent hierarchies exceeding the domain nesting budget (typically depth <= 5).

Code SHOULD enforce path-depth validation at the ingestion layer prior to executing OpenFGA `Write` operations, rejecting child-to-parent hierarchies exceeding the domain nesting budget (typically depth <= 5).

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 pass an explicit cancellation context or timeout (maximum 200ms for Check calls) to abort runaway graph resolutions before exhausting connection pools.

Services MUST pass an explicit cancellation context or timeout (maximum 200ms for Check calls) to abort runaway graph resolutions before exhausting connection pools.

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 execute raw unbounded recursive checks on dynamically constructed user relations without enforcing tenant-partitioned object namespaces.

Components NEVER execute raw unbounded recursive checks on dynamically constructed user relations without enforcing tenant-partitioned object namespaces.

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 Recursive Relation Evaluation Depth Ceiling and Cycle Guard critical for AI coding assistants?

Enforces deterministic bounding on OpenFGA graph traversal depth and mandates cycle prevention in recursive authorization hierarchies. Failure to bound recursive evaluation allows adversarial or misconfigured nested groups to trigger catastrophic goroutine or memory exhaustion in multi-tenant authorization engines. Production environments must strictly configure engine-level resolution depth limits and intercept relationship creation to reject cyclic or excessive graph chains. 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 recursive tuple resolution and unvalidated cyclic relationships leading to authorization engine denial-of-service) 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