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

OpenFGA Distributed ReBAC Subgraph Traversal Latency Budget Guardrail

Enforces deterministic depth limits and strict sub-5ms p99 cache-aside memoization policies for recursive OpenFGA relationship-based access control (ReBAC) evaluations across microservices. Prevents unbounded graph traversals, circular reference latency spikes, and downstream connection pool exhaustion by requiring contextual multi-tier caching (in-memory L1 LRU + Redis L2) and strict per-request evaluation deadlines.

Prohibited Anti-Pattern: Unbounded Recursive ReBAC Subgraph Traversal Without Memoization or Latency Budgets

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Distributed ReBAC Subgraph Traversal Latency Budget Guardrail - Enforces deterministic depth limits and strict sub-5ms p99 cache-aside memoization policies for recursive OpenFGA relationship-based access control (ReBAC) evaluations across microservices. Prevents unbounded graph traversals, circular reference latency spikes, and downstream connection pool exhaustion by requiring contextual multi-tier caching (in-memory L1 LRU + Redis L2) and strict per-request evaluation deadlines.
globs: src/auth/**/*.ts, src/authorization/**/*.ts, src/services/fga/**/*.ts, src/middlewares/auth*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-rebac-subgraph-traversal-latency-budget-guardrail"
---

# OpenFGA Distributed ReBAC Subgraph Traversal Latency Budget Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Recursive ReBAC Subgraph Traversal Without Memoization or Latency Budgets

## System Constraints
You are a Principal Backend and Security Architect enforcing deterministic latency budgets and depth-bound execution for OpenFGA ReBAC graph traversals. Mandate that every authorization check evaluates against an explicit contextual deadline, enforces an upper bound on traversal depth, and integrates a dual-tier memoization strategy (L1 process cache, L2 Redis) to maintain sub-5ms p99 response times while avoiding cold-path downstream thundering herds.

## Strict Guidelines
- Engineers MUST ALWAYS pass a bounded contextual deadline (timeout <= 15ms total, with sub-5ms target p99) and an explicit AbortSignal to OpenFGA Check and Expand calls.
- Engineers MUST implement a two-tier memoization layer (local in-memory LRU with max 60s TTL as L1, distributed Redis with max 300s TTL as L2) keyed deterministically by canonical tuple representations (user, relation, object, contextual_tuples hash).
- Engineers MUST NOT issue unmemoized OpenFGA checks within hot-path request loops or unbounded nested middleware filters.
- Engineers MUST configure and validate OpenFGA authorization model depth limits (max_traversal_depth <= 15) to prevent recursive loop amplification during indirect membership evaluations.
- Services MUST log OpenFGA evaluation latency histograms and emit tracing spans detailing cache hit/miss status and subgraph traversal resolution times.
- Components NEVER execute raw unbounded OpenFGA Expand or ListObjects APIs synchronously in critical paths without pagination and depth boundaries.

## Bad vs Good Implementations
### Unbounded Direct FGA Check vs. Budgeted Memoized Traversal

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: This implementation issues raw RPC calls directly to the OpenFga server for every authorization check without caching or timeout budgets. In deep organizational or group hierarchies, recursive subgraph traversal creates latency spikes (>100ms), depletes connection pools, and exposes the service to cascading failures.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// Anti-pattern: No timeout, no memoization, no depth control, direct call in critical path
export async function authorizeUser(userId: string, relation: string, documentId: string): Promise<boolean> {
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation,
    object: `document:${documentId}`,
  });
  return response.allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: Implements an industrial-grade dual-tier cache (L1 in-memory + L2 Redis) with a deterministic SHA-256 cache key. Restricts execution to a strict 15ms timeout budget using AbortController, ensuring p99 latency stays under sub-5ms targets for cached hits and fails fast under adverse network conditions.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { LRUCache } from 'lru-cache';
import Redis from 'ioredis';
import { createHash } from 'node:crypto';

interface FgaCheckParams {
  userId: string;
  relation: string;
  documentId: string;
}

const l1Cache = new LRUCache<string, boolean>({ max: 50000, ttl: 1000 * 30 }); // 30s local TTL
const l2Redis = new Redis(process.env.REDIS_URL!);
const fgaClient = new OpenFgaClient({
  apiUrl: process.env.FGA_API_URL,
  storeId: process.env.FGA_STORE_ID,
});

const MAX_CHECK_TIMEOUT_MS = 15;

function computeCacheKey(user: string, relation: string, object: string): string {
  return `fga:${createHash('sha256').update(`${user}|${relation}|${object}`).digest('hex')}`;
}

