This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-contextual-traversal-budgeting-standard

OpenFGA Graph Traversal Budgeting and Deadlock Prevention Standard

Enforces strict upper bounds on OpenFGA graph expansion depth, query budgets, and contextual tuple payloads during real-time authorization checks. Eliminates recursive relationship exhaustion and cascading distributed database deadlocks across high-throughput check pipelines by mandating deterministic timeouts, concurrency bounding, and pre-evaluated contextual assertions.

Prohibited Anti-Pattern: Unbounded Recursive Evaluation and Massive Contextual Tuple Injection Inducing Database Lock Contention

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Graph Traversal Budgeting and Deadlock Prevention Standard - Enforces strict upper bounds on OpenFGA graph expansion depth, query budgets, and contextual tuple payloads during real-time authorization checks. Eliminates recursive relationship exhaustion and cascading distributed database deadlocks across high-throughput check pipelines by mandating deterministic timeouts, concurrency bounding, and pre-evaluated contextual assertions.
globs: src/**/auth/**/*.{ts,tsx}, src/**/guards/**/*.{ts,tsx}, src/**/fga/**/*.{ts,tsx}, src/**/middleware/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-traversal-budgeting-standard"
---

# OpenFGA Graph Traversal Budgeting and Deadlock Prevention Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded Recursive Evaluation and Massive Contextual Tuple Injection Inducing Database Lock Contention

## System Constraints
You are a Principal Engineer enforcing the OpenFGA Real-Time Contextual Tuple Graph Traversal Budgeting Standard. Mandate deterministic graph traversal limits, strict context payload validation, and non-blocking sub-millisecond resolution paths. Never allow unbounded contextual expansion, arbitrary recursive depth, or raw transaction wrappers around OpenFGA resolution queries.

## Strict Guidelines
- Engineers MUST ALWAYS enforce explicit request-scoped deadlines and OpenFGA client-side resolution timeouts not exceeding 150ms.
- Engineers MUST NOT pass dynamic, unbounded arrays of contextual tuples directly into the OpenFGA Check API without validating length and uniqueness (MAX_TUPLES <= 20).
- Code SHOULD pre-resolve transitive dynamic context locally via bounded bitmaps or cached parent references when traversal depth exceeds configured limits.
- Services MUST configure OpenFGA Check requests with an explicit max_results and bound graph expansion depth to avoid cycle-amplified relational fan-out.
- Components NEVER hold open an active relational database transaction or row-level lock while awaiting the resolution of an asynchronous OpenFGA Check call.

## Bad vs Good Implementations
### Unbounded Contextual Tuples and Inline DB Lock vs. Bounded Check with Out-of-Band Context

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Holding a distributed or relational lock across a remote FGA Check RPC causes cascading connection pool exhaustion and deadlocks. Passing arbitrary dynamicContext tuples without size validation risks recursive graph expansion and excessive traversal latency.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { db } from './db';

