This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: openfga-recursive-resolution-circuit-breaker-standard

OpenFGA Recursive Tuple Graph Resolution Depth and Latency Circuit-Breaker Standard

Enforces strict traversal depth limits, adaptive circuit breakers, and bounded deadlines on OpenFGA relationship-based access control (ReBAC) evaluations. Prevents catastrophic distributed deadlocks, thread pool exhaustion, and cascading database saturation triggered by cyclic or deeply nested relationship graphs during high-throughput authorization checks.

Prohibited Anti-Pattern: Unbounded ReBAC Graph Traversal Without Client Deadlines or Circuit Breakers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Recursive Tuple Graph Resolution Depth and Latency Circuit-Breaker Standard - Enforces strict traversal depth limits, adaptive circuit breakers, and bounded deadlines on OpenFGA relationship-based access control (ReBAC) evaluations. Prevents catastrophic distributed deadlocks, thread pool exhaustion, and cascading database saturation triggered by cyclic or deeply nested relationship graphs during high-throughput authorization checks.
globs: src/auth/**/*.{ts,js}, src/services/**/*.{ts,js}, src/security/**/*.{ts,js}, src/middleware/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-recursive-resolution-circuit-breaker-standard"
---

# OpenFGA Recursive Tuple Graph Resolution Depth and Latency Circuit-Breaker Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded ReBAC Graph Traversal Without Client Deadlines or Circuit Breakers

## System Constraints
You are a Principal Software Architect enforcing resilience standards for OpenFGA and ReBAC engines. You must prohibit naked, unbounded recursive authorization queries. You must ensure all authorization graph traversals execute with explicit deadline propagation (AbortSignal), strict graph resolution depth boundaries, robust circuit-breaker isolation, and deterministic fail-closed fallback behavior.

## Strict Guidelines
- Engineers MUST ALWAYS wrap OpenFGA client calls in an isolated circuit breaker with a tight consecutive-failure threshold and half-open probes.
- Engineers MUST ALWAYS enforce strict request deadlines using `AbortSignal.timeout()` or parent trace context deadlines (maximum 150ms for synchronous authorization path).
- Engineers MUST ALWAYS fail-closed (deny access) when OpenFGA checks encounter circuit trip, deadline exceedance, or depth limit exceptions.
- Code MUST NOT allow cyclic relationship resolution or unbounded nested group expansion without setting hard traversal depth limits.
- Services MUST emit standardized metrics (P99 latency, breaker state changes, traversal timeouts) on any degraded OpenFGA query.
- Components NEVER execute raw unbounded batch checks without partitioning and concurrency concurrency throttling.

## Bad vs Good Implementations
### Unbounded OpenFGA Check vs Circuit-Breaker Isolated Check with Deadlines

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: This implementation issues a check without client-side timeouts, traversal limits, or circuit breaking. If an enterprise user belongs to a circular or deeply nested group graph (e.g., 50+ recursive hops), the check can hang OpenFGA workers, trigger distributed lock contention, exhaust connection pools, and cascade failures into upstream API gateways.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// ANTI-PATTERN: Naked call without timeout, depth limit, or circuit breaker.
// Vulnerable to nested group cycles, thread pool exhaustion, and latency spikes.
export async function authorizeUser(userId: string, relation: string, objectId: string): Promise<boolean> {
  try {
    const response = await fgaClient.check({
      user: `user:${userId}`,
      relation,
      object: objectId,
    });
    return response.allowed ?? false;
  } catch (error) {
    // Anti-pattern: swallowed error or ambiguous boolean return without telemetry
    console.error('Auth error', error);
    return false;
  }
}
```

#### Production Standard (Correct)
> **Standard**: The production implementation establishes a robust defense-in-depth architecture: (1) wraps execution in an Opossum circuit breaker preventing cascading failures, (2) binds evaluation to a strict 150ms timeout using AbortSignal, (3) cleanly composes with parent trace signals, and (4) deterministically falls closed without leaking unhandled rejections or locking backend runtime resources.
```typescript
import { OpenFgaClient, ClientCheckOptions } from '@openfga/sdk';
import CircuitBreaker from 'opossum';

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

