This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: openfga-contextual-tuple-bound-latency-guardrail

OpenFGA 1.6 Contextual Tuple Bounding & Recursion Depth Guardrail

Enforces strict cardinality constraints on dynamic contextual tuples and sets explicit evaluation depth limits during OpenFGA authorization checks. Prevents combinatorial graph expansion and tail-latency degradation across high-cardinality Zanzibar relationship graphs by mandating fail-fast validation, chunked batch evaluation, and client-side deadline propagation.

Prohibited Anti-Pattern: Unbounded Contextual Tuple Injection Causing High-Cardinality Zanzibar Traversal Storms

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA 1.6 Contextual Tuple Bounding & Recursion Depth Guardrail - Enforces strict cardinality constraints on dynamic contextual tuples and sets explicit evaluation depth limits during OpenFGA authorization checks. Prevents combinatorial graph expansion and tail-latency degradation across high-cardinality Zanzibar relationship graphs by mandating fail-fast validation, chunked batch evaluation, and client-side deadline propagation.
globs: src/auth/**/*.{ts,js}, src/security/**/*.{ts,js}, src/middleware/**/*.{ts,js}, src/services/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-bound-latency-guardrail"
---

# OpenFGA 1.6 Contextual Tuple Bounding & Recursion Depth Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Contextual Tuple Injection Causing High-Cardinality Zanzibar Traversal Storms

## System Constraints
You are a Principal Software Architect enforcing OpenFGA 1.6 Distributed ReBAC Contextual Tuple Bound invariants. You must reject any authorization logic that passes unbounded, dynamic contextual tuples to OpenFGA Check or BatchCheck calls without strict cardinality limits, schema validation, and context deadline propagation. Mandate deterministic graph traversal bounds to prevent engine thread exhaustion and latency spikes.

## Strict Guidelines
- Engineers MUST ALWAYS enforce a hard ceiling (e.g., maximum 20 tuples) on dynamic `contextual_tuples` before passing them to the OpenFGA client.
- Engineers MUST NOT map raw request payloads, dynamic user lists, or unvalidated multi-tenant claims directly into contextual tuples without pre-validating cardinality and format.
- Code SHOULD enforce strict per-request client timeouts (<= 150ms) using abort controllers or context deadlines to terminate runaway recursive graph resolutions.
- Services MUST prefer persistent relation tuples in OpenFGA storage over large contextual tuple arrays when modeling structural relations like groups, roles, and folder hierarchies.
- Components NEVER execute unbounded parallel `fgaClient.check` calls with heterogeneous contextual tuples; engineers MUST partition requests using deterministic batching with bounded concurrency.

## Bad vs Good Implementations
### Unbounded Contextual Tuple Pass-Through vs. Strictly Bounded ReBAC Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing arbitrary, client-controlled dynamic arrays directly into contextualTuples bypasses graph traversal safety. An array with 50+ items can trigger exponential recursive graph checks across Zanzibar relation trees, exhausting memory and causing p99 latencies to skyrocket.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

export async function authorizeUser(
  userId: string,
  objectId: string,
  relation: string,
  dynamicAttributes: Array<{ user: string; relation: string; object: string }>
): Promise<boolean> {
  // ANTI-PATTERN: Dynamic tuples directly injected without validation or size limits.
  // A high-cardinality array causes OpenFGA engine goroutine explosion and tail-latency spikes.
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation,
    object: `document:${objectId}`,
    contextualTuples: dynamicAttributes,
  });

  return response.allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: Enforces a strict upper bound on contextual tuples (max 16) and encapsulates the check within an AbortController with a 150ms deadline. This protects the distributed OpenFGA cluster from graph explosion, eliminates tail latency spikes, and ensures predictable response times.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

const MAX_CONTEXTUAL_TUPLES = 16;
const CHECK_TIMEOUT_MS = 150;

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

export interface ContextTuple {
  user: `user:${string}` | `role:${string}`;
  relation: string;
  object: string;
}

export async function authorizeUserBounded(
  userId: string,
  objectId: string,
  relation: string,
  contextTuples: ContextTuple[]
): Promise<boolean> {
  // GUARD: Enforce maximum bounded cardinality before invoking OpenFGA engine
  if (contextTuples.length > MAX_CONTEXTUAL_TUPLES) {
    throw new Error(
      `Contextual tuple limit exceeded: got ${contextTuples.length}, max allowed is ${MAX_CONTEXTUAL_TUPLES}`
    );
  }

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

  try {
    const payload: ClientCheckRequest = {
      user: `user:${userId}`,
      relation,
      object: `document:${objectId}`,
      contextualTuples: contextTuples,
    };

    const response = await fgaClient.check(payload, {
      signal: controller.signal,
    });

    return response.allowed ?? false;
  } catch (error: unknown) {
    if (error instanceof Error && error.name === 'AbortError') {
      throw new Error(`OpenFGA authorization evaluation timed out after ${CHECK_TIMEOUT_MS}ms`);
    }
    throw error;
  } 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 1.6 Contextual Tuple Bounding & Recursion Depth Guardrail

OpenFGA 1.6 Contextual Tuple Bounding & Recursion Depth Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict cardinality constraints on dynamic contextual tuples and sets explicit evaluation depth limits during OpenFGA authorization checks. Prevents combinatorial graph expansion and tail-latency degradation across high-cardinality Zanzibar relationship graphs by mandating fail-fast validation, chunked batch evaluation, and client-side deadline propagation. 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 Contextual Tuple Injection Causing High-Cardinality Zanzibar Traversal Storms 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 Contextual Tuple Injection Causing High-Cardinality Zanzibar Traversal StormsCritical
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 a hard ceiling (e.g., maximum 20 tuples) on dynamic `contextual_tuples` before passing them to the OpenFGA client.

Engineers MUST ALWAYS enforce a hard ceiling (e.g., maximum 20 tuples) on dynamic `contextual_tuples` before passing them to the OpenFGA client.

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 map raw request payloads, dynamic user lists, or unvalidated multi-tenant claims directly into contextual tuples without pre-validating cardinality and format.

Engineers MUST NOT map raw request payloads, dynamic user lists, or unvalidated multi-tenant claims directly into contextual tuples without pre-validating cardinality and format.

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 strict per-request client timeouts (<= 150ms) using abort controllers or context deadlines to terminate runaway recursive graph resolutions.

Code SHOULD enforce strict per-request client timeouts (<= 150ms) using abort controllers or context deadlines to terminate runaway recursive graph resolutions.

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 prefer persistent relation tuples in OpenFGA storage over large contextual tuple arrays when modeling structural relations like groups, roles, and folder hierarchies.

Services MUST prefer persistent relation tuples in OpenFGA storage over large contextual tuple arrays when modeling structural relations like groups, roles, and folder hierarchies.

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 unbounded parallel `fgaClient.check` calls with heterogeneous contextual tuples

Components NEVER execute unbounded parallel `fgaClient.check` calls with heterogeneous contextual tuples; engineers MUST partition requests using deterministic batching with bounded concurrency.

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 1.6 Contextual Tuple Bounding & Recursion Depth Guardrail critical for AI coding assistants?

Enforces strict cardinality constraints on dynamic contextual tuples and sets explicit evaluation depth limits during OpenFGA authorization checks. Prevents combinatorial graph expansion and tail-latency degradation across high-cardinality Zanzibar relationship graphs by mandating fail-fast validation, chunked batch evaluation, and client-side deadline propagation. 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 Contextual Tuple Injection Causing High-Cardinality Zanzibar Traversal Storms) 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