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

Bounded Graph Traversal Depth and Contextual Cache Invalidation for OpenFGA Zanzibar

Enforces strict limits on authorization graph traversal depth, mandatory context timeouts, and atomic contextual cache invalidation in OpenFGA Zanzibar implementations. Deeply nested group-of-groups hierarchies and transitive relationship queries can trigger catastrophic cascade latencies, resource exhaustion, and stale authorization decisions without bound resolution parameters. All check operations must configure explicit query depth limits, propagate distributed trace deadlines, and use deterministic tuple-versioned cache eviction keys.

Prohibited Anti-Pattern: Unbounded Recursive Traversal and Uncoordinated In-Memory Caching in Authorization Checks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bounded Graph Traversal Depth and Contextual Cache Invalidation for OpenFGA Zanzibar - Enforces strict limits on authorization graph traversal depth, mandatory context timeouts, and atomic contextual cache invalidation in OpenFGA Zanzibar implementations. Deeply nested group-of-groups hierarchies and transitive relationship queries can trigger catastrophic cascade latencies, resource exhaustion, and stale authorization decisions without bound resolution parameters. All check operations must configure explicit query depth limits, propagate distributed trace deadlines, and use deterministic tuple-versioned cache eviction keys.
globs: src/auth/**/*.{ts,js}, src/services/**/*.{ts,js}, src/middleware/**/*.{ts,js}, src/lib/openfga/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-zanzibar-traversal-cache-guardrails"
---

# Bounded Graph Traversal Depth and Contextual Cache Invalidation for OpenFGA Zanzibar

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded Recursive Traversal and Uncoordinated In-Memory Caching in Authorization Checks

## System Constraints
You are a Principal Security Architect enforcing OpenFGA/Zanzibar Relationship-Based Access Control (ReBAC) evaluation guardrails. You must mandate bounded evaluation depth, non-blocking check timeouts, and atomic cache invalidation tied to write-time changelogs. Never permit unmetered recursive relation expansions or naive unbounded TTL-based caching across distributed authorization models.

## Strict Guidelines
- Engineers MUST ALWAYS supply an explicit contextual timeout (maximum 200ms recommended for interactive requests) and enforce an upper bound for OpenFGA evaluation depth via client configuration or max-depth constraints.
- Engineers MUST NOT execute check operations with unbounded relational models where nested groups or transitive relations can form self-referential cycles without depth termination.
- Code SHOULD propagate a distributed tracing context (such as W3C traceparent headers) into OpenFGA Check and Expand calls to expose authorization evaluation graph latencies across sub-queries.
- Services MUST evict or invalidate downstream authorization decision caches atomically upon successful OpenFGA Write/Delete tuple operations, leveraging transactional outbox patterns or OpenFGA ReadChanges changelogs.
- Components NEVER execute raw bulk check loops in application code without evaluating Check batching or batch-checking endpoints to avoid head-of-line blocking and connection pool depletion.

## Bad vs Good Implementations
### Unbounded Check vs. Bounded, Trace-Instrumented Evaluation with Invalidation Hook

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The authorization check lacks an explicit context deadline/timeout, allowing nested ReBAC group expansions to block the worker thread and induce cascading latency. It relies on a local, non-invalidatable memory cache that results in stale authorization states when relationships are revoked.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// ANTI-PATTERN: Unbounded check without timeouts, depth guardrails, or cache invalidation
export async function authorizeUser(
  userId: string,
  relation: string,
  documentId: string
): Promise<boolean> {
  // In-memory static cache vulnerable to stale authorization decisions
  const cacheKey = `${userId}:${relation}:${documentId}`;
  if (globalCache.has(cacheKey)) {
    return globalCache.get(cacheKey)!;
  }

  // Raw check can recurse infinitely through nested group hierarchies without deadline
  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation,
    object: `document:${documentId}`,
  });

  globalCache.set(cacheKey, allowed ?? false);
  return allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: Implements hard query deadlines via AbortSignal to halt unbounded recursive traversals, fail-closed error handling to protect the system, short-lived bounded distributed caching, and coordinated cache eviction on relationship modification.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';
import { trace, context } from '@opentelemetry/api';
import type { Redis } from 'ioredis';

const tracer = trace.getTracer('openfga-authz');
const MAX_CHECK_TIMEOUT_MS = 150;

export class BoundedAuthorizer {
  constructor(
    private readonly fgaClient: OpenFgaClient,
    private readonly redisClient: Redis
  ) {}

  private buildCacheKey(user: string, relation: string, object: string): string {
    return `authz:decision:v1:${user}:${relation}:${object}`;
  }