export async function authorizeUser(
  userId: string,
  relation: string,
  documentId: string,
  parentSignal?: AbortSignal
): Promise<boolean> {
  const user = `user:${userId}`;
  const object = `document:${documentId}`;
  const cacheKey = computeCacheKey(user, relation, object);

  // Check L1 Process Memory
  const cachedL1 = l1Cache.get(cacheKey);
  if (cachedL1 !== undefined) return cachedL1;

  // Check L2 Redis with soft fallback
  try {
    const cachedL2 = await l2Redis.get(cacheKey);
    if (cachedL2 !== null) {
      const allowed = cachedL2 === '1';
      l1Cache.set(cacheKey, allowed);
      return allowed;
    }
  } catch (err) {
    // Non-blocking L2 cache error: continue to FGA
  }

  // Enforce strict latency budget on OpenFGA RPC
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), MAX_CHECK_TIMEOUT_MS);
  if (parentSignal) parentSignal.addEventListener('abort', () => controller.abort(), { once: true });

  try {
    const response = await fgaClient.check(
      {
        user,
        relation,
        object,
      },
      { signal: controller.signal }
    );

    const allowed = response.allowed ?? false;

    // Populate caches asynchronously
    l1Cache.set(cacheKey, allowed);
    l2Redis.setex(cacheKey, 120, allowed ? '1' : '0').catch(() => {});

    return allowed;
  } catch (error) {
    if (controller.signal.aborted) {
      throw new Error(`OpenFGA check exceeded latency budget of ${MAX_CHECK_TIMEOUT_MS}ms`);
    }
    throw error;
  } finally {
    clearTimeout(timeoutId);
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Distributed ReBAC Subgraph Traversal Latency Budget Guardrail

OpenFGA Distributed ReBAC Subgraph Traversal Latency Budget Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic depth limits and strict sub-5ms p99 cache-aside memoization policies for recursive OpenFGA relationship-based access control (ReBAC) evaluations across microservices. Prevents unbounded graph traversals, circular reference latency spikes, and downstream connection pool exhaustion by requiring contextual multi-tier caching (in-memory L1 LRU + Redis L2) and strict per-request evaluation deadlines. 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 ReBAC Subgraph Traversal Without Memoization or Latency Budgets 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 ReBAC Subgraph Traversal Without Memoization or Latency BudgetsCritical
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 pass a bounded contextual deadline (timeout <= 15ms total, with sub-5ms target p99) and an explicit AbortSignal to OpenFGA Check and Expand calls.

Engineers MUST ALWAYS pass a bounded contextual deadline (timeout <= 15ms total, with sub-5ms target p99) and an explicit AbortSignal to OpenFGA Check and Expand calls.

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 implement a two-tier memoization layer (local in-memory LRU with max 60s TTL as L1, distributed Redis with max 300s TTL as L2) keyed deterministically by canonical tuple representations (user, relation, object, contextual_tuples hash).

Engineers MUST implement a two-tier memoization layer (local in-memory LRU with max 60s TTL as L1, distributed Redis with max 300s TTL as L2) keyed deterministically by canonical tuple representations (user, relation, object, contextual_tuples hash).

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 NOT issue unmemoized OpenFGA checks within hot-path request loops or unbounded nested middleware filters.

Engineers MUST NOT issue unmemoized OpenFGA checks within hot-path request loops or unbounded nested middleware filters.

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

Engineers MUST configure and validate OpenFGA authorization model depth limits (max_traversal_depth <= 15) to prevent recursive loop amplification during indirect membership evaluations.

Engineers MUST configure and validate OpenFGA authorization model depth limits (max_traversal_depth <= 15) to prevent recursive loop amplification during indirect membership evaluations.

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 log OpenFGA evaluation latency histograms and emit tracing spans detailing cache hit/miss status and subgraph traversal resolution times.

Services MUST log OpenFGA evaluation latency histograms and emit tracing spans detailing cache hit/miss status and subgraph traversal resolution times.

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 OpenFGA Expand or ListObjects APIs synchronously in critical paths without pagination and depth boundaries.

Components NEVER execute raw unbounded OpenFGA Expand or ListObjects APIs synchronously in critical paths without pagination and depth boundaries.

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 Distributed ReBAC Subgraph Traversal Latency Budget Guardrail critical for AI coding assistants?

Enforces deterministic depth limits and strict sub-5ms p99 cache-aside memoization policies for recursive OpenFGA relationship-based access control (ReBAC) evaluations across microservices. Prevents unbounded graph traversals, circular reference latency spikes, and downstream connection pool exhaustion by requiring contextual multi-tier caching (in-memory L1 LRU + Redis L2) and strict per-request evaluation deadlines. 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 ReBAC Subgraph Traversal Without Memoization or Latency Budgets) 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