export async function authorizeUserAction(fga: OpenFgaClient, userId: string, documentId: string, dynamicContext: any[]) {
  // ANTI-PATTERN: Open DB transaction and hold lock across network call
  return await db.transaction(async (tx) => {
    await tx.query('SELECT * FROM documents WHERE id = $1 FOR UPDATE', [documentId]);
    
    // ANTI-PATTERN: Injecting arbitrary dynamicContext tuples without size checks or timeouts
    const response = await fga.check({
      user: `user:${userId}`,
      relation: 'viewer',
      object: `document:${documentId}`,
      contextualTuples: dynamicContext.map((c) => ({
        user: c.user,
        relation: c.relation,
        object: c.object
      }))
    });
    
    return response.allowed;
  });
}
```

#### Production Standard (Correct)
> **Standard**: Validates and caps contextual tuples to avoid deep graph traversal spikes, enforces a strict timeout budget using AbortController, and isolates authorization resolution from relational database transactions to prevent cascading lock deadlocks.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

const MAX_ALLOWED_CONTEXT_TUPLES = 10;
const CHECK_TIMEOUT_MS = 150;

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

export async function authorizeUserAction(
  fga: OpenFgaClient,
  userId: string,
  documentId: string,
  dynamicContext: SafeContextTuple[]
): Promise<boolean> {
  // GUARDS: Validate context payload upper bound to prevent traversal expansion explosion
  if (dynamicContext.length > MAX_ALLOWED_CONTEXT_TUPLES) {
    throw new Error(`Context tuple budget exceeded: maximum ${MAX_ALLOWED_CONTEXT_TUPLES} allowed.`);
  }

  const checkRequest: ClientCheckRequest = {
    user: `user:${userId}`,
    relation: 'viewer',
    object: `document:${documentId}`,
    contextualTuples: dynamicContext
  };

  // INVARIANT: Execute check outside of transactional locks with strict timeout signal
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), CHECK_TIMEOUT_MS);

  try {
    const response = await fga.check(checkRequest, {
      signal: controller.signal
    });
    return Boolean(response.allowed);
  } catch (err: unknown) {
    if (err instanceof Error && err.name === 'AbortError') {
      throw new Error(`OpenFGA Check exceeded latency budget of ${CHECK_TIMEOUT_MS}ms.`);
    }
    throw err;
  } finally {
    clearTimeout(timer);
  }
}
```

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 Graph Traversal Budgeting and Deadlock Prevention Standard

OpenFGA Graph Traversal Budgeting and Deadlock Prevention Standard defines an industrial-grade behavioral standard for security engineering. Enforces strict upper bounds on OpenFGA graph expansion depth, query budgets, and contextual tuple payloads during real-time authorization checks. Eliminates recursive relationship exhaustion and cascading distributed database deadlocks across high-throughput check pipelines by mandating deterministic timeouts, concurrency bounding, and pre-evaluated contextual assertions. 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 Evaluation and Massive Contextual Tuple Injection Inducing Database Lock Contention 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 Evaluation and Massive Contextual Tuple Injection Inducing Database Lock ContentionCritical
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 explicit request-scoped deadlines and OpenFGA client-side resolution timeouts not exceeding 150ms.

Engineers MUST ALWAYS enforce explicit request-scoped deadlines and OpenFGA client-side resolution timeouts not exceeding 150ms.

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 pass dynamic, unbounded arrays of contextual tuples directly into the OpenFGA Check API without validating length and uniqueness (MAX_TUPLES <= 20).

Engineers MUST NOT pass dynamic, unbounded arrays of contextual tuples directly into the OpenFGA Check API without validating length and uniqueness (MAX_TUPLES <= 20).

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 pre-resolve transitive dynamic context locally via bounded bitmaps or cached parent references when traversal depth exceeds configured limits.

Code SHOULD pre-resolve transitive dynamic context locally via bounded bitmaps or cached parent references when traversal depth exceeds configured 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.
4

Services MUST configure OpenFGA Check requests with an explicit max_results and bound graph expansion depth to avoid cycle-amplified relational fan-out.

Services MUST configure OpenFGA Check requests with an explicit max_results and bound graph expansion depth to avoid cycle-amplified relational fan-out.

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 hold open an active relational database transaction or row-level lock while awaiting the resolution of an asynchronous OpenFGA Check call.

Components NEVER hold open an active relational database transaction or row-level lock while awaiting the resolution of an asynchronous OpenFGA Check call.

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 Traversal Budgeting and Deadlock Prevention Standard critical for AI coding assistants?

Enforces strict upper bounds on OpenFGA graph expansion depth, query budgets, and contextual tuple payloads during real-time authorization checks. Eliminates recursive relationship exhaustion and cascading distributed database deadlocks across high-throughput check pipelines by mandating deterministic timeouts, concurrency bounding, and pre-evaluated contextual assertions. 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 Evaluation and Massive Contextual Tuple Injection Inducing Database Lock Contention) 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