  public async authorizeUser(
    userId: string,
    relation: string,
    documentId: string,
    abortSignal?: AbortSignal
  ): Promise<boolean> {
    return tracer.startActiveSpan('authorizeUser', async (span) => {
      const user = `user:${userId}`;
      const object = `document:${documentId}`;
      const cacheKey = this.buildCacheKey(user, relation, object);
      span.setAttributes({ 'fga.user': user, 'fga.relation': relation, 'fga.object': object });

      try {
        const cached = await this.redisClient.get(cacheKey);
        if (cached !== null) {
          span.setAttribute('fga.cache_hit', true);
          return cached === '1';
        }

        // Enforce strict evaluation deadline using an AbortController
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), MAX_CHECK_TIMEOUT_MS);
        if (abortSignal) {
          abortSignal.addEventListener('abort', () => controller.abort());
        }

        const checkPayload: ClientCheckRequest = {
          user,
          relation,
          object,
          context: { current_time: new Date().toISOString() },
        };

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

        clearTimeout(timeoutId);
        const isAllowed = response.allowed ?? false;

        // Bounded ephemeral cache with short TTL (e.g. 15s) to mitigate race conditions
        await this.redisClient.set(cacheKey, isAllowed ? '1' : '0', 'EX', 15);
        return isAllowed;
      } catch (err: unknown) {
        span.recordException(err as Error);
        // Fail closed on evaluation timeout or traversal failure
        return false;
      } finally {
        span.end();
      }
    });
  }

  public async writeTupleAndInvalidate(user: string, relation: string, object: string): Promise<void> {
    await this.fgaClient.write({
      writes: [{ user, relation, object }],
    });
    // Invalidate affected cache keys directly after writing
    const pattern = `authz:decision:v1:*:${object}`;
    const keys = await this.redisClient.keys(pattern);
    if (keys.length > 0) {
      await this.redisClient.del(...keys);
    }
  }
}
```

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: Bounded Graph Traversal Depth and Contextual Cache Invalidation for OpenFGA Zanzibar

Bounded Graph Traversal Depth and Contextual Cache Invalidation for OpenFGA Zanzibar defines an industrial-grade behavioral standard for security engineering. Enforces strict limits on authorization graph traversal depth, mandatory context timeouts, and atomic contextual cache invalidation in OpenFGA Zanzibar implementations. Deeply nested group-of-groups hierarchies and transitive relationship queries can trigger catastrophic cascade latencies, resource exhaustion, and stale authorization decisions without bound resolution parameters. All check operations must configure explicit query depth limits, propagate distributed trace deadlines, and use deterministic tuple-versioned cache eviction keys. 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 Traversal and Uncoordinated In-Memory Caching in Authorization Checks 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 Traversal and Uncoordinated In-Memory Caching in Authorization ChecksCritical
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 supply an explicit contextual timeout (maximum 200ms recommended for interactive requests) and enforce an upper bound for OpenFGA evaluation depth via client configuration or max-depth constraints.

Engineers MUST ALWAYS supply an explicit contextual timeout (maximum 200ms recommended for interactive requests) and enforce an upper bound for OpenFGA evaluation depth via client configuration or max-depth constraints.

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 execute check operations with unbounded relational models where nested groups or transitive relations can form self-referential cycles without depth termination.

Engineers MUST NOT execute check operations with unbounded relational models where nested groups or transitive relations can form self-referential cycles without depth termination.

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 propagate a distributed tracing context (such as W3C traceparent headers) into OpenFGA Check and Expand calls to expose authorization evaluation graph latencies across sub-queries.

Code SHOULD propagate a distributed tracing context (such as W3C traceparent headers) into OpenFGA Check and Expand calls to expose authorization evaluation graph latencies across sub-queries.

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 evict or invalidate downstream authorization decision caches atomically upon successful OpenFGA Write/Delete tuple operations, leveraging transactional outbox patterns or OpenFGA ReadChanges changelogs.

Services MUST evict or invalidate downstream authorization decision caches atomically upon successful OpenFGA Write/Delete tuple operations, leveraging transactional outbox patterns or OpenFGA ReadChanges changelogs.

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 raw bulk check loops in application code without evaluating Check batching or batch-checking endpoints to avoid head-of-line blocking and connection pool depletion.

Components NEVER execute raw bulk check loops in application code without evaluating Check batching or batch-checking endpoints to avoid head-of-line blocking and connection pool depletion.

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 Bounded Graph Traversal Depth and Contextual Cache Invalidation for OpenFGA Zanzibar critical for AI coding assistants?

Enforces strict limits on authorization graph traversal depth, mandatory context timeouts, and atomic contextual cache invalidation in OpenFGA Zanzibar implementations. Deeply nested group-of-groups hierarchies and transitive relationship queries can trigger catastrophic cascade latencies, resource exhaustion, and stale authorization decisions without bound resolution parameters. All check operations must configure explicit query depth limits, propagate distributed trace deadlines, and use deterministic tuple-versioned cache eviction keys. 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 Traversal and Uncoordinated In-Memory Caching in Authorization Checks) 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

Bounded