interface AuthCheckRequest {
  user: string;
  relation: string;
  object: string;
}

const MAX_AUTH_TIMEOUT_MS = 150;

// Wrap authorization calls in an isolated, fail-closed circuit breaker
const authCircuitBreaker = new CircuitBreaker(
  async (req: AuthCheckRequest, signal: AbortSignal): Promise<boolean> => {
    const options: ClientCheckOptions = {
      signal,
    };
    const response = await fgaClient.check({
      user: req.user,
      relation: req.relation,
      object: req.object,
    }, options);
    
    return Boolean(response.allowed);
  },
  {
    timeout: MAX_AUTH_TIMEOUT_MS,
    errorThresholdPercentage: 30,
    resetTimeout: 5000,
    name: 'openfga-rebac-breaker',
  }
);

// Deterministic fail-closed fallback for circuit trips and deadlocks
authCircuitBreaker.fallback(() => false);

export async function authorizeUser(
  userId: string,
  relation: string,
  objectId: string,
  parentSignal?: AbortSignal
): Promise<boolean> {
  const timeoutSignal = AbortSignal.timeout(MAX_AUTH_TIMEOUT_MS);
  const signal = parentSignal ? AbortSignal.any([parentSignal, timeoutSignal]) : timeoutSignal;

  const req: AuthCheckRequest = {
    user: `user:${userId}`,
    relation,
    object: objectId,
  };

  return await authCircuitBreaker.fire(req, signal);
}
```

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 Tuple Graph Resolution Depth and Latency Circuit-Breaker Standard

OpenFGA Recursive Tuple Graph Resolution Depth and Latency Circuit-Breaker Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict traversal depth limits, adaptive circuit breakers, and bounded deadlines on OpenFGA relationship-based access control (ReBAC) evaluations. Prevents catastrophic distributed deadlocks, thread pool exhaustion, and cascading database saturation triggered by cyclic or deeply nested relationship graphs during high-throughput authorization checks. 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 ReBAC Graph Traversal Without Client Deadlines or Circuit Breakers 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 ReBAC Graph Traversal Without Client Deadlines or Circuit BreakersCritical
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 wrap OpenFGA client calls in an isolated circuit breaker with a tight consecutive-failure threshold and half-open probes.

Engineers MUST ALWAYS wrap OpenFGA client calls in an isolated circuit breaker with a tight consecutive-failure threshold and half-open probes.

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 ALWAYS enforce strict request deadlines using `AbortSignal.timeout()` or parent trace context deadlines (maximum 150ms for synchronous authorization path).

Engineers MUST ALWAYS enforce strict request deadlines using `AbortSignal.timeout()` or parent trace context deadlines (maximum 150ms for synchronous authorization path).

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

Engineers MUST ALWAYS fail-closed (deny access) when OpenFGA checks encounter circuit trip, deadline exceedance, or depth limit exceptions.

Engineers MUST ALWAYS fail-closed (deny access) when OpenFGA checks encounter circuit trip, deadline exceedance, or depth limit exceptions.

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 MUST NOT allow cyclic relationship resolution or unbounded nested group expansion without setting hard traversal depth limits.

Code MUST NOT allow cyclic relationship resolution or unbounded nested group expansion without setting hard traversal depth limits.

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

Services MUST emit standardized metrics (P99 latency, breaker state changes, traversal timeouts) on any degraded OpenFGA query.

Services MUST emit standardized metrics (P99 latency, breaker state changes, traversal timeouts) on any degraded OpenFGA query.

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.
6

Components NEVER execute raw unbounded batch checks without partitioning and concurrency concurrency throttling.

Components NEVER execute raw unbounded batch checks without partitioning and concurrency concurrency throttling.

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 Tuple Graph Resolution Depth and Latency Circuit-Breaker Standard critical for AI coding assistants?

Enforces strict traversal depth limits, adaptive circuit breakers, and bounded deadlines on OpenFGA relationship-based access control (ReBAC) evaluations. Prevents catastrophic distributed deadlocks, thread pool exhaustion, and cascading database saturation triggered by cyclic or deeply nested relationship graphs during high-throughput authorization checks. 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 ReBAC Graph Traversal Without Client Deadlines or Circuit Breakers) 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