This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-cache-invalidation-cycle-boundary-standard

OpenFGA Consistency Boundary: Generation-Aware Invalidation and Bounded Graph Traversal

Enforces strict snapshot consistency tokens (Zookies/LST), atomic cache invalidation boundaries, and bounded cycle-pruning traversals during OpenFGA relationship-based access evaluations. Eliminates security windows where stale access grants persist post-revocation and prevents authorization engine denial-of-service from cyclic group-nesting graphs under concurrent mutations.

Prohibited Anti-Pattern: Unversioned In-Memory Tuple Caching with Unbounded Recursive Graph Traversal

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Consistency Boundary: Generation-Aware Invalidation and Bounded Graph Traversal - Enforces strict snapshot consistency tokens (Zookies/LST), atomic cache invalidation boundaries, and bounded cycle-pruning traversals during OpenFGA relationship-based access evaluations. Eliminates security windows where stale access grants persist post-revocation and prevents authorization engine denial-of-service from cyclic group-nesting graphs under concurrent mutations.
globs: src/auth/**/*.{ts,tsx}, src/services/fga/**/*.{ts,tsx}, src/security/**/*.{ts,tsx}, src/lib/authorization/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-cache-invalidation-cycle-boundary-standard"
---

# OpenFGA Consistency Boundary: Generation-Aware Invalidation and Bounded Graph Traversal

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unversioned In-Memory Tuple Caching with Unbounded Recursive Graph Traversal

## System Constraints
You are a Principal Software Architect enforcing enterprise-grade OpenFGA (Zanzibar-style ReBAC) invariants. You must mandate strict transactional read-after-write consistency tokens, generational cache invalidation barriers, and cycle-aware depth-bounded graph traversals across all authorization evaluation pipelines.

## Strict Guidelines
- Engineers MUST ALWAYS pass a monotonic consistency token (e.g., transactional log offset, write token, or model timestamp) to every OpenFGA check request to guarantee read-after-write consistency.
- Engineers MUST NOT rely solely on time-to-live (TTL) expiration for tuple caches; any tuple mutation MUST immediately invalidate cache segments or bump generation counters before returning write acknowledgment.
- Graph traversal engines MUST track an immutable visited path set of `(object_type:object_id#relation@user)` tuples during recursive evaluations to preemptively halt and prune cyclic references.
- Services MUST enforce a hard maximum traversal depth (e.g., `MAX_GRAPH_DEPTH = 25`) to prevent algorithmic complexity and stack exhaustion attacks via deeply nested relation structures.
- Components NEVER evaluate authorization queries using unversioned shared caches when the calling execution context involves recent mutation operations on identity, role, or team assignments.

## Bad vs Good Implementations
### Cache Invalidation and Cycle Detection in ReBAC Graph Evaluation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The naive implementation caches authorization results in an unversioned in-memory map without a snapshot consistency token, causing revoked permissions to remain active until process restart. Additionally, it ignores graph cycle detection, risking infinite traversal loops on cyclic group hierarchies and failing to respect concurrent mutations.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

const localTupleCache = new Map<string, boolean>();

// VULNERABILITY 1: Unversioned cache key prone to stale read windows post-revocation
// VULNERABILITY 2: Unbounded recursive check vulnerable to infinite cycles (e.g. Group A -> Group B -> Group A)
export async function checkAccessNaive(
  fga: OpenFgaClient,
  user: string,
  relation: string,
  object: string
): Promise<boolean> {
  const cacheKey = `${user}#${relation}@${object}`;
  if (localTupleCache.has(cacheKey)) {
    return localTupleCache.get(cacheKey)!;
  }

  // Naive direct check without consistency token
  const response = await fga.check({
    tuple_key: { user, relation, object }
  });

  const allowed = response.allowed ?? false;
  localTupleCache.set(cacheKey, allowed); // Leaks stale access indefinitely
  return allowed;
}
```

#### Production Standard (Correct)
> **Standard**: The hardened evaluator scopes cache entries to an immutable consistency token, preventing cross-transaction cache poisoning and stale reads after tuple mutations. It detects and terminates cyclic relationships via an immutable visited set and enforces a strict maximum depth threshold to prevent stack and query exhaustion.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

export interface EvaluationContext {
  readonly consistencyToken: string;
  readonly visitedNodes: ReadonlySet<string>;
  readonly currentDepth: number;
}

export class CycleDetectedError extends Error {
  constructor(node: string) {
    super(`Cycle detected in relation graph at node: ${node}`);
    this.name = 'CycleDetectedError';
  }
}

export class MaxDepthExceededError extends Error {
  constructor(depth: number) {
    super(`Max traversal depth exceeded: ${depth}`);
    this.name = 'MaxDepthExceededError';
  }
}

const MAX_ALLOWED_GRAPH_DEPTH = 25;

export class ConsistentRebacEvaluator {
  constructor(
    private readonly fgaClient: OpenFgaClient,
    private readonly cacheStore: {
      get: (key: string) => Promise<boolean | null>;
      set: (key: string, val: boolean, ttlSec: number) => Promise<void>;
    }
  ) {}

  public async checkConsistentAccess(
    tuple: ClientCheckRequest['tuple_key'],
    context: EvaluationContext
  ): Promise<boolean> {
    if (context.currentDepth > MAX_ALLOWED_GRAPH_DEPTH) {
      throw new MaxDepthExceededError(context.currentDepth);
    }

    const nodeSignature = `${tuple.user}#${tuple.relation}@${tuple.object}`;
    if (context.visitedNodes.has(nodeSignature)) {
      // Graph cycle detected: fail closed to prevent infinite recursion
      throw new CycleDetectedError(nodeSignature);
    }

    // Invariant: Generation-bound cache key incorporating the transactional consistency token
    const scopedCacheKey = `fga:${context.consistencyToken}:${nodeSignature}`;
    const cachedResult = await this.cacheStore.get(scopedCacheKey);
    if (cachedResult !== null) {
      return cachedResult;
    }

    const updatedVisited = new Set(context.visitedNodes).add(nodeSignature);

    const { allowed } = await this.fgaClient.check(
      {
        tuple_key: tuple,
        context: { consistency_token: context.consistencyToken }
      },
      {
        // Force strict consistency parameter when token is present
        headers: { 'X-OpenFGA-Consistency-Token': context.consistencyToken }
      }
    );

    const decision = allowed ?? false;
    // Short-lived deterministic memoization scoped to consistency token
    await this.cacheStore.set(scopedCacheKey, decision, 30);

    return decision;
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Consistency Boundary: Generation-Aware Invalidation and Bounded Graph Traversal

OpenFGA Consistency Boundary: Generation-Aware Invalidation and Bounded Graph Traversal defines an industrial-grade behavioral standard for security engineering. Enforces strict snapshot consistency tokens (Zookies/LST), atomic cache invalidation boundaries, and bounded cycle-pruning traversals during OpenFGA relationship-based access evaluations. Eliminates security windows where stale access grants persist post-revocation and prevents authorization engine denial-of-service from cyclic group-nesting graphs under concurrent mutations. 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: Unversioned In-Memory Tuple Caching with Unbounded Recursive Graph Traversal 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 DriftUnversioned In-Memory Tuple Caching with Unbounded Recursive Graph TraversalCritical
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 monotonic consistency token (e.g., transactional log offset, write token, or model timestamp) to every OpenFGA check request to guarantee read-after-write consistency.

Engineers MUST ALWAYS pass a monotonic consistency token (e.g., transactional log offset, write token, or model timestamp) to every OpenFGA check request to guarantee read-after-write consistency.

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 rely solely on time-to-live (TTL) expiration for tuple caches

Engineers MUST NOT rely solely on time-to-live (TTL) expiration for tuple caches; any tuple mutation MUST immediately invalidate cache segments or bump generation counters before returning write acknowledgment.

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

Graph traversal engines MUST track an immutable visited path set of `(object_type

Graph traversal engines MUST track an immutable visited path set of `(object_type:object_id#relation@user)` tuples during recursive evaluations to preemptively halt and prune cyclic references.

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 enforce a hard maximum traversal depth (e.g., `MAX_GRAPH_DEPTH = 25`) to prevent algorithmic complexity and stack exhaustion attacks via deeply nested relation structures.

Services MUST enforce a hard maximum traversal depth (e.g., `MAX_GRAPH_DEPTH = 25`) to prevent algorithmic complexity and stack exhaustion attacks via deeply nested relation structures.

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 evaluate authorization queries using unversioned shared caches when the calling execution context involves recent mutation operations on identity, role, or team assignments.

Components NEVER evaluate authorization queries using unversioned shared caches when the calling execution context involves recent mutation operations on identity, role, or team assignments.

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 Consistency Boundary: Generation-Aware Invalidation and Bounded Graph Traversal critical for AI coding assistants?

Enforces strict snapshot consistency tokens (Zookies/LST), atomic cache invalidation boundaries, and bounded cycle-pruning traversals during OpenFGA relationship-based access evaluations. Eliminates security windows where stale access grants persist post-revocation and prevents authorization engine denial-of-service from cyclic group-nesting graphs under concurrent mutations. 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 (Unversioned In-Memory Tuple Caching with Unbounded Recursive Graph Traversal